-
-
Notifications
You must be signed in to change notification settings - Fork 415
[codex] restore Codex session history #536
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dsus4wang
wants to merge
2
commits into
tiann:main
Choose a base branch
from
dsus4wang:codex/restore-codex-session-history
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
| import { mkdir, rm, writeFile } from 'node:fs/promises'; | ||
| import { join } from 'node:path'; | ||
| import { tmpdir } from 'node:os'; | ||
| import { importCodexSessionHistory } from './importHistory'; | ||
| import type { ApiSessionClient } from '@/lib'; | ||
| import type { Metadata } from '@hapi/protocol'; | ||
|
|
||
| describe('importCodexSessionHistory', () => { | ||
| const originalCodexHome = process.env.CODEX_HOME; | ||
| let codexHome: string; | ||
|
|
||
| beforeEach(async () => { | ||
| codexHome = join(tmpdir(), `hapi-codex-history-${Date.now()}-${Math.random().toString(16).slice(2)}`); | ||
| process.env.CODEX_HOME = codexHome; | ||
| await mkdir(join(codexHome, 'sessions', '2026', '04', '27'), { recursive: true }); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| if (originalCodexHome === undefined) { | ||
| delete process.env.CODEX_HOME; | ||
| } else { | ||
| process.env.CODEX_HOME = originalCodexHome; | ||
| } | ||
| await rm(codexHome, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| it('imports user and agent messages from the matching Codex transcript', async () => { | ||
| const transcriptPath = join(codexHome, 'sessions', '2026', '04', '27', 'session.jsonl'); | ||
| await writeFile( | ||
| transcriptPath, | ||
| [ | ||
| JSON.stringify({ type: 'session_meta', payload: { id: 'thread-1' } }), | ||
| JSON.stringify({ type: 'event_msg', payload: { type: 'user_message', message: 'old prompt' } }), | ||
| JSON.stringify({ type: 'event_msg', payload: { type: 'agent_message', message: 'old answer' } }) | ||
| ].join('\n') + '\n' | ||
| ); | ||
| await writeFile( | ||
| join(codexHome, 'session_index.jsonl'), | ||
| `${JSON.stringify({ id: 'thread-1', thread_name: 'codex generated title', updated_at: '2026-04-27T00:00:00.000Z' })}\n` | ||
| ); | ||
|
|
||
| const userMessages: string[] = []; | ||
| const agentMessages: unknown[] = []; | ||
| const updateMetadata = vi.fn(); | ||
| const session = { | ||
| updateMetadata, | ||
| sendUserMessage: (message: string) => userMessages.push(message), | ||
| sendAgentMessage: (message: unknown) => agentMessages.push(message), | ||
| } as unknown as ApiSessionClient; | ||
|
|
||
| const result = await importCodexSessionHistory({ | ||
| session, | ||
| codexSessionId: 'thread-1', | ||
| }); | ||
|
|
||
| expect(result).toEqual({ imported: 2, filePath: transcriptPath }); | ||
| expect(updateMetadata).toHaveBeenCalledTimes(2); | ||
| const metadata = updateMetadata.mock.calls.reduce<Metadata>( | ||
| (current, call) => call[0](current), | ||
| { path: '/repo', host: 'test' } | ||
| ); | ||
| expect(metadata).toMatchObject({ | ||
| codexSessionId: 'thread-1', | ||
| summary: { text: 'codex generated title' } | ||
| }); | ||
| expect(userMessages).toEqual(['old prompt']); | ||
| expect(agentMessages).toMatchObject([ | ||
| { type: 'message', message: 'old answer' } | ||
| ]); | ||
| }); | ||
|
|
||
| it('restores Codex session metadata from transcript model, reasoning effort, and latest usage', async () => { | ||
| const transcriptPath = join(codexHome, 'sessions', '2026', '04', '27', 'session.jsonl'); | ||
| await writeFile( | ||
| transcriptPath, | ||
| [ | ||
| JSON.stringify({ type: 'session_meta', payload: { id: 'thread-usage', model: 'gpt-5.4' } }), | ||
| JSON.stringify({ | ||
| type: 'event_msg', | ||
| payload: { | ||
| type: 'turn_context', | ||
| model: 'gpt-5.4', | ||
| reasoning_effort: 'high' | ||
| } | ||
| }), | ||
| JSON.stringify({ | ||
| type: 'event_msg', | ||
| payload: { | ||
| type: 'token_count', | ||
| info: { | ||
| model_context_window: 100_000, | ||
| total_token_usage: { | ||
| input_tokens: 1000, | ||
| cached_input_tokens: 500, | ||
| output_tokens: 250, | ||
| reasoning_output_tokens: 250, | ||
| total_tokens: 2000 | ||
| } | ||
| }, | ||
| rate_limits: { | ||
| primary: { | ||
| used_percent: 25, | ||
| window_minutes: 300 | ||
| } | ||
| } | ||
| } | ||
| }) | ||
| ].join('\n') + '\n' | ||
| ); | ||
|
|
||
| const updateMetadata = vi.fn(); | ||
| const applySessionConfig = vi.fn(); | ||
| const session = { | ||
| updateMetadata, | ||
| applySessionConfig, | ||
| sendUserMessage: vi.fn(), | ||
| sendAgentMessage: vi.fn(), | ||
| } as unknown as ApiSessionClient; | ||
|
|
||
| const result = await importCodexSessionHistory({ | ||
| session, | ||
| codexSessionId: 'thread-usage', | ||
| }); | ||
|
|
||
| expect(result).toMatchObject({ | ||
| imported: 1, | ||
| filePath: transcriptPath, | ||
| model: 'gpt-5.4', | ||
| modelReasoningEffort: 'high' | ||
| }); | ||
| expect(applySessionConfig).toHaveBeenCalledWith({ | ||
| model: 'gpt-5.4', | ||
| modelReasoningEffort: 'high' | ||
| }); | ||
| const metadata = updateMetadata.mock.calls.reduce<Metadata>( | ||
| (current, call) => call[0](current), | ||
| { path: '/repo', host: 'test' } | ||
| ); | ||
| expect(metadata).toMatchObject({ | ||
| codexSessionId: 'thread-usage', | ||
| codexUsage: { | ||
| contextWindow: { | ||
| usedTokens: 2000, | ||
| limitTokens: 100_000, | ||
| percent: 2 | ||
| }, | ||
| rateLimits: { | ||
| fiveHour: { | ||
| usedPercent: 25, | ||
| windowMinutes: 300 | ||
| } | ||
| }, | ||
| totalTokenUsage: { | ||
| inputTokens: 1000, | ||
| cachedInputTokens: 500, | ||
| outputTokens: 250, | ||
| reasoningOutputTokens: 250, | ||
| totalTokens: 2000 | ||
| } | ||
| } | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| import { readFile } from 'node:fs/promises'; | ||
| import type { ApiSessionClient } from '@/lib'; | ||
| import { findCodexSessionFile, findCodexSessionTitle, formatCodexSessionTitle } from '@/modules/common/codexSessions'; | ||
| import { logger } from '@/ui/logger'; | ||
| import { convertCodexEvent, type CodexSessionEvent } from './utils/codexEventConverter'; | ||
| import { normalizeCodexUsage } from './utils/codexUsage'; | ||
|
|
||
| type TitleSource = 'index' | 'user' | 'agent'; | ||
| type ImportSessionConfig = { | ||
| model?: string; | ||
| modelReasoningEffort?: string; | ||
| }; | ||
| type ImportSessionClient = ApiSessionClient & { | ||
| applySessionConfig?: (config: ImportSessionConfig) => void; | ||
| }; | ||
|
|
||
| function parseCodexSessionEvent(line: string): CodexSessionEvent | null { | ||
| let parsed: unknown; | ||
| try { | ||
| parsed = JSON.parse(line); | ||
| } catch { | ||
| return null; | ||
| } | ||
| if (!parsed || typeof parsed !== 'object') { | ||
| return null; | ||
| } | ||
| const record = parsed as Record<string, unknown>; | ||
| if (typeof record.type !== 'string' || record.type.length === 0) { | ||
| return null; | ||
| } | ||
| return { | ||
| timestamp: typeof record.timestamp === 'string' ? record.timestamp : undefined, | ||
| type: record.type, | ||
| payload: record.payload | ||
| }; | ||
| } | ||
|
|
||
| export async function importCodexSessionHistory(args: { | ||
| session: ImportSessionClient; | ||
| codexSessionId: string; | ||
| }): Promise<{ imported: number; filePath: string | null; model?: string; modelReasoningEffort?: string }> { | ||
| const filePath = await findCodexSessionFile(args.codexSessionId); | ||
| if (!filePath) { | ||
| logger.debug(`[codex-history-import] No transcript found for Codex session ${args.codexSessionId}`); | ||
| return { imported: 0, filePath: null }; | ||
| } | ||
|
|
||
| const content = await readFile(filePath, 'utf8'); | ||
| let imported = 0; | ||
| let title = await findCodexSessionTitle(args.codexSessionId); | ||
| let titleSource: TitleSource | null = title ? 'index' : null; | ||
| let restoredModel: string | undefined; | ||
| let restoredModelReasoningEffort: string | undefined; | ||
| for (const line of content.split('\n')) { | ||
| if (!line.trim()) { | ||
| continue; | ||
| } | ||
| const event = parseCodexSessionEvent(line); | ||
| if (!event) { | ||
| continue; | ||
| } | ||
| const converted = convertCodexEvent(event); | ||
| if (converted?.sessionId) { | ||
| const payload = event.payload && typeof event.payload === 'object' | ||
| ? event.payload as Record<string, unknown> | ||
| : null; | ||
| if (typeof payload?.model === 'string' && payload.model.length > 0) { | ||
| restoredModel = payload.model; | ||
| } | ||
| const sessionReasoningEffort = payload?.model_reasoning_effort ?? payload?.modelReasoningEffort ?? payload?.reasoning_effort ?? payload?.reasoningEffort; | ||
| if (typeof sessionReasoningEffort === 'string' && sessionReasoningEffort.length > 0) { | ||
| restoredModelReasoningEffort = sessionReasoningEffort; | ||
| } | ||
| args.session.updateMetadata((metadata) => ({ | ||
| ...metadata, | ||
| codexSessionId: converted.sessionId | ||
| })); | ||
| } | ||
| if (event.type === 'event_msg' && event.payload && typeof event.payload === 'object') { | ||
| const payload = event.payload as Record<string, unknown>; | ||
| if (payload.type === 'turn_context') { | ||
| if (typeof payload.model === 'string' && payload.model.length > 0) { | ||
| restoredModel = payload.model; | ||
| } | ||
| const reasoningEffort = payload.reasoning_effort ?? payload.reasoningEffort ?? payload.model_reasoning_effort ?? payload.modelReasoningEffort; | ||
| if (typeof reasoningEffort === 'string' && reasoningEffort.length > 0) { | ||
| restoredModelReasoningEffort = reasoningEffort; | ||
| } | ||
| } | ||
| } | ||
| if (converted?.userMessage) { | ||
| const userTitle = formatCodexSessionTitle(converted.userMessage); | ||
| if (userTitle && titleSource !== 'index' && titleSource !== 'user') { | ||
| title = userTitle; | ||
| titleSource = 'user'; | ||
| } | ||
| args.session.sendUserMessage(converted.userMessage); | ||
| imported += 1; | ||
| } | ||
| if (converted?.message) { | ||
| if (converted.message.type === 'token_count') { | ||
| const codexUsage = normalizeCodexUsage(converted.message); | ||
| if (codexUsage) { | ||
| args.session.updateMetadata((metadata) => ({ | ||
| ...metadata, | ||
| codexUsage | ||
| })); | ||
| } | ||
| } | ||
| if (converted.message.type === 'message' && !title) { | ||
| title = formatCodexSessionTitle(converted.message.message); | ||
| titleSource = 'agent'; | ||
| } | ||
| args.session.sendAgentMessage(converted.message); | ||
| imported += 1; | ||
| } | ||
| } | ||
|
|
||
| if (title) { | ||
| args.session.updateMetadata((metadata) => ({ | ||
| ...metadata, | ||
| summary: { | ||
| text: title, | ||
| updatedAt: Date.now() | ||
| } | ||
| })); | ||
| } | ||
|
|
||
| const restoredConfig: ImportSessionConfig = { | ||
| ...(restoredModel ? { model: restoredModel } : {}), | ||
| ...(restoredModelReasoningEffort ? { modelReasoningEffort: restoredModelReasoningEffort } : {}) | ||
| }; | ||
| if (restoredConfig.model || restoredConfig.modelReasoningEffort) { | ||
| args.session.applySessionConfig?.(restoredConfig); | ||
| } | ||
|
|
||
| logger.debug(`[codex-history-import] Imported ${imported} messages from ${filePath}`); | ||
| return { | ||
| imported, | ||
| filePath, | ||
| ...restoredConfig | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[MAJOR]
runCodexalready imports the transcript before the loop starts when--hapi-import-historyis set, so passing the same flag into the local scanner makes it replay the same persisted JSONL again. This duplicates the restored conversation for terminal resumes, and also after a web-restored session switches to local mode.Suggested fix: