From 95de52fb863b4946f36e9e9515b6afe61a860d23 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:38:07 -0800 Subject: [PATCH 01/30] fix(codex): legacy migration never overwrites transcripts or drops history lines The one-time legacy migration now copies session files with exclusive create, keeps an occupied preserved copy and picks the next free name, and appends missing history lines instead of rewriting history.jsonl from an earlier snapshot. --- .../runtime-home-legacy-migration.test.ts | 60 +++++++++++++ .../runtime-home-service-legacy-migration.ts | 87 ++++++++++++++----- .../runtime-home-service-state.ts | 7 +- 3 files changed, 129 insertions(+), 25 deletions(-) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index df6510834652..b826ee0b4f06 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { + appendFileSync, existsSync, mkdirSync, readlinkSync, @@ -29,6 +30,17 @@ vi.mock('electron', () => ({ })) beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) +const fsHooks = vi.hoisted(() => ({ afterRead: new Map void>() })) +vi.mock(import('node:fs'), async (importOriginal) => { + const actual = await importOriginal() + const readFileSync = ((...args: Parameters) => { + const contents = actual.readFileSync(...args) + fsHooks.afterRead.get(String(args[0]))?.() + return contents + }) as typeof actual.readFileSync + return { ...actual, default: { ...actual, readFileSync }, readFileSync } +}) + vi.mock(import('node:os'), async (importOriginal) => { const actual = await importOriginal() return { @@ -43,6 +55,7 @@ describe('CodexRuntimeHomeService', () => { }) afterEach(() => { + fsHooks.afterRead.clear() teardownRuntimeHomeTest() }) @@ -172,4 +185,51 @@ describe('CodexRuntimeHomeService', () => { expect(diagnostics).toHaveLength(2) expect(diagnostics[0]).toContain('"type":"session-conflict"') }) + + it('keeps history lines Codex appends while legacy history is merged', async () => { + const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') + writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}\n', 'utf-8') + const managedHomePath = createManagedAuth( + testState.userDataDir, + 'account-1', + '{"account":"managed"}\n' + ) + const legacyHistoryPath = join(managedHomePath, 'history.jsonl') + writeFileSync(legacyHistoryPath, '{"id":"managed-2"}\n', 'utf-8') + fsHooks.afterRead.set(legacyHistoryPath, () => + appendFileSync(runtimeHistoryPath, '{"id":"codex-live"}\n', 'utf-8') + ) + const store = createStore(createSettings()) + + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + new CodexRuntimeHomeService(store as never) + + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( + '{"id":"shared-1"}\n{"id":"codex-live"}\n{"id":"managed-2"}\n' + ) + }) + + it('never overwrites an existing preserved session copy', async () => { + const runtimeSessionsDir = join(getRuntimeCodexHomePath(), 'sessions') + mkdirSync(runtimeSessionsDir, { recursive: true }) + writeFileSync(join(runtimeSessionsDir, 'session.json'), '{"turns":[1]}', 'utf-8') + const occupiedPreservedPath = join(runtimeSessionsDir, 'session.orca-legacy-account-1.json') + writeFileSync(occupiedPreservedPath, '{"turns":["kept"]}', 'utf-8') + const managedHomePath = createManagedAuth( + testState.userDataDir, + 'account-1', + '{"account":"managed"}\n' + ) + mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'session.json'), '{"turns":[1,2]}', 'utf-8') + const store = createStore(createSettings()) + + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + new CodexRuntimeHomeService(store as never) + + expect(readFileSync(occupiedPreservedPath, 'utf-8')).toBe('{"turns":["kept"]}') + expect( + readFileSync(join(runtimeSessionsDir, 'session.orca-legacy-account-1-1.json'), 'utf-8') + ).toBe('{"turns":[1,2]}') + }) }) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 860b7ca558d0..d685754a4bf2 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -1,5 +1,6 @@ import { appendFileSync, + constants, copyFileSync, existsSync, mkdirSync, @@ -9,6 +10,7 @@ import { } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' +import { nodeFileContentsEqualSync } from '../../../../shared/file-content/node-file-content-equality' import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-migration' import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' @@ -105,23 +107,28 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } const runtimeHistoryPath = join(this.getRuntimeHomePath(), 'history.jsonl') - const existingLines = existsSync(runtimeHistoryPath) - ? readFileSync(runtimeHistoryPath, 'utf-8').split('\n').filter(Boolean) - : [] - const mergedLines = [...existingLines] - const seenLines = new Set(existingLines) + const existingHistory = existsSync(runtimeHistoryPath) + ? readFileSync(runtimeHistoryPath, 'utf-8') + : '' + const seenLines = new Set(existingHistory.split('\n').filter(Boolean)) + const missingLines: string[] = [] for (const line of readFileSync(legacyHistoryPath, 'utf-8').split('\n')) { if (!line || seenLines.has(line)) { continue } seenLines.add(line) - mergedLines.push(line) + missingLines.push(line) } - if (mergedLines.length === 0) { + if (missingLines.length === 0) { return } - writeFileAtomically(runtimeHistoryPath, `${mergedLines.join('\n')}\n`) + // Append instead of rewriting a snapshot so lines a running Codex adds meanwhile survive. + const separator = existingHistory && !existingHistory.endsWith('\n') ? '\n' : '' + appendFileSync(runtimeHistoryPath, `${separator}${missingLines.join('\n')}\n`, { + encoding: 'utf-8', + mode: 0o600 + }) } protected migrateLegacySessions(managedHomePath: string, accountId: string): void { @@ -136,25 +143,52 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa const relativePath = relative(legacySessionsRoot, legacyFilePath) const runtimeFilePath = join(runtimeSessionsRoot, relativePath) mkdirSync(dirname(runtimeFilePath), { recursive: true }) - if (!existsSync(runtimeFilePath)) { - copyFileSync(legacyFilePath, runtimeFilePath) + if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, runtimeFilePath) !== 'conflict') { continue } - const legacyContents = readFileSync(legacyFilePath) - const runtimeContents = readFileSync(runtimeFilePath) - if (runtimeContents.equals(legacyContents)) { - continue + for (let attempt = 0; ; attempt++) { + const preservedPath = this.getPreservedLegacySessionPath( + runtimeFilePath, + accountId, + attempt + ) + const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath) + if (result === 'conflict') { + continue + } + if (result === 'copied') { + this.appendMigrationDiagnostic({ + type: 'session-conflict', + accountId, + runtimeFilePath, + preservedPath + }) + } + break } + } + } - const preservedPath = this.getPreservedLegacySessionPath(runtimeFilePath, accountId) - copyFileSync(legacyFilePath, preservedPath) - this.appendMigrationDiagnostic({ - type: 'session-conflict', - accountId, - runtimeFilePath, - preservedPath - }) + /** Exclusive create never replaces or writes through a name, even one that appears after a check. */ + protected copyLegacyFileWithoutOverwrite( + legacyFilePath: string, + targetPath: string + ): 'copied' | 'identical' | 'conflict' { + try { + copyFileSync(legacyFilePath, targetPath, constants.COPYFILE_EXCL) + return 'copied' + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { + throw error + } + } + const legacyContents = readFileSync(legacyFilePath) + try { + return nodeFileContentsEqualSync(targetPath, legacyContents) ? 'identical' : 'conflict' + } catch { + // A dangling link or directory at this name still occupies it. + return 'conflict' } } @@ -185,10 +219,15 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } } - protected getPreservedLegacySessionPath(runtimeFilePath: string, accountId: string): string { + protected getPreservedLegacySessionPath( + runtimeFilePath: string, + accountId: string, + attempt: number + ): string { const extension = extname(runtimeFilePath) const basename = runtimeFilePath.slice(0, runtimeFilePath.length - extension.length) - return `${basename}.orca-legacy-${accountId}${extension}` + const suffix = attempt === 0 ? '' : `-${attempt}` + return `${basename}.orca-legacy-${accountId}${suffix}${extension}` } protected appendMigrationDiagnostic(record: Record): void { diff --git a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts index 7018b357c9ca..8bd8a21ff6b1 100644 --- a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts @@ -205,8 +205,13 @@ export abstract class CodexRuntimeHomeState { protected abstract appendListedFiles(target: string[], source: readonly string[]): void protected abstract getPreservedLegacySessionPath( runtimeFilePath: string, - accountId: string + accountId: string, + attempt: number ): string + protected abstract copyLegacyFileWithoutOverwrite( + legacyFilePath: string, + targetPath: string + ): 'copied' | 'identical' | 'conflict' protected abstract appendMigrationDiagnostic(record: Record): void protected abstract captureSystemDefaultSnapshot(options: { force: boolean }): void From cb03fef7462dff0807fc62ced6a5b87c66baec73 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:43:36 -0800 Subject: [PATCH 02/30] fix(codex): import legacy prompt history only while no Codex thread is live A live Codex appends to and trims history.jsonl under a lock Orca can't share, so the one-time import now runs only while Codex's thread-writer locks are idle and coordination is held; otherwise it stays pending in the migration marker and retries on the next launch. Each imported line is its own write, started on a fresh line, so a failed write damages only its own record. Adds codex_legacy_history_import telemetry for imported vs skipped launches. --- .../legacy-prompt-history-import.ts | 114 ++++++++++++++++++ .../runtime-home-legacy-migration.test.ts | 82 ++++++++++++- .../runtime-home-service-legacy-migration.ts | 88 +++++++++----- .../shared-store/codex-thread-writer-locks.ts | 30 +++++ src/main/ipc/telemetry.ts | 1 + ...etry-codex-legacy-history-event-schemas.ts | 19 +++ .../telemetry/telemetry-event-registry.ts | 2 + 7 files changed, 300 insertions(+), 36 deletions(-) create mode 100644 src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts create mode 100644 src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts new file mode 100644 index 000000000000..51f05689f306 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -0,0 +1,114 @@ +import { closeSync, existsSync, openSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { + runWhileNoCodexThreadIsLive, + type LockFolderBusy +} from '../../../codex/history/shared-store/codex-thread-writer-locks' +import { track } from '../../../telemetry/client' +import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas' + +type ImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] + +const SKIPPED_OUTCOMES: Record<'held' | LockFolderBusy, ImportOutcome> = { + held: 'codex_live', + busy: 'busy', + 'no-helper': 'no_helper' +} + +export type LegacyMigrationMarker = { + completedAt?: number + migratedHomeCount?: number + /** Legacy prompt history still waits for a launch with no live Codex in the shared home. */ + historyPending?: true +} + +function readFileVersion(path: string): string { + try { + const stats = statSync(path, { bigint: true }) + return `${stats.ino}:${stats.size}:${stats.mtimeNs}` + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return 'absent' + } + throw error + } +} + +/** + * A live Codex appends to and trims history.jsonl under a lock Orca can't share, so the import runs + * only while no Codex thread is live in the home and none can start; otherwise it stays pending for + * the next launch. + */ +export async function importLegacyHistoryWhenNoCodexIsLive(args: { + runtimeHomePath: string + importHistory: () => void +}): Promise { + let outcome: ImportOutcome + try { + const runtimeHistoryPath = join(args.runtimeHomePath, 'history.jsonl') + const versionBefore = readFileVersion(runtimeHistoryPath) + const result = await runWhileNoCodexThreadIsLive(args.runtimeHomePath, () => { + if (readFileVersion(runtimeHistoryPath) !== versionBefore) { + return false + } + args.importHistory() + return true + }) + outcome = result.ran ? (result.value ? 'imported' : 'changed') : SKIPPED_OUTCOMES[result.reason] + } catch (error) { + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) + outcome = 'failed' + } + try { + track('codex_legacy_history_import', { + outcome, + platform: + process.platform === 'win32' || process.platform === 'linux' ? process.platform : 'darwin' + }) + } catch { + // Telemetry never costs the import. + } +} + +/** Appends the legacy lines runtime history lacks; never rewrites what Codex already wrote. */ +export function appendMissingLegacyHistory( + legacyHistoryPath: string, + runtimeHistoryPath: string +): void { + const existingHistory = existsSync(runtimeHistoryPath) + ? readFileSync(runtimeHistoryPath, 'utf-8') + : '' + const seenLines = new Set(existingHistory.split('\n').filter(Boolean)) + const missingLines: string[] = [] + for (const line of readFileSync(legacyHistoryPath, 'utf-8').split('\n')) { + if (!line || seenLines.has(line)) { + continue + } + seenLines.add(line) + missingLines.push(line) + } + if (missingLines.length === 0) { + return + } + // One write per line, each started on a fresh line, so a failed write damages only its own record. + const fd = openSync(runtimeHistoryPath, 'a', 0o600) + try { + if (existingHistory && !existingHistory.endsWith('\n')) { + writeFileSync(fd, '\n') + } + for (const line of missingLines) { + try { + writeFileSync(fd, `${line}\n`, 'utf-8') + } catch (error) { + try { + writeFileSync(fd, '\n') + } catch { + // The original write error is the one to report. + } + throw error + } + } + } finally { + closeSync(fd) + } +} diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index b826ee0b4f06..ead0c9170e4a 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -2,14 +2,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { appendFileSync, - existsSync, mkdirSync, readlinkSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs' +import { spawn } from 'node:child_process' import { join } from 'node:path' +import { createInterface } from 'node:readline' import { createSettings } from '../runtime-home-settings-test-fixtures' import { createManagedAuth, @@ -30,6 +31,38 @@ vi.mock('electron', () => ({ })) beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) +const trackMock = vi.hoisted(() => vi.fn()) +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) + +function trackedImportOutcomes(): string[] { + return trackMock.mock.calls + .filter(([event]) => event === 'codex_legacy_history_import') + .map(([, props]) => (props as { outcome: string }).outcome) +} + +async function waitForHistoryImport(): Promise { + await vi.waitFor(() => expect(trackedImportOutcomes()).toContain('imported'), { + timeout: 15_000 + }) + trackMock.mockClear() +} + +// Holds a lock the way Codex does: flock(2) on the file, until released. +async function holdWithFlock(lockPath: string): Promise<() => Promise> { + writeFileSync(lockPath, '') + const holder = spawn('perl', [ + '-e', + 'use Fcntl qw(:flock); open(my $l, "+<", $ARGV[0]) or die; flock($l, LOCK_EX) or die; $| = 1; print "locked\\n"; ', + lockPath + ]) + const closed = new Promise((resolve) => holder.once('close', resolve)) + await createInterface({ input: holder.stdout })[Symbol.asyncIterator]().next() + return async () => { + holder.stdin.end() + await closed + } +} + const fsHooks = vi.hoisted(() => ({ afterRead: new Map void>() })) vi.mock(import('node:fs'), async (importOriginal) => { const actual = await importOriginal() @@ -56,6 +89,7 @@ describe('CodexRuntimeHomeService', () => { afterEach(() => { fsHooks.afterRead.clear() + trackMock.mockClear() teardownRuntimeHomeTest() }) @@ -109,12 +143,10 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) + await waitForHistoryImport() expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( '{"id":"shared-1"}\n{"id":"managed-2"}\n' ) - expect(existsSync(join(testState.userDataDir, 'codex-runtime-home', 'migration-v1.json'))).toBe( - true - ) }) it('does not re-run migration when marker already exists', async () => { @@ -129,6 +161,7 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) + await waitForHistoryImport() const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') expect(readFileSync(runtimeHistoryPath, 'utf-8')).toContain('legacy-1') @@ -204,6 +237,7 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) + await waitForHistoryImport() expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( '{"id":"shared-1"}\n{"id":"codex-live"}\n{"id":"managed-2"}\n' ) @@ -232,4 +266,44 @@ describe('CodexRuntimeHomeService', () => { readFileSync(join(runtimeSessionsDir, 'session.orca-legacy-account-1-1.json'), 'utf-8') ).toBe('{"turns":[1,2]}') }) + + it.skipIf(process.platform === 'win32')( + 'leaves legacy history pending while a Codex thread is live, then imports it', + async () => { + const runtimeHomePath = getRuntimeCodexHomePath() + const runtimeHistoryPath = join(runtimeHomePath, 'history.jsonl') + writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}\n', 'utf-8') + const managedHomePath = createManagedAuth( + testState.userDataDir, + 'account-1', + '{"account":"managed"}\n' + ) + writeFileSync(join(managedHomePath, 'history.jsonl'), '{"id":"managed-2"}\n', 'utf-8') + const locks = join(runtimeHomePath, 'thread-writer-locks') + mkdirSync(locks, { recursive: true }) + const releaseThread = await holdWithFlock( + join(locks, '0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5c.lock') + ) + const store = createStore(createSettings()) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + try { + new CodexRuntimeHomeService(store as never) + await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['codex_live']), { + timeout: 15_000 + }) + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}\n') + } finally { + await releaseThread() + } + + vi.resetModules() + const relaunched = await import('../../runtime-home-service') + new relaunched.CodexRuntimeHomeService(store as never) + + await waitForHistoryImport() + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( + '{"id":"shared-1"}\n{"id":"managed-2"}\n' + ) + } + ) }) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index d685754a4bf2..c2f9f8e51477 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -15,6 +15,11 @@ import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-mi import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' +import { + appendMissingLegacyHistory, + importLegacyHistoryWhenNoCodexIsLive, + type LegacyMigrationMarker +} from './legacy-prompt-history-import' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { @@ -57,7 +62,11 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - if (existsSync(this.getMigrationMarkerPath())) { + const existingMarker = this.readMigrationMarker() + if (existingMarker) { + if (existingMarker.historyPending) { + void this.importLegacyHistoryWhenNoCodexIsLive(existingMarker) + } return } @@ -69,15 +78,51 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa if (!accountId) { continue } - this.migrateLegacyHistory(managedHomePath) this.migrateLegacySessions(managedHomePath, accountId) } + const historyPending = managedHomes.some((home) => existsSync(join(home, 'history.jsonl'))) + const marker: LegacyMigrationMarker = { + completedAt: Date.now(), + migratedHomeCount: managedHomes.length, + ...(historyPending ? { historyPending } : {}) + } // Mark completion so later startups cannot replay stale managed-home state. - writeFileAtomically( - this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` - ) + this.writeMigrationMarker(marker) + if (historyPending) { + void this.importLegacyHistoryWhenNoCodexIsLive(marker) + } + } + + protected importLegacyHistoryWhenNoCodexIsLive(marker: LegacyMigrationMarker): Promise { + return importLegacyHistoryWhenNoCodexIsLive({ + runtimeHomePath: this.getRuntimeHomePath(), + importHistory: () => { + for (const managedHomePath of this.getLegacyManagedHomes()) { + this.migrateLegacyHistory(managedHomePath) + } + const { historyPending: _imported, ...completed } = marker + this.writeMigrationMarker(completed) + } + }) + } + + protected readMigrationMarker(): LegacyMigrationMarker | null { + const markerPath = this.getMigrationMarkerPath() + if (!existsSync(markerPath)) { + return null + } + try { + const parsed: unknown = JSON.parse(readFileSync(markerPath, 'utf-8')) + return parsed && typeof parsed === 'object' ? (parsed as LegacyMigrationMarker) : {} + } catch { + // An unreadable marker still means the one-time migration ran. + return {} + } + } + + protected writeMigrationMarker(marker: LegacyMigrationMarker): void { + writeFileAtomically(this.getMigrationMarkerPath(), `${JSON.stringify(marker)}\n`) } protected getLegacyManagedHomes(): string[] { @@ -102,33 +147,12 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa protected migrateLegacyHistory(managedHomePath: string): void { const legacyHistoryPath = join(managedHomePath, 'history.jsonl') - if (!existsSync(legacyHistoryPath)) { - return + if (existsSync(legacyHistoryPath)) { + appendMissingLegacyHistory( + legacyHistoryPath, + join(this.getRuntimeHomePath(), 'history.jsonl') + ) } - - const runtimeHistoryPath = join(this.getRuntimeHomePath(), 'history.jsonl') - const existingHistory = existsSync(runtimeHistoryPath) - ? readFileSync(runtimeHistoryPath, 'utf-8') - : '' - const seenLines = new Set(existingHistory.split('\n').filter(Boolean)) - const missingLines: string[] = [] - for (const line of readFileSync(legacyHistoryPath, 'utf-8').split('\n')) { - if (!line || seenLines.has(line)) { - continue - } - seenLines.add(line) - missingLines.push(line) - } - - if (missingLines.length === 0) { - return - } - // Append instead of rewriting a snapshot so lines a running Codex adds meanwhile survive. - const separator = existingHistory && !existingHistory.endsWith('\n') ? '\n' : '' - appendFileSync(runtimeHistoryPath, `${separator}${missingLines.join('\n')}\n`, { - encoding: 'utf-8', - mode: 0o600 - }) } protected migrateLegacySessions(managedHomePath: string, accountId: string): void { diff --git a/src/main/codex/history/shared-store/codex-thread-writer-locks.ts b/src/main/codex/history/shared-store/codex-thread-writer-locks.ts index a8bf53b4f9dd..ae9a57748710 100644 --- a/src/main/codex/history/shared-store/codex-thread-writer-locks.ts +++ b/src/main/codex/history/shared-store/codex-thread-writer-locks.ts @@ -225,6 +225,36 @@ export async function moveIdleThreadLockFolder( } // A Codex that started meanwhile: a file it opened (Windows) or the folder it recreated mid-swap. +/** + * Runs `action` only when no Codex thread is live in `codexHome`, with its coordination held so none + * can start until `action` returns; otherwise says why it didn't run. + */ +export async function runWhileNoCodexThreadIsLive( + codexHome: string, + action: () => T +): Promise<{ ran: true; value: T } | { ran: false; reason: 'held' | LockFolderBusy }> { + const locks = join(codexHome, WRITER_LOCKS) + await mkdir(locks, { recursive: true }) + const hold = await startProbe([locks], true) + if (hold?.answer === 'held') { + return { ran: false, reason: 'held' } + } + if (hold?.answer === 'unavailable') { + return { ran: false, reason: 'no-helper' } + } + if (!hold || !('release' in hold)) { + return { ran: false, reason: 'busy' } + } + try { + if (!hold.stillHeld()) { + return { ran: false, reason: 'busy' } + } + return { ran: true, value: action() } + } finally { + await hold.release() + } +} + function isStartingCodexError(error: unknown): boolean { if (error instanceof DirectoryLinkError) { return error.code === 'link-failed' diff --git a/src/main/ipc/telemetry.ts b/src/main/ipc/telemetry.ts index 953edfe66354..c5d8706ecc45 100644 --- a/src/main/ipc/telemetry.ts +++ b/src/main/ipc/telemetry.ts @@ -36,6 +36,7 @@ const MAIN_OWNED_TELEMETRY_EVENTS = new Set([ 'browser_extensions_banner_assigned', 'app_starred_orca', 'codex_history_cleanup_sweep', + 'codex_legacy_history_import', 'daemon_adopted', 'daemon_async_io_health', 'daemon_audit_eligibility', diff --git a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts new file mode 100644 index 000000000000..0dd66fb62830 --- /dev/null +++ b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts @@ -0,0 +1,19 @@ +import { z } from 'zod' + +/** `codex_live`, `busy`, `no_helper` and `changed` are skips the next launch retries. */ +export const CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES = [ + 'imported', + 'codex_live', + 'busy', + 'no_helper', + 'changed', + 'failed' +] as const + +/** One row per launch that still had the one-time legacy prompt-history import pending. */ +export const codexLegacyHistoryImportSchema = z + .object({ + outcome: z.enum(CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES), + platform: z.enum(['darwin', 'linux', 'win32']) + }) + .strict() diff --git a/src/shared/telemetry/telemetry-event-registry.ts b/src/shared/telemetry/telemetry-event-registry.ts index 256251d24aaa..c57987b8c6cb 100644 --- a/src/shared/telemetry/telemetry-event-registry.ts +++ b/src/shared/telemetry/telemetry-event-registry.ts @@ -5,6 +5,7 @@ import { } from './schemas/telemetry-onboarding-language-schemas' import { agentTokenUsageSchema } from './schemas/telemetry-agent-token-usage-schema' import { codexHistoryCleanupSweepSchema } from './schemas/telemetry-codex-history-cleanup-event-schemas' +import { codexLegacyHistoryImportSchema } from './schemas/telemetry-codex-legacy-history-event-schemas' import { agentDashboardActiveSchema, agentDashboardEnabledSchema, @@ -268,6 +269,7 @@ export const eventSchemas = { wsl_usage_snapshot: wslUsageSnapshotSchema, codex_history_cleanup_sweep: codexHistoryCleanupSweepSchema, + codex_legacy_history_import: codexLegacyHistoryImportSchema, plugin_installed: pluginInstalledSchema, From e5b7009c4df0771e92b537381519c7594b3f3253 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:09:17 -0800 Subject: [PATCH 03/30] fix(codex): never write a live shared history during the legacy migration The one-time import now only creates the shared history.jsonl when none exists, from a temp file published with a no-overwrite hard link, off the startup path. When a shared history already exists, or Codex creates one meanwhile, it is left untouched and each account's legacy history is kept aside under Orca's runtime metadata, which account removal and history cleanup never reach. Drops the thread-lock gate and deferred retry. --- .../legacy-prompt-history-import.ts | 136 ++++------- .../runtime-home-legacy-migration.test.ts | 217 ++++++++---------- .../runtime-home-service-legacy-migration.ts | 166 +++++++------- .../runtime-home-service-state.ts | 4 +- .../codex-account-history-cleanup.test.ts | 3 + .../codex-account-history-links.test.ts | 2 + .../shared-store/codex-thread-writer-locks.ts | 30 --- ...etry-codex-legacy-history-event-schemas.ts | 9 +- 8 files changed, 236 insertions(+), 331 deletions(-) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 51f05689f306..a1e4012ecde2 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,64 +1,61 @@ -import { closeSync, existsSync, openSync, readFileSync, statSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { - runWhileNoCodexThreadIsLive, - type LockFolderBusy -} from '../../../codex/history/shared-store/codex-thread-writer-locks' +import { randomUUID } from 'node:crypto' +import { lstat, open, readFile, rm } from 'node:fs/promises' +import { publishFileWithoutOverwrite } from '../../../filesystem/atomic-file-publication' import { track } from '../../../telemetry/client' import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas' -type ImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] +export type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] -const SKIPPED_OUTCOMES: Record<'held' | LockFolderBusy, ImportOutcome> = { - held: 'codex_live', - busy: 'busy', - 'no-helper': 'no_helper' -} - -export type LegacyMigrationMarker = { - completedAt?: number - migratedHomeCount?: number - /** Legacy prompt history still waits for a launch with no live Codex in the shared home. */ - historyPending?: true -} - -function readFileVersion(path: string): string { +async function pathExists(path: string): Promise { try { - const stats = statSync(path, { bigint: true }) - return `${stats.ino}:${stats.size}:${stats.mtimeNs}` + await lstat(path) + return true } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') { - return 'absent' + return false } throw error } } -/** - * A live Codex appends to and trims history.jsonl under a lock Orca can't share, so the import runs - * only while no Codex thread is live in the home and none can start; otherwise it stays pending for - * the next launch. - */ -export async function importLegacyHistoryWhenNoCodexIsLive(args: { - runtimeHomePath: string - importHistory: () => void -}): Promise { - let outcome: ImportOutcome - try { - const runtimeHistoryPath = join(args.runtimeHomePath, 'history.jsonl') - const versionBefore = readFileVersion(runtimeHistoryPath) - const result = await runWhileNoCodexThreadIsLive(args.runtimeHomePath, () => { - if (readFileVersion(runtimeHistoryPath) !== versionBefore) { - return false +/** Creates the shared history from the legacy ones only while it doesn't exist; never writes one. */ +export async function publishLegacyHistoryIfAbsent( + legacyHistoryPaths: readonly string[], + runtimeHistoryPath: string +): Promise { + if (await pathExists(runtimeHistoryPath)) { + return 'skipped_existing' + } + const seenLines = new Set() + for (const legacyHistoryPath of legacyHistoryPaths) { + for (const line of (await readFile(legacyHistoryPath, 'utf-8')).split('\n')) { + if (line) { + seenLines.add(line) } - args.importHistory() - return true - }) - outcome = result.ran ? (result.value ? 'imported' : 'changed') : SKIPPED_OUTCOMES[result.reason] - } catch (error) { - console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) - outcome = 'failed' + } } + if (seenLines.size === 0) { + return 'skipped_existing' + } + const tmpPath = `${runtimeHistoryPath}.${process.pid}.${randomUUID()}.tmp` + try { + const handle = await open(tmpPath, 'wx', 0o600) + try { + await handle.writeFile(`${[...seenLines].join('\n')}\n`, 'utf-8') + await handle.sync() + } finally { + await handle.close() + } + // A hard link publishes only into a free name: one Codex created meanwhile stays as it is. + return publishFileWithoutOverwrite(tmpPath, runtimeHistoryPath) + ? 'imported' + : 'skipped_existing' + } finally { + await rm(tmpPath, { force: true }) + } +} + +export function trackLegacyHistoryImport(outcome: LegacyHistoryImportOutcome): void { try { track('codex_legacy_history_import', { outcome, @@ -66,49 +63,6 @@ export async function importLegacyHistoryWhenNoCodexIsLive(args: { process.platform === 'win32' || process.platform === 'linux' ? process.platform : 'darwin' }) } catch { - // Telemetry never costs the import. - } -} - -/** Appends the legacy lines runtime history lacks; never rewrites what Codex already wrote. */ -export function appendMissingLegacyHistory( - legacyHistoryPath: string, - runtimeHistoryPath: string -): void { - const existingHistory = existsSync(runtimeHistoryPath) - ? readFileSync(runtimeHistoryPath, 'utf-8') - : '' - const seenLines = new Set(existingHistory.split('\n').filter(Boolean)) - const missingLines: string[] = [] - for (const line of readFileSync(legacyHistoryPath, 'utf-8').split('\n')) { - if (!line || seenLines.has(line)) { - continue - } - seenLines.add(line) - missingLines.push(line) - } - if (missingLines.length === 0) { - return - } - // One write per line, each started on a fresh line, so a failed write damages only its own record. - const fd = openSync(runtimeHistoryPath, 'a', 0o600) - try { - if (existingHistory && !existingHistory.endsWith('\n')) { - writeFileSync(fd, '\n') - } - for (const line of missingLines) { - try { - writeFileSync(fd, `${line}\n`, 'utf-8') - } catch (error) { - try { - writeFileSync(fd, '\n') - } catch { - // The original write error is the one to report. - } - throw error - } - } - } finally { - closeSync(fd) + // Telemetry never costs the migration. } } diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index ead0c9170e4a..e241bf3bcde1 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -1,17 +1,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { - appendFileSync, + existsSync, mkdirSync, readlinkSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs' -import { spawn } from 'node:child_process' import { join } from 'node:path' -import { createInterface } from 'node:readline' import { createSettings } from '../runtime-home-settings-test-fixtures' +import type { CodexManagedHomePath } from '../../managed-homes/codex-managed-home-path' import { createManagedAuth, createStore, @@ -40,38 +39,57 @@ function trackedImportOutcomes(): string[] { .map(([, props]) => (props as { outcome: string }).outcome) } -async function waitForHistoryImport(): Promise { - await vi.waitFor(() => expect(trackedImportOutcomes()).toContain('imported'), { - timeout: 15_000 - }) - trackMock.mockClear() +function writeHistory(accountId: string, contents: string): string { + const managedHomePath = createManagedAuth( + testState.userDataDir, + accountId, + '{"account":"managed"}\n' + ) + writeFileSync(join(managedHomePath, 'history.jsonl'), contents, 'utf-8') + return managedHomePath } -// Holds a lock the way Codex does: flock(2) on the file, until released. -async function holdWithFlock(lockPath: string): Promise<() => Promise> { - writeFileSync(lockPath, '') - const holder = spawn('perl', [ - '-e', - 'use Fcntl qw(:flock); open(my $l, "+<", $ARGV[0]) or die; flock($l, LOCK_EX) or die; $| = 1; print "locked\\n"; ', - lockPath - ]) - const closed = new Promise((resolve) => holder.once('close', resolve)) - await createInterface({ input: holder.stdout })[Symbol.asyncIterator]().next() - return async () => { - holder.stdin.end() - await closed - } +function archivedHistoryPath(accountId: string): string { + return join( + testState.userDataDir, + 'codex-runtime-home', + 'legacy-history-not-imported', + accountId, + 'history.jsonl' + ) +} + +async function startService(): Promise { + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + new CodexRuntimeHomeService(createStore(createSettings()) as never) + await waitForMigrationMarker() +} + +async function waitForMigrationMarker(): Promise { + const markerPath = join(testState.userDataDir, 'codex-runtime-home', 'migration-v1.json') + await vi.waitFor(() => expect(existsSync(markerPath)).toBe(true)) +} + +async function removeAccountHome(managedHomePath: string): Promise { + const { CodexManagedHomeLifecycle } = + await import('../../managed-homes/codex-managed-home-lifecycle') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: safeRemove reads only these two members. + const paths = { + assert: async (candidate: string) => candidate, + getRoot: () => join(testState.userDataDir, 'codex-accounts') + } as unknown as CodexManagedHomePath + await new CodexManagedHomeLifecycle(paths).safeRemove(managedHomePath, 'account-1') } const fsHooks = vi.hoisted(() => ({ afterRead: new Map void>() })) -vi.mock(import('node:fs'), async (importOriginal) => { +vi.mock(import('node:fs/promises'), async (importOriginal) => { const actual = await importOriginal() - const readFileSync = ((...args: Parameters) => { - const contents = actual.readFileSync(...args) + const readFile = (async (...args: Parameters) => { + const contents = await actual.readFile(...args) fsHooks.afterRead.get(String(args[0]))?.() return contents - }) as typeof actual.readFileSync - return { ...actual, default: { ...actual, readFileSync }, readFileSync } + }) as typeof actual.readFile + return { ...actual, default: { ...actual, readFile }, readFile } }) vi.mock(import('node:os'), async (importOriginal) => { @@ -115,6 +133,7 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) + await waitForMigrationMarker() expect(normalizeLinkTarget(readlinkSync(legacyActiveHomePath))).toBe( normalizeLinkTarget(getRuntimeCodexHomePath()) @@ -124,58 +143,68 @@ describe('CodexRuntimeHomeService', () => { ) }) - it('imports legacy managed-home history into the shared runtime history', async () => { - const runtimeHomePath = getRuntimeCodexHomePath() - const runtimeHistoryPath = join(runtimeHomePath, 'history.jsonl') - writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}\n', 'utf-8') - const managedHomePath = createManagedAuth( - testState.userDataDir, - 'account-1', - '{"account":"managed"}\n' - ) - writeFileSync( - join(managedHomePath, 'history.jsonl'), - '{"id":"shared-1"}\n{"id":"managed-2"}\n', - 'utf-8' - ) - const store = createStore(createSettings()) + it('creates the shared history from legacy histories when none exists', async () => { + const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') + writeHistory('account-1', '{"id":"a-1"}\n{"id":"both"}\n') + writeHistory('account-2', '{"id":"both"}\n{"id":"b-1"}\n') - const { CodexRuntimeHomeService } = await import('../../runtime-home-service') - new CodexRuntimeHomeService(store as never) + await startService() - await waitForHistoryImport() expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( - '{"id":"shared-1"}\n{"id":"managed-2"}\n' + '{"id":"a-1"}\n{"id":"both"}\n{"id":"b-1"}\n' ) + expect(trackedImportOutcomes()).toEqual(['imported']) + expect(existsSync(archivedHistoryPath('account-1'))).toBe(false) }) - it('does not re-run migration when marker already exists', async () => { - const managedHomePath = createManagedAuth( - testState.userDataDir, - 'account-1', - '{"account":"managed"}\n' + it('never writes an existing shared history and keeps the legacy one aside, even past account removal', async () => { + const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') + writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}', 'utf-8') + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + + await startService() + + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}') + expect(trackedImportOutcomes()).toEqual(['skipped_existing']) + expect(readFileSync(join(managedHomePath, 'history.jsonl'), 'utf-8')).toBe( + '{"id":"legacy-1"}\n' ) - writeFileSync(join(managedHomePath, 'history.jsonl'), '{"id":"legacy-1"}\n', 'utf-8') - const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('../../runtime-home-service') - new CodexRuntimeHomeService(store as never) + await removeAccountHome(managedHomePath) + + expect(existsSync(join(managedHomePath, 'history.jsonl'))).toBe(false) + expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') + }) + + it('leaves a shared history Codex creates during the import as it is', async () => { + const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + fsHooks.afterRead.set(join(managedHomePath, 'history.jsonl'), () => + writeFileSync(runtimeHistoryPath, '{"id":"codex-new"}\n', 'utf-8') + ) + + await startService() + + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"codex-new"}\n') + expect(trackedImportOutcomes()).toEqual(['skipped_existing']) + expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') + }) - await waitForHistoryImport() + it('does not re-run migration when marker already exists', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') - expect(readFileSync(runtimeHistoryPath, 'utf-8')).toContain('legacy-1') + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + await startService() + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') writeFileSync( join(managedHomePath, 'history.jsonl'), '{"id":"legacy-1"}\n{"id":"legacy-2"}\n', 'utf-8' ) - vi.resetModules() - const mod2 = await import('../../runtime-home-service') - new mod2.CodexRuntimeHomeService(store as never) + await startService() - expect(readFileSync(runtimeHistoryPath, 'utf-8')).not.toContain('legacy-2') + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') }) it('preserves conflicting legacy session files under deterministic names', async () => { @@ -198,6 +227,7 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) + await waitForMigrationMarker() expect(readFileSync(join(runtimeSessionsDir, 'session.json'), 'utf-8')).toBe('{"turns":[1]}') expect( @@ -219,30 +249,6 @@ describe('CodexRuntimeHomeService', () => { expect(diagnostics[0]).toContain('"type":"session-conflict"') }) - it('keeps history lines Codex appends while legacy history is merged', async () => { - const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') - writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}\n', 'utf-8') - const managedHomePath = createManagedAuth( - testState.userDataDir, - 'account-1', - '{"account":"managed"}\n' - ) - const legacyHistoryPath = join(managedHomePath, 'history.jsonl') - writeFileSync(legacyHistoryPath, '{"id":"managed-2"}\n', 'utf-8') - fsHooks.afterRead.set(legacyHistoryPath, () => - appendFileSync(runtimeHistoryPath, '{"id":"codex-live"}\n', 'utf-8') - ) - const store = createStore(createSettings()) - - const { CodexRuntimeHomeService } = await import('../../runtime-home-service') - new CodexRuntimeHomeService(store as never) - - await waitForHistoryImport() - expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( - '{"id":"shared-1"}\n{"id":"codex-live"}\n{"id":"managed-2"}\n' - ) - }) - it('never overwrites an existing preserved session copy', async () => { const runtimeSessionsDir = join(getRuntimeCodexHomePath(), 'sessions') mkdirSync(runtimeSessionsDir, { recursive: true }) @@ -260,50 +266,11 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) + await waitForMigrationMarker() expect(readFileSync(occupiedPreservedPath, 'utf-8')).toBe('{"turns":["kept"]}') expect( readFileSync(join(runtimeSessionsDir, 'session.orca-legacy-account-1-1.json'), 'utf-8') ).toBe('{"turns":[1,2]}') }) - - it.skipIf(process.platform === 'win32')( - 'leaves legacy history pending while a Codex thread is live, then imports it', - async () => { - const runtimeHomePath = getRuntimeCodexHomePath() - const runtimeHistoryPath = join(runtimeHomePath, 'history.jsonl') - writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}\n', 'utf-8') - const managedHomePath = createManagedAuth( - testState.userDataDir, - 'account-1', - '{"account":"managed"}\n' - ) - writeFileSync(join(managedHomePath, 'history.jsonl'), '{"id":"managed-2"}\n', 'utf-8') - const locks = join(runtimeHomePath, 'thread-writer-locks') - mkdirSync(locks, { recursive: true }) - const releaseThread = await holdWithFlock( - join(locks, '0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5c.lock') - ) - const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('../../runtime-home-service') - try { - new CodexRuntimeHomeService(store as never) - await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['codex_live']), { - timeout: 15_000 - }) - expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}\n') - } finally { - await releaseThread() - } - - vi.resetModules() - const relaunched = await import('../../runtime-home-service') - new relaunched.CodexRuntimeHomeService(store as never) - - await waitForHistoryImport() - expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( - '{"id":"shared-1"}\n{"id":"managed-2"}\n' - ) - } - ) }) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index c2f9f8e51477..9c47d5ec95df 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -16,9 +16,9 @@ import { normalizeCodexRuntimeSelection } from '../../account-management/runtime import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' import { - appendMissingLegacyHistory, - importLegacyHistoryWhenNoCodexIsLive, - type LegacyMigrationMarker + publishLegacyHistoryIfAbsent, + trackLegacyHistoryImport, + type LegacyHistoryImportOutcome } from './legacy-prompt-history-import' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { @@ -62,69 +62,41 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - const existingMarker = this.readMigrationMarker() - if (existingMarker) { - if (existingMarker.historyPending) { - void this.importLegacyHistoryWhenNoCodexIsLive(existingMarker) - } + if (existsSync(this.getMigrationMarkerPath())) { return } - const managedHomes = this.getLegacyManagedHomes() - for (const managedHomePath of managedHomes) { - const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( + const managedHomes: { accountId: string; homePath: string }[] = [] + for (const homePath of this.getLegacyManagedHomes()) { + const accountId = parse(relative(this.getManagedAccountsRoot(), homePath)).dir.split( /[\\/]/ )[0] - if (!accountId) { - continue + if (accountId) { + managedHomes.push({ accountId, homePath }) } - this.migrateLegacySessions(managedHomePath, accountId) } - - const historyPending = managedHomes.some((home) => existsSync(join(home, 'history.jsonl'))) - const marker: LegacyMigrationMarker = { - completedAt: Date.now(), - migratedHomeCount: managedHomes.length, - ...(historyPending ? { historyPending } : {}) - } - // Mark completion so later startups cannot replay stale managed-home state. - this.writeMigrationMarker(marker) - if (historyPending) { - void this.importLegacyHistoryWhenNoCodexIsLive(marker) + for (const { accountId, homePath } of managedHomes) { + this.migrateLegacySessions(homePath, accountId) } + void this.finishLegacyManagedStateMigration(managedHomes) } - protected importLegacyHistoryWhenNoCodexIsLive(marker: LegacyMigrationMarker): Promise { - return importLegacyHistoryWhenNoCodexIsLive({ - runtimeHomePath: this.getRuntimeHomePath(), - importHistory: () => { - for (const managedHomePath of this.getLegacyManagedHomes()) { - this.migrateLegacyHistory(managedHomePath) - } - const { historyPending: _imported, ...completed } = marker - this.writeMigrationMarker(completed) - } - }) - } - - protected readMigrationMarker(): LegacyMigrationMarker | null { - const markerPath = this.getMigrationMarkerPath() - if (!existsSync(markerPath)) { - return null - } + // History reads and writes stay off the startup path: a large history takes tens of milliseconds. + protected async finishLegacyManagedStateMigration( + managedHomes: { accountId: string; homePath: string }[] + ): Promise { try { - const parsed: unknown = JSON.parse(readFileSync(markerPath, 'utf-8')) - return parsed && typeof parsed === 'object' ? (parsed as LegacyMigrationMarker) : {} - } catch { - // An unreadable marker still means the one-time migration ran. - return {} + await this.migrateLegacyHistory(managedHomes) + // Mark completion so later startups cannot replay stale managed-home state. + writeFileAtomically( + this.getMigrationMarkerPath(), + `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` + ) + } catch (error) { + console.warn('[codex-runtime-home] Failed to migrate legacy managed Codex state:', error) } } - protected writeMigrationMarker(marker: LegacyMigrationMarker): void { - writeFileAtomically(this.getMigrationMarkerPath(), `${JSON.stringify(marker)}\n`) - } - protected getLegacyManagedHomes(): string[] { const managedAccountsRoot = this.getManagedAccountsRoot() if (!existsSync(managedAccountsRoot)) { @@ -145,14 +117,42 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return managedHomes.sort() } - protected migrateLegacyHistory(managedHomePath: string): void { - const legacyHistoryPath = join(managedHomePath, 'history.jsonl') - if (existsSync(legacyHistoryPath)) { - appendMissingLegacyHistory( - legacyHistoryPath, + /** + * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one + * is created, and never over one Codex creates meanwhile. Otherwise each account's legacy history + * is kept aside in Orca's metadata, which account removal and history cleanup never touch. + */ + protected async migrateLegacyHistory( + managedHomes: { accountId: string; homePath: string }[] + ): Promise { + const legacyHistories = managedHomes + .map(({ accountId, homePath }) => ({ accountId, path: join(homePath, 'history.jsonl') })) + .filter(({ path }) => existsSync(path)) + if (legacyHistories.length === 0) { + return + } + let outcome: LegacyHistoryImportOutcome + try { + outcome = await publishLegacyHistoryIfAbsent( + legacyHistories.map(({ path }) => path), join(this.getRuntimeHomePath(), 'history.jsonl') ) + } catch (error) { + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) + outcome = 'failed' + } + if (outcome !== 'imported') { + const archiveRoot = join(this.getRuntimeMetadataDir(), 'legacy-history-not-imported') + for (const { accountId, path } of legacyHistories) { + mkdirSync(join(archiveRoot, accountId), { recursive: true }) + this.copyLegacyFilePreservingConflicts( + path, + join(archiveRoot, accountId, 'history.jsonl'), + accountId + ) + } } + trackLegacyHistoryImport(outcome) } protected migrateLegacySessions(managedHomePath: string, accountId: string): void { @@ -167,29 +167,39 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa const relativePath = relative(legacySessionsRoot, legacyFilePath) const runtimeFilePath = join(runtimeSessionsRoot, relativePath) mkdirSync(dirname(runtimeFilePath), { recursive: true }) - if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, runtimeFilePath) !== 'conflict') { - continue + const preservedPath = this.copyLegacyFilePreservingConflicts( + legacyFilePath, + runtimeFilePath, + accountId + ) + if (preservedPath) { + this.appendMigrationDiagnostic({ + type: 'session-conflict', + accountId, + runtimeFilePath, + preservedPath + }) } + } + } - for (let attempt = 0; ; attempt++) { - const preservedPath = this.getPreservedLegacySessionPath( - runtimeFilePath, - accountId, - attempt - ) - const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath) - if (result === 'conflict') { - continue - } - if (result === 'copied') { - this.appendMigrationDiagnostic({ - type: 'session-conflict', - accountId, - runtimeFilePath, - preservedPath - }) - } - break + /** + * Copies to `targetPath` unless it already holds these bytes; when it holds others, copies beside + * it under the next free preserved name and returns that name. + */ + protected copyLegacyFilePreservingConflicts( + legacyFilePath: string, + targetPath: string, + accountId: string + ): string | null { + if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath) !== 'conflict') { + return null + } + for (let attempt = 0; ; attempt++) { + const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) + const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath) + if (result !== 'conflict') { + return result === 'copied' ? preservedPath : null } } } diff --git a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts index 8bd8a21ff6b1..3f16c367b0a1 100644 --- a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts @@ -199,7 +199,9 @@ export abstract class CodexRuntimeHomeState { protected abstract isWindowsReadableLink(targetPath: string): boolean protected abstract migrateLegacyManagedStateIfNeeded(): void protected abstract getLegacyManagedHomes(): string[] - protected abstract migrateLegacyHistory(managedHomePath: string): void + protected abstract migrateLegacyHistory( + managedHomes: { accountId: string; homePath: string }[] + ): Promise protected abstract migrateLegacySessions(managedHomePath: string, accountId: string): void protected abstract listFilesRecursively(rootPath: string): string[] protected abstract appendListedFiles(target: string[], source: readonly string[]): void diff --git a/src/main/codex/history/shared-store/codex-account-history-cleanup.test.ts b/src/main/codex/history/shared-store/codex-account-history-cleanup.test.ts index e3e97aa3e19c..a440d2e7eafe 100644 --- a/src/main/codex/history/shared-store/codex-account-history-cleanup.test.ts +++ b/src/main/codex/history/shared-store/codex-account-history-cleanup.test.ts @@ -2,6 +2,7 @@ import { existsSync, mkdirSync, mkdtempSync, + readFileSync, realpathSync, rmSync, utimesSync, @@ -164,6 +165,7 @@ async function sharedHome() { describe('cleanUpCodexHistoryLeftBehind', () => { it('deletes only proven copies, and the databases only after the home has worked shared', async () => { const { account, aside, share, cleanUp } = await sharedHome() + writeFileSync(join(account, 'history.jsonl'), '{"id":"legacy"}\n') expect((await cleanUp(NOW)).rollouts.deleted).toBe(1) expect(existsSync(join(aside, SAME))).toBe(false) @@ -186,6 +188,7 @@ describe('cleanUpCodexHistoryLeftBehind', () => { expect(existsSync(join(account, 'thread_history_1.sqlite-wal'))).toBe(false) // Codex can't rebuild memories from the rollouts. expect(existsSync(join(account, 'memories_1.sqlite'))).toBe(true) + expect(readFileSync(join(account, 'history.jsonl'), 'utf8')).toBe('{"id":"legacy"}\n') }) it('in report mode deletes nothing but counts what enforce would delete', async () => { diff --git a/src/main/codex/history/shared-store/codex-account-history-links.test.ts b/src/main/codex/history/shared-store/codex-account-history-links.test.ts index f49a5cee4b1e..f09b9bd00edf 100644 --- a/src/main/codex/history/shared-store/codex-account-history-links.test.ts +++ b/src/main/codex/history/shared-store/codex-account-history-links.test.ts @@ -211,11 +211,13 @@ describe('shareCodexAccountHistory', () => { it('renames the ownership marker before a Windows home gets junctions', async () => { const f = fixture('win32') writeFileSync(join(f.account, '.orca-managed-home'), 'account-1\n') + writeFileSync(join(f.account, 'history.jsonl'), '{"id":"legacy"}\n') expect(await f.share()).toBe('shared') expect(existsSync(join(f.account, '.orca-managed-home'))).toBe(false) expect(readFileSync(join(f.account, '.orca-managed-home-linked'), 'utf8')).toBe('account-1\n') + expect(readFileSync(join(f.account, 'history.jsonl'), 'utf8')).toBe('{"id":"legacy"}\n') }) it('links nothing into a Windows home without an ownership marker', async () => { diff --git a/src/main/codex/history/shared-store/codex-thread-writer-locks.ts b/src/main/codex/history/shared-store/codex-thread-writer-locks.ts index ae9a57748710..a8bf53b4f9dd 100644 --- a/src/main/codex/history/shared-store/codex-thread-writer-locks.ts +++ b/src/main/codex/history/shared-store/codex-thread-writer-locks.ts @@ -225,36 +225,6 @@ export async function moveIdleThreadLockFolder( } // A Codex that started meanwhile: a file it opened (Windows) or the folder it recreated mid-swap. -/** - * Runs `action` only when no Codex thread is live in `codexHome`, with its coordination held so none - * can start until `action` returns; otherwise says why it didn't run. - */ -export async function runWhileNoCodexThreadIsLive( - codexHome: string, - action: () => T -): Promise<{ ran: true; value: T } | { ran: false; reason: 'held' | LockFolderBusy }> { - const locks = join(codexHome, WRITER_LOCKS) - await mkdir(locks, { recursive: true }) - const hold = await startProbe([locks], true) - if (hold?.answer === 'held') { - return { ran: false, reason: 'held' } - } - if (hold?.answer === 'unavailable') { - return { ran: false, reason: 'no-helper' } - } - if (!hold || !('release' in hold)) { - return { ran: false, reason: 'busy' } - } - try { - if (!hold.stillHeld()) { - return { ran: false, reason: 'busy' } - } - return { ran: true, value: action() } - } finally { - await hold.release() - } -} - function isStartingCodexError(error: unknown): boolean { if (error instanceof DirectoryLinkError) { return error.code === 'link-failed' diff --git a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts index 0dd66fb62830..8348fa43ee17 100644 --- a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts +++ b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts @@ -1,16 +1,13 @@ import { z } from 'zod' -/** `codex_live`, `busy`, `no_helper` and `changed` are skips the next launch retries. */ +/** `skipped_existing` and `failed` keep each legacy history aside in Orca's metadata. */ export const CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES = [ 'imported', - 'codex_live', - 'busy', - 'no_helper', - 'changed', + 'skipped_existing', 'failed' ] as const -/** One row per launch that still had the one-time legacy prompt-history import pending. */ +/** Sent once per install, by the one-time migration of legacy per-account prompt history. */ export const codexLegacyHistoryImportSchema = z .object({ outcome: z.enum(CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES), From e29d1795a2e49193d2727fcd0a7492771eb38f9a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:35:04 -0800 Subject: [PATCH 04/30] fix(codex): keep legacy prompt history aside before anything else in the migration Each account's legacy history.jsonl is copied under Orca's runtime metadata synchronously, before session copies and before startup returns, so a failed session copy or an account removed while the import runs can't leave it without a kept copy. The import reads only the kept copies. Exclusive copies clone where the filesystem can. --- .../runtime-home-legacy-migration.test.ts | 25 +++++- .../runtime-home-service-legacy-migration.ts | 83 +++++++++++-------- .../runtime-home-service-state.ts | 4 +- 3 files changed, 72 insertions(+), 40 deletions(-) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index e241bf3bcde1..600151902066 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -53,7 +53,7 @@ function archivedHistoryPath(accountId: string): string { return join( testState.userDataDir, 'codex-runtime-home', - 'legacy-history-not-imported', + 'legacy-account-history', accountId, 'history.jsonl' ) @@ -154,7 +154,24 @@ describe('CodexRuntimeHomeService', () => { '{"id":"a-1"}\n{"id":"both"}\n{"id":"b-1"}\n' ) expect(trackedImportOutcomes()).toEqual(['imported']) - expect(existsSync(archivedHistoryPath('account-1'))).toBe(false) + }) + + it('keeps every legacy history aside before startup returns, even when a session copy fails', async () => { + const accountOneHome = writeHistory('account-1', '{"id":"a-1"}\n') + const accountTwoHome = writeHistory('account-2', '{"id":"b-1"}\n') + mkdirSync(join(accountTwoHome, 'sessions', 'nested'), { recursive: true }) + writeFileSync(join(accountTwoHome, 'sessions', 'nested', 'rollout.jsonl'), '{}', 'utf-8') + mkdirSync(join(getRuntimeCodexHomePath(), 'sessions'), { recursive: true }) + // A file where account 2's session folder must go: its session copy throws. + writeFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested'), 'not a folder', 'utf-8') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + + new CodexRuntimeHomeService(createStore(createSettings()) as never) + await removeAccountHome(accountOneHome) + + expect(existsSync(join(accountOneHome, 'history.jsonl'))).toBe(false) + expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"a-1"}\n') + expect(readFileSync(archivedHistoryPath('account-2'), 'utf-8')).toBe('{"id":"b-1"}\n') }) it('never writes an existing shared history and keeps the legacy one aside, even past account removal', async () => { @@ -178,8 +195,8 @@ describe('CodexRuntimeHomeService', () => { it('leaves a shared history Codex creates during the import as it is', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') - const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') - fsHooks.afterRead.set(join(managedHomePath, 'history.jsonl'), () => + writeHistory('account-1', '{"id":"legacy-1"}\n') + fsHooks.afterRead.set(archivedHistoryPath('account-1'), () => writeFileSync(runtimeHistoryPath, '{"id":"codex-new"}\n', 'utf-8') ) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 9c47d5ec95df..4addbd17d2e3 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -75,22 +75,26 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa managedHomes.push({ accountId, homePath }) } } + // First and synchronously: nothing later (a failed session copy, an account removed while the + // import runs) may leave a legacy history without a copy Orca keeps. + const keptHistoryPaths = this.keepLegacyHistoriesAside(managedHomes) for (const { accountId, homePath } of managedHomes) { this.migrateLegacySessions(homePath, accountId) } - void this.finishLegacyManagedStateMigration(managedHomes) + void this.finishLegacyManagedStateMigration(keptHistoryPaths, managedHomes.length) } // History reads and writes stay off the startup path: a large history takes tens of milliseconds. protected async finishLegacyManagedStateMigration( - managedHomes: { accountId: string; homePath: string }[] + keptHistoryPaths: string[], + migratedHomeCount: number ): Promise { try { - await this.migrateLegacyHistory(managedHomes) + await this.migrateLegacyHistory(keptHistoryPaths) // Mark completion so later startups cannot replay stale managed-home state. writeFileAtomically( this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` + `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount })}\n` ) } catch (error) { console.warn('[codex-runtime-home] Failed to migrate legacy managed Codex state:', error) @@ -117,41 +121,54 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return managedHomes.sort() } + /** Copies each account's legacy history under Orca's metadata, which no removal or cleanup reaches. */ + protected keepLegacyHistoriesAside( + managedHomes: { accountId: string; homePath: string }[] + ): string[] { + const keptRoot = join(this.getRuntimeMetadataDir(), 'legacy-account-history') + const keptPaths: string[] = [] + let firstError: unknown = null + for (const { accountId, homePath } of managedHomes) { + const legacyHistoryPath = join(homePath, 'history.jsonl') + if (!existsSync(legacyHistoryPath)) { + continue + } + try { + mkdirSync(join(keptRoot, accountId), { recursive: true }) + const kept = this.copyLegacyFilePreservingConflicts( + legacyHistoryPath, + join(keptRoot, accountId, 'history.jsonl'), + accountId + ) + keptPaths.push(kept.path) + } catch (error) { + firstError ??= error + } + } + if (firstError) { + throw firstError + } + return keptPaths + } + /** * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one - * is created, and never over one Codex creates meanwhile. Otherwise each account's legacy history - * is kept aside in Orca's metadata, which account removal and history cleanup never touch. + * is created from the kept copies, and never over one Codex creates meanwhile. */ - protected async migrateLegacyHistory( - managedHomes: { accountId: string; homePath: string }[] - ): Promise { - const legacyHistories = managedHomes - .map(({ accountId, homePath }) => ({ accountId, path: join(homePath, 'history.jsonl') })) - .filter(({ path }) => existsSync(path)) - if (legacyHistories.length === 0) { + protected async migrateLegacyHistory(keptHistoryPaths: string[]): Promise { + if (keptHistoryPaths.length === 0) { return } let outcome: LegacyHistoryImportOutcome try { outcome = await publishLegacyHistoryIfAbsent( - legacyHistories.map(({ path }) => path), + keptHistoryPaths, join(this.getRuntimeHomePath(), 'history.jsonl') ) } catch (error) { console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) outcome = 'failed' } - if (outcome !== 'imported') { - const archiveRoot = join(this.getRuntimeMetadataDir(), 'legacy-history-not-imported') - for (const { accountId, path } of legacyHistories) { - mkdirSync(join(archiveRoot, accountId), { recursive: true }) - this.copyLegacyFilePreservingConflicts( - path, - join(archiveRoot, accountId, 'history.jsonl'), - accountId - ) - } - } trackLegacyHistoryImport(outcome) } @@ -167,17 +184,17 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa const relativePath = relative(legacySessionsRoot, legacyFilePath) const runtimeFilePath = join(runtimeSessionsRoot, relativePath) mkdirSync(dirname(runtimeFilePath), { recursive: true }) - const preservedPath = this.copyLegacyFilePreservingConflicts( + const copy = this.copyLegacyFilePreservingConflicts( legacyFilePath, runtimeFilePath, accountId ) - if (preservedPath) { + if (copy.preserved) { this.appendMigrationDiagnostic({ type: 'session-conflict', accountId, runtimeFilePath, - preservedPath + preservedPath: copy.path }) } } @@ -185,21 +202,21 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa /** * Copies to `targetPath` unless it already holds these bytes; when it holds others, copies beside - * it under the next free preserved name and returns that name. + * it under the next free preserved name. Returns where the legacy bytes now are. */ protected copyLegacyFilePreservingConflicts( legacyFilePath: string, targetPath: string, accountId: string - ): string | null { + ): { path: string; preserved: boolean } { if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath) !== 'conflict') { - return null + return { path: targetPath, preserved: false } } for (let attempt = 0; ; attempt++) { const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath) if (result !== 'conflict') { - return result === 'copied' ? preservedPath : null + return { path: preservedPath, preserved: result === 'copied' } } } } @@ -210,7 +227,7 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa targetPath: string ): 'copied' | 'identical' | 'conflict' { try { - copyFileSync(legacyFilePath, targetPath, constants.COPYFILE_EXCL) + copyFileSync(legacyFilePath, targetPath, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE) return 'copied' } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { diff --git a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts index 3f16c367b0a1..fd96a93c7378 100644 --- a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts @@ -199,9 +199,7 @@ export abstract class CodexRuntimeHomeState { protected abstract isWindowsReadableLink(targetPath: string): boolean protected abstract migrateLegacyManagedStateIfNeeded(): void protected abstract getLegacyManagedHomes(): string[] - protected abstract migrateLegacyHistory( - managedHomes: { accountId: string; homePath: string }[] - ): Promise + protected abstract migrateLegacyHistory(keptHistoryPaths: string[]): Promise protected abstract migrateLegacySessions(managedHomePath: string, accountId: string): void protected abstract listFilesRecursively(rootPath: string): string[] protected abstract appendListedFiles(target: string[], source: readonly string[]): void From 614be279df267a91bf5652e964ba9cc4b9bae66a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:53:45 -0800 Subject: [PATCH 05/30] fix(codex): retry the legacy history import from Orca's kept copies The kept copy is read once and written with exclusive create, so a history Codex trims mid-copy can't stall startup. The marker records a pending import; a failed one retries on later launches (at most three), reading only the kept copies under Orca's metadata, so a removed account's history still seeds a missing shared history. The publish is fully async. --- config/main-blocking-helper-baseline.txt | 2 +- config/main-sync-fs-baseline.txt | 2 +- .../legacy-prompt-history-import.ts | 119 +++++++++++--- .../runtime-home-legacy-migration.test.ts | 43 ++++- .../runtime-home-service-legacy-migration.ts | 148 +++++++++++------- .../runtime-home-service-state.ts | 1 - ...etry-codex-legacy-history-event-schemas.ts | 5 +- 7 files changed, 229 insertions(+), 91 deletions(-) diff --git a/config/main-blocking-helper-baseline.txt b/config/main-blocking-helper-baseline.txt index bc27d446b591..eb869b6a8870 100644 --- a/config/main-blocking-helper-baseline.txt +++ b/config/main-blocking-helper-baseline.txt @@ -271,7 +271,7 @@ 4 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 19 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts -3 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +2 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 11 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts # Codex launch prep from #43365 already merged; unblocks main, async follow-up owed 9 src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts 8 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 1cde027fcdbb..ed54dbde7406 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -128,7 +128,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -19 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +18 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index a1e4012ecde2..a323c8de62d0 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,55 +1,130 @@ import { randomUUID } from 'node:crypto' -import { lstat, open, readFile, rm } from 'node:fs/promises' -import { publishFileWithoutOverwrite } from '../../../filesystem/atomic-file-publication' +import { link, lstat, open, readFile, readdir, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { track } from '../../../telemetry/client' import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas' export type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] +/** Launches that try the import before it gives up; the kept copies stay either way. */ +export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 + +export type LegacyMigrationMarker = { + completedAt?: number + migratedHomeCount?: number + /** Kept legacy histories still wait to seed a shared history that doesn't exist yet. */ + historyImportPending?: true + historyImportAttempts?: number +} + +export function parseLegacyMigrationMarker(text: string): LegacyMigrationMarker { + const parsed: unknown = JSON.parse(text) + if (!parsed || typeof parsed !== 'object') { + return {} + } + const marker: LegacyMigrationMarker = {} + if ('completedAt' in parsed && typeof parsed.completedAt === 'number') { + marker.completedAt = parsed.completedAt + } + if ('migratedHomeCount' in parsed && typeof parsed.migratedHomeCount === 'number') { + marker.migratedHomeCount = parsed.migratedHomeCount + } + if ('historyImportPending' in parsed && parsed.historyImportPending === true) { + marker.historyImportPending = true + } + if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') { + marker.historyImportAttempts = parsed.historyImportAttempts + } + return marker +} + async function pathExists(path: string): Promise { try { await lstat(path) return true } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + if (errnoCodeOrUnknown(error) === 'ENOENT') { return false } throw error } } -/** Creates the shared history from the legacy ones only while it doesn't exist; never writes one. */ -export async function publishLegacyHistoryIfAbsent( - legacyHistoryPaths: readonly string[], +// Every kept copy, accounts and their preserved versions in a stable order. +async function listKeptLegacyHistories(keptRoot: string): Promise { + const paths: string[] = [] + const accounts = await readdir(keptRoot, { withFileTypes: true }).catch((error: unknown) => { + if (errnoCodeOrUnknown(error) === 'ENOENT') { + return [] + } + throw error + }) + for (const account of accounts.filter((entry) => entry.isDirectory()).sort(byName)) { + const files = await readdir(join(keptRoot, account.name), { withFileTypes: true }) + for (const file of files.filter((entry) => entry.isFile()).sort(byName)) { + if (file.name.endsWith('.jsonl')) { + paths.push(join(keptRoot, account.name, file.name)) + } + } + } + return paths +} + +function byName(left: { name: string }, right: { name: string }): number { + return left.name < right.name ? -1 : left.name > right.name ? 1 : 0 +} + +/** + * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one is + * created from Orca's kept copies, and never over one Codex creates meanwhile. + */ +export async function publishKeptLegacyHistoriesIfAbsent( + keptRoot: string, runtimeHistoryPath: string ): Promise { - if (await pathExists(runtimeHistoryPath)) { - return 'skipped_existing' - } - const seenLines = new Set() - for (const legacyHistoryPath of legacyHistoryPaths) { - for (const line of (await readFile(legacyHistoryPath, 'utf-8')).split('\n')) { - if (line) { - seenLines.add(line) + try { + if (await pathExists(runtimeHistoryPath)) { + return 'skipped_existing' + } + const seenLines = new Set() + for (const keptPath of await listKeptLegacyHistories(keptRoot)) { + for (const line of (await readFile(keptPath, 'utf-8')).split('\n')) { + if (line) { + seenLines.add(line) + } } } + if (seenLines.size === 0) { + return 'nothing_to_import' + } + return (await publishWithoutOverwrite(`${[...seenLines].join('\n')}\n`, runtimeHistoryPath)) + ? 'imported' + : 'skipped_existing' + } catch (error) { + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) + return 'failed' } - if (seenLines.size === 0) { - return 'skipped_existing' - } - const tmpPath = `${runtimeHistoryPath}.${process.pid}.${randomUUID()}.tmp` +} + +async function publishWithoutOverwrite(contents: string, targetPath: string): Promise { + const tmpPath = `${targetPath}.${process.pid}.${randomUUID()}.tmp` try { const handle = await open(tmpPath, 'wx', 0o600) try { - await handle.writeFile(`${[...seenLines].join('\n')}\n`, 'utf-8') + await handle.writeFile(contents, 'utf-8') await handle.sync() } finally { await handle.close() } // A hard link publishes only into a free name: one Codex created meanwhile stays as it is. - return publishFileWithoutOverwrite(tmpPath, runtimeHistoryPath) - ? 'imported' - : 'skipped_existing' + await link(tmpPath, targetPath) + return true + } catch (error) { + if (errnoCodeOrUnknown(error) === 'EEXIST') { + return false + } + throw error } finally { await rm(tmpPath, { force: true }) } diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 600151902066..2068f2da31a0 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -36,7 +36,9 @@ vi.mock('../../../telemetry/client', () => ({ track: trackMock })) function trackedImportOutcomes(): string[] { return trackMock.mock.calls .filter(([event]) => event === 'codex_legacy_history_import') - .map(([, props]) => (props as { outcome: string }).outcome) + .map(([, props]: unknown[]) => + props && typeof props === 'object' && 'outcome' in props ? String(props.outcome) : '' + ) } function writeHistory(accountId: string, contents: string): string { @@ -59,24 +61,33 @@ function archivedHistoryPath(accountId: string): string { ) } -async function startService(): Promise { +async function constructService(): Promise { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture store implements what the service reads. new CodexRuntimeHomeService(createStore(createSettings()) as never) +} + +async function startService(): Promise { + await constructService() await waitForMigrationMarker() } +// Settled: the marker exists and no longer waits on the history import. async function waitForMigrationMarker(): Promise { const markerPath = join(testState.userDataDir, 'codex-runtime-home', 'migration-v1.json') - await vi.waitFor(() => expect(existsSync(markerPath)).toBe(true)) + await vi.waitFor(() => { + expect(existsSync(markerPath)).toBe(true) + expect(readFileSync(markerPath, 'utf-8')).not.toContain('"historyImportPending"') + }) } async function removeAccountHome(managedHomePath: string): Promise { const { CodexManagedHomeLifecycle } = await import('../../managed-homes/codex-managed-home-lifecycle') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: safeRemove reads only these two members. const paths = { assert: async (candidate: string) => candidate, getRoot: () => join(testState.userDataDir, 'codex-accounts') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: safeRemove reads only these two members. } as unknown as CodexManagedHomePath await new CodexManagedHomeLifecycle(paths).safeRemove(managedHomePath, 'account-1') } @@ -84,6 +95,7 @@ async function removeAccountHome(managedHomePath: string): Promise { const fsHooks = vi.hoisted(() => ({ afterRead: new Map void>() })) vi.mock(import('node:fs/promises'), async (importOriginal) => { const actual = await importOriginal() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: forwards every overload unchanged. const readFile = (async (...args: Parameters) => { const contents = await actual.readFile(...args) fsHooks.afterRead.get(String(args[0]))?.() @@ -164,9 +176,7 @@ describe('CodexRuntimeHomeService', () => { mkdirSync(join(getRuntimeCodexHomePath(), 'sessions'), { recursive: true }) // A file where account 2's session folder must go: its session copy throws. writeFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested'), 'not a folder', 'utf-8') - const { CodexRuntimeHomeService } = await import('../../runtime-home-service') - - new CodexRuntimeHomeService(createStore(createSettings()) as never) + await constructService() await removeAccountHome(accountOneHome) expect(existsSync(join(accountOneHome, 'history.jsonl'))).toBe(false) @@ -207,6 +217,25 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') }) + it('retries a failed import on a later launch from the kept copy, after the account is gone', async () => { + const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + fsHooks.afterRead.set(archivedHistoryPath('account-1'), () => { + throw Object.assign(new Error('busy'), { code: 'EBUSY' }) + }) + await constructService() + await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['failed'])) + expect(existsSync(runtimeHistoryPath)).toBe(false) + await removeAccountHome(managedHomePath) + fsHooks.afterRead.clear() + + vi.resetModules() + await startService() + + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') + expect(trackedImportOutcomes()).toEqual(['failed', 'imported']) + }) + it('does not re-run migration when marker already exists', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 4addbd17d2e3..0ba71703d50d 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -6,19 +6,22 @@ import { mkdirSync, readFileSync, readdirSync, - statSync + statSync, + writeFileSync } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' -import { nodeFileContentsEqualSync } from '../../../../shared/file-content/node-file-content-equality' +import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-migration' import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' import { - publishLegacyHistoryIfAbsent, + MAX_HISTORY_IMPORT_ATTEMPTS, + parseLegacyMigrationMarker, + publishKeptLegacyHistoriesIfAbsent, trackLegacyHistoryImport, - type LegacyHistoryImportOutcome + type LegacyMigrationMarker } from './legacy-prompt-history-import' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { @@ -62,7 +65,11 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - if (existsSync(this.getMigrationMarkerPath())) { + const existingMarker = this.readMigrationMarker() + if (existingMarker) { + if (existingMarker.historyImportPending) { + void this.importKeptLegacyHistories(existingMarker) + } return } @@ -77,30 +84,62 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } // First and synchronously: nothing later (a failed session copy, an account removed while the // import runs) may leave a legacy history without a copy Orca keeps. - const keptHistoryPaths = this.keepLegacyHistoriesAside(managedHomes) + const keptAny = this.keepLegacyHistoriesAside(managedHomes) for (const { accountId, homePath } of managedHomes) { this.migrateLegacySessions(homePath, accountId) } - void this.finishLegacyManagedStateMigration(keptHistoryPaths, managedHomes.length) + const marker: LegacyMigrationMarker = { + completedAt: Date.now(), + migratedHomeCount: managedHomes.length, + ...(keptAny ? { historyImportPending: true } : {}) + } + // Mark completion so later startups cannot replay stale managed-home state. + this.writeMigrationMarker(marker) + if (keptAny) { + void this.importKeptLegacyHistories(marker) + } } - // History reads and writes stay off the startup path: a large history takes tens of milliseconds. - protected async finishLegacyManagedStateMigration( - keptHistoryPaths: string[], - migratedHomeCount: number - ): Promise { + // Off the startup path (a large history takes tens of milliseconds), from Orca's kept copies only. + protected async importKeptLegacyHistories(marker: LegacyMigrationMarker): Promise { try { - await this.migrateLegacyHistory(keptHistoryPaths) - // Mark completion so later startups cannot replay stale managed-home state. - writeFileAtomically( - this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount })}\n` + const outcome = await publishKeptLegacyHistoriesIfAbsent( + this.getKeptLegacyHistoryRoot(), + join(this.getRuntimeHomePath(), 'history.jsonl') ) + trackLegacyHistoryImport(outcome) + const attempts = (marker.historyImportAttempts ?? 0) + 1 + if (outcome === 'failed' && attempts < MAX_HISTORY_IMPORT_ATTEMPTS) { + this.writeMigrationMarker({ ...marker, historyImportAttempts: attempts }) + return + } + const { historyImportPending: _done, historyImportAttempts: _attempts, ...completed } = marker + this.writeMigrationMarker(completed) } catch (error) { - console.warn('[codex-runtime-home] Failed to migrate legacy managed Codex state:', error) + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) } } + protected readMigrationMarker(): LegacyMigrationMarker | null { + if (!existsSync(this.getMigrationMarkerPath())) { + return null + } + try { + return parseLegacyMigrationMarker(readFileSync(this.getMigrationMarkerPath(), 'utf-8')) + } catch { + // An unreadable marker still means the one-time migration ran. + return {} + } + } + + protected writeMigrationMarker(marker: LegacyMigrationMarker): void { + writeFileAtomically(this.getMigrationMarkerPath(), `${JSON.stringify(marker)}\n`) + } + + protected getKeptLegacyHistoryRoot(): string { + return join(this.getRuntimeMetadataDir(), 'legacy-account-history') + } + protected getLegacyManagedHomes(): string[] { const managedAccountsRoot = this.getManagedAccountsRoot() if (!existsSync(managedAccountsRoot)) { @@ -124,9 +163,8 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa /** Copies each account's legacy history under Orca's metadata, which no removal or cleanup reaches. */ protected keepLegacyHistoriesAside( managedHomes: { accountId: string; homePath: string }[] - ): string[] { - const keptRoot = join(this.getRuntimeMetadataDir(), 'legacy-account-history') - const keptPaths: string[] = [] + ): boolean { + let keptAny = false let firstError: unknown = null for (const { accountId, homePath } of managedHomes) { const legacyHistoryPath = join(homePath, 'history.jsonl') @@ -134,13 +172,17 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa continue } try { - mkdirSync(join(keptRoot, accountId), { recursive: true }) - const kept = this.copyLegacyFilePreservingConflicts( + const keptDir = join(this.getKeptLegacyHistoryRoot(), accountId) + mkdirSync(keptDir, { recursive: true }) + // Read once rather than copied: Codex may trim it meanwhile, and a copy of a file that + // shrinks mid-copy never finishes. + this.copyLegacyFilePreservingConflicts( legacyHistoryPath, - join(keptRoot, accountId, 'history.jsonl'), - accountId + join(keptDir, 'history.jsonl'), + accountId, + readFileSync(legacyHistoryPath) ) - keptPaths.push(kept.path) + keptAny = true } catch (error) { firstError ??= error } @@ -148,28 +190,7 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa if (firstError) { throw firstError } - return keptPaths - } - - /** - * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one - * is created from the kept copies, and never over one Codex creates meanwhile. - */ - protected async migrateLegacyHistory(keptHistoryPaths: string[]): Promise { - if (keptHistoryPaths.length === 0) { - return - } - let outcome: LegacyHistoryImportOutcome - try { - outcome = await publishLegacyHistoryIfAbsent( - keptHistoryPaths, - join(this.getRuntimeHomePath(), 'history.jsonl') - ) - } catch (error) { - console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) - outcome = 'failed' - } - trackLegacyHistoryImport(outcome) + return keptAny } protected migrateLegacySessions(managedHomePath: string, accountId: string): void { @@ -207,36 +228,49 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa protected copyLegacyFilePreservingConflicts( legacyFilePath: string, targetPath: string, - accountId: string + accountId: string, + contents?: Buffer ): { path: string; preserved: boolean } { - if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath) !== 'conflict') { + if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath, contents) !== 'conflict') { return { path: targetPath, preserved: false } } for (let attempt = 0; ; attempt++) { const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) - const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath) + const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath, contents) if (result !== 'conflict') { return { path: preservedPath, preserved: result === 'copied' } } } } - /** Exclusive create never replaces or writes through a name, even one that appears after a check. */ + /** + * Exclusive create never replaces or writes through a name, even one that appears after a check. + * With `contents`, writes those bytes instead of copying the file. + */ protected copyLegacyFileWithoutOverwrite( legacyFilePath: string, - targetPath: string + targetPath: string, + contents?: Buffer ): 'copied' | 'identical' | 'conflict' { try { - copyFileSync(legacyFilePath, targetPath, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE) + if (contents) { + writeFileSync(targetPath, contents, { flag: 'wx', mode: 0o600 }) + } else { + copyFileSync( + legacyFilePath, + targetPath, + constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE + ) + } return 'copied' } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { + if (errnoCodeOrUnknown(error) !== 'EEXIST') { throw error } } - const legacyContents = readFileSync(legacyFilePath) + const legacyContents = contents ?? readFileSync(legacyFilePath) try { - return nodeFileContentsEqualSync(targetPath, legacyContents) ? 'identical' : 'conflict' + return readFileSync(targetPath).equals(legacyContents) ? 'identical' : 'conflict' } catch { // A dangling link or directory at this name still occupies it. return 'conflict' diff --git a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts index fd96a93c7378..32dfb4e927bd 100644 --- a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts @@ -199,7 +199,6 @@ export abstract class CodexRuntimeHomeState { protected abstract isWindowsReadableLink(targetPath: string): boolean protected abstract migrateLegacyManagedStateIfNeeded(): void protected abstract getLegacyManagedHomes(): string[] - protected abstract migrateLegacyHistory(keptHistoryPaths: string[]): Promise protected abstract migrateLegacySessions(managedHomePath: string, accountId: string): void protected abstract listFilesRecursively(rootPath: string): string[] protected abstract appendListedFiles(target: string[], source: readonly string[]): void diff --git a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts index 8348fa43ee17..5b64605a9cbb 100644 --- a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts +++ b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts @@ -1,13 +1,14 @@ import { z } from 'zod' -/** `skipped_existing` and `failed` keep each legacy history aside in Orca's metadata. */ +/** Orca keeps every legacy history aside in its metadata whatever the outcome; `failed` retries. */ export const CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES = [ 'imported', 'skipped_existing', + 'nothing_to_import', 'failed' ] as const -/** Sent once per install, by the one-time migration of legacy per-account prompt history. */ +/** Sent by each launch that tries the one-time import of legacy per-account prompt history. */ export const codexLegacyHistoryImportSchema = z .object({ outcome: z.enum(CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES), From c62e27ce8b82b8f03ad3e4be2c672ccaf974b7dd Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:08:05 -0800 Subject: [PATCH 06/30] fix(codex): run the kept legacy history import independently of session copies The import keeps its own state beside Orca's kept copies and runs on any launch with kept copies until it settles, so a failed session copy, or an account removed after one, can't leave a kept history unimported. --- config/main-sync-fs-baseline.txt | 2 +- .../legacy-prompt-history-import.ts | 77 ++++++++++++------- .../runtime-home-legacy-migration.test.ts | 27 ++++--- .../runtime-home-service-legacy-migration.ts | 66 ++++------------ 4 files changed, 79 insertions(+), 93 deletions(-) diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index ed54dbde7406..537cf93e47a7 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -128,7 +128,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -18 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +17 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index a323c8de62d0..24901451bc6b 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,42 +1,61 @@ import { randomUUID } from 'node:crypto' -import { link, lstat, open, readFile, readdir, rm } from 'node:fs/promises' +import { link, lstat, open, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { track } from '../../../telemetry/client' import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas' -export type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] +type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] /** Launches that try the import before it gives up; the kept copies stay either way. */ -export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 +const MAX_IMPORT_ATTEMPTS = 3 +const IMPORT_STATE_FILE = 'import-state.json' -export type LegacyMigrationMarker = { - completedAt?: number - migratedHomeCount?: number - /** Kept legacy histories still wait to seed a shared history that doesn't exist yet. */ - historyImportPending?: true - historyImportAttempts?: number -} +type ImportState = { done: boolean; attempts: number } -export function parseLegacyMigrationMarker(text: string): LegacyMigrationMarker { - const parsed: unknown = JSON.parse(text) - if (!parsed || typeof parsed !== 'object') { - return {} - } - const marker: LegacyMigrationMarker = {} - if ('completedAt' in parsed && typeof parsed.completedAt === 'number') { - marker.completedAt = parsed.completedAt +async function readImportState(path: string): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(path, 'utf-8')) + if (parsed && typeof parsed === 'object') { + return { + done: 'done' in parsed && parsed.done === true, + attempts: 'attempts' in parsed && typeof parsed.attempts === 'number' ? parsed.attempts : 0 + } + } + } catch (error) { + if (errnoCodeOrUnknown(error) !== 'ENOENT') { + // Unreadable state never re-imports: the shared history may exist by now anyway. + return { done: true, attempts: 0 } + } } - if ('migratedHomeCount' in parsed && typeof parsed.migratedHomeCount === 'number') { - marker.migratedHomeCount = parsed.migratedHomeCount + return { done: false, attempts: 0 } +} + +/** + * Seeds a missing shared history from Orca's kept copies, once: each launch tries until the import + * settles or has failed three times. Nothing runs while there are no kept copies. + */ +export async function importKeptLegacyHistoriesOnce( + keptRoot: string, + runtimeHistoryPath: string +): Promise { + const statePath = join(keptRoot, IMPORT_STATE_FILE) + const state = await readImportState(statePath) + if (state.done) { + return } - if ('historyImportPending' in parsed && parsed.historyImportPending === true) { - marker.historyImportPending = true + const keptPaths = await listKeptLegacyHistories(keptRoot) + if (keptPaths.length === 0) { + return } - if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') { - marker.historyImportAttempts = parsed.historyImportAttempts + const outcome = await publishKeptLegacyHistoriesIfAbsent(keptPaths, runtimeHistoryPath) + trackLegacyHistoryImport(outcome) + const attempts = state.attempts + 1 + const next: ImportState = { + done: outcome !== 'failed' || attempts >= MAX_IMPORT_ATTEMPTS, + attempts } - return marker + await writeFile(statePath, `${JSON.stringify(next)}\n`, 'utf-8') } async function pathExists(path: string): Promise { @@ -79,8 +98,8 @@ function byName(left: { name: string }, right: { name: string }): number { * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one is * created from Orca's kept copies, and never over one Codex creates meanwhile. */ -export async function publishKeptLegacyHistoriesIfAbsent( - keptRoot: string, +async function publishKeptLegacyHistoriesIfAbsent( + keptPaths: readonly string[], runtimeHistoryPath: string ): Promise { try { @@ -88,7 +107,7 @@ export async function publishKeptLegacyHistoriesIfAbsent( return 'skipped_existing' } const seenLines = new Set() - for (const keptPath of await listKeptLegacyHistories(keptRoot)) { + for (const keptPath of keptPaths) { for (const line of (await readFile(keptPath, 'utf-8')).split('\n')) { if (line) { seenLines.add(line) @@ -130,7 +149,7 @@ async function publishWithoutOverwrite(contents: string, targetPath: string): Pr } } -export function trackLegacyHistoryImport(outcome: LegacyHistoryImportOutcome): void { +function trackLegacyHistoryImport(outcome: LegacyHistoryImportOutcome): void { try { track('codex_legacy_history_import', { outcome, diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 2068f2da31a0..89b8c4cbb679 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -10,7 +10,6 @@ import { } from 'node:fs' import { join } from 'node:path' import { createSettings } from '../runtime-home-settings-test-fixtures' -import type { CodexManagedHomePath } from '../../managed-homes/codex-managed-home-path' import { createManagedAuth, createStore, @@ -72,24 +71,26 @@ async function startService(): Promise { await waitForMigrationMarker() } -// Settled: the marker exists and no longer waits on the history import. +// Settled: the marker exists and any kept history finished its import attempt. async function waitForMigrationMarker(): Promise { - const markerPath = join(testState.userDataDir, 'codex-runtime-home', 'migration-v1.json') + const runtimeHome = join(testState.userDataDir, 'codex-runtime-home') await vi.waitFor(() => { - expect(existsSync(markerPath)).toBe(true) - expect(readFileSync(markerPath, 'utf-8')).not.toContain('"historyImportPending"') + expect(existsSync(join(runtimeHome, 'migration-v1.json'))).toBe(true) + const kept = join(runtimeHome, 'legacy-account-history') + if (existsSync(kept)) { + expect(readFileSync(join(kept, 'import-state.json'), 'utf-8')).toContain('"done":true') + } }) } async function removeAccountHome(managedHomePath: string): Promise { const { CodexManagedHomeLifecycle } = await import('../../managed-homes/codex-managed-home-lifecycle') - const paths = { - assert: async (candidate: string) => candidate, - getRoot: () => join(testState.userDataDir, 'codex-accounts') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: safeRemove reads only these two members. - } as unknown as CodexManagedHomePath - await new CodexManagedHomeLifecycle(paths).safeRemove(managedHomePath, 'account-1') + const { CodexManagedHomePath } = await import('../../managed-homes/codex-managed-home-path') + await new CodexManagedHomeLifecycle(new CodexManagedHomePath()).safeRemove( + managedHomePath, + 'account-1' + ) } const fsHooks = vi.hoisted(() => ({ afterRead: new Map void>() })) @@ -182,6 +183,10 @@ describe('CodexRuntimeHomeService', () => { expect(existsSync(join(accountOneHome, 'history.jsonl'))).toBe(false) expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"a-1"}\n') expect(readFileSync(archivedHistoryPath('account-2'), 'utf-8')).toBe('{"id":"b-1"}\n') + await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['imported'])) + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + '{"id":"a-1"}\n{"id":"b-1"}\n' + ) }) it('never writes an existing shared history and keeps the legacy one aside, even past account removal', async () => { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 0ba71703d50d..386d1211dfeb 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -16,13 +16,7 @@ import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-mi import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' -import { - MAX_HISTORY_IMPORT_ATTEMPTS, - parseLegacyMigrationMarker, - publishKeptLegacyHistoriesIfAbsent, - trackLegacyHistoryImport, - type LegacyMigrationMarker -} from './legacy-prompt-history-import' +import { importKeptLegacyHistoriesOnce } from './legacy-prompt-history-import' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { @@ -65,11 +59,8 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - const existingMarker = this.readMigrationMarker() - if (existingMarker) { - if (existingMarker.historyImportPending) { - void this.importKeptLegacyHistories(existingMarker) - } + if (existsSync(this.getMigrationMarkerPath())) { + void this.importKeptLegacyHistories() return } @@ -84,58 +75,32 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } // First and synchronously: nothing later (a failed session copy, an account removed while the // import runs) may leave a legacy history without a copy Orca keeps. - const keptAny = this.keepLegacyHistoriesAside(managedHomes) + this.keepLegacyHistoriesAside(managedHomes) + // Independent of the session copies below, so one that fails can't hold the import back. + void this.importKeptLegacyHistories() for (const { accountId, homePath } of managedHomes) { this.migrateLegacySessions(homePath, accountId) } - const marker: LegacyMigrationMarker = { - completedAt: Date.now(), - migratedHomeCount: managedHomes.length, - ...(keptAny ? { historyImportPending: true } : {}) - } + // Mark completion so later startups cannot replay stale managed-home state. - this.writeMigrationMarker(marker) - if (keptAny) { - void this.importKeptLegacyHistories(marker) - } + writeFileAtomically( + this.getMigrationMarkerPath(), + `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` + ) } // Off the startup path (a large history takes tens of milliseconds), from Orca's kept copies only. - protected async importKeptLegacyHistories(marker: LegacyMigrationMarker): Promise { + protected async importKeptLegacyHistories(): Promise { try { - const outcome = await publishKeptLegacyHistoriesIfAbsent( + await importKeptLegacyHistoriesOnce( this.getKeptLegacyHistoryRoot(), join(this.getRuntimeHomePath(), 'history.jsonl') ) - trackLegacyHistoryImport(outcome) - const attempts = (marker.historyImportAttempts ?? 0) + 1 - if (outcome === 'failed' && attempts < MAX_HISTORY_IMPORT_ATTEMPTS) { - this.writeMigrationMarker({ ...marker, historyImportAttempts: attempts }) - return - } - const { historyImportPending: _done, historyImportAttempts: _attempts, ...completed } = marker - this.writeMigrationMarker(completed) } catch (error) { console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) } } - protected readMigrationMarker(): LegacyMigrationMarker | null { - if (!existsSync(this.getMigrationMarkerPath())) { - return null - } - try { - return parseLegacyMigrationMarker(readFileSync(this.getMigrationMarkerPath(), 'utf-8')) - } catch { - // An unreadable marker still means the one-time migration ran. - return {} - } - } - - protected writeMigrationMarker(marker: LegacyMigrationMarker): void { - writeFileAtomically(this.getMigrationMarkerPath(), `${JSON.stringify(marker)}\n`) - } - protected getKeptLegacyHistoryRoot(): string { return join(this.getRuntimeMetadataDir(), 'legacy-account-history') } @@ -163,8 +128,7 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa /** Copies each account's legacy history under Orca's metadata, which no removal or cleanup reaches. */ protected keepLegacyHistoriesAside( managedHomes: { accountId: string; homePath: string }[] - ): boolean { - let keptAny = false + ): void { let firstError: unknown = null for (const { accountId, homePath } of managedHomes) { const legacyHistoryPath = join(homePath, 'history.jsonl') @@ -182,7 +146,6 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa accountId, readFileSync(legacyHistoryPath) ) - keptAny = true } catch (error) { firstError ??= error } @@ -190,7 +153,6 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa if (firstError) { throw firstError } - return keptAny } protected migrateLegacySessions(managedHomePath: string, accountId: string): void { From acedce55035082fa958511d701fc58e661b54e57 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:28:46 -0800 Subject: [PATCH 07/30] fix(codex): keep one real copy of each legacy history, published by rename Each account's kept history is taken once, written to a temp file and renamed into place, so it is never partial, never a link to the original, and repeated unfinished launches add no snapshots. The import state is written the same way, and unparseable state retries the import. --- config/main-blocking-helper-baseline.txt | 2 +- .../legacy-prompt-history-import.ts | 31 ++++++++--- .../runtime-home-legacy-migration.test.ts | 54 +++++++++++++++---- .../runtime-home-service-legacy-migration.ts | 52 ++++++++---------- 4 files changed, 92 insertions(+), 47 deletions(-) diff --git a/config/main-blocking-helper-baseline.txt b/config/main-blocking-helper-baseline.txt index eb869b6a8870..bc27d446b591 100644 --- a/config/main-blocking-helper-baseline.txt +++ b/config/main-blocking-helper-baseline.txt @@ -271,7 +271,7 @@ 4 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 19 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts -2 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +3 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 11 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts # Codex launch prep from #43365 already merged; unblocks main, async follow-up owed 9 src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts 8 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 24901451bc6b..8c3dd12e1dd1 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto' -import { link, lstat, open, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { link, lstat, open, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { track } from '../../../telemetry/client' @@ -14,23 +14,38 @@ const IMPORT_STATE_FILE = 'import-state.json' type ImportState = { done: boolean; attempts: number } async function readImportState(path: string): Promise { + let text: string try { - const parsed: unknown = JSON.parse(await readFile(path, 'utf-8')) + text = await readFile(path, 'utf-8') + } catch (error) { + // Unreadable (not missing) state never re-imports: Orca couldn't record a later outcome either. + return { done: errnoCodeOrUnknown(error) !== 'ENOENT', attempts: 0 } + } + try { + const parsed: unknown = JSON.parse(text) if (parsed && typeof parsed === 'object') { return { done: 'done' in parsed && parsed.done === true, attempts: 'attempts' in parsed && typeof parsed.attempts === 'number' ? parsed.attempts : 0 } } - } catch (error) { - if (errnoCodeOrUnknown(error) !== 'ENOENT') { - // Unreadable state never re-imports: the shared history may exist by now anyway. - return { done: true, attempts: 0 } - } + } catch { + // Retried below: the import itself never writes into an existing shared history. } return { done: false, attempts: 0 } } +// Temp then rename: never torn, and a link at the name is replaced rather than written through. +async function writeImportState(path: string, state: ImportState): Promise { + const tmpPath = `${path}.${process.pid}.${randomUUID()}.tmp` + try { + await writeFile(tmpPath, `${JSON.stringify(state)}\n`, { encoding: 'utf-8', flag: 'wx' }) + await rename(tmpPath, path) + } finally { + await rm(tmpPath, { force: true }) + } +} + /** * Seeds a missing shared history from Orca's kept copies, once: each launch tries until the import * settles or has failed three times. Nothing runs while there are no kept copies. @@ -55,7 +70,7 @@ export async function importKeptLegacyHistoriesOnce( done: outcome !== 'failed' || attempts >= MAX_IMPORT_ATTEMPTS, attempts } - await writeFile(statePath, `${JSON.stringify(next)}\n`, 'utf-8') + await writeImportState(statePath, next) } async function pathExists(path: string): Promise { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 89b8c4cbb679..6a819f8ba2f6 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { existsSync, + linkSync, + readdirSync, mkdirSync, readlinkSync, readFileSync, @@ -74,15 +76,21 @@ async function startService(): Promise { // Settled: the marker exists and any kept history finished its import attempt. async function waitForMigrationMarker(): Promise { const runtimeHome = join(testState.userDataDir, 'codex-runtime-home') - await vi.waitFor(() => { - expect(existsSync(join(runtimeHome, 'migration-v1.json'))).toBe(true) - const kept = join(runtimeHome, 'legacy-account-history') - if (existsSync(kept)) { - expect(readFileSync(join(kept, 'import-state.json'), 'utf-8')).toContain('"done":true') - } - }) + await vi.waitFor( + () => { + expect(existsSync(join(runtimeHome, 'migration-v1.json'))).toBe(true) + const kept = join(runtimeHome, 'legacy-account-history') + if (existsSync(kept)) { + expect(readFileSync(join(kept, 'import-state.json'), 'utf-8')).toContain('"done":true') + } + }, + { timeout: WAIT_MS } + ) } +// Slow CI hosts take seconds to construct the service. +const WAIT_MS = 20_000 + async function removeAccountHome(managedHomePath: string): Promise { const { CodexManagedHomeLifecycle } = await import('../../managed-homes/codex-managed-home-lifecycle') @@ -183,7 +191,9 @@ describe('CodexRuntimeHomeService', () => { expect(existsSync(join(accountOneHome, 'history.jsonl'))).toBe(false) expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"a-1"}\n') expect(readFileSync(archivedHistoryPath('account-2'), 'utf-8')).toBe('{"id":"b-1"}\n') - await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['imported'])) + await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['imported']), { + timeout: WAIT_MS + }) expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( '{"id":"a-1"}\n{"id":"b-1"}\n' ) @@ -222,6 +232,30 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') }) + it('keeps one real copy per account: never a link to the original, never a second snapshot', async () => { + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + const keptPath = archivedHistoryPath('account-1') + mkdirSync(join(keptPath, '..'), { recursive: true }) + linkSync(join(managedHomePath, 'history.jsonl'), keptPath) + // A file where a session folder must go keeps the migration unfinished across launches. + mkdirSync(join(managedHomePath, 'sessions', 'nested'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'nested', 'rollout.jsonl'), '{}', 'utf-8') + mkdirSync(join(getRuntimeCodexHomePath(), 'sessions'), { recursive: true }) + writeFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested'), 'not a folder', 'utf-8') + + await constructService() + await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['imported']), { + timeout: WAIT_MS + }) + writeFileSync(join(managedHomePath, 'history.jsonl'), '{"id":"legacy-2"}\n', 'utf-8') + vi.resetModules() + await constructService() + await removeAccountHome(managedHomePath) + + expect(readFileSync(keptPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') + expect(readdirSync(join(keptPath, '..'))).toEqual(['history.jsonl']) + }) + it('retries a failed import on a later launch from the kept copy, after the account is gone', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') @@ -229,7 +263,9 @@ describe('CodexRuntimeHomeService', () => { throw Object.assign(new Error('busy'), { code: 'EBUSY' }) }) await constructService() - await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['failed'])) + await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['failed']), { + timeout: WAIT_MS + }) expect(existsSync(runtimeHistoryPath)).toBe(false) await removeAccountHome(managedHomePath) fsHooks.afterRead.clear() diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 386d1211dfeb..b99a684927c2 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -5,12 +5,13 @@ import { existsSync, mkdirSync, readFileSync, + lstatSync, readdirSync, - statSync, - writeFileSync + statSync } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' +import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-migration' import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' @@ -137,14 +138,20 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } try { const keptDir = join(this.getKeptLegacyHistoryRoot(), accountId) + const keptPath = join(keptDir, 'history.jsonl') + const kept = lstatSync(keptPath, { throwIfNoEntry: false }) + if (kept?.isFile() && kept.nlink === 1) { + // Kept by an earlier launch; history Codex wrote since stays in the account's own file. + continue + } mkdirSync(keptDir, { recursive: true }) - // Read once rather than copied: Codex may trim it meanwhile, and a copy of a file that - // shrinks mid-copy never finishes. - this.copyLegacyFilePreservingConflicts( - legacyHistoryPath, - join(keptDir, 'history.jsonl'), - accountId, - readFileSync(legacyHistoryPath) + // Read once rather than copied (a copy of a file Codex trims mid-copy never finishes), then + // published by rename: never partial, and a link at the name is replaced, not written through. + writeFileDurableSync( + durableWriteTempPath(keptPath), + keptPath, + readFileSync(legacyHistoryPath), + 0o600 ) } catch (error) { firstError ??= error @@ -190,47 +197,34 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa protected copyLegacyFilePreservingConflicts( legacyFilePath: string, targetPath: string, - accountId: string, - contents?: Buffer + accountId: string ): { path: string; preserved: boolean } { - if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath, contents) !== 'conflict') { + if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath) !== 'conflict') { return { path: targetPath, preserved: false } } for (let attempt = 0; ; attempt++) { const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) - const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath, contents) + const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath) if (result !== 'conflict') { return { path: preservedPath, preserved: result === 'copied' } } } } - /** - * Exclusive create never replaces or writes through a name, even one that appears after a check. - * With `contents`, writes those bytes instead of copying the file. - */ + /** Exclusive create never replaces or writes through a name, even one that appears after a check. */ protected copyLegacyFileWithoutOverwrite( legacyFilePath: string, - targetPath: string, - contents?: Buffer + targetPath: string ): 'copied' | 'identical' | 'conflict' { try { - if (contents) { - writeFileSync(targetPath, contents, { flag: 'wx', mode: 0o600 }) - } else { - copyFileSync( - legacyFilePath, - targetPath, - constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE - ) - } + copyFileSync(legacyFilePath, targetPath, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE) return 'copied' } catch (error) { if (errnoCodeOrUnknown(error) !== 'EEXIST') { throw error } } - const legacyContents = contents ?? readFileSync(legacyFilePath) + const legacyContents = readFileSync(legacyFilePath) try { return readFileSync(targetPath).equals(legacyContents) ? 'identical' : 'conflict' } catch { From 1e35b8b2d8acf17bd3953c1d857f148fe2d3dcfe Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:45:20 -0800 Subject: [PATCH 08/30] fix(codex): refresh the kept legacy history and refuse linked kept folders Each unfinished launch refreshes Orca's one kept copy from the account's current history, so prompts written between launches survive account removal. The kept copy is refused when its folder or the kept-copies root is a link. Session conflict probing reads the legacy file once. --- config/main-sync-fs-baseline.txt | 2 +- .../runtime-home-legacy-migration.test.ts | 36 ++++++++++++++++--- .../runtime-home-service-legacy-migration.ts | 28 +++++++++------ .../runtime-home-service-state.ts | 3 +- 4 files changed, 53 insertions(+), 16 deletions(-) diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 537cf93e47a7..ed54dbde7406 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -128,7 +128,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -17 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +18 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 6a819f8ba2f6..31b56e736d97 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -232,8 +232,8 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') }) - it('keeps one real copy per account: never a link to the original, never a second snapshot', async () => { - const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + it('keeps one real copy per account, refreshed while the migration is unfinished', async () => { + const managedHomePath = writeHistory('account-1', '{"id":"first"}\n') const keptPath = archivedHistoryPath('account-1') mkdirSync(join(keptPath, '..'), { recursive: true }) linkSync(join(managedHomePath, 'history.jsonl'), keptPath) @@ -247,15 +247,43 @@ describe('CodexRuntimeHomeService', () => { await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['imported']), { timeout: WAIT_MS }) - writeFileSync(join(managedHomePath, 'history.jsonl'), '{"id":"legacy-2"}\n', 'utf-8') + writeFileSync( + join(managedHomePath, 'history.jsonl'), + '{"id":"first"}\n{"id":"later"}\n', + 'utf-8' + ) vi.resetModules() await constructService() await removeAccountHome(managedHomePath) - expect(readFileSync(keptPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') + expect(readFileSync(keptPath, 'utf-8')).toBe('{"id":"first"}\n{"id":"later"}\n') expect(readdirSync(join(keptPath, '..'))).toEqual(['history.jsonl']) }) + it('never keeps a copy through a linked folder', async () => { + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + const elsewhere = join(testState.userDataDir, 'elsewhere') + mkdirSync(elsewhere, { recursive: true }) + writeFileSync(join(elsewhere, 'history.jsonl'), '{"id":"someone-else"}\n', 'utf-8') + const keptRoot = join(testState.userDataDir, 'codex-runtime-home', 'legacy-account-history') + mkdirSync(keptRoot, { recursive: true }) + symlinkSync( + elsewhere, + join(keptRoot, 'account-1'), + process.platform === 'win32' ? 'junction' : 'dir' + ) + + await constructService() + + expect(readFileSync(join(elsewhere, 'history.jsonl'), 'utf-8')).toBe('{"id":"someone-else"}\n') + expect(readFileSync(join(managedHomePath, 'history.jsonl'), 'utf-8')).toBe( + '{"id":"legacy-1"}\n' + ) + expect(existsSync(join(testState.userDataDir, 'codex-runtime-home', 'migration-v1.json'))).toBe( + false + ) + }) + it('retries a failed import on a later launch from the kept copy, after the account is gone', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index b99a684927c2..4ac77b1db7bb 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -138,15 +138,18 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } try { const keptDir = join(this.getKeptLegacyHistoryRoot(), accountId) - const keptPath = join(keptDir, 'history.jsonl') - const kept = lstatSync(keptPath, { throwIfNoEntry: false }) - if (kept?.isFile() && kept.nlink === 1) { - // Kept by an earlier launch; history Codex wrote since stays in the account's own file. - continue - } mkdirSync(keptDir, { recursive: true }) + // A linked folder could aim the kept copy at a real history somewhere else. + if ( + !lstatSync(this.getKeptLegacyHistoryRoot()).isDirectory() || + !lstatSync(keptDir).isDirectory() + ) { + throw new Error(`Refusing to keep legacy Codex history in a linked folder: ${keptDir}`) + } // Read once rather than copied (a copy of a file Codex trims mid-copy never finishes), then // published by rename: never partial, and a link at the name is replaced, not written through. + // Each unfinished launch refreshes Orca's one copy, so it holds what the account has now. + const keptPath = join(keptDir, 'history.jsonl') writeFileDurableSync( durableWriteTempPath(keptPath), keptPath, @@ -199,12 +202,16 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa targetPath: string, accountId: string ): { path: string; preserved: boolean } { - if (this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath) !== 'conflict') { + let legacyContents: Buffer | null = null + const readLegacy = (): Buffer => (legacyContents ??= readFileSync(legacyFilePath)) + if ( + this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath, readLegacy) !== 'conflict' + ) { return { path: targetPath, preserved: false } } for (let attempt = 0; ; attempt++) { const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) - const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath) + const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath, readLegacy) if (result !== 'conflict') { return { path: preservedPath, preserved: result === 'copied' } } @@ -214,7 +221,8 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa /** Exclusive create never replaces or writes through a name, even one that appears after a check. */ protected copyLegacyFileWithoutOverwrite( legacyFilePath: string, - targetPath: string + targetPath: string, + readLegacy: () => Buffer ): 'copied' | 'identical' | 'conflict' { try { copyFileSync(legacyFilePath, targetPath, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE) @@ -224,7 +232,7 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa throw error } } - const legacyContents = readFileSync(legacyFilePath) + const legacyContents = readLegacy() try { return readFileSync(targetPath).equals(legacyContents) ? 'identical' : 'conflict' } catch { diff --git a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts index 32dfb4e927bd..9c935f343c4d 100644 --- a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts @@ -209,7 +209,8 @@ export abstract class CodexRuntimeHomeState { ): string protected abstract copyLegacyFileWithoutOverwrite( legacyFilePath: string, - targetPath: string + targetPath: string, + readLegacy: () => Buffer ): 'copied' | 'identical' | 'conflict' protected abstract appendMigrationDiagnostic(record: Record): void From 1148b24ba0ead77e1f1261f056eaa0f1edd9f6b4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:55:49 -0800 Subject: [PATCH 09/30] fix(codex): set the earlier kept history aside when Codex trimmed the account's Before refreshing the kept copy, lines the earlier copy holds that the account history no longer has keep that copy under a numbered name, so a history Codex trims between unfinished launches loses nothing. Listing the kept copies counts toward the import's attempt cap. --- config/main-sync-fs-baseline.txt | 2 +- .../legacy-prompt-history-import.ts | 15 +++++-- .../runtime-home-legacy-migration.test.ts | 24 +++++++++++ .../runtime-home-service-legacy-migration.ts | 42 +++++++++++++++---- 4 files changed, 71 insertions(+), 12 deletions(-) diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index ed54dbde7406..1cde027fcdbb 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -128,7 +128,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -18 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +19 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 8c3dd12e1dd1..5eedad9056ff 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -59,11 +59,18 @@ export async function importKeptLegacyHistoriesOnce( if (state.done) { return } - const keptPaths = await listKeptLegacyHistories(keptRoot) - if (keptPaths.length === 0) { - return + let keptPaths: string[] + let outcome: LegacyHistoryImportOutcome + try { + keptPaths = await listKeptLegacyHistories(keptRoot) + if (keptPaths.length === 0) { + return + } + outcome = await publishKeptLegacyHistoriesIfAbsent(keptPaths, runtimeHistoryPath) + } catch (error) { + console.warn('[codex-runtime-home] Failed to list kept legacy Codex prompt history:', error) + outcome = 'failed' } - const outcome = await publishKeptLegacyHistoriesIfAbsent(keptPaths, runtimeHistoryPath) trackLegacyHistoryImport(outcome) const attempts = state.attempts + 1 const next: ImportState = { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 31b56e736d97..786050ac4dc5 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -260,6 +260,30 @@ describe('CodexRuntimeHomeService', () => { expect(readdirSync(join(keptPath, '..'))).toEqual(['history.jsonl']) }) + it('sets the earlier kept copy aside when Codex trimmed the account history in between', async () => { + writeFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), '{"id":"shared"}\n', 'utf-8') + const managedHomePath = writeHistory('account-1', '{"id":"A"}\n{"id":"B"}\n') + mkdirSync(join(managedHomePath, 'sessions', 'nested'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'nested', 'rollout.jsonl'), '{}', 'utf-8') + mkdirSync(join(getRuntimeCodexHomePath(), 'sessions'), { recursive: true }) + writeFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested'), 'not a folder', 'utf-8') + await constructService() + await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['skipped_existing']), { + timeout: WAIT_MS + }) + + writeFileSync(join(managedHomePath, 'history.jsonl'), '{"id":"B"}\n{"id":"C"}\n', 'utf-8') + vi.resetModules() + await constructService() + await removeAccountHome(managedHomePath) + + const keptDir = join(archivedHistoryPath('account-1'), '..') + expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"B"}\n{"id":"C"}\n') + expect(readFileSync(join(keptDir, 'history.orca-legacy-account-1.jsonl'), 'utf-8')).toBe( + '{"id":"A"}\n{"id":"B"}\n' + ) + }) + it('never keeps a copy through a linked folder', async () => { const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') const elsewhere = join(testState.userDataDir, 'elsewhere') diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 4ac77b1db7bb..271c7684b4e4 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -148,14 +148,11 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } // Read once rather than copied (a copy of a file Codex trims mid-copy never finishes), then // published by rename: never partial, and a link at the name is replaced, not written through. - // Each unfinished launch refreshes Orca's one copy, so it holds what the account has now. + // Each unfinished launch refreshes the copy so it holds what the account has now. const keptPath = join(keptDir, 'history.jsonl') - writeFileDurableSync( - durableWriteTempPath(keptPath), - keptPath, - readFileSync(legacyHistoryPath), - 0o600 - ) + const current = readFileSync(legacyHistoryPath) + this.setAsideKeptHistoryCodexTrimmed(keptPath, accountId, current) + writeFileDurableSync(durableWriteTempPath(keptPath), keptPath, current, 0o600) } catch (error) { firstError ??= error } @@ -165,6 +162,37 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } } + // Codex trims history from the front; lines the earlier copy has and the account lost stay kept. + protected setAsideKeptHistoryCodexTrimmed( + keptPath: string, + accountId: string, + current: Buffer + ): void { + let previous: Buffer + try { + previous = readFileSync(keptPath) + } catch { + return + } + const currentLines = new Set(current.toString('utf-8').split('\n')) + if ( + previous + .toString('utf-8') + .split('\n') + .every((line) => currentLines.has(line)) + ) { + return + } + for (let attempt = 0; ; attempt++) { + const preservedPath = this.getPreservedLegacySessionPath(keptPath, accountId, attempt) + if ( + this.copyLegacyFileWithoutOverwrite(keptPath, preservedPath, () => previous) !== 'conflict' + ) { + return + } + } + } + protected migrateLegacySessions(managedHomePath: string, accountId: string): void { const legacySessionsRoot = join(managedHomePath, 'sessions') if (!existsSync(legacySessionsRoot)) { From 190d3472d172ec06a487fc7ceef6f3f9f7cf0a9e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:13:38 -0800 Subject: [PATCH 10/30] fix(codex): account removal keeps prompt history; import reads accounts directly Account removal now keeps an account's history.jsonl, as it already keeps its sessions, so no Orca path deletes or moves an account's prompt history. That replaces the kept copies: the one-time import only reads the account histories, creates the shared history only when none exists, runs independently of session copies and retries on the next launch after a failure. Without hard links it publishes by exclusive create in append mode, which never touches an existing file and never writes over a Codex append to the new one. --- config/main-blocking-helper-baseline.txt | 2 +- config/main-sync-fs-baseline.txt | 2 +- .../codex-managed-home-lifecycle.test.ts | 4 +- .../codex-managed-home-lifecycle.ts | 4 +- .../legacy-prompt-history-import.ts | 191 +++++++----------- .../runtime-home-legacy-migration.test.ts | 185 +++++------------ .../runtime-home-service-legacy-migration.ts | 128 +++--------- ...etry-codex-legacy-history-event-schemas.ts | 2 +- 8 files changed, 168 insertions(+), 350 deletions(-) diff --git a/config/main-blocking-helper-baseline.txt b/config/main-blocking-helper-baseline.txt index bc27d446b591..eb869b6a8870 100644 --- a/config/main-blocking-helper-baseline.txt +++ b/config/main-blocking-helper-baseline.txt @@ -271,7 +271,7 @@ 4 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 19 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts -3 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +2 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 11 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts # Codex launch prep from #43365 already merged; unblocks main, async follow-up owed 9 src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts 8 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 1cde027fcdbb..9de6342021fe 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -128,7 +128,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -19 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +13 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index db75d8304d94..6864a2d058a1 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -59,11 +59,13 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { const f = fixture() mkdirSync(join(f.home, 'sessions')) writeFileSync(join(f.home, 'sessions', 'rollout.jsonl'), 'only copy\n') + writeFileSync(join(f.home, 'history.jsonl'), '{"text":"only prompt"}\n') writeFileSync(join(f.home, 'auth.json'), '{}') await f.lifecycle.safeRemove(f.home, 'a') - expect(readdirSync(f.home)).toEqual(['sessions']) + expect(readdirSync(f.home).sort()).toEqual(['history.jsonl', 'sessions']) + expect(readFileSync(join(f.home, 'history.jsonl'), 'utf8')).toBe('{"text":"only prompt"}\n') expect(readFileSync(join(f.home, 'sessions', 'rollout.jsonl'), 'utf8')).toBe('only copy\n') }) diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index ffb522ee3902..efc80c2c5159 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -30,8 +30,10 @@ const WSL_MANAGED_HOME_TIMEOUT_MS = 5_000 // that was busy at every launch may still hold its only copy, and a merge keeps conflicting // copies (and set-aside rollout forms, listed in the cleanup manifest) beside the links; all of // it outlives the login. A home that was shared (it has the manifest) keeps its own databases -// too: deleting them waits for a later release that has seen the shared store work. +// too: deleting them waits for a later release that has seen the shared store work. The prompt +// history stays as well: it may be the only copy of prompts never merged into the shared history. const KEPT_HISTORY = [ + 'history.jsonl', 'sessions', 'archived_sessions', SET_ASIDE_ROLLOUTS_DIR, diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 5eedad9056ff..ad23ae5cc877 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto' -import { link, lstat, open, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises' +import { link, lstat, open, readFile, readdir, rm } from 'node:fs/promises' import { join } from 'node:path' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { track } from '../../../telemetry/client' @@ -7,79 +7,6 @@ import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/te type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] -/** Launches that try the import before it gives up; the kept copies stay either way. */ -const MAX_IMPORT_ATTEMPTS = 3 -const IMPORT_STATE_FILE = 'import-state.json' - -type ImportState = { done: boolean; attempts: number } - -async function readImportState(path: string): Promise { - let text: string - try { - text = await readFile(path, 'utf-8') - } catch (error) { - // Unreadable (not missing) state never re-imports: Orca couldn't record a later outcome either. - return { done: errnoCodeOrUnknown(error) !== 'ENOENT', attempts: 0 } - } - try { - const parsed: unknown = JSON.parse(text) - if (parsed && typeof parsed === 'object') { - return { - done: 'done' in parsed && parsed.done === true, - attempts: 'attempts' in parsed && typeof parsed.attempts === 'number' ? parsed.attempts : 0 - } - } - } catch { - // Retried below: the import itself never writes into an existing shared history. - } - return { done: false, attempts: 0 } -} - -// Temp then rename: never torn, and a link at the name is replaced rather than written through. -async function writeImportState(path: string, state: ImportState): Promise { - const tmpPath = `${path}.${process.pid}.${randomUUID()}.tmp` - try { - await writeFile(tmpPath, `${JSON.stringify(state)}\n`, { encoding: 'utf-8', flag: 'wx' }) - await rename(tmpPath, path) - } finally { - await rm(tmpPath, { force: true }) - } -} - -/** - * Seeds a missing shared history from Orca's kept copies, once: each launch tries until the import - * settles or has failed three times. Nothing runs while there are no kept copies. - */ -export async function importKeptLegacyHistoriesOnce( - keptRoot: string, - runtimeHistoryPath: string -): Promise { - const statePath = join(keptRoot, IMPORT_STATE_FILE) - const state = await readImportState(statePath) - if (state.done) { - return - } - let keptPaths: string[] - let outcome: LegacyHistoryImportOutcome - try { - keptPaths = await listKeptLegacyHistories(keptRoot) - if (keptPaths.length === 0) { - return - } - outcome = await publishKeptLegacyHistoriesIfAbsent(keptPaths, runtimeHistoryPath) - } catch (error) { - console.warn('[codex-runtime-home] Failed to list kept legacy Codex prompt history:', error) - outcome = 'failed' - } - trackLegacyHistoryImport(outcome) - const attempts = state.attempts + 1 - const next: ImportState = { - done: outcome !== 'failed' || attempts >= MAX_IMPORT_ATTEMPTS, - attempts - } - await writeImportState(statePath, next) -} - async function pathExists(path: string): Promise { try { await lstat(path) @@ -92,60 +19,68 @@ async function pathExists(path: string): Promise { } } -// Every kept copy, accounts and their preserved versions in a stable order. -async function listKeptLegacyHistories(keptRoot: string): Promise { - const paths: string[] = [] - const accounts = await readdir(keptRoot, { withFileTypes: true }).catch((error: unknown) => { +// Every account's own history file, ownership marker or not: a removed or shared home keeps it. +async function listAccountHistories(accountsRoot: string): Promise { + const accounts = await readdir(accountsRoot, { withFileTypes: true }).catch((error: unknown) => { if (errnoCodeOrUnknown(error) === 'ENOENT') { return [] } throw error }) - for (const account of accounts.filter((entry) => entry.isDirectory()).sort(byName)) { - const files = await readdir(join(keptRoot, account.name), { withFileTypes: true }) - for (const file of files.filter((entry) => entry.isFile()).sort(byName)) { - if (file.name.endsWith('.jsonl')) { - paths.push(join(keptRoot, account.name, file.name)) - } + const paths: string[] = [] + for (const account of accounts.filter((entry) => entry.isDirectory())) { + const historyPath = join(accountsRoot, account.name, 'home', 'history.jsonl') + const stats = await lstat(historyPath).catch(() => null) + if (stats?.isFile()) { + paths.push(historyPath) } } - return paths -} - -function byName(left: { name: string }, right: { name: string }): number { - return left.name < right.name ? -1 : left.name > right.name ? 1 : 0 + return paths.sort() } /** - * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one is - * created from Orca's kept copies, and never over one Codex creates meanwhile. + * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one + * is created from the account histories, which are only read, and never over one Codex creates + * meanwhile. Rejects on failure, so the migration retries on the next launch. */ -async function publishKeptLegacyHistoriesIfAbsent( - keptPaths: readonly string[], +export async function importLegacyHistoriesIfSharedAbsent( + accountsRoot: string, runtimeHistoryPath: string -): Promise { +): Promise { + const accountHistoryPaths = await listAccountHistories(accountsRoot) + if (accountHistoryPaths.length === 0) { + return + } + let outcome: LegacyHistoryImportOutcome = 'failed' try { - if (await pathExists(runtimeHistoryPath)) { - return 'skipped_existing' - } - const seenLines = new Set() - for (const keptPath of keptPaths) { - for (const line of (await readFile(keptPath, 'utf-8')).split('\n')) { - if (line) { - seenLines.add(line) - } + outcome = await publishLegacyHistoriesIfAbsent(accountHistoryPaths, runtimeHistoryPath) + } finally { + trackLegacyHistoryImport(outcome) + } +} + +async function publishLegacyHistoriesIfAbsent( + accountHistoryPaths: readonly string[], + runtimeHistoryPath: string +): Promise { + if (await pathExists(runtimeHistoryPath)) { + return 'skipped_existing' + } + const seenLines = new Set() + for (const accountHistoryPath of accountHistoryPaths) { + for (const line of (await readFile(accountHistoryPath, 'utf-8')).split('\n')) { + if (line) { + seenLines.add(line) } } - if (seenLines.size === 0) { - return 'nothing_to_import' - } - return (await publishWithoutOverwrite(`${[...seenLines].join('\n')}\n`, runtimeHistoryPath)) - ? 'imported' - : 'skipped_existing' - } catch (error) { - console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) - return 'failed' } + if (seenLines.size === 0) { + return 'nothing_to_import' + } + const contents = `${[...seenLines].join('\n')}\n` + return (await publishWithoutOverwrite(contents, runtimeHistoryPath)) + ? 'imported' + : 'skipped_existing' } async function publishWithoutOverwrite(contents: string, targetPath: string): Promise { @@ -161,14 +96,44 @@ async function publishWithoutOverwrite(contents: string, targetPath: string): Pr // A hard link publishes only into a free name: one Codex created meanwhile stays as it is. await link(tmpPath, targetPath) return true + } catch (error) { + const code = errnoCodeOrUnknown(error) + if (code === 'EEXIST') { + return false + } + if (!HARD_LINK_UNSUPPORTED.has(code)) { + throw error + } + return appendIntoNewFile(contents, targetPath) + } finally { + await rm(tmpPath, { force: true }) + } +} + +// exFAT, FAT32 and some network or FUSE mounts refuse hard links. +const HARD_LINK_UNSUPPORTED = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV']) + +/** + * Without hard links: exclusive create still never touches an existing file, and append mode puts + * Orca's single write and any Codex append to the new file one after the other, never over it. + */ +async function appendIntoNewFile(contents: string, targetPath: string): Promise { + let handle: Awaited> + try { + handle = await open(targetPath, 'ax', 0o600) } catch (error) { if (errnoCodeOrUnknown(error) === 'EEXIST') { return false } throw error + } + try { + await handle.writeFile(contents, 'utf-8') + await handle.sync() } finally { - await rm(tmpPath, { force: true }) + await handle.close() } + return true } function trackLegacyHistoryImport(outcome: LegacyHistoryImportOutcome): void { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 786050ac4dc5..5962b809b247 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -2,8 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { existsSync, - linkSync, - readdirSync, mkdirSync, readlinkSync, readFileSync, @@ -52,14 +50,20 @@ function writeHistory(accountId: string, contents: string): string { return managedHomePath } -function archivedHistoryPath(accountId: string): string { - return join( - testState.userDataDir, - 'codex-runtime-home', - 'legacy-account-history', - accountId, - 'history.jsonl' - ) +function blockSessionCopies(managedHomePath: string): void { + // A file where a session folder must go: the session copy throws. + mkdirSync(join(managedHomePath, 'sessions', 'nested'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'nested', 'rollout.jsonl'), '{}', 'utf-8') + mkdirSync(join(getRuntimeCodexHomePath(), 'sessions'), { recursive: true }) + writeFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested'), 'not a folder', 'utf-8') +} + +function migrationMarkerPath(): string { + return join(testState.userDataDir, 'codex-runtime-home', 'migration-v1.json') +} + +async function waitForImportOutcomes(outcomes: string[]): Promise { + await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(outcomes), { timeout: WAIT_MS }) } async function constructService(): Promise { @@ -73,19 +77,10 @@ async function startService(): Promise { await waitForMigrationMarker() } -// Settled: the marker exists and any kept history finished its import attempt. async function waitForMigrationMarker(): Promise { - const runtimeHome = join(testState.userDataDir, 'codex-runtime-home') - await vi.waitFor( - () => { - expect(existsSync(join(runtimeHome, 'migration-v1.json'))).toBe(true) - const kept = join(runtimeHome, 'legacy-account-history') - if (existsSync(kept)) { - expect(readFileSync(join(kept, 'import-state.json'), 'utf-8')).toContain('"done":true') - } - }, - { timeout: WAIT_MS } - ) + await vi.waitFor(() => expect(existsSync(migrationMarkerPath())).toBe(true), { + timeout: WAIT_MS + }) } // Slow CI hosts take seconds to construct the service. @@ -101,7 +96,12 @@ async function removeAccountHome(managedHomePath: string): Promise { ) } -const fsHooks = vi.hoisted(() => ({ afterRead: new Map void>() })) +const fsHooks = vi.hoisted( + (): { afterRead: Map void>; linkError: NodeJS.ErrnoException | null } => ({ + afterRead: new Map(), + linkError: null + }) +) vi.mock(import('node:fs/promises'), async (importOriginal) => { const actual = await importOriginal() // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: forwards every overload unchanged. @@ -110,7 +110,13 @@ vi.mock(import('node:fs/promises'), async (importOriginal) => { fsHooks.afterRead.get(String(args[0]))?.() return contents }) as typeof actual.readFile - return { ...actual, default: { ...actual, readFile }, readFile } + const link = async (...args: Parameters): Promise => { + if (fsHooks.linkError) { + throw fsHooks.linkError + } + await actual.link(...args) + } + return { ...actual, default: { ...actual, readFile, link }, readFile, link } }) vi.mock(import('node:os'), async (importOriginal) => { @@ -128,6 +134,7 @@ describe('CodexRuntimeHomeService', () => { afterEach(() => { fsHooks.afterRead.clear() + fsHooks.linkError = null trackMock.mockClear() teardownRuntimeHomeTest() }) @@ -177,51 +184,38 @@ describe('CodexRuntimeHomeService', () => { expect(trackedImportOutcomes()).toEqual(['imported']) }) - it('keeps every legacy history aside before startup returns, even when a session copy fails', async () => { - const accountOneHome = writeHistory('account-1', '{"id":"a-1"}\n') - const accountTwoHome = writeHistory('account-2', '{"id":"b-1"}\n') - mkdirSync(join(accountTwoHome, 'sessions', 'nested'), { recursive: true }) - writeFileSync(join(accountTwoHome, 'sessions', 'nested', 'rollout.jsonl'), '{}', 'utf-8') - mkdirSync(join(getRuntimeCodexHomePath(), 'sessions'), { recursive: true }) - // A file where account 2's session folder must go: its session copy throws. - writeFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested'), 'not a folder', 'utf-8') - await constructService() - await removeAccountHome(accountOneHome) - - expect(existsSync(join(accountOneHome, 'history.jsonl'))).toBe(false) - expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"a-1"}\n') - expect(readFileSync(archivedHistoryPath('account-2'), 'utf-8')).toBe('{"id":"b-1"}\n') - await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['imported']), { - timeout: WAIT_MS - }) - expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( - '{"id":"a-1"}\n{"id":"b-1"}\n' - ) - }) - - it('never writes an existing shared history and keeps the legacy one aside, even past account removal', async () => { + it('never writes an existing shared history, and account removal keeps the account history', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}', 'utf-8') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') await startService() + await removeAccountHome(managedHomePath) expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}') expect(trackedImportOutcomes()).toEqual(['skipped_existing']) expect(readFileSync(join(managedHomePath, 'history.jsonl'), 'utf-8')).toBe( '{"id":"legacy-1"}\n' ) + }) - await removeAccountHome(managedHomePath) + it('imports history even when a session copy fails', async () => { + const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') + blockSessionCopies(managedHomePath) + + await constructService() + await waitForImportOutcomes(['imported']) - expect(existsSync(join(managedHomePath, 'history.jsonl'))).toBe(false) - expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + '{"id":"a-1"}\n' + ) + expect(existsSync(migrationMarkerPath())).toBe(false) }) it('leaves a shared history Codex creates during the import as it is', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') - writeHistory('account-1', '{"id":"legacy-1"}\n') - fsHooks.afterRead.set(archivedHistoryPath('account-1'), () => + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + fsHooks.afterRead.set(join(managedHomePath, 'history.jsonl'), () => writeFileSync(runtimeHistoryPath, '{"id":"codex-new"}\n', 'utf-8') ) @@ -229,97 +223,30 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"codex-new"}\n') expect(trackedImportOutcomes()).toEqual(['skipped_existing']) - expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') - }) - - it('keeps one real copy per account, refreshed while the migration is unfinished', async () => { - const managedHomePath = writeHistory('account-1', '{"id":"first"}\n') - const keptPath = archivedHistoryPath('account-1') - mkdirSync(join(keptPath, '..'), { recursive: true }) - linkSync(join(managedHomePath, 'history.jsonl'), keptPath) - // A file where a session folder must go keeps the migration unfinished across launches. - mkdirSync(join(managedHomePath, 'sessions', 'nested'), { recursive: true }) - writeFileSync(join(managedHomePath, 'sessions', 'nested', 'rollout.jsonl'), '{}', 'utf-8') - mkdirSync(join(getRuntimeCodexHomePath(), 'sessions'), { recursive: true }) - writeFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested'), 'not a folder', 'utf-8') - - await constructService() - await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['imported']), { - timeout: WAIT_MS - }) - writeFileSync( - join(managedHomePath, 'history.jsonl'), - '{"id":"first"}\n{"id":"later"}\n', - 'utf-8' - ) - vi.resetModules() - await constructService() - await removeAccountHome(managedHomePath) - - expect(readFileSync(keptPath, 'utf-8')).toBe('{"id":"first"}\n{"id":"later"}\n') - expect(readdirSync(join(keptPath, '..'))).toEqual(['history.jsonl']) }) - it('sets the earlier kept copy aside when Codex trimmed the account history in between', async () => { - writeFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), '{"id":"shared"}\n', 'utf-8') - const managedHomePath = writeHistory('account-1', '{"id":"A"}\n{"id":"B"}\n') - mkdirSync(join(managedHomePath, 'sessions', 'nested'), { recursive: true }) - writeFileSync(join(managedHomePath, 'sessions', 'nested', 'rollout.jsonl'), '{}', 'utf-8') - mkdirSync(join(getRuntimeCodexHomePath(), 'sessions'), { recursive: true }) - writeFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested'), 'not a folder', 'utf-8') - await constructService() - await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['skipped_existing']), { - timeout: WAIT_MS - }) - - writeFileSync(join(managedHomePath, 'history.jsonl'), '{"id":"B"}\n{"id":"C"}\n', 'utf-8') - vi.resetModules() - await constructService() - await removeAccountHome(managedHomePath) - - const keptDir = join(archivedHistoryPath('account-1'), '..') - expect(readFileSync(archivedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"B"}\n{"id":"C"}\n') - expect(readFileSync(join(keptDir, 'history.orca-legacy-account-1.jsonl'), 'utf-8')).toBe( - '{"id":"A"}\n{"id":"B"}\n' - ) - }) - - it('never keeps a copy through a linked folder', async () => { - const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') - const elsewhere = join(testState.userDataDir, 'elsewhere') - mkdirSync(elsewhere, { recursive: true }) - writeFileSync(join(elsewhere, 'history.jsonl'), '{"id":"someone-else"}\n', 'utf-8') - const keptRoot = join(testState.userDataDir, 'codex-runtime-home', 'legacy-account-history') - mkdirSync(keptRoot, { recursive: true }) - symlinkSync( - elsewhere, - join(keptRoot, 'account-1'), - process.platform === 'win32' ? 'junction' : 'dir' - ) + it('creates the shared history where hard links are refused', async () => { + writeHistory('account-1', '{"id":"legacy-1"}\n') + fsHooks.linkError = Object.assign(new Error('no hard links'), { code: 'ENOTSUP' }) - await constructService() + await startService() - expect(readFileSync(join(elsewhere, 'history.jsonl'), 'utf-8')).toBe('{"id":"someone-else"}\n') - expect(readFileSync(join(managedHomePath, 'history.jsonl'), 'utf-8')).toBe( + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( '{"id":"legacy-1"}\n' ) - expect(existsSync(join(testState.userDataDir, 'codex-runtime-home', 'migration-v1.json'))).toBe( - false - ) + expect(trackedImportOutcomes()).toEqual(['imported']) }) - it('retries a failed import on a later launch from the kept copy, after the account is gone', async () => { + it('retries a failed import on the next launch', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') - fsHooks.afterRead.set(archivedHistoryPath('account-1'), () => { + fsHooks.afterRead.set(join(managedHomePath, 'history.jsonl'), () => { throw Object.assign(new Error('busy'), { code: 'EBUSY' }) }) await constructService() - await vi.waitFor(() => expect(trackedImportOutcomes()).toEqual(['failed']), { - timeout: WAIT_MS - }) + await waitForImportOutcomes(['failed']) expect(existsSync(runtimeHistoryPath)).toBe(false) - await removeAccountHome(managedHomePath) + expect(existsSync(migrationMarkerPath())).toBe(false) fsHooks.afterRead.clear() vi.resetModules() diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 271c7684b4e4..e566e8915be7 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -5,19 +5,17 @@ import { existsSync, mkdirSync, readFileSync, - lstatSync, readdirSync, statSync } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' -import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-migration' import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' -import { importKeptLegacyHistoriesOnce } from './legacy-prompt-history-import' +import { importLegacyHistoriesIfSharedAbsent } from './legacy-prompt-history-import' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { @@ -61,49 +59,40 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa protected migrateLegacyManagedStateIfNeeded(): void { if (existsSync(this.getMigrationMarkerPath())) { - void this.importKeptLegacyHistories() return } - const managedHomes: { accountId: string; homePath: string }[] = [] - for (const homePath of this.getLegacyManagedHomes()) { - const accountId = parse(relative(this.getManagedAccountsRoot(), homePath)).dir.split( + // Started first and independent of the session copies, so one that fails can't hold it back. + const historyImported = importLegacyHistoriesIfSharedAbsent( + this.getManagedAccountsRoot(), + join(this.getRuntimeHomePath(), 'history.jsonl') + ).then( + () => true, + (error: unknown) => { + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) + return false + } + ) + const managedHomes = this.getLegacyManagedHomes() + for (const managedHomePath of managedHomes) { + const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( /[\\/]/ )[0] if (accountId) { - managedHomes.push({ accountId, homePath }) + this.migrateLegacySessions(managedHomePath, accountId) } } - // First and synchronously: nothing later (a failed session copy, an account removed while the - // import runs) may leave a legacy history without a copy Orca keeps. - this.keepLegacyHistoriesAside(managedHomes) - // Independent of the session copies below, so one that fails can't hold the import back. - void this.importKeptLegacyHistories() - for (const { accountId, homePath } of managedHomes) { - this.migrateLegacySessions(homePath, accountId) - } - // Mark completion so later startups cannot replay stale managed-home state. - writeFileAtomically( - this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` - ) - } - - // Off the startup path (a large history takes tens of milliseconds), from Orca's kept copies only. - protected async importKeptLegacyHistories(): Promise { - try { - await importKeptLegacyHistoriesOnce( - this.getKeptLegacyHistoryRoot(), - join(this.getRuntimeHomePath(), 'history.jsonl') + void historyImported.then((imported) => { + if (!imported) { + return + } + // Mark completion so later startups cannot replay stale managed-home state. + writeFileAtomically( + this.getMigrationMarkerPath(), + `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` ) - } catch (error) { - console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) - } - } - - protected getKeptLegacyHistoryRoot(): string { - return join(this.getRuntimeMetadataDir(), 'legacy-account-history') + }) } protected getLegacyManagedHomes(): string[] { @@ -126,73 +115,6 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return managedHomes.sort() } - /** Copies each account's legacy history under Orca's metadata, which no removal or cleanup reaches. */ - protected keepLegacyHistoriesAside( - managedHomes: { accountId: string; homePath: string }[] - ): void { - let firstError: unknown = null - for (const { accountId, homePath } of managedHomes) { - const legacyHistoryPath = join(homePath, 'history.jsonl') - if (!existsSync(legacyHistoryPath)) { - continue - } - try { - const keptDir = join(this.getKeptLegacyHistoryRoot(), accountId) - mkdirSync(keptDir, { recursive: true }) - // A linked folder could aim the kept copy at a real history somewhere else. - if ( - !lstatSync(this.getKeptLegacyHistoryRoot()).isDirectory() || - !lstatSync(keptDir).isDirectory() - ) { - throw new Error(`Refusing to keep legacy Codex history in a linked folder: ${keptDir}`) - } - // Read once rather than copied (a copy of a file Codex trims mid-copy never finishes), then - // published by rename: never partial, and a link at the name is replaced, not written through. - // Each unfinished launch refreshes the copy so it holds what the account has now. - const keptPath = join(keptDir, 'history.jsonl') - const current = readFileSync(legacyHistoryPath) - this.setAsideKeptHistoryCodexTrimmed(keptPath, accountId, current) - writeFileDurableSync(durableWriteTempPath(keptPath), keptPath, current, 0o600) - } catch (error) { - firstError ??= error - } - } - if (firstError) { - throw firstError - } - } - - // Codex trims history from the front; lines the earlier copy has and the account lost stay kept. - protected setAsideKeptHistoryCodexTrimmed( - keptPath: string, - accountId: string, - current: Buffer - ): void { - let previous: Buffer - try { - previous = readFileSync(keptPath) - } catch { - return - } - const currentLines = new Set(current.toString('utf-8').split('\n')) - if ( - previous - .toString('utf-8') - .split('\n') - .every((line) => currentLines.has(line)) - ) { - return - } - for (let attempt = 0; ; attempt++) { - const preservedPath = this.getPreservedLegacySessionPath(keptPath, accountId, attempt) - if ( - this.copyLegacyFileWithoutOverwrite(keptPath, preservedPath, () => previous) !== 'conflict' - ) { - return - } - } - } - protected migrateLegacySessions(managedHomePath: string, accountId: string): void { const legacySessionsRoot = join(managedHomePath, 'sessions') if (!existsSync(legacySessionsRoot)) { diff --git a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts index 5b64605a9cbb..3d7164b2f193 100644 --- a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts +++ b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts @@ -1,6 +1,6 @@ import { z } from 'zod' -/** Orca keeps every legacy history aside in its metadata whatever the outcome; `failed` retries. */ +/** Account histories are only read, whatever the outcome; `failed` retries on the next launch. */ export const CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES = [ 'imported', 'skipped_existing', From 6e2f6083a0033eb1393e3bcdfde67dc6611064aa Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:26:43 -0800 Subject: [PATCH 11/30] fix(codex): skip the history import where hard links are refused; say removal keeps history Without hard links there is no way to publish a new shared history that a running Codex can't append into mid-write, so the import writes nothing there and each account history stays in its own home. The account-removal dialog now says the account's Codex history stays in its folder. A failed migration-marker write is logged instead of surfacing as an unhandled rejection. --- .../legacy-prompt-history-import.ts | 51 ++++++------------- .../runtime-home-legacy-migration.test.ts | 9 ++-- .../runtime-home-service-legacy-migration.ts | 14 +++-- .../accounts-pane-removal-dialogs.tsx | 2 +- src/renderer/src/i18n/locales/en.json | 2 +- src/renderer/src/i18n/locales/zh.json | 2 +- ...etry-codex-legacy-history-event-schemas.ts | 1 + 7 files changed, 33 insertions(+), 48 deletions(-) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index ad23ae5cc877..496ab88dedd9 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -77,13 +77,16 @@ async function publishLegacyHistoriesIfAbsent( if (seenLines.size === 0) { return 'nothing_to_import' } - const contents = `${[...seenLines].join('\n')}\n` - return (await publishWithoutOverwrite(contents, runtimeHistoryPath)) - ? 'imported' - : 'skipped_existing' + return publishWithoutOverwrite(`${[...seenLines].join('\n')}\n`, runtimeHistoryPath) } -async function publishWithoutOverwrite(contents: string, targetPath: string): Promise { +// exFAT, FAT32 and some network or FUSE mounts refuse hard links. +const HARD_LINK_UNSUPPORTED = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV']) + +async function publishWithoutOverwrite( + contents: string, + targetPath: string +): Promise { const tmpPath = `${targetPath}.${process.pid}.${randomUUID()}.tmp` try { const handle = await open(tmpPath, 'wx', 0o600) @@ -95,45 +98,21 @@ async function publishWithoutOverwrite(contents: string, targetPath: string): Pr } // A hard link publishes only into a free name: one Codex created meanwhile stays as it is. await link(tmpPath, targetPath) - return true + return 'imported' } catch (error) { const code = errnoCodeOrUnknown(error) if (code === 'EEXIST') { - return false + return 'skipped_existing' } - if (!HARD_LINK_UNSUPPORTED.has(code)) { - throw error - } - return appendIntoNewFile(contents, targetPath) - } finally { - await rm(tmpPath, { force: true }) - } -} - -// exFAT, FAT32 and some network or FUSE mounts refuse hard links. -const HARD_LINK_UNSUPPORTED = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV']) - -/** - * Without hard links: exclusive create still never touches an existing file, and append mode puts - * Orca's single write and any Codex append to the new file one after the other, never over it. - */ -async function appendIntoNewFile(contents: string, targetPath: string): Promise { - let handle: Awaited> - try { - handle = await open(targetPath, 'ax', 0o600) - } catch (error) { - if (errnoCodeOrUnknown(error) === 'EEXIST') { - return false + // No safe way to publish without replacing: every other way leaves a name Codex can append + // into mid-write. The account histories stay in their homes, so nothing is lost. + if (HARD_LINK_UNSUPPORTED.has(code)) { + return 'skipped_no_hard_links' } throw error - } - try { - await handle.writeFile(contents, 'utf-8') - await handle.sync() } finally { - await handle.close() + await rm(tmpPath, { force: true }) } - return true } function trackLegacyHistoryImport(outcome: LegacyHistoryImportOutcome): void { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 5962b809b247..209b70fb80c4 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -225,16 +225,17 @@ describe('CodexRuntimeHomeService', () => { expect(trackedImportOutcomes()).toEqual(['skipped_existing']) }) - it('creates the shared history where hard links are refused', async () => { - writeHistory('account-1', '{"id":"legacy-1"}\n') + it('writes no shared history where hard links are refused, and keeps the account history', async () => { + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') fsHooks.linkError = Object.assign(new Error('no hard links'), { code: 'ENOTSUP' }) await startService() - expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + expect(existsSync(join(getRuntimeCodexHomePath(), 'history.jsonl'))).toBe(false) + expect(trackedImportOutcomes()).toEqual(['skipped_no_hard_links']) + expect(readFileSync(join(managedHomePath, 'history.jsonl'), 'utf-8')).toBe( '{"id":"legacy-1"}\n' ) - expect(trackedImportOutcomes()).toEqual(['imported']) }) it('retries a failed import on the next launch', async () => { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index e566e8915be7..3a53bad052d8 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -87,11 +87,15 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa if (!imported) { return } - // Mark completion so later startups cannot replay stale managed-home state. - writeFileAtomically( - this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` - ) + try { + // Mark completion so later startups cannot replay stale managed-home state. + writeFileAtomically( + this.getMigrationMarkerPath(), + `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` + ) + } catch (error) { + console.warn('[codex-runtime-home] Failed to mark legacy Codex migration complete:', error) + } }) } diff --git a/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx b/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx index ffe06ab8e220..ff0e26bce8f1 100644 --- a/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx +++ b/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx @@ -57,7 +57,7 @@ export function renderAccountsRemovalDialogs( {t( 'settings.accounts.codexRemoveHome', - "Orca deletes this account's Codex folder on {{host}}, including its sign-in, MCP logins and any Codex history stored only in that folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", + "Orca deletes this account's sign-in and MCP logins on {{host}}. Its Codex history, sessions and prompts, stays in the account's folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", { host: accountRuntimeSentenceLabel } )} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 6a9a2d602fd8..74d53413af52 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1196,7 +1196,7 @@ "followSymlinkedDirectories": "Follow symlinked directories", "followSymlinkedDirectoriesDescription": "Search linked folders in Quick Open and expand local linked folders in File Explorer.", "accounts": { - "codexRemoveHome": "Orca deletes this account's Codex folder on {{host}}, including its sign-in, MCP logins and any Codex history stored only in that folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", + "codexRemoveHome": "Orca deletes this account's sign-in and MCP logins on {{host}}. Its Codex history, sessions and prompts, stays in the account's folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", "claudeRemoveProfile": "Orca deletes this account's own Claude folder and the sign-in saved in it on {{host}}. Your System default login and chat history shared with it stay. If it is selected, the next Claude you start uses System default." }, "sourceControl": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 57a0e7ae8060..c1429717ce6f 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -576,7 +576,7 @@ "followSymlinkedDirectories": "跟随符号链接目录", "followSymlinkedDirectoriesDescription": "在快速打开中搜索链接文件夹,并在文件资源管理器中展开本地链接文件夹", "accounts": { - "codexRemoveHome": "Orca 会删除此账户在 {{host}} 上的 Codex 文件夹,包括其中的登录信息、MCP 登录以及仅保存在该文件夹中的 Codex 历史记录,此操作无法撤销。如果此账户被选中,你下次启动的 Codex 将使用系统默认", + "codexRemoveHome": "Orca 会删除此账户在 {{host}} 上的登录信息和 MCP 登录。它的 Codex 历史记录(会话和提示)会保留在该账户的文件夹中。此操作无法撤销。如果此账户被选中,你下次启动的 Codex 将使用系统默认", "claudeRemoveProfile": "Orca 会删除此账户在 {{host}} 上自己的 Claude 文件夹及其中保存的登录信息,你的系统默认登录以及与其共享的聊天记录会保留。如果此账户被选中,你下次启动的 Claude 将使用系统默认" }, "sourceControl": { diff --git a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts index 3d7164b2f193..e3d02e249972 100644 --- a/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts +++ b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts @@ -5,6 +5,7 @@ export const CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES = [ 'imported', 'skipped_existing', 'nothing_to_import', + 'skipped_no_hard_links', 'failed' ] as const From 048ae7116d581c7c5330bb18ba9decb72e980016 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:58:11 -0800 Subject: [PATCH 12/30] fix(codex): retry on unreadable account histories; classify only link errors as no hard links --- .../legacy-prompt-history-import.ts | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 496ab88dedd9..f59a4e2b4199 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -30,7 +30,13 @@ async function listAccountHistories(accountsRoot: string): Promise { const paths: string[] = [] for (const account of accounts.filter((entry) => entry.isDirectory())) { const historyPath = join(accountsRoot, account.name, 'home', 'history.jsonl') - const stats = await lstat(historyPath).catch(() => null) + // Only a missing file means no history; any other error retries rather than skip an account. + const stats = await lstat(historyPath).catch((error: unknown) => { + if (errnoCodeOrUnknown(error) === 'ENOENT') { + return null + } + throw error + }) if (stats?.isFile()) { paths.push(historyPath) } @@ -96,7 +102,18 @@ async function publishWithoutOverwrite( } finally { await handle.close() } - // A hard link publishes only into a free name: one Codex created meanwhile stays as it is. + return await linkIntoFreeName(tmpPath, targetPath) + } finally { + await rm(tmpPath, { force: true }) + } +} + +// A hard link publishes only into a free name: one Codex created meanwhile stays as it is. +async function linkIntoFreeName( + tmpPath: string, + targetPath: string +): Promise { + try { await link(tmpPath, targetPath) return 'imported' } catch (error) { @@ -110,8 +127,6 @@ async function publishWithoutOverwrite( return 'skipped_no_hard_links' } throw error - } finally { - await rm(tmpPath, { force: true }) } } From c08949a048bdae83329aa454d23a9e44fa4c0292 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:14:53 -0800 Subject: [PATCH 13/30] fix(codex): mark the migration after the session copies; retry only a failed history import A history import that keeps failing no longer reruns the synchronous session pass at every launch: the marker is written once the session copies succeed and records a pending import, which later launches retry alone, at most three times. The import still starts first and runs independently of the session copies. --- config/main-sync-fs-baseline.txt | 2 +- .../legacy-prompt-history-import.ts | 31 ++++++ .../runtime-home-legacy-migration.test.ts | 22 ++++- .../runtime-home-service-legacy-migration.ts | 94 ++++++++++++++----- 4 files changed, 117 insertions(+), 32 deletions(-) diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 9de6342021fe..cb2b7009908f 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -128,7 +128,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -13 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +14 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index f59a4e2b4199..211efc404b6f 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -7,6 +7,37 @@ import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/te type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] +/** Launches that try the history import before it gives up; account histories stay either way. */ +export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 + +export type LegacyMigrationMarker = { + completedAt?: number + migratedHomeCount?: number + historyImportPending?: true + historyImportAttempts?: number +} + +export function parseLegacyMigrationMarker(text: string): LegacyMigrationMarker { + const parsed: unknown = JSON.parse(text) + const marker: LegacyMigrationMarker = {} + if (!parsed || typeof parsed !== 'object') { + return marker + } + if ('completedAt' in parsed && typeof parsed.completedAt === 'number') { + marker.completedAt = parsed.completedAt + } + if ('migratedHomeCount' in parsed && typeof parsed.migratedHomeCount === 'number') { + marker.migratedHomeCount = parsed.migratedHomeCount + } + if ('historyImportPending' in parsed && parsed.historyImportPending === true) { + marker.historyImportPending = true + } + if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') { + marker.historyImportAttempts = parsed.historyImportAttempts + } + return marker +} + async function pathExists(path: string): Promise { try { await lstat(path) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 209b70fb80c4..dceb44a5ed2b 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -77,10 +77,15 @@ async function startService(): Promise { await waitForMigrationMarker() } +// Settled: marked, and the history import no longer pending. async function waitForMigrationMarker(): Promise { - await vi.waitFor(() => expect(existsSync(migrationMarkerPath())).toBe(true), { - timeout: WAIT_MS - }) + await vi.waitFor( + () => { + expect(existsSync(migrationMarkerPath())).toBe(true) + expect(readFileSync(migrationMarkerPath(), 'utf-8')).not.toContain('historyImportPending') + }, + { timeout: WAIT_MS } + ) } // Slow CI hosts take seconds to construct the service. @@ -238,7 +243,7 @@ describe('CodexRuntimeHomeService', () => { ) }) - it('retries a failed import on the next launch', async () => { + it('retries only the failed history import on the next launch, not the session copies', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') fsHooks.afterRead.set(join(managedHomePath, 'history.jsonl'), () => { @@ -246,15 +251,22 @@ describe('CodexRuntimeHomeService', () => { }) await constructService() await waitForImportOutcomes(['failed']) + await vi.waitFor( + () => + expect(readFileSync(migrationMarkerPath(), 'utf-8')).toContain('"historyImportAttempts":1'), + { timeout: WAIT_MS } + ) expect(existsSync(runtimeHistoryPath)).toBe(false) - expect(existsSync(migrationMarkerPath())).toBe(false) fsHooks.afterRead.clear() + mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'later.jsonl'), '{}', 'utf-8') vi.resetModules() await startService() expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') expect(trackedImportOutcomes()).toEqual(['failed', 'imported']) + expect(existsSync(join(getRuntimeCodexHomePath(), 'sessions', 'later.jsonl'))).toBe(false) }) it('does not re-run migration when marker already exists', async () => { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 3a53bad052d8..a07f8634e12a 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -15,7 +15,12 @@ import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-mi import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' -import { importLegacyHistoriesIfSharedAbsent } from './legacy-prompt-history-import' +import { + importLegacyHistoriesIfSharedAbsent, + MAX_HISTORY_IMPORT_ATTEMPTS, + parseLegacyMigrationMarker, + type LegacyMigrationMarker +} from './legacy-prompt-history-import' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { @@ -58,21 +63,18 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - if (existsSync(this.getMigrationMarkerPath())) { + const existingMarker = this.readMigrationMarker() + if (existingMarker) { + if (existingMarker.historyImportPending) { + void this.importLegacyHistory().then((imported) => + this.recordHistoryImport(existingMarker, imported) + ) + } return } // Started first and independent of the session copies, so one that fails can't hold it back. - const historyImported = importLegacyHistoriesIfSharedAbsent( - this.getManagedAccountsRoot(), - join(this.getRuntimeHomePath(), 'history.jsonl') - ).then( - () => true, - (error: unknown) => { - console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) - return false - } - ) + const historyImported = this.importLegacyHistory() const managedHomes = this.getLegacyManagedHomes() for (const managedHomePath of managedHomes) { const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( @@ -83,20 +85,60 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } } - void historyImported.then((imported) => { - if (!imported) { - return - } - try { - // Mark completion so later startups cannot replay stale managed-home state. - writeFileAtomically( - this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` - ) - } catch (error) { - console.warn('[codex-runtime-home] Failed to mark legacy Codex migration complete:', error) - } - }) + // Marked before the history import settles: an import that keeps failing retries alone, never + // the session pass above. + const marker: LegacyMigrationMarker = { + completedAt: Date.now(), + migratedHomeCount: managedHomes.length, + historyImportPending: true + } + this.writeMigrationMarker(marker) + void historyImported.then((imported) => this.recordHistoryImport(marker, imported)) + } + + // Off the startup path; never rejects. + protected async importLegacyHistory(): Promise { + try { + await importLegacyHistoriesIfSharedAbsent( + this.getManagedAccountsRoot(), + join(this.getRuntimeHomePath(), 'history.jsonl') + ) + return true + } catch (error) { + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) + return false + } + } + + // Account histories are only read, so giving up after a few failed launches loses nothing. + protected recordHistoryImport(marker: LegacyMigrationMarker, imported: boolean): void { + const attempts = (marker.historyImportAttempts ?? 0) + 1 + const { historyImportPending: _pending, historyImportAttempts: _attempts, ...settled } = marker + try { + this.writeMigrationMarker( + imported || attempts >= MAX_HISTORY_IMPORT_ATTEMPTS + ? settled + : { ...marker, historyImportAttempts: attempts } + ) + } catch (error) { + console.warn('[codex-runtime-home] Failed to record legacy Codex history import:', error) + } + } + + protected readMigrationMarker(): LegacyMigrationMarker | null { + if (!existsSync(this.getMigrationMarkerPath())) { + return null + } + try { + return parseLegacyMigrationMarker(readFileSync(this.getMigrationMarkerPath(), 'utf-8')) + } catch { + // An unreadable marker still means the one-time migration ran. + return {} + } + } + + protected writeMigrationMarker(marker: LegacyMigrationMarker): void { + writeFileAtomically(this.getMigrationMarkerPath(), `${JSON.stringify(marker)}\n`) } protected getLegacyManagedHomes(): string[] { From 392a18ff66c958efa4379a232ab0f76c84f03f73 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:55:16 -0800 Subject: [PATCH 14/30] fix(codex): read linked account histories; ignore account folders without a home folder --- .../legacy-prompt-history-import.ts | 10 +++++---- .../runtime-home-legacy-migration.test.ts | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 211efc404b6f..b9d558ce76a0 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto' -import { link, lstat, open, readFile, readdir, rm } from 'node:fs/promises' +import { link, lstat, open, readFile, readdir, rm, stat } from 'node:fs/promises' import { join } from 'node:path' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { track } from '../../../telemetry/client' @@ -61,9 +61,11 @@ async function listAccountHistories(accountsRoot: string): Promise { const paths: string[] = [] for (const account of accounts.filter((entry) => entry.isDirectory())) { const historyPath = join(accountsRoot, account.name, 'home', 'history.jsonl') - // Only a missing file means no history; any other error retries rather than skip an account. - const stats = await lstat(historyPath).catch((error: unknown) => { - if (errnoCodeOrUnknown(error) === 'ENOENT') { + // Followed through a link, as Codex reads it. Only an absent file (or no home folder) means no + // history; any other error retries rather than skip an account. + const stats = await stat(historyPath).catch((error: unknown) => { + const code = errnoCodeOrUnknown(error) + if (code === 'ENOENT' || code === 'ENOTDIR') { return null } throw error diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index dceb44a5ed2b..c4d52da13c62 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -189,6 +189,27 @@ describe('CodexRuntimeHomeService', () => { expect(trackedImportOutcomes()).toEqual(['imported']) }) + it('imports a linked account history and ignores an account folder without a home folder', async () => { + const elsewhere = join(testState.userDataDir, 'elsewhere-history.jsonl') + writeFileSync(elsewhere, '{"id":"linked-1"}\n', 'utf-8') + const managedHomePath = createManagedAuth( + testState.userDataDir, + 'account-1', + '{"account":"managed"}\n' + ) + symlinkSync(elsewhere, join(managedHomePath, 'history.jsonl')) + const orphan = join(testState.userDataDir, 'codex-accounts', 'orphan') + mkdirSync(orphan, { recursive: true }) + writeFileSync(join(orphan, 'home'), 'not a folder', 'utf-8') + + await startService() + + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + '{"id":"linked-1"}\n' + ) + expect(readFileSync(elsewhere, 'utf-8')).toBe('{"id":"linked-1"}\n') + }) + it('never writes an existing shared history, and account removal keeps the account history', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}', 'utf-8') From 75dee20042efdcb57e37cbe3c616273bf17dcac5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:12:31 -0800 Subject: [PATCH 15/30] fix(codex): mark the migration done only once history settles; keep a linked history's target migration-v1.json, the only marker older builds read, is written once the history import has landed or been skipped, so a downgrade after an interrupted first launch still owes the import. Session completion and retry state live in migration-v1-sessions.json. An import that gave up retries once the account histories change. Account removal (host and WSL) also keeps what a linked history.jsonl points to inside the home. --- config/main-blocking-helper-baseline.txt | 2 +- config/main-sync-fs-baseline.txt | 2 +- .../codex-managed-home-lifecycle.test.ts | 13 +++ .../codex-managed-home-lifecycle.ts | 23 ++++- .../legacy-prompt-history-import.ts | 37 +++++--- .../runtime-home-legacy-migration.test.ts | 38 ++++++-- .../runtime-home-service-legacy-migration.ts | 91 ++++++++++++------- 7 files changed, 149 insertions(+), 57 deletions(-) diff --git a/config/main-blocking-helper-baseline.txt b/config/main-blocking-helper-baseline.txt index eb869b6a8870..bc27d446b591 100644 --- a/config/main-blocking-helper-baseline.txt +++ b/config/main-blocking-helper-baseline.txt @@ -271,7 +271,7 @@ 4 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 19 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts -2 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +3 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 11 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts # Codex launch prep from #43365 already merged; unblocks main, async follow-up owed 9 src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts 8 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index cb2b7009908f..5276ff1bfcf9 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -128,7 +128,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -14 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +15 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index 6864a2d058a1..d919b965ab89 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -69,6 +69,19 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { expect(readFileSync(join(f.home, 'sessions', 'rollout.jsonl'), 'utf8')).toBe('only copy\n') }) + it('keeps what a linked prompt history points to inside the home', async () => { + const f = fixture() + mkdirSync(join(f.home, 'backup')) + writeFileSync(join(f.home, 'backup', 'prompts.jsonl'), '{"text":"only prompt"}\n') + symlinkSync(join(f.home, 'backup', 'prompts.jsonl'), join(f.home, 'history.jsonl')) + writeFileSync(join(f.home, 'auth.json'), '{}') + + await f.lifecycle.safeRemove(f.home, 'a') + + expect(readdirSync(f.home).sort()).toEqual(['backup', 'history.jsonl']) + expect(readFileSync(join(f.home, 'history.jsonl'), 'utf8')).toBe('{"text":"only prompt"}\n') + }) + it('removes a home that never shared history entirely', async () => { const f = fixture() writeFileSync(join(f.home, 'auth.json'), '{}') diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index efc80c2c5159..6b640352e055 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -1,6 +1,6 @@ import { mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync, type Dirent } from 'node:fs' -import { readdir, rm } from 'node:fs/promises' -import { join, resolve, sep } from 'node:path' +import { readdir, realpath, rm } from 'node:fs/promises' +import { isAbsolute, join, relative, resolve, sep } from 'node:path' import { isDefinitiveAbsence } from '../../../shared/errors/definitive-filesystem-absence' import { WINDOWS_RM_MAX_RETRIES, @@ -43,7 +43,13 @@ const KEPT_HISTORY = [ const KEEP_ON_REMOVAL_SCRIPT = [ 'set -u', 'home=$1', + // A linked prompt history keeps the folder entry inside the home that holds what it points to. + 'real_home=$(readlink -f -- "$home" 2>/dev/null || printf %s "$home")', + 'history_target=$(readlink -f -- "$home/history.jsonl" 2>/dev/null || true)', + 'history_entry=', + 'case "$history_target" in "$real_home"/?*) rest=${history_target#"$real_home"/}; history_entry=${rest%%/*} ;; esac', 'kept() {', + ' if [ -n "$history_entry" ] && [ "${1##*/}" = "$history_entry" ]; then return 0; fi', ' case "${1##*/}" in', ' *.orca-profile-merge) return 0 ;;', ` ${KEPT_HISTORY.join(' | ')}) return 0 ;;`, @@ -70,11 +76,24 @@ const KEEP_ON_REMOVAL_SCRIPT = [ * Deletes the login and private state but keeps shared history; true when anything was kept. * Links are removed one by one first, so no recursive delete ever meets a Windows junction. */ +// The top-level entry holding what a linked history.jsonl points to, when that is inside the home. +async function linkedHistoryEntry(home: string): Promise { + try { + const target = await realpath(join(home, 'history.jsonl')) + const inside = relative(await realpath(home), target) + return inside && !inside.startsWith('..') && !isAbsolute(inside) ? inside.split(sep)[0] : null + } catch { + return null + } +} + async function removeManagedHomeKeepingSharedHistory(home: string): Promise { const entries = await readdir(home, { withFileTypes: true }) const sharedOnce = entries.some((entry) => entry.name === HISTORY_CLEANUP_MANIFEST) + const historyEntry = await linkedHistoryEntry(home) const kept = (entry: Dirent): boolean => KEPT_HISTORY.includes(entry.name) || + entry.name === historyEntry || entry.name.endsWith(MERGE_PENDING_SUFFIX) || (sharedOnce && entry.isFile() && CODEX_DATABASE_FILE.test(entry.name)) for (const entry of entries.filter((candidate) => !kept(candidate))) { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index b9d558ce76a0..84a7fa3980ed 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -7,35 +7,46 @@ import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/te type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] -/** Launches that try the history import before it gives up; account histories stay either way. */ +/** Failed launches before the import waits for the account histories to change. */ export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 -export type LegacyMigrationMarker = { +export type LegacyMigrationState = { completedAt?: number migratedHomeCount?: number - historyImportPending?: true historyImportAttempts?: number + /** The account histories' sizes and times when the import last gave up. */ + historyImportInputs?: string } -export function parseLegacyMigrationMarker(text: string): LegacyMigrationMarker { +export function parseLegacyMigrationState(text: string): LegacyMigrationState { const parsed: unknown = JSON.parse(text) - const marker: LegacyMigrationMarker = {} + const state: LegacyMigrationState = {} if (!parsed || typeof parsed !== 'object') { - return marker + return state } if ('completedAt' in parsed && typeof parsed.completedAt === 'number') { - marker.completedAt = parsed.completedAt + state.completedAt = parsed.completedAt } if ('migratedHomeCount' in parsed && typeof parsed.migratedHomeCount === 'number') { - marker.migratedHomeCount = parsed.migratedHomeCount - } - if ('historyImportPending' in parsed && parsed.historyImportPending === true) { - marker.historyImportPending = true + state.migratedHomeCount = parsed.migratedHomeCount } if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') { - marker.historyImportAttempts = parsed.historyImportAttempts + state.historyImportAttempts = parsed.historyImportAttempts + } + if ('historyImportInputs' in parsed && typeof parsed.historyImportInputs === 'string') { + state.historyImportInputs = parsed.historyImportInputs + } + return state +} + +/** Stats only: cheap enough to ask at every launch whether the account histories changed. */ +export async function legacyHistoryInputsKey(accountsRoot: string): Promise { + const parts: string[] = [] + for (const historyPath of await listAccountHistories(accountsRoot)) { + const stats = await stat(historyPath) + parts.push(`${historyPath}:${stats.size}:${stats.mtimeMs}`) } - return marker + return parts.join('|') } async function pathExists(path: string): Promise { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index c4d52da13c62..efcc8ca01fa7 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -77,15 +77,15 @@ async function startService(): Promise { await waitForMigrationMarker() } -// Settled: marked, and the history import no longer pending. +// Settled: the history import landed or was skipped, so the one-time migration is marked done. async function waitForMigrationMarker(): Promise { - await vi.waitFor( - () => { - expect(existsSync(migrationMarkerPath())).toBe(true) - expect(readFileSync(migrationMarkerPath(), 'utf-8')).not.toContain('historyImportPending') - }, - { timeout: WAIT_MS } - ) + await vi.waitFor(() => expect(existsSync(migrationMarkerPath())).toBe(true), { + timeout: WAIT_MS + }) +} + +function sessionsMigratedStatePath(): string { + return join(testState.userDataDir, 'codex-runtime-home', 'migration-v1-sessions.json') } // Slow CI hosts take seconds to construct the service. @@ -274,10 +274,14 @@ describe('CodexRuntimeHomeService', () => { await waitForImportOutcomes(['failed']) await vi.waitFor( () => - expect(readFileSync(migrationMarkerPath(), 'utf-8')).toContain('"historyImportAttempts":1'), + expect(readFileSync(sessionsMigratedStatePath(), 'utf-8')).toContain( + '"historyImportAttempts":1' + ), { timeout: WAIT_MS } ) expect(existsSync(runtimeHistoryPath)).toBe(false) + // An older build only checks this marker: it must still owe the history import. + expect(existsSync(migrationMarkerPath())).toBe(false) fsHooks.afterRead.clear() mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) writeFileSync(join(managedHomePath, 'sessions', 'later.jsonl'), '{}', 'utf-8') @@ -290,6 +294,22 @@ describe('CodexRuntimeHomeService', () => { expect(existsSync(join(getRuntimeCodexHomePath(), 'sessions', 'later.jsonl'))).toBe(false) }) + it('retries an import it gave up on once the account history changed', async () => { + writeHistory('account-1', '{"id":"legacy-1"}\n') + mkdirSync(join(sessionsMigratedStatePath(), '..'), { recursive: true }) + writeFileSync( + sessionsMigratedStatePath(), + JSON.stringify({ historyImportAttempts: 3, historyImportInputs: 'before the change' }), + 'utf-8' + ) + + await startService() + + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + '{"id":"legacy-1"}\n' + ) + }) + it('does not re-run migration when marker already exists', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index a07f8634e12a..d7866114699b 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -17,9 +17,10 @@ import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' import { importLegacyHistoriesIfSharedAbsent, + legacyHistoryInputsKey, MAX_HISTORY_IMPORT_ATTEMPTS, - parseLegacyMigrationMarker, - type LegacyMigrationMarker + parseLegacyMigrationState, + type LegacyMigrationState } from './legacy-prompt-history-import' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { @@ -63,13 +64,14 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - const existingMarker = this.readMigrationMarker() - if (existingMarker) { - if (existingMarker.historyImportPending) { - void this.importLegacyHistory().then((imported) => - this.recordHistoryImport(existingMarker, imported) - ) - } + // Written only once history settles: an older build sees it alone, and must not skip a history + // import still owed (its account removal deletes history.jsonl). + if (existsSync(this.getMigrationMarkerPath())) { + return + } + const sessionsDone = this.readSessionsMigratedState() + if (sessionsDone) { + void this.retryLegacyHistoryImport(sessionsDone) return } @@ -85,15 +87,26 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } } - // Marked before the history import settles: an import that keeps failing retries alone, never - // the session pass above. - const marker: LegacyMigrationMarker = { + // Recorded apart from the history import: one that keeps failing retries alone, never the + // session pass above. + const state: LegacyMigrationState = { completedAt: Date.now(), - migratedHomeCount: managedHomes.length, - historyImportPending: true + migratedHomeCount: managedHomes.length + } + this.writeSessionsMigratedState(state) + void historyImported.then((imported) => this.recordHistoryImport(state, imported)) + } + + // After a few failed launches, only a change to the account histories earns another attempt. + protected async retryLegacyHistoryImport(state: LegacyMigrationState): Promise { + if ((state.historyImportAttempts ?? 0) >= MAX_HISTORY_IMPORT_ATTEMPTS) { + const inputs = await legacyHistoryInputsKey(this.getManagedAccountsRoot()).catch(() => null) + if (inputs === null || inputs === state.historyImportInputs) { + return + } + state = { ...state, historyImportAttempts: 0 } } - this.writeMigrationMarker(marker) - void historyImported.then((imported) => this.recordHistoryImport(marker, imported)) + await this.recordHistoryImport(state, await this.importLegacyHistory()) } // Off the startup path; never rejects. @@ -110,35 +123,51 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } } - // Account histories are only read, so giving up after a few failed launches loses nothing. - protected recordHistoryImport(marker: LegacyMigrationMarker, imported: boolean): void { - const attempts = (marker.historyImportAttempts ?? 0) + 1 - const { historyImportPending: _pending, historyImportAttempts: _attempts, ...settled } = marker + protected async recordHistoryImport( + state: LegacyMigrationState, + imported: boolean + ): Promise { try { - this.writeMigrationMarker( - imported || attempts >= MAX_HISTORY_IMPORT_ATTEMPTS - ? settled - : { ...marker, historyImportAttempts: attempts } - ) + if (imported) { + writeFileAtomically( + this.getMigrationMarkerPath(), + `${JSON.stringify({ completedAt: state.completedAt, migratedHomeCount: state.migratedHomeCount })}\n` + ) + return + } + const attempts = (state.historyImportAttempts ?? 0) + 1 + const historyImportInputs = + attempts >= MAX_HISTORY_IMPORT_ATTEMPTS + ? await legacyHistoryInputsKey(this.getManagedAccountsRoot()).catch(() => undefined) + : undefined + this.writeSessionsMigratedState({ + ...state, + historyImportAttempts: attempts, + historyImportInputs + }) } catch (error) { console.warn('[codex-runtime-home] Failed to record legacy Codex history import:', error) } } - protected readMigrationMarker(): LegacyMigrationMarker | null { - if (!existsSync(this.getMigrationMarkerPath())) { + protected getSessionsMigratedStatePath(): string { + return join(this.getRuntimeMetadataDir(), 'migration-v1-sessions.json') + } + + protected readSessionsMigratedState(): LegacyMigrationState | null { + if (!existsSync(this.getSessionsMigratedStatePath())) { return null } try { - return parseLegacyMigrationMarker(readFileSync(this.getMigrationMarkerPath(), 'utf-8')) + return parseLegacyMigrationState(readFileSync(this.getSessionsMigratedStatePath(), 'utf-8')) } catch { - // An unreadable marker still means the one-time migration ran. + // Unreadable: the sessions pass still ran; the history import retries from scratch. return {} } } - protected writeMigrationMarker(marker: LegacyMigrationMarker): void { - writeFileAtomically(this.getMigrationMarkerPath(), `${JSON.stringify(marker)}\n`) + protected writeSessionsMigratedState(state: LegacyMigrationState): void { + writeFileAtomically(this.getSessionsMigratedStatePath(), `${JSON.stringify(state)}\n`) } protected getLegacyManagedHomes(): string[] { From 7caad8a59878698772e4f076d23908a8288c6903 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:26:49 -0800 Subject: [PATCH 16/30] fix(codex): keep every entry a linked prompt history passes through; retry a given-up import daily --- .../codex-managed-home-lifecycle.test.ts | 11 ++--- .../codex-managed-home-lifecycle.ts | 44 ++++++++++--------- .../managed-homes/linked-history-entries.ts | 39 ++++++++++++++++ .../legacy-prompt-history-import.ts | 6 +++ .../runtime-home-legacy-migration.test.ts | 23 ++++++++++ .../runtime-home-service-legacy-migration.ts | 25 +++++++---- 6 files changed, 115 insertions(+), 33 deletions(-) create mode 100644 src/main/codex-accounts/managed-homes/linked-history-entries.ts diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index d919b965ab89..8b38136bc27f 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -69,16 +69,17 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { expect(readFileSync(join(f.home, 'sessions', 'rollout.jsonl'), 'utf8')).toBe('only copy\n') }) - it('keeps what a linked prompt history points to inside the home', async () => { + it('keeps every entry a linked prompt history passes through inside the home', async () => { const f = fixture() - mkdirSync(join(f.home, 'backup')) - writeFileSync(join(f.home, 'backup', 'prompts.jsonl'), '{"text":"only prompt"}\n') - symlinkSync(join(f.home, 'backup', 'prompts.jsonl'), join(f.home, 'history.jsonl')) + mkdirSync(join(f.home, '..backup')) + writeFileSync(join(f.home, '..backup', 'prompts.jsonl'), '{"text":"only prompt"}\n') + symlinkSync('..backup', join(f.home, 'current')) + symlinkSync(join('current', 'prompts.jsonl'), join(f.home, 'history.jsonl')) writeFileSync(join(f.home, 'auth.json'), '{}') await f.lifecycle.safeRemove(f.home, 'a') - expect(readdirSync(f.home).sort()).toEqual(['backup', 'history.jsonl']) + expect(readdirSync(f.home).sort()).toEqual(['..backup', 'current', 'history.jsonl']) expect(readFileSync(join(f.home, 'history.jsonl'), 'utf8')).toBe('{"text":"only prompt"}\n') }) diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index 6b640352e055..1bb6e8c11747 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -1,6 +1,6 @@ import { mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync, type Dirent } from 'node:fs' -import { readdir, realpath, rm } from 'node:fs/promises' -import { isAbsolute, join, relative, resolve, sep } from 'node:path' +import { readdir, rm } from 'node:fs/promises' +import { join, resolve, sep } from 'node:path' import { isDefinitiveAbsence } from '../../../shared/errors/definitive-filesystem-absence' import { WINDOWS_RM_MAX_RETRIES, @@ -15,6 +15,7 @@ import type { } from '../account-management/codex-account-service-types' import { writeFileAtomically } from '../../filesystem/atomic-file-publication' import { MERGE_PENDING_SUFFIX, removeDirectoryLink } from '../../filesystem/merged-directory-link' +import { linkedHistoryEntries } from './linked-history-entries' import { CODEX_DATABASE_FILE, HISTORY_CLEANUP_MANIFEST, @@ -43,13 +44,27 @@ const KEPT_HISTORY = [ const KEEP_ON_REMOVAL_SCRIPT = [ 'set -u', 'home=$1', - // A linked prompt history keeps the folder entry inside the home that holds what it points to. + // A linked prompt history keeps every top-level entry it reaches: each link and the final file. 'real_home=$(readlink -f -- "$home" 2>/dev/null || printf %s "$home")', - 'history_target=$(readlink -f -- "$home/history.jsonl" 2>/dev/null || true)', - 'history_entry=', - 'case "$history_target" in "$real_home"/?*) rest=${history_target#"$real_home"/}; history_entry=${rest%%/*} ;; esac', + 'history_entries=/', + 'keep_entry() {', + ' for root in "$home" "$real_home"; do', + ' case "$1" in "$root"/?*) rest=${1#"$root"/}; first=${rest%%/*}', + ' case "$first" in .|..) ;; *) history_entries="$history_entries$first/"; return ;; esac ;; esac', + ' done', + '}', + 'path="$home/history.jsonl"', + 'hop=0', + 'while [ -L "$path" ] && [ "$hop" -lt 40 ]; do', + ' next=$(readlink -- "$path") || break', + ' case "$next" in /*) path=$next ;; *) path=${path%/*}/$next ;; esac', + ' keep_entry "$path"', + ' hop=$((hop + 1))', + 'done', + 'final=$(readlink -f -- "$home/history.jsonl" 2>/dev/null || true)', + '[ -n "$final" ] && keep_entry "$final"', 'kept() {', - ' if [ -n "$history_entry" ] && [ "${1##*/}" = "$history_entry" ]; then return 0; fi', + ' case "$history_entries" in *"/${1##*/}/"*) return 0 ;; esac', ' case "${1##*/}" in', ' *.orca-profile-merge) return 0 ;;', ` ${KEPT_HISTORY.join(' | ')}) return 0 ;;`, @@ -76,24 +91,13 @@ const KEEP_ON_REMOVAL_SCRIPT = [ * Deletes the login and private state but keeps shared history; true when anything was kept. * Links are removed one by one first, so no recursive delete ever meets a Windows junction. */ -// The top-level entry holding what a linked history.jsonl points to, when that is inside the home. -async function linkedHistoryEntry(home: string): Promise { - try { - const target = await realpath(join(home, 'history.jsonl')) - const inside = relative(await realpath(home), target) - return inside && !inside.startsWith('..') && !isAbsolute(inside) ? inside.split(sep)[0] : null - } catch { - return null - } -} - async function removeManagedHomeKeepingSharedHistory(home: string): Promise { const entries = await readdir(home, { withFileTypes: true }) const sharedOnce = entries.some((entry) => entry.name === HISTORY_CLEANUP_MANIFEST) - const historyEntry = await linkedHistoryEntry(home) + const historyEntries = await linkedHistoryEntries(home) const kept = (entry: Dirent): boolean => KEPT_HISTORY.includes(entry.name) || - entry.name === historyEntry || + historyEntries.has(entry.name) || entry.name.endsWith(MERGE_PENDING_SUFFIX) || (sharedOnce && entry.isFile() && CODEX_DATABASE_FILE.test(entry.name)) for (const entry of entries.filter((candidate) => !kept(candidate))) { diff --git a/src/main/codex-accounts/managed-homes/linked-history-entries.ts b/src/main/codex-accounts/managed-homes/linked-history-entries.ts new file mode 100644 index 000000000000..646814f2954f --- /dev/null +++ b/src/main/codex-accounts/managed-homes/linked-history-entries.ts @@ -0,0 +1,39 @@ +import { lstat, readlink, realpath } from 'node:fs/promises' +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' + +const MAX_HISTORY_LINK_HOPS = 40 + +// The top-level entries a linked history.jsonl reaches inside the home: every link on the way and +// the file it resolves to, so removal keeps them all. +export async function linkedHistoryEntries(home: string): Promise> { + const entries = new Set() + const roots = [home, await realpath(home).catch(() => home)] + const keepTopEntry = (path: string): void => { + for (const root of roots) { + const inside = relative(root, path) + const first = inside.split(sep)[0] + if (inside && first !== '..' && !isAbsolute(inside)) { + entries.add(first) + return + } + } + } + let path = join(home, 'history.jsonl') + for (let hop = 0; hop < MAX_HISTORY_LINK_HOPS; hop++) { + const stats = await lstat(path).catch(() => null) + if (!stats?.isSymbolicLink()) { + break + } + const next = await readlink(path).catch(() => null) + if (next === null) { + break + } + path = resolve(dirname(path), next) + keepTopEntry(path) + } + const target = await realpath(join(home, 'history.jsonl')).catch(() => null) + if (target) { + keepTopEntry(target) + } + return entries +} diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 84a7fa3980ed..f6f599029b6b 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -9,6 +9,8 @@ type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[ /** Failed launches before the import waits for the account histories to change. */ export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 +/** How long a given-up import waits before trying again with unchanged account histories. */ +export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 export type LegacyMigrationState = { completedAt?: number @@ -16,6 +18,7 @@ export type LegacyMigrationState = { historyImportAttempts?: number /** The account histories' sizes and times when the import last gave up. */ historyImportInputs?: string + historyImportGaveUpAt?: number } export function parseLegacyMigrationState(text: string): LegacyMigrationState { @@ -36,6 +39,9 @@ export function parseLegacyMigrationState(text: string): LegacyMigrationState { if ('historyImportInputs' in parsed && typeof parsed.historyImportInputs === 'string') { state.historyImportInputs = parsed.historyImportInputs } + if ('historyImportGaveUpAt' in parsed && typeof parsed.historyImportGaveUpAt === 'number') { + state.historyImportGaveUpAt = parsed.historyImportGaveUpAt + } return state } diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index efcc8ca01fa7..03391f754d77 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -310,6 +310,29 @@ describe('CodexRuntimeHomeService', () => { ) }) + it('retries an import it gave up on a day later when nothing changed', async () => { + writeHistory('account-1', '{"id":"legacy-1"}\n') + const { legacyHistoryInputsKey } = await import('./legacy-prompt-history-import') + mkdirSync(join(sessionsMigratedStatePath(), '..'), { recursive: true }) + writeFileSync( + sessionsMigratedStatePath(), + JSON.stringify({ + historyImportAttempts: 3, + historyImportInputs: await legacyHistoryInputsKey( + join(testState.userDataDir, 'codex-accounts') + ), + historyImportGaveUpAt: Date.now() - 25 * 60 * 60 * 1000 + }), + 'utf-8' + ) + + await startService() + + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + '{"id":"legacy-1"}\n' + ) + }) + it('does not re-run migration when marker already exists', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index d7866114699b..67049176a515 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -18,6 +18,7 @@ import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' import { importLegacyHistoriesIfSharedAbsent, legacyHistoryInputsKey, + HISTORY_IMPORT_RETRY_INTERVAL_MS, MAX_HISTORY_IMPORT_ATTEMPTS, parseLegacyMigrationState, type LegacyMigrationState @@ -97,14 +98,21 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa void historyImported.then((imported) => this.recordHistoryImport(state, imported)) } - // After a few failed launches, only a change to the account histories earns another attempt. + // After a few failed launches, a change to the account histories or a day's wait earns another + // attempt, so a failure that clears (permissions, a mount) still imports. protected async retryLegacyHistoryImport(state: LegacyMigrationState): Promise { if ((state.historyImportAttempts ?? 0) >= MAX_HISTORY_IMPORT_ATTEMPTS) { const inputs = await legacyHistoryInputsKey(this.getManagedAccountsRoot()).catch(() => null) - if (inputs === null || inputs === state.historyImportInputs) { + if (inputs !== null && inputs !== state.historyImportInputs) { + state = { ...state, historyImportAttempts: 0 } + } else if ( + Date.now() - (state.historyImportGaveUpAt ?? 0) < + HISTORY_IMPORT_RETRY_INTERVAL_MS + ) { return + } else { + state = { ...state, historyImportAttempts: MAX_HISTORY_IMPORT_ATTEMPTS - 1 } } - state = { ...state, historyImportAttempts: 0 } } await this.recordHistoryImport(state, await this.importLegacyHistory()) } @@ -136,14 +144,15 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return } const attempts = (state.historyImportAttempts ?? 0) + 1 - const historyImportInputs = - attempts >= MAX_HISTORY_IMPORT_ATTEMPTS - ? await legacyHistoryInputsKey(this.getManagedAccountsRoot()).catch(() => undefined) - : undefined + const gaveUp = attempts >= MAX_HISTORY_IMPORT_ATTEMPTS + const historyImportInputs = gaveUp + ? await legacyHistoryInputsKey(this.getManagedAccountsRoot()).catch(() => undefined) + : undefined this.writeSessionsMigratedState({ ...state, historyImportAttempts: attempts, - historyImportInputs + historyImportInputs, + historyImportGaveUpAt: gaveUp ? Date.now() : undefined }) } catch (error) { console.warn('[codex-runtime-home] Failed to record legacy Codex history import:', error) From 351c00fba42dfd7b1491f772f401015e40174714 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:39:15 -0800 Subject: [PATCH 17/30] fix(codex): follow a linked prompt history one component at a time; stop removal on any step it can't read --- .../codex-managed-home-lifecycle.test.ts | 30 ++++- .../codex-managed-home-lifecycle.ts | 22 +--- .../managed-homes/linked-history-entries.ts | 108 +++++++++++++++--- .../runtime-home-legacy-migration.test.ts | 2 +- 4 files changed, 120 insertions(+), 42 deletions(-) diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index 8b38136bc27f..60c4f9bd98f4 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -1,4 +1,5 @@ import { + chmodSync, existsSync, mkdirSync, mkdtempSync, @@ -73,16 +74,39 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { const f = fixture() mkdirSync(join(f.home, '..backup')) writeFileSync(join(f.home, '..backup', 'prompts.jsonl'), '{"text":"only prompt"}\n') - symlinkSync('..backup', join(f.home, 'current')) - symlinkSync(join('current', 'prompts.jsonl'), join(f.home, 'history.jsonl')) + mkdirSync(join(f.home, 'middle')) + symlinkSync(join('..', '..backup'), join(f.home, 'middle', 'next')) + symlinkSync(join('middle', 'next'), join(f.home, 'bridge')) + symlinkSync(join('bridge', 'prompts.jsonl'), join(f.home, 'history.jsonl')) writeFileSync(join(f.home, 'auth.json'), '{}') await f.lifecycle.safeRemove(f.home, 'a') - expect(readdirSync(f.home).sort()).toEqual(['..backup', 'current', 'history.jsonl']) + expect(readdirSync(f.home).sort()).toEqual(['..backup', 'bridge', 'history.jsonl', 'middle']) expect(readFileSync(join(f.home, 'history.jsonl'), 'utf8')).toBe('{"text":"only prompt"}\n') }) + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'removes nothing when a linked prompt history cannot be followed', + async () => { + const f = fixture() + const outside = join(f.accountsRoot, 'outside') + mkdirSync(outside) + writeFileSync(join(f.home, 'prompts.saved'), '{"text":"only prompt"}\n') + symlinkSync(join(f.home, 'prompts.saved'), join(outside, 'link')) + symlinkSync(join(outside, 'link'), join(f.home, 'history.jsonl')) + writeFileSync(join(f.home, 'auth.json'), '{}') + chmodSync(outside, 0o000) + try { + await f.lifecycle.safeRemove(f.home, 'a') + } finally { + chmodSync(outside, 0o755) + } + + expect(readdirSync(f.home).sort()).toEqual(['auth.json', 'history.jsonl', 'prompts.saved']) + } + ) + it('removes a home that never shared history entirely', async () => { const f = fixture() writeFileSync(join(f.home, 'auth.json'), '{}') diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index 1bb6e8c11747..a8111abcfc14 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -15,7 +15,7 @@ import type { } from '../account-management/codex-account-service-types' import { writeFileAtomically } from '../../filesystem/atomic-file-publication' import { MERGE_PENDING_SUFFIX, removeDirectoryLink } from '../../filesystem/merged-directory-link' -import { linkedHistoryEntries } from './linked-history-entries' +import { LINKED_HISTORY_ENTRIES_SCRIPT, linkedHistoryEntries } from './linked-history-entries' import { CODEX_DATABASE_FILE, HISTORY_CLEANUP_MANIFEST, @@ -44,25 +44,7 @@ const KEPT_HISTORY = [ const KEEP_ON_REMOVAL_SCRIPT = [ 'set -u', 'home=$1', - // A linked prompt history keeps every top-level entry it reaches: each link and the final file. - 'real_home=$(readlink -f -- "$home" 2>/dev/null || printf %s "$home")', - 'history_entries=/', - 'keep_entry() {', - ' for root in "$home" "$real_home"; do', - ' case "$1" in "$root"/?*) rest=${1#"$root"/}; first=${rest%%/*}', - ' case "$first" in .|..) ;; *) history_entries="$history_entries$first/"; return ;; esac ;; esac', - ' done', - '}', - 'path="$home/history.jsonl"', - 'hop=0', - 'while [ -L "$path" ] && [ "$hop" -lt 40 ]; do', - ' next=$(readlink -- "$path") || break', - ' case "$next" in /*) path=$next ;; *) path=${path%/*}/$next ;; esac', - ' keep_entry "$path"', - ' hop=$((hop + 1))', - 'done', - 'final=$(readlink -f -- "$home/history.jsonl" 2>/dev/null || true)', - '[ -n "$final" ] && keep_entry "$final"', + ...LINKED_HISTORY_ENTRIES_SCRIPT, 'kept() {', ' case "$history_entries" in *"/${1##*/}/"*) return 0 ;; esac', ' case "${1##*/}" in', diff --git a/src/main/codex-accounts/managed-homes/linked-history-entries.ts b/src/main/codex-accounts/managed-homes/linked-history-entries.ts index 646814f2954f..5043d58d9a1c 100644 --- a/src/main/codex-accounts/managed-homes/linked-history-entries.ts +++ b/src/main/codex-accounts/managed-homes/linked-history-entries.ts @@ -1,15 +1,39 @@ +import type { Stats } from 'node:fs' import { lstat, readlink, realpath } from 'node:fs/promises' -import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' +import { dirname, isAbsolute, join, parse, relative, sep } from 'node:path' +import { errnoCodeOrUnknown } from '../../../shared/errors/errno-code' const MAX_HISTORY_LINK_HOPS = 40 -// The top-level entries a linked history.jsonl reaches inside the home: every link on the way and -// the file it resolves to, so removal keeps them all. +async function lstatIfPresent(path: string): Promise { + try { + return await lstat(path) + } catch (error) { + const code = errnoCodeOrUnknown(error) + if (code === 'ENOENT' || code === 'ENOTDIR') { + return null + } + throw error + } +} + +function pathComponents(path: string): string[] { + return path.slice(parse(path).root.length).split(/[\\/]/) +} + +/** + * The top-level entries a linked history.jsonl passes through inside the home, one path component + * at a time: every link and folder on the way and the file it reaches, so removal keeps them all. + * Throws when a step can't be read, so removal stops instead of deleting what it couldn't follow. + */ export async function linkedHistoryEntries(home: string): Promise> { const entries = new Set() - const roots = [home, await realpath(home).catch(() => home)] + if (!(await lstatIfPresent(join(home, 'history.jsonl')))?.isSymbolicLink()) { + return entries + } + const realHome = await realpath(home) const keepTopEntry = (path: string): void => { - for (const root of roots) { + for (const root of [realHome, home]) { const inside = relative(root, path) const first = inside.split(sep)[0] if (inside && first !== '..' && !isAbsolute(inside)) { @@ -18,22 +42,70 @@ export async function linkedHistoryEntries(home: string): Promise> { } } } - let path = join(home, 'history.jsonl') - for (let hop = 0; hop < MAX_HISTORY_LINK_HOPS; hop++) { - const stats = await lstat(path).catch(() => null) - if (!stats?.isSymbolicLink()) { - break + let dir = realHome + let pending = ['history.jsonl'] + let hops = 0 + while (pending.length > 0) { + const name = pending.shift() + if (!name || name === '.') { + continue } - const next = await readlink(path).catch(() => null) - if (next === null) { - break + if (name === '..') { + dir = dirname(dir) + continue } - path = resolve(dirname(path), next) + const path = join(dir, name) keepTopEntry(path) - } - const target = await realpath(join(home, 'history.jsonl')).catch(() => null) - if (target) { - keepTopEntry(target) + const stats = await lstatIfPresent(path) + if (!stats) { + // Nothing exists past a missing step, so nothing more needs keeping. + return entries + } + if (!stats.isSymbolicLink()) { + dir = path + continue + } + if (++hops > MAX_HISTORY_LINK_HOPS) { + throw new Error('Too many links on the way to the prompt history') + } + const target = await readlink(path) + if (isAbsolute(target)) { + dir = parse(target).root + } + pending = [...pathComponents(target), ...pending] } return entries } + +/** + * The same walk for a WSL home, as bash lines run with the home in $home: collects the entries into + * $history_entries ("/a/b/"), and exits nonzero on any step it can't read. + */ +export const LINKED_HISTORY_ENTRIES_SCRIPT = [ + 'real_home=$(cd -P -- "$home" && pwd) || exit 1', + 'history_entries=/', + 'keep_entry() {', + ' for root in "$real_home" "$home"; do', + ' case "$1" in "$root"/?*) inside=${1#"$root"/}; first=${inside%%/*}', + ' case "$first" in .|..) ;; *) history_entries="$history_entries$first/"; return ;; esac ;; esac', + ' done', + '}', + 'if [ -L "$home/history.jsonl" ]; then', + ' dir=$real_home; rest=history.jsonl; hops=0', + ' while [ -n "$rest" ]; do', + ' case "$rest" in */*) name=${rest%%/*}; rest=${rest#*/} ;; *) name=$rest; rest= ;; esac', + ' case "$name" in "" | .) continue ;; ..) dir=${dir%/*}; dir=${dir:-/}; continue ;; esac', + ' next=${dir%/}/$name', + ' keep_entry "$next"', + ' if [ -L "$next" ]; then', + ' hops=$((hops + 1)); [ "$hops" -le 40 ] || exit 1', + ' target=$(readlink -- "$next") || exit 1', + ' case "$target" in /*) dir=/ ;; esac', + ' rest=$target${rest:+/$rest}', + ' elif [ -e "$next" ]; then dir=$next', + ' elif [ -x "$dir" ]; then break', + ' else exit 1', + ' fi', + ' done', + 'fi' +] diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 03391f754d77..32225e6774e4 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -321,7 +321,7 @@ describe('CodexRuntimeHomeService', () => { historyImportInputs: await legacyHistoryInputsKey( join(testState.userDataDir, 'codex-accounts') ), - historyImportGaveUpAt: Date.now() - 25 * 60 * 60 * 1000 + historyImportGaveUpAt: 0 }), 'utf-8' ) From deddf1f4434f927a8433dd4e01bc1be49020cd0b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:53:55 -0800 Subject: [PATCH 18/30] fix(codex): preserve each account history in the runtime home, then mark the migration done An older build checks only migration-v1.json. Writing it after the session pass keeps that build from rerunning its overwriting migration, and the preserved copies (exclusive create, never overwritten) mean its account removal can't take the only copy of prompts the import hasn't merged. The import reads the preserved copies too, and its completion is tracked in migration-v1-sessions.json. --- .../legacy-history-import-attempts.ts | 114 ++++++++++++++ .../legacy-prompt-history-import.ts | 61 +++----- .../runtime-home-legacy-migration.test.ts | 66 ++++++-- .../runtime-home-service-legacy-migration.ts | 147 ++++++++++-------- 4 files changed, 272 insertions(+), 116 deletions(-) create mode 100644 src/main/codex-accounts/runtime-home/legacy-host/legacy-history-import-attempts.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-import-attempts.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-import-attempts.ts new file mode 100644 index 000000000000..95a3284cacc1 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-import-attempts.ts @@ -0,0 +1,114 @@ +import { + importLegacyHistoriesIfSharedAbsent, + legacyHistoryInputsKey +} from './legacy-prompt-history-import' + +/** Failed launches before the import waits for the account histories to change. */ +export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 +/** How long a given-up import waits before trying again with unchanged account histories. */ +export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 + +export type LegacyMigrationState = { + completedAt?: number + migratedHomeCount?: number + historyImportAttempts?: number + /** The account histories' sizes and times when the import last gave up. */ + historyImportInputs?: string + historyImportGaveUpAt?: number + /** The shared history was created, or already existed, so nothing is owed. */ + historyImportSettled?: boolean +} + +export function parseLegacyMigrationState(text: string): LegacyMigrationState { + const parsed: unknown = JSON.parse(text) + const state: LegacyMigrationState = {} + if (!parsed || typeof parsed !== 'object') { + return state + } + if ('completedAt' in parsed && typeof parsed.completedAt === 'number') { + state.completedAt = parsed.completedAt + } + if ('migratedHomeCount' in parsed && typeof parsed.migratedHomeCount === 'number') { + state.migratedHomeCount = parsed.migratedHomeCount + } + if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') { + state.historyImportAttempts = parsed.historyImportAttempts + } + if ('historyImportInputs' in parsed && typeof parsed.historyImportInputs === 'string') { + state.historyImportInputs = parsed.historyImportInputs + } + if ('historyImportSettled' in parsed && typeof parsed.historyImportSettled === 'boolean') { + state.historyImportSettled = parsed.historyImportSettled + } + if ('historyImportGaveUpAt' in parsed && typeof parsed.historyImportGaveUpAt === 'number') { + state.historyImportGaveUpAt = parsed.historyImportGaveUpAt + } + return state +} + +/** Where the import reads and writes, and how its attempts are recorded. */ +export type LegacyHistoryImportTarget = { + accountsRoot: string + runtimeHistoryPath: string + writeState: (state: LegacyMigrationState) => void +} + +/** Off the startup path; never rejects. */ +export async function attemptLegacyHistoryImport( + target: LegacyHistoryImportTarget +): Promise { + try { + await importLegacyHistoriesIfSharedAbsent(target.accountsRoot, target.runtimeHistoryPath) + return true + } catch (error) { + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) + return false + } +} + +/** + * After a few failed launches, a change to the account histories or a day's wait earns another + * attempt, so a failure that clears (permissions, a mount) still imports. + */ +export async function retryLegacyHistoryImport( + target: LegacyHistoryImportTarget, + state: LegacyMigrationState +): Promise { + if ((state.historyImportAttempts ?? 0) >= MAX_HISTORY_IMPORT_ATTEMPTS) { + const inputs = await legacyHistoryInputsKey(target.accountsRoot).catch(() => null) + if (inputs !== null && inputs !== state.historyImportInputs) { + state = { ...state, historyImportAttempts: 0 } + } else if (Date.now() - (state.historyImportGaveUpAt ?? 0) < HISTORY_IMPORT_RETRY_INTERVAL_MS) { + return + } else { + state = { ...state, historyImportAttempts: MAX_HISTORY_IMPORT_ATTEMPTS - 1 } + } + } + await recordLegacyHistoryImport(target, state, await attemptLegacyHistoryImport(target)) +} + +export async function recordLegacyHistoryImport( + target: LegacyHistoryImportTarget, + state: LegacyMigrationState, + imported: boolean +): Promise { + try { + if (imported) { + target.writeState({ ...state, historyImportSettled: true }) + return + } + const attempts = (state.historyImportAttempts ?? 0) + 1 + const gaveUp = attempts >= MAX_HISTORY_IMPORT_ATTEMPTS + const historyImportInputs = gaveUp + ? await legacyHistoryInputsKey(target.accountsRoot).catch(() => undefined) + : undefined + target.writeState({ + ...state, + historyImportAttempts: attempts, + historyImportInputs, + historyImportGaveUpAt: gaveUp ? Date.now() : undefined + }) + } catch (error) { + console.warn('[codex-runtime-home] Failed to record legacy Codex history import:', error) + } +} diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index f6f599029b6b..21f1ce1869a7 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,50 +1,12 @@ import { randomUUID } from 'node:crypto' import { link, lstat, open, readFile, readdir, rm, stat } from 'node:fs/promises' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { track } from '../../../telemetry/client' import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas' type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] -/** Failed launches before the import waits for the account histories to change. */ -export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 -/** How long a given-up import waits before trying again with unchanged account histories. */ -export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 - -export type LegacyMigrationState = { - completedAt?: number - migratedHomeCount?: number - historyImportAttempts?: number - /** The account histories' sizes and times when the import last gave up. */ - historyImportInputs?: string - historyImportGaveUpAt?: number -} - -export function parseLegacyMigrationState(text: string): LegacyMigrationState { - const parsed: unknown = JSON.parse(text) - const state: LegacyMigrationState = {} - if (!parsed || typeof parsed !== 'object') { - return state - } - if ('completedAt' in parsed && typeof parsed.completedAt === 'number') { - state.completedAt = parsed.completedAt - } - if ('migratedHomeCount' in parsed && typeof parsed.migratedHomeCount === 'number') { - state.migratedHomeCount = parsed.migratedHomeCount - } - if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') { - state.historyImportAttempts = parsed.historyImportAttempts - } - if ('historyImportInputs' in parsed && typeof parsed.historyImportInputs === 'string') { - state.historyImportInputs = parsed.historyImportInputs - } - if ('historyImportGaveUpAt' in parsed && typeof parsed.historyImportGaveUpAt === 'number') { - state.historyImportGaveUpAt = parsed.historyImportGaveUpAt - } - return state -} - /** Stats only: cheap enough to ask at every launch whether the account histories changed. */ export async function legacyHistoryInputsKey(accountsRoot: string): Promise { const parts: string[] = [] @@ -94,6 +56,22 @@ async function listAccountHistories(accountsRoot: string): Promise { return paths.sort() } +const PRESERVED_HISTORY_NAME = /^history\.orca-legacy-.+\.jsonl$/ + +// The account histories the migration preserved in the runtime home, which outlive the accounts. +async function listPreservedHistories(runtimeHome: string): Promise { + const entries = await readdir(runtimeHome, { withFileTypes: true }).catch((error: unknown) => { + if (errnoCodeOrUnknown(error) === 'ENOENT') { + return [] + } + throw error + }) + return entries + .filter((entry) => entry.isFile() && PRESERVED_HISTORY_NAME.test(entry.name)) + .map((entry) => join(runtimeHome, entry.name)) + .sort() +} + /** * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one * is created from the account histories, which are only read, and never over one Codex creates @@ -103,7 +81,10 @@ export async function importLegacyHistoriesIfSharedAbsent( accountsRoot: string, runtimeHistoryPath: string ): Promise { - const accountHistoryPaths = await listAccountHistories(accountsRoot) + const accountHistoryPaths = [ + ...(await listAccountHistories(accountsRoot)), + ...(await listPreservedHistories(dirname(runtimeHistoryPath))) + ] if (accountHistoryPaths.length === 0) { return } diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 32225e6774e4..3d2c152483a8 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -74,14 +74,22 @@ async function constructService(): Promise { async function startService(): Promise { await constructService() - await waitForMigrationMarker() + await waitForHistorySettled() } -// Settled: the history import landed or was skipped, so the one-time migration is marked done. -async function waitForMigrationMarker(): Promise { - await vi.waitFor(() => expect(existsSync(migrationMarkerPath())).toBe(true), { - timeout: WAIT_MS - }) +// Settled: the history import landed or was skipped, so nothing more is owed. +async function waitForHistorySettled(): Promise { + await vi.waitFor( + () => + expect(readFileSync(sessionsMigratedStatePath(), 'utf-8')).toContain( + '"historyImportSettled":true' + ), + { timeout: WAIT_MS } + ) +} + +function preservedHistoryPath(accountId: string): string { + return join(getRuntimeCodexHomePath(), `history.orca-legacy-${accountId}.jsonl`) } function sessionsMigratedStatePath(): string { @@ -166,7 +174,7 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) - await waitForMigrationMarker() + await waitForHistorySettled() expect(normalizeLinkTarget(readlinkSync(legacyActiveHomePath))).toBe( normalizeLinkTarget(getRuntimeCodexHomePath()) @@ -225,6 +233,44 @@ describe('CodexRuntimeHomeService', () => { ) }) + it('preserves each account history in the runtime home before marking the migration done', async () => { + const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') + writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}\n', 'utf-8') + writeFileSync(preservedHistoryPath('account-1'), '{"id":"older-copy"}\n', 'utf-8') + writeHistory('account-1', '{"id":"legacy-1"}\n') + + await startService() + + // An older build sees only this marker: it must not rerun its overwriting migration, and its + // account removal must not take the only copy of these prompts. + expect(existsSync(migrationMarkerPath())).toBe(true) + expect(readFileSync(preservedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"older-copy"}\n') + expect( + readFileSync( + join(getRuntimeCodexHomePath(), 'history.orca-legacy-account-1-1.jsonl'), + 'utf-8' + ) + ).toBe('{"id":"legacy-1"}\n') + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}\n') + }) + + it('imports from the preserved history once the account folder is gone', async () => { + mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) + writeFileSync(preservedHistoryPath('account-1'), '{"id":"legacy-1"}\n', 'utf-8') + mkdirSync(join(sessionsMigratedStatePath(), '..'), { recursive: true }) + writeFileSync( + sessionsMigratedStatePath(), + JSON.stringify({ historyImportAttempts: 1 }), + 'utf-8' + ) + + await startService() + + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + '{"id":"legacy-1"}\n' + ) + }) + it('imports history even when a session copy fails', async () => { const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') blockSessionCopies(managedHomePath) @@ -280,8 +326,6 @@ describe('CodexRuntimeHomeService', () => { { timeout: WAIT_MS } ) expect(existsSync(runtimeHistoryPath)).toBe(false) - // An older build only checks this marker: it must still owe the history import. - expect(existsSync(migrationMarkerPath())).toBe(false) fsHooks.afterRead.clear() mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) writeFileSync(join(managedHomePath, 'sessions', 'later.jsonl'), '{}', 'utf-8') @@ -370,7 +414,7 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) - await waitForMigrationMarker() + await waitForHistorySettled() expect(readFileSync(join(runtimeSessionsDir, 'session.json'), 'utf-8')).toBe('{"turns":[1]}') expect( @@ -409,7 +453,7 @@ describe('CodexRuntimeHomeService', () => { const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) - await waitForMigrationMarker() + await waitForHistorySettled() expect(readFileSync(occupiedPreservedPath, 'utf-8')).toBe('{"turns":["kept"]}') expect( diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 67049176a515..9219afdf9d18 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -6,7 +6,9 @@ import { mkdirSync, readFileSync, readdirSync, - statSync + realpathSync, + statSync, + type Dirent } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' @@ -16,13 +18,29 @@ import { normalizeCodexRuntimeSelection } from '../../account-management/runtime import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' import { - importLegacyHistoriesIfSharedAbsent, - legacyHistoryInputsKey, - HISTORY_IMPORT_RETRY_INTERVAL_MS, - MAX_HISTORY_IMPORT_ATTEMPTS, + attemptLegacyHistoryImport, parseLegacyMigrationState, + recordLegacyHistoryImport, + retryLegacyHistoryImport, + type LegacyHistoryImportTarget, type LegacyMigrationState -} from './legacy-prompt-history-import' +} from './legacy-history-import-attempts' + +function realpathIfPresent(path: string): string | null { + try { + return realpathSync(path) + } catch (error) { + const code = errnoCodeOrUnknown(error) + if (code === 'ENOENT' || code === 'ENOTDIR') { + return null + } + throw error + } +} + +function byName(a: Dirent, b: Dirent): number { + return a.name < b.name ? -1 : a.name > b.name ? 1 : 0 +} export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { @@ -65,19 +83,22 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - // Written only once history settles: an older build sees it alone, and must not skip a history - // import still owed (its account removal deletes history.jsonl). - if (existsSync(this.getMigrationMarkerPath())) { + const migrated = this.readSessionsMigratedState() + if (migrated) { + this.writeMigrationMarkerIfAbsent(migrated) + if (!migrated.historyImportSettled) { + void retryLegacyHistoryImport(this.legacyHistoryImportTarget(), migrated) + } return } - const sessionsDone = this.readSessionsMigratedState() - if (sessionsDone) { - void this.retryLegacyHistoryImport(sessionsDone) + // Migrated by an older build. + if (existsSync(this.getMigrationMarkerPath())) { return } // Started first and independent of the session copies, so one that fails can't hold it back. - const historyImported = this.importLegacyHistory() + const historyImport = this.legacyHistoryImportTarget() + const historyImported = attemptLegacyHistoryImport(historyImport) const managedHomes = this.getLegacyManagedHomes() for (const managedHomePath of managedHomes) { const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( @@ -87,75 +108,62 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa this.migrateLegacySessions(managedHomePath, accountId) } } + this.preserveLegacyHistories() // Recorded apart from the history import: one that keeps failing retries alone, never the - // session pass above. + // passes above. const state: LegacyMigrationState = { completedAt: Date.now(), migratedHomeCount: managedHomes.length } this.writeSessionsMigratedState(state) - void historyImported.then((imported) => this.recordHistoryImport(state, imported)) + // Safe for an older build to see now: with every account history preserved, its account + // removal can't take the only copy, and it must not rerun its overwriting migration. + this.writeMigrationMarkerIfAbsent(state) + void historyImported.then((imported) => + recordLegacyHistoryImport(historyImport, state, imported) + ) } - // After a few failed launches, a change to the account histories or a day's wait earns another - // attempt, so a failure that clears (permissions, a mount) still imports. - protected async retryLegacyHistoryImport(state: LegacyMigrationState): Promise { - if ((state.historyImportAttempts ?? 0) >= MAX_HISTORY_IMPORT_ATTEMPTS) { - const inputs = await legacyHistoryInputsKey(this.getManagedAccountsRoot()).catch(() => null) - if (inputs !== null && inputs !== state.historyImportInputs) { - state = { ...state, historyImportAttempts: 0 } - } else if ( - Date.now() - (state.historyImportGaveUpAt ?? 0) < - HISTORY_IMPORT_RETRY_INTERVAL_MS - ) { - return - } else { - state = { ...state, historyImportAttempts: MAX_HISTORY_IMPORT_ATTEMPTS - 1 } + // Every account's own history, kept in the runtime home where no Orca path deletes it. + protected preserveLegacyHistories(): void { + const runtimeHistoryPath = join(this.getRuntimeHomePath(), 'history.jsonl') + const sharedHistory = realpathIfPresent(runtimeHistoryPath) + const preserved = new Set() + const accountsRoot = this.getManagedAccountsRoot() + const accounts = existsSync(accountsRoot) + ? readdirSync(accountsRoot, { withFileTypes: true }) + : [] + for (const account of accounts.filter((entry) => entry.isDirectory()).sort(byName)) { + const historyPath = join(accountsRoot, account.name, 'home', 'history.jsonl') + const source = realpathIfPresent(historyPath) + if (!source || source === sharedHistory || preserved.has(source)) { + continue + } + if (!statSync(source).isFile()) { + continue } + preserved.add(source) + let contents: Buffer | null = null + const readLegacy = (): Buffer => (contents ??= readFileSync(source)) + this.copyToFreePreservedName(source, runtimeHistoryPath, account.name, readLegacy) } - await this.recordHistoryImport(state, await this.importLegacyHistory()) } - // Off the startup path; never rejects. - protected async importLegacyHistory(): Promise { - try { - await importLegacyHistoriesIfSharedAbsent( - this.getManagedAccountsRoot(), - join(this.getRuntimeHomePath(), 'history.jsonl') + protected writeMigrationMarkerIfAbsent(state: LegacyMigrationState): void { + if (!existsSync(this.getMigrationMarkerPath())) { + writeFileAtomically( + this.getMigrationMarkerPath(), + `${JSON.stringify({ completedAt: state.completedAt, migratedHomeCount: state.migratedHomeCount })}\n` ) - return true - } catch (error) { - console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) - return false } } - protected async recordHistoryImport( - state: LegacyMigrationState, - imported: boolean - ): Promise { - try { - if (imported) { - writeFileAtomically( - this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: state.completedAt, migratedHomeCount: state.migratedHomeCount })}\n` - ) - return - } - const attempts = (state.historyImportAttempts ?? 0) + 1 - const gaveUp = attempts >= MAX_HISTORY_IMPORT_ATTEMPTS - const historyImportInputs = gaveUp - ? await legacyHistoryInputsKey(this.getManagedAccountsRoot()).catch(() => undefined) - : undefined - this.writeSessionsMigratedState({ - ...state, - historyImportAttempts: attempts, - historyImportInputs, - historyImportGaveUpAt: gaveUp ? Date.now() : undefined - }) - } catch (error) { - console.warn('[codex-runtime-home] Failed to record legacy Codex history import:', error) + protected legacyHistoryImportTarget(): LegacyHistoryImportTarget { + return { + accountsRoot: this.getManagedAccountsRoot(), + runtimeHistoryPath: join(this.getRuntimeHomePath(), 'history.jsonl'), + writeState: (state) => this.writeSessionsMigratedState(state) } } @@ -243,6 +251,15 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa ) { return { path: targetPath, preserved: false } } + return this.copyToFreePreservedName(legacyFilePath, targetPath, accountId, readLegacy) + } + + protected copyToFreePreservedName( + legacyFilePath: string, + targetPath: string, + accountId: string, + readLegacy: () => Buffer + ): { path: string; preserved: boolean } { for (let attempt = 0; ; attempt++) { const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath, readLegacy) From 0c1abd940ae739337e1160a57ec6ea8e346e32a7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:05:54 -0800 Subject: [PATCH 19/30] fix(codex): preserve account histories off the main thread, before marking the migration done The history migration runs async and independent of the session pass: it copies each account history into the runtime home, then writes migration-v1.json once the session pass has also finished, then imports the shared history until it settles. Its state lives in its own migration-v1-history.json, so it never races the session pass's record. --- config/main-blocking-helper-baseline.txt | 2 +- config/main-sync-fs-baseline.txt | 2 +- .../legacy-history-import-attempts.ts | 114 --------- .../legacy-host/legacy-history-migration.ts | 227 ++++++++++++++++++ .../runtime-home-legacy-migration.test.ts | 27 ++- .../runtime-home-service-legacy-migration.ts | 138 ++--------- 6 files changed, 262 insertions(+), 248 deletions(-) delete mode 100644 src/main/codex-accounts/runtime-home/legacy-host/legacy-history-import-attempts.ts create mode 100644 src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts diff --git a/config/main-blocking-helper-baseline.txt b/config/main-blocking-helper-baseline.txt index bc27d446b591..eb869b6a8870 100644 --- a/config/main-blocking-helper-baseline.txt +++ b/config/main-blocking-helper-baseline.txt @@ -271,7 +271,7 @@ 4 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 19 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts -3 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +2 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 11 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts # Codex launch prep from #43365 already merged; unblocks main, async follow-up owed 9 src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts 8 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 5276ff1bfcf9..cb2b7009908f 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -128,7 +128,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -15 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +14 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-import-attempts.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-import-attempts.ts deleted file mode 100644 index 95a3284cacc1..000000000000 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-import-attempts.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { - importLegacyHistoriesIfSharedAbsent, - legacyHistoryInputsKey -} from './legacy-prompt-history-import' - -/** Failed launches before the import waits for the account histories to change. */ -export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 -/** How long a given-up import waits before trying again with unchanged account histories. */ -export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 - -export type LegacyMigrationState = { - completedAt?: number - migratedHomeCount?: number - historyImportAttempts?: number - /** The account histories' sizes and times when the import last gave up. */ - historyImportInputs?: string - historyImportGaveUpAt?: number - /** The shared history was created, or already existed, so nothing is owed. */ - historyImportSettled?: boolean -} - -export function parseLegacyMigrationState(text: string): LegacyMigrationState { - const parsed: unknown = JSON.parse(text) - const state: LegacyMigrationState = {} - if (!parsed || typeof parsed !== 'object') { - return state - } - if ('completedAt' in parsed && typeof parsed.completedAt === 'number') { - state.completedAt = parsed.completedAt - } - if ('migratedHomeCount' in parsed && typeof parsed.migratedHomeCount === 'number') { - state.migratedHomeCount = parsed.migratedHomeCount - } - if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') { - state.historyImportAttempts = parsed.historyImportAttempts - } - if ('historyImportInputs' in parsed && typeof parsed.historyImportInputs === 'string') { - state.historyImportInputs = parsed.historyImportInputs - } - if ('historyImportSettled' in parsed && typeof parsed.historyImportSettled === 'boolean') { - state.historyImportSettled = parsed.historyImportSettled - } - if ('historyImportGaveUpAt' in parsed && typeof parsed.historyImportGaveUpAt === 'number') { - state.historyImportGaveUpAt = parsed.historyImportGaveUpAt - } - return state -} - -/** Where the import reads and writes, and how its attempts are recorded. */ -export type LegacyHistoryImportTarget = { - accountsRoot: string - runtimeHistoryPath: string - writeState: (state: LegacyMigrationState) => void -} - -/** Off the startup path; never rejects. */ -export async function attemptLegacyHistoryImport( - target: LegacyHistoryImportTarget -): Promise { - try { - await importLegacyHistoriesIfSharedAbsent(target.accountsRoot, target.runtimeHistoryPath) - return true - } catch (error) { - console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) - return false - } -} - -/** - * After a few failed launches, a change to the account histories or a day's wait earns another - * attempt, so a failure that clears (permissions, a mount) still imports. - */ -export async function retryLegacyHistoryImport( - target: LegacyHistoryImportTarget, - state: LegacyMigrationState -): Promise { - if ((state.historyImportAttempts ?? 0) >= MAX_HISTORY_IMPORT_ATTEMPTS) { - const inputs = await legacyHistoryInputsKey(target.accountsRoot).catch(() => null) - if (inputs !== null && inputs !== state.historyImportInputs) { - state = { ...state, historyImportAttempts: 0 } - } else if (Date.now() - (state.historyImportGaveUpAt ?? 0) < HISTORY_IMPORT_RETRY_INTERVAL_MS) { - return - } else { - state = { ...state, historyImportAttempts: MAX_HISTORY_IMPORT_ATTEMPTS - 1 } - } - } - await recordLegacyHistoryImport(target, state, await attemptLegacyHistoryImport(target)) -} - -export async function recordLegacyHistoryImport( - target: LegacyHistoryImportTarget, - state: LegacyMigrationState, - imported: boolean -): Promise { - try { - if (imported) { - target.writeState({ ...state, historyImportSettled: true }) - return - } - const attempts = (state.historyImportAttempts ?? 0) + 1 - const gaveUp = attempts >= MAX_HISTORY_IMPORT_ATTEMPTS - const historyImportInputs = gaveUp - ? await legacyHistoryInputsKey(target.accountsRoot).catch(() => undefined) - : undefined - target.writeState({ - ...state, - historyImportAttempts: attempts, - historyImportInputs, - historyImportGaveUpAt: gaveUp ? Date.now() : undefined - }) - } catch (error) { - console.warn('[codex-runtime-home] Failed to record legacy Codex history import:', error) - } -} diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts new file mode 100644 index 000000000000..8c63393a4610 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -0,0 +1,227 @@ +import { randomUUID } from 'node:crypto' +import { constants } from 'node:fs' +import { + access, + copyFile, + readFile, + readdir, + realpath, + rename, + rm, + stat, + writeFile +} from 'node:fs/promises' +import { join } from 'node:path' +import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' +import { + importLegacyHistoriesIfSharedAbsent, + legacyHistoryInputsKey +} from './legacy-prompt-history-import' + +/** Failed launches before the import waits for the account histories to change. */ +export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 +/** How long a given-up import waits before trying again with unchanged account histories. */ +export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 + +type LegacyHistoryState = { + /** Every account history has a copy in the runtime home. */ + historiesPreserved?: boolean + /** The shared history was created, or already existed, so nothing is owed. */ + historyImportSettled?: boolean + historyImportAttempts?: number + /** The account histories' sizes and times when the import last gave up. */ + historyImportInputs?: string + historyImportGaveUpAt?: number +} + +/** Where the legacy history migration reads and records its work. */ +export type LegacyHistoryMigrationPaths = { + accountsRoot: string + runtimeHistoryPath: string + statePath: string + /** Written once the session pass finishes; its contents become the migration marker. */ + sessionsStatePath: string + /** The only marker older builds read. */ + markerPath: string +} + +function parseLegacyHistoryState(text: string): LegacyHistoryState { + const parsed: unknown = JSON.parse(text) + const state: LegacyHistoryState = {} + if (!parsed || typeof parsed !== 'object') { + return state + } + if ('historiesPreserved' in parsed && parsed.historiesPreserved === true) { + state.historiesPreserved = true + } + if ('historyImportSettled' in parsed && parsed.historyImportSettled === true) { + state.historyImportSettled = true + } + if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') { + state.historyImportAttempts = parsed.historyImportAttempts + } + if ('historyImportInputs' in parsed && typeof parsed.historyImportInputs === 'string') { + state.historyImportInputs = parsed.historyImportInputs + } + if ('historyImportGaveUpAt' in parsed && typeof parsed.historyImportGaveUpAt === 'number') { + state.historyImportGaveUpAt = parsed.historyImportGaveUpAt + } + return state +} + +async function readTextIfPresent(path: string): Promise { + try { + return await readFile(path, 'utf-8') + } catch (error) { + if (errnoCodeOrUnknown(error) === 'ENOENT') { + return null + } + throw error + } +} + +async function writeTextAtomically(path: string, text: string): Promise { + const tmpPath = `${path}.${process.pid}.${randomUUID()}.tmp` + try { + await writeFile(tmpPath, text, { encoding: 'utf-8', flag: 'wx' }) + await rename(tmpPath, path) + } finally { + await rm(tmpPath, { force: true }) + } +} + +async function realpathIfPresent(path: string): Promise { + try { + return await realpath(path) + } catch (error) { + const code = errnoCodeOrUnknown(error) + if (code === 'ENOENT' || code === 'ENOTDIR') { + return null + } + throw error + } +} + +/** Exclusive create never replaces or writes through a name; same bytes there count as copied. */ +async function copyIntoFreeName(source: string, targetPath: string): Promise { + try { + await copyFile(source, targetPath, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE) + return true + } catch (error) { + if (errnoCodeOrUnknown(error) !== 'EEXIST') { + throw error + } + } + try { + return (await readFile(targetPath)).equals(await readFile(source)) + } catch { + // A dangling link or directory at this name still occupies it. + return false + } +} + +// Every account's own history, copied into the runtime home where no Orca path deletes it, so an +// older build's account removal can never take the only copy. +async function preserveLegacyHistories( + accountsRoot: string, + runtimeHistoryPath: string +): Promise { + const accounts = await readdir(accountsRoot, { withFileTypes: true }).catch((error: unknown) => { + if (errnoCodeOrUnknown(error) === 'ENOENT') { + return [] + } + throw error + }) + const sharedHistory = await realpathIfPresent(runtimeHistoryPath) + const preserved = new Set() + const names = accounts.filter((entry) => entry.isDirectory()).map((entry) => entry.name) + for (const accountId of names.sort()) { + const source = await realpathIfPresent(join(accountsRoot, accountId, 'home', 'history.jsonl')) + if (!source || source === sharedHistory || preserved.has(source)) { + continue + } + if (!(await stat(source)).isFile()) { + continue + } + preserved.add(source) + const base = runtimeHistoryPath.replace(/\.jsonl$/, '') + for (let attempt = 0; ; attempt++) { + const suffix = attempt === 0 ? '' : `-${attempt}` + if (await copyIntoFreeName(source, `${base}.orca-legacy-${accountId}${suffix}.jsonl`)) { + break + } + } + } +} + +async function writeMarkerOnceSessionsDone(paths: LegacyHistoryMigrationPaths): Promise { + const sessionsState = await readTextIfPresent(paths.sessionsStatePath) + if (sessionsState === null) { + return + } + try { + await access(paths.markerPath) + } catch { + await writeTextAtomically(paths.markerPath, sessionsState) + } +} + +/** + * Off the startup path. Preserves the account histories, then marks the migration done for older + * builds (once the session pass also finished), then imports the shared history until it settles. + * Never rejects; whatever fails retries on a later launch. + */ +export async function settleLegacyHistory(paths: LegacyHistoryMigrationPaths): Promise { + try { + const text = await readTextIfPresent(paths.statePath) + let state = text === null ? {} : parseLegacyHistoryState(text) + if (!state.historiesPreserved) { + await preserveLegacyHistories(paths.accountsRoot, paths.runtimeHistoryPath) + state = { ...state, historiesPreserved: true } + await writeTextAtomically(paths.statePath, `${JSON.stringify(state)}\n`) + } + await writeMarkerOnceSessionsDone(paths) + if (!state.historyImportSettled) { + await retryLegacyHistoryImport(paths, state) + } + } catch (error) { + console.warn('[codex-runtime-home] Failed to migrate legacy Codex prompt history:', error) + } +} + +/** + * After a few failed launches, a change to the account histories or a day's wait earns another + * attempt, so a failure that clears (permissions, a mount) still imports. + */ +async function retryLegacyHistoryImport( + paths: LegacyHistoryMigrationPaths, + state: LegacyHistoryState +): Promise { + if ((state.historyImportAttempts ?? 0) >= MAX_HISTORY_IMPORT_ATTEMPTS) { + const inputs = await legacyHistoryInputsKey(paths.accountsRoot).catch(() => null) + if (inputs !== null && inputs !== state.historyImportInputs) { + state = { ...state, historyImportAttempts: 0 } + } else if (Date.now() - (state.historyImportGaveUpAt ?? 0) < HISTORY_IMPORT_RETRY_INTERVAL_MS) { + return + } else { + state = { ...state, historyImportAttempts: MAX_HISTORY_IMPORT_ATTEMPTS - 1 } + } + } + try { + await importLegacyHistoriesIfSharedAbsent(paths.accountsRoot, paths.runtimeHistoryPath) + state = { ...state, historyImportSettled: true } + } catch (error) { + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) + const attempts = (state.historyImportAttempts ?? 0) + 1 + const gaveUp = attempts >= MAX_HISTORY_IMPORT_ATTEMPTS + state = { + ...state, + historyImportAttempts: attempts, + historyImportInputs: gaveUp + ? await legacyHistoryInputsKey(paths.accountsRoot).catch(() => undefined) + : undefined, + historyImportGaveUpAt: gaveUp ? Date.now() : undefined + } + } + await writeTextAtomically(paths.statePath, `${JSON.stringify(state)}\n`) +} diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 3d2c152483a8..2cb8c485bea1 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -81,9 +81,7 @@ async function startService(): Promise { async function waitForHistorySettled(): Promise { await vi.waitFor( () => - expect(readFileSync(sessionsMigratedStatePath(), 'utf-8')).toContain( - '"historyImportSettled":true' - ), + expect(readFileSync(historyStatePath(), 'utf-8')).toContain('"historyImportSettled":true'), { timeout: WAIT_MS } ) } @@ -96,6 +94,10 @@ function sessionsMigratedStatePath(): string { return join(testState.userDataDir, 'codex-runtime-home', 'migration-v1-sessions.json') } +function historyStatePath(): string { + return join(testState.userDataDir, 'codex-runtime-home', 'migration-v1-history.json') +} + // Slow CI hosts take seconds to construct the service. const WAIT_MS = 20_000 @@ -257,10 +259,11 @@ describe('CodexRuntimeHomeService', () => { it('imports from the preserved history once the account folder is gone', async () => { mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) writeFileSync(preservedHistoryPath('account-1'), '{"id":"legacy-1"}\n', 'utf-8') - mkdirSync(join(sessionsMigratedStatePath(), '..'), { recursive: true }) + mkdirSync(join(historyStatePath(), '..'), { recursive: true }) + writeFileSync(sessionsMigratedStatePath(), '{}', 'utf-8') writeFileSync( - sessionsMigratedStatePath(), - JSON.stringify({ historyImportAttempts: 1 }), + historyStatePath(), + JSON.stringify({ historiesPreserved: true, historyImportAttempts: 1 }), 'utf-8' ) @@ -320,9 +323,7 @@ describe('CodexRuntimeHomeService', () => { await waitForImportOutcomes(['failed']) await vi.waitFor( () => - expect(readFileSync(sessionsMigratedStatePath(), 'utf-8')).toContain( - '"historyImportAttempts":1' - ), + expect(readFileSync(historyStatePath(), 'utf-8')).toContain('"historyImportAttempts":1'), { timeout: WAIT_MS } ) expect(existsSync(runtimeHistoryPath)).toBe(false) @@ -340,9 +341,9 @@ describe('CodexRuntimeHomeService', () => { it('retries an import it gave up on once the account history changed', async () => { writeHistory('account-1', '{"id":"legacy-1"}\n') - mkdirSync(join(sessionsMigratedStatePath(), '..'), { recursive: true }) + mkdirSync(join(historyStatePath(), '..'), { recursive: true }) writeFileSync( - sessionsMigratedStatePath(), + historyStatePath(), JSON.stringify({ historyImportAttempts: 3, historyImportInputs: 'before the change' }), 'utf-8' ) @@ -357,9 +358,9 @@ describe('CodexRuntimeHomeService', () => { it('retries an import it gave up on a day later when nothing changed', async () => { writeHistory('account-1', '{"id":"legacy-1"}\n') const { legacyHistoryInputsKey } = await import('./legacy-prompt-history-import') - mkdirSync(join(sessionsMigratedStatePath(), '..'), { recursive: true }) + mkdirSync(join(historyStatePath(), '..'), { recursive: true }) writeFileSync( - sessionsMigratedStatePath(), + historyStatePath(), JSON.stringify({ historyImportAttempts: 3, historyImportInputs: await legacyHistoryInputsKey( diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 9219afdf9d18..24df61dc0dd9 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -6,9 +6,7 @@ import { mkdirSync, readFileSync, readdirSync, - realpathSync, - statSync, - type Dirent + statSync } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' @@ -17,30 +15,7 @@ import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-mi import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' -import { - attemptLegacyHistoryImport, - parseLegacyMigrationState, - recordLegacyHistoryImport, - retryLegacyHistoryImport, - type LegacyHistoryImportTarget, - type LegacyMigrationState -} from './legacy-history-import-attempts' - -function realpathIfPresent(path: string): string | null { - try { - return realpathSync(path) - } catch (error) { - const code = errnoCodeOrUnknown(error) - if (code === 'ENOENT' || code === 'ENOTDIR') { - return null - } - throw error - } -} - -function byName(a: Dirent, b: Dirent): number { - return a.name < b.name ? -1 : a.name > b.name ? 1 : 0 -} +import { settleLegacyHistory } from './legacy-history-migration' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { @@ -83,22 +58,23 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - const migrated = this.readSessionsMigratedState() - if (migrated) { - this.writeMigrationMarkerIfAbsent(migrated) - if (!migrated.historyImportSettled) { - void retryLegacyHistoryImport(this.legacyHistoryImportTarget(), migrated) - } - return - } + const sessionsDone = existsSync(this.getSessionsMigratedStatePath()) // Migrated by an older build. - if (existsSync(this.getMigrationMarkerPath())) { + if (!sessionsDone && existsSync(this.getMigrationMarkerPath())) { return } // Started first and independent of the session copies, so one that fails can't hold it back. - const historyImport = this.legacyHistoryImportTarget() - const historyImported = attemptLegacyHistoryImport(historyImport) + void settleLegacyHistory({ + accountsRoot: this.getManagedAccountsRoot(), + runtimeHistoryPath: join(this.getRuntimeHomePath(), 'history.jsonl'), + statePath: join(this.getRuntimeMetadataDir(), 'migration-v1-history.json'), + sessionsStatePath: this.getSessionsMigratedStatePath(), + markerPath: this.getMigrationMarkerPath() + }) + if (sessionsDone) { + return + } const managedHomes = this.getLegacyManagedHomes() for (const managedHomePath of managedHomes) { const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( @@ -108,85 +84,18 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa this.migrateLegacySessions(managedHomePath, accountId) } } - this.preserveLegacyHistories() - - // Recorded apart from the history import: one that keeps failing retries alone, never the - // passes above. - const state: LegacyMigrationState = { - completedAt: Date.now(), - migratedHomeCount: managedHomes.length - } - this.writeSessionsMigratedState(state) - // Safe for an older build to see now: with every account history preserved, its account - // removal can't take the only copy, and it must not rerun its overwriting migration. - this.writeMigrationMarkerIfAbsent(state) - void historyImported.then((imported) => - recordLegacyHistoryImport(historyImport, state, imported) + // The history migration turns this into the marker older builds read, once it has preserved + // every account history: only then can't their account removal take the only copy. + writeFileAtomically( + this.getSessionsMigratedStatePath(), + `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` ) } - // Every account's own history, kept in the runtime home where no Orca path deletes it. - protected preserveLegacyHistories(): void { - const runtimeHistoryPath = join(this.getRuntimeHomePath(), 'history.jsonl') - const sharedHistory = realpathIfPresent(runtimeHistoryPath) - const preserved = new Set() - const accountsRoot = this.getManagedAccountsRoot() - const accounts = existsSync(accountsRoot) - ? readdirSync(accountsRoot, { withFileTypes: true }) - : [] - for (const account of accounts.filter((entry) => entry.isDirectory()).sort(byName)) { - const historyPath = join(accountsRoot, account.name, 'home', 'history.jsonl') - const source = realpathIfPresent(historyPath) - if (!source || source === sharedHistory || preserved.has(source)) { - continue - } - if (!statSync(source).isFile()) { - continue - } - preserved.add(source) - let contents: Buffer | null = null - const readLegacy = (): Buffer => (contents ??= readFileSync(source)) - this.copyToFreePreservedName(source, runtimeHistoryPath, account.name, readLegacy) - } - } - - protected writeMigrationMarkerIfAbsent(state: LegacyMigrationState): void { - if (!existsSync(this.getMigrationMarkerPath())) { - writeFileAtomically( - this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: state.completedAt, migratedHomeCount: state.migratedHomeCount })}\n` - ) - } - } - - protected legacyHistoryImportTarget(): LegacyHistoryImportTarget { - return { - accountsRoot: this.getManagedAccountsRoot(), - runtimeHistoryPath: join(this.getRuntimeHomePath(), 'history.jsonl'), - writeState: (state) => this.writeSessionsMigratedState(state) - } - } - protected getSessionsMigratedStatePath(): string { return join(this.getRuntimeMetadataDir(), 'migration-v1-sessions.json') } - protected readSessionsMigratedState(): LegacyMigrationState | null { - if (!existsSync(this.getSessionsMigratedStatePath())) { - return null - } - try { - return parseLegacyMigrationState(readFileSync(this.getSessionsMigratedStatePath(), 'utf-8')) - } catch { - // Unreadable: the sessions pass still ran; the history import retries from scratch. - return {} - } - } - - protected writeSessionsMigratedState(state: LegacyMigrationState): void { - writeFileAtomically(this.getSessionsMigratedStatePath(), `${JSON.stringify(state)}\n`) - } - protected getLegacyManagedHomes(): string[] { const managedAccountsRoot = this.getManagedAccountsRoot() if (!existsSync(managedAccountsRoot)) { @@ -251,15 +160,6 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa ) { return { path: targetPath, preserved: false } } - return this.copyToFreePreservedName(legacyFilePath, targetPath, accountId, readLegacy) - } - - protected copyToFreePreservedName( - legacyFilePath: string, - targetPath: string, - accountId: string, - readLegacy: () => Buffer - ): { path: string; preserved: boolean } { for (let attempt = 0; ; attempt++) { const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath, readLegacy) From 653270d8316754d5d4b69918153939b869c401d2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:30:53 -0800 Subject: [PATCH 20/30] fix(codex): delete only the logins from a home whose history is a link; never count a link as a preserved copy Following a linked history.jsonl to decide what to keep kept missing cases (case-insensitive names, backslashes, newline-ending targets). A home whose history.jsonl is a link now loses only auth.json and .credentials.json, the sign-in and MCP logins the dialog names. Preservation treats a link at a preserved name as taken, not as the copy, and copies an account history that the shared history links to. --- .../codex-managed-home-lifecycle.test.ts | 36 +++--- .../codex-managed-home-lifecycle.ts | 18 ++- .../managed-homes/linked-history-entries.ts | 111 ------------------ .../legacy-host/legacy-history-migration.ts | 26 +++- .../runtime-home-legacy-migration.test.ts | 17 +++ 5 files changed, 65 insertions(+), 143 deletions(-) delete mode 100644 src/main/codex-accounts/managed-homes/linked-history-entries.ts diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index 60c4f9bd98f4..a51eea6b3dd3 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -1,5 +1,4 @@ import { - chmodSync, existsSync, mkdirSync, mkdtempSync, @@ -70,7 +69,7 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { expect(readFileSync(join(f.home, 'sessions', 'rollout.jsonl'), 'utf8')).toBe('only copy\n') }) - it('keeps every entry a linked prompt history passes through inside the home', async () => { + it('deletes only the logins from a home whose prompt history is a link', async () => { const f = fixture() mkdirSync(join(f.home, '..backup')) writeFileSync(join(f.home, '..backup', 'prompts.jsonl'), '{"text":"only prompt"}\n') @@ -79,6 +78,7 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { symlinkSync(join('middle', 'next'), join(f.home, 'bridge')) symlinkSync(join('bridge', 'prompts.jsonl'), join(f.home, 'history.jsonl')) writeFileSync(join(f.home, 'auth.json'), '{}') + writeFileSync(join(f.home, '.credentials.json'), '{}') await f.lifecycle.safeRemove(f.home, 'a') @@ -86,26 +86,18 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { expect(readFileSync(join(f.home, 'history.jsonl'), 'utf8')).toBe('{"text":"only prompt"}\n') }) - it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( - 'removes nothing when a linked prompt history cannot be followed', - async () => { - const f = fixture() - const outside = join(f.accountsRoot, 'outside') - mkdirSync(outside) - writeFileSync(join(f.home, 'prompts.saved'), '{"text":"only prompt"}\n') - symlinkSync(join(f.home, 'prompts.saved'), join(outside, 'link')) - symlinkSync(join(outside, 'link'), join(f.home, 'history.jsonl')) - writeFileSync(join(f.home, 'auth.json'), '{}') - chmodSync(outside, 0o000) - try { - await f.lifecycle.safeRemove(f.home, 'a') - } finally { - chmodSync(outside, 0o755) - } - - expect(readdirSync(f.home).sort()).toEqual(['auth.json', 'history.jsonl', 'prompts.saved']) - } - ) + it('deletes only the logins when the prompt history is a link it cannot follow', async () => { + const f = fixture() + const outside = join(f.accountsRoot, 'outside') + mkdirSync(outside) + writeFileSync(join(f.home, 'PROMPTS.saved'), '{"text":"only prompt"}\n') + symlinkSync(join(outside, 'gone', 'link'), join(f.home, 'history.jsonl')) + writeFileSync(join(f.home, 'auth.json'), '{}') + + await f.lifecycle.safeRemove(f.home, 'a') + + expect(readdirSync(f.home).sort()).toEqual(['PROMPTS.saved', 'history.jsonl']) + }) it('removes a home that never shared history entirely', async () => { const f = fixture() diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index a8111abcfc14..448a0e01d6ad 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -15,7 +15,6 @@ import type { } from '../account-management/codex-account-service-types' import { writeFileAtomically } from '../../filesystem/atomic-file-publication' import { MERGE_PENDING_SUFFIX, removeDirectoryLink } from '../../filesystem/merged-directory-link' -import { LINKED_HISTORY_ENTRIES_SCRIPT, linkedHistoryEntries } from './linked-history-entries' import { CODEX_DATABASE_FILE, HISTORY_CLEANUP_MANIFEST, @@ -41,12 +40,18 @@ const KEPT_HISTORY = [ HISTORY_CLEANUP_MANIFEST, PRE_SHARE_DATABASES_DIR ] +// The sign-in and MCP logins: all that removal deletes from a home whose history.jsonl is a link, +// since what the link reaches inside the home can't be told apart from private state by name. +const LOGIN_FILES = ['auth.json', '.credentials.json'] const KEEP_ON_REMOVAL_SCRIPT = [ 'set -u', 'home=$1', - ...LINKED_HISTORY_ENTRIES_SCRIPT, + 'linked_history=0', + 'if [ -L "$home/history.jsonl" ]; then linked_history=1; fi', 'kept() {', - ' case "$history_entries" in *"/${1##*/}/"*) return 0 ;; esac', + ' if [ "$linked_history" = 1 ]; then', + ` case "\${1##*/}" in ${LOGIN_FILES.join(' | ')}) return 1 ;; *) return 0 ;; esac`, + ' fi', ' case "${1##*/}" in', ' *.orca-profile-merge) return 0 ;;', ` ${KEPT_HISTORY.join(' | ')}) return 0 ;;`, @@ -76,10 +81,11 @@ const KEEP_ON_REMOVAL_SCRIPT = [ async function removeManagedHomeKeepingSharedHistory(home: string): Promise { const entries = await readdir(home, { withFileTypes: true }) const sharedOnce = entries.some((entry) => entry.name === HISTORY_CLEANUP_MANIFEST) - const historyEntries = await linkedHistoryEntries(home) + const linkedHistory = entries.some( + (entry) => entry.name === 'history.jsonl' && entry.isSymbolicLink() + ) const kept = (entry: Dirent): boolean => - KEPT_HISTORY.includes(entry.name) || - historyEntries.has(entry.name) || + (linkedHistory ? !LOGIN_FILES.includes(entry.name) : KEPT_HISTORY.includes(entry.name)) || entry.name.endsWith(MERGE_PENDING_SUFFIX) || (sharedOnce && entry.isFile() && CODEX_DATABASE_FILE.test(entry.name)) for (const entry of entries.filter((candidate) => !kept(candidate))) { diff --git a/src/main/codex-accounts/managed-homes/linked-history-entries.ts b/src/main/codex-accounts/managed-homes/linked-history-entries.ts deleted file mode 100644 index 5043d58d9a1c..000000000000 --- a/src/main/codex-accounts/managed-homes/linked-history-entries.ts +++ /dev/null @@ -1,111 +0,0 @@ -import type { Stats } from 'node:fs' -import { lstat, readlink, realpath } from 'node:fs/promises' -import { dirname, isAbsolute, join, parse, relative, sep } from 'node:path' -import { errnoCodeOrUnknown } from '../../../shared/errors/errno-code' - -const MAX_HISTORY_LINK_HOPS = 40 - -async function lstatIfPresent(path: string): Promise { - try { - return await lstat(path) - } catch (error) { - const code = errnoCodeOrUnknown(error) - if (code === 'ENOENT' || code === 'ENOTDIR') { - return null - } - throw error - } -} - -function pathComponents(path: string): string[] { - return path.slice(parse(path).root.length).split(/[\\/]/) -} - -/** - * The top-level entries a linked history.jsonl passes through inside the home, one path component - * at a time: every link and folder on the way and the file it reaches, so removal keeps them all. - * Throws when a step can't be read, so removal stops instead of deleting what it couldn't follow. - */ -export async function linkedHistoryEntries(home: string): Promise> { - const entries = new Set() - if (!(await lstatIfPresent(join(home, 'history.jsonl')))?.isSymbolicLink()) { - return entries - } - const realHome = await realpath(home) - const keepTopEntry = (path: string): void => { - for (const root of [realHome, home]) { - const inside = relative(root, path) - const first = inside.split(sep)[0] - if (inside && first !== '..' && !isAbsolute(inside)) { - entries.add(first) - return - } - } - } - let dir = realHome - let pending = ['history.jsonl'] - let hops = 0 - while (pending.length > 0) { - const name = pending.shift() - if (!name || name === '.') { - continue - } - if (name === '..') { - dir = dirname(dir) - continue - } - const path = join(dir, name) - keepTopEntry(path) - const stats = await lstatIfPresent(path) - if (!stats) { - // Nothing exists past a missing step, so nothing more needs keeping. - return entries - } - if (!stats.isSymbolicLink()) { - dir = path - continue - } - if (++hops > MAX_HISTORY_LINK_HOPS) { - throw new Error('Too many links on the way to the prompt history') - } - const target = await readlink(path) - if (isAbsolute(target)) { - dir = parse(target).root - } - pending = [...pathComponents(target), ...pending] - } - return entries -} - -/** - * The same walk for a WSL home, as bash lines run with the home in $home: collects the entries into - * $history_entries ("/a/b/"), and exits nonzero on any step it can't read. - */ -export const LINKED_HISTORY_ENTRIES_SCRIPT = [ - 'real_home=$(cd -P -- "$home" && pwd) || exit 1', - 'history_entries=/', - 'keep_entry() {', - ' for root in "$real_home" "$home"; do', - ' case "$1" in "$root"/?*) inside=${1#"$root"/}; first=${inside%%/*}', - ' case "$first" in .|..) ;; *) history_entries="$history_entries$first/"; return ;; esac ;; esac', - ' done', - '}', - 'if [ -L "$home/history.jsonl" ]; then', - ' dir=$real_home; rest=history.jsonl; hops=0', - ' while [ -n "$rest" ]; do', - ' case "$rest" in */*) name=${rest%%/*}; rest=${rest#*/} ;; *) name=$rest; rest= ;; esac', - ' case "$name" in "" | .) continue ;; ..) dir=${dir%/*}; dir=${dir:-/}; continue ;; esac', - ' next=${dir%/}/$name', - ' keep_entry "$next"', - ' if [ -L "$next" ]; then', - ' hops=$((hops + 1)); [ "$hops" -le 40 ] || exit 1', - ' target=$(readlink -- "$next") || exit 1', - ' case "$target" in /*) dir=/ ;; esac', - ' rest=$target${rest:+/$rest}', - ' elif [ -e "$next" ]; then dir=$next', - ' elif [ -x "$dir" ]; then break', - ' else exit 1', - ' fi', - ' done', - 'fi' -] diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts index 8c63393a4610..09a39d2dce03 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -3,6 +3,7 @@ import { constants } from 'node:fs' import { access, copyFile, + lstat, readFile, readdir, realpath, @@ -102,7 +103,10 @@ async function realpathIfPresent(path: string): Promise { } } -/** Exclusive create never replaces or writes through a name; same bytes there count as copied. */ +/** + * Exclusive create never replaces or writes through a name. A regular file already holding the same + * bytes counts as the copy; a link there does not, since it isn't a copy of its own. + */ async function copyIntoFreeName(source: string, targetPath: string): Promise { try { await copyFile(source, targetPath, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE) @@ -113,13 +117,27 @@ async function copyIntoFreeName(source: string, targetPath: string): Promise { + const stats = await lstat(runtimeHistoryPath).catch((error: unknown) => { + if (errnoCodeOrUnknown(error) === 'ENOENT') { + return null + } + throw error + }) + return stats?.isFile() ? realpath(runtimeHistoryPath) : null +} + // Every account's own history, copied into the runtime home where no Orca path deletes it, so an // older build's account removal can never take the only copy. async function preserveLegacyHistories( @@ -132,7 +150,7 @@ async function preserveLegacyHistories( } throw error }) - const sharedHistory = await realpathIfPresent(runtimeHistoryPath) + const sharedHistory = await sharedHistoryFile(runtimeHistoryPath) const preserved = new Set() const names = accounts.filter((entry) => entry.isDirectory()).map((entry) => entry.name) for (const accountId of names.sort()) { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 2cb8c485bea1..173d5e5ae868 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { existsSync, + lstatSync, mkdirSync, readlinkSync, readFileSync, @@ -256,6 +257,22 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}\n') }) + it('makes a real copy when the shared history and the preserved name only link to the account history', async () => { + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) + symlinkSync(join(managedHomePath, 'history.jsonl'), preservedHistoryPath('account-1')) + symlinkSync( + join(managedHomePath, 'history.jsonl'), + join(getRuntimeCodexHomePath(), 'history.jsonl') + ) + + await startService() + + const copyPath = join(getRuntimeCodexHomePath(), 'history.orca-legacy-account-1-1.jsonl') + expect(lstatSync(copyPath).isFile()).toBe(true) + expect(readFileSync(copyPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') + }) + it('imports from the preserved history once the account folder is gone', async () => { mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) writeFileSync(preservedHistoryPath('account-1'), '{"id":"legacy-1"}\n', 'utf-8') From c18400377d2b4245ea4d227a863773f384721d22 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:59:49 -0800 Subject: [PATCH 21/30] fix(codex): run the session pass after the history copies, and write its marker in the same step A quit between the session copies and migration-v1.json let an older build rerun its overwriting migration. The session pass now runs once every account history has its copy, and writes its state and the marker synchronously with the copies. Preservation is recorded per account so a retry never copies one twice. A home with a linked history also loses Codex's encrypted login store. --- config/main-blocking-helper-baseline.txt | 2 +- .../codex-managed-home-lifecycle.test.ts | 2 + .../codex-managed-home-lifecycle.ts | 11 +-- .../legacy-host/legacy-history-migration.ts | 67 ++++++++++++++----- .../runtime-home-legacy-migration.test.ts | 29 ++++++++ .../runtime-home-service-legacy-migration.ts | 35 +++++----- 6 files changed, 106 insertions(+), 40 deletions(-) diff --git a/config/main-blocking-helper-baseline.txt b/config/main-blocking-helper-baseline.txt index eb869b6a8870..bc27d446b591 100644 --- a/config/main-blocking-helper-baseline.txt +++ b/config/main-blocking-helper-baseline.txt @@ -271,7 +271,7 @@ 4 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 19 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts -2 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +3 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 11 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts # Codex launch prep from #43365 already merged; unblocks main, async follow-up owed 9 src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts 8 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index a51eea6b3dd3..e3b5932d5868 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -79,6 +79,8 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { symlinkSync(join('bridge', 'prompts.jsonl'), join(f.home, 'history.jsonl')) writeFileSync(join(f.home, 'auth.json'), '{}') writeFileSync(join(f.home, '.credentials.json'), '{}') + mkdirSync(join(f.home, 'secrets')) + writeFileSync(join(f.home, 'secrets', 'codex_auth.age'), 'sealed') await f.lifecycle.safeRemove(f.home, 'a') diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index 448a0e01d6ad..d73f704edcbf 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -40,9 +40,10 @@ const KEPT_HISTORY = [ HISTORY_CLEANUP_MANIFEST, PRE_SHARE_DATABASES_DIR ] -// The sign-in and MCP logins: all that removal deletes from a home whose history.jsonl is a link, -// since what the link reaches inside the home can't be told apart from private state by name. -const LOGIN_FILES = ['auth.json', '.credentials.json'] +// The sign-in and MCP logins, in files or Codex's encrypted store: all that removal deletes from a +// home whose history.jsonl is a link, since what the link reaches inside the home can't be told +// apart from private state by name. +const LOGIN_ENTRIES = ['auth.json', '.credentials.json', 'secrets'] const KEEP_ON_REMOVAL_SCRIPT = [ 'set -u', 'home=$1', @@ -50,7 +51,7 @@ const KEEP_ON_REMOVAL_SCRIPT = [ 'if [ -L "$home/history.jsonl" ]; then linked_history=1; fi', 'kept() {', ' if [ "$linked_history" = 1 ]; then', - ` case "\${1##*/}" in ${LOGIN_FILES.join(' | ')}) return 1 ;; *) return 0 ;; esac`, + ` case "\${1##*/}" in ${LOGIN_ENTRIES.join(' | ')}) return 1 ;; *) return 0 ;; esac`, ' fi', ' case "${1##*/}" in', ' *.orca-profile-merge) return 0 ;;', @@ -85,7 +86,7 @@ async function removeManagedHomeKeepingSharedHistory(home: string): Promise entry.name === 'history.jsonl' && entry.isSymbolicLink() ) const kept = (entry: Dirent): boolean => - (linkedHistory ? !LOGIN_FILES.includes(entry.name) : KEPT_HISTORY.includes(entry.name)) || + (linkedHistory ? !LOGIN_ENTRIES.includes(entry.name) : KEPT_HISTORY.includes(entry.name)) || entry.name.endsWith(MERGE_PENDING_SUFFIX) || (sharedOnce && entry.isFile() && CODEX_DATABASE_FILE.test(entry.name)) for (const entry of entries.filter((candidate) => !kept(candidate))) { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts index 09a39d2dce03..8337565677e2 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -27,6 +27,8 @@ export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 type LegacyHistoryState = { /** Every account history has a copy in the runtime home. */ historiesPreserved?: boolean + /** Accounts whose history has its copy, so a retry doesn't copy them again. */ + preservedAccounts?: string[] /** The shared history was created, or already existed, so nothing is owed. */ historyImportSettled?: boolean historyImportAttempts?: number @@ -40,7 +42,7 @@ export type LegacyHistoryMigrationPaths = { accountsRoot: string runtimeHistoryPath: string statePath: string - /** Written once the session pass finishes; its contents become the migration marker. */ + /** Written with the marker once the session pass finishes. */ sessionsStatePath: string /** The only marker older builds read. */ markerPath: string @@ -55,6 +57,11 @@ function parseLegacyHistoryState(text: string): LegacyHistoryState { if ('historiesPreserved' in parsed && parsed.historiesPreserved === true) { state.historiesPreserved = true } + if ('preservedAccounts' in parsed && Array.isArray(parsed.preservedAccounts)) { + state.preservedAccounts = parsed.preservedAccounts.filter( + (accountId): accountId is string => typeof accountId === 'string' + ) + } if ('historyImportSettled' in parsed && parsed.historyImportSettled === true) { state.historyImportSettled = true } @@ -142,7 +149,9 @@ async function sharedHistoryFile(runtimeHistoryPath: string): Promise, + recordPreserved: (accountId: string) => Promise ): Promise { const accounts = await readdir(accountsRoot, { withFileTypes: true }).catch((error: unknown) => { if (errnoCodeOrUnknown(error) === 'ENOENT') { @@ -151,27 +160,31 @@ async function preserveLegacyHistories( throw error }) const sharedHistory = await sharedHistoryFile(runtimeHistoryPath) - const preserved = new Set() + const copiedSources = new Set() const names = accounts.filter((entry) => entry.isDirectory()).map((entry) => entry.name) for (const accountId of names.sort()) { - const source = await realpathIfPresent(join(accountsRoot, accountId, 'home', 'history.jsonl')) - if (!source || source === sharedHistory || preserved.has(source)) { + if (alreadyPreserved.has(accountId)) { continue } - if (!(await stat(source)).isFile()) { + const source = await realpathIfPresent(join(accountsRoot, accountId, 'home', 'history.jsonl')) + if (!source || !(await stat(source)).isFile()) { continue } - preserved.add(source) - const base = runtimeHistoryPath.replace(/\.jsonl$/, '') - for (let attempt = 0; ; attempt++) { - const suffix = attempt === 0 ? '' : `-${attempt}` - if (await copyIntoFreeName(source, `${base}.orca-legacy-${accountId}${suffix}.jsonl`)) { - break + if (source !== sharedHistory && !copiedSources.has(source)) { + const base = runtimeHistoryPath.replace(/\.jsonl$/, '') + for (let attempt = 0; ; attempt++) { + const suffix = attempt === 0 ? '' : `-${attempt}` + if (await copyIntoFreeName(source, `${base}.orca-legacy-${accountId}${suffix}.jsonl`)) { + break + } } + copiedSources.add(source) } + await recordPreserved(accountId) } } +// Repairs a marker lost to a crash right after the session pass. async function writeMarkerOnceSessionsDone(paths: LegacyHistoryMigrationPaths): Promise { const sessionsState = await readTextIfPresent(paths.sessionsStatePath) if (sessionsState === null) { @@ -185,19 +198,39 @@ async function writeMarkerOnceSessionsDone(paths: LegacyHistoryMigrationPaths): } /** - * Off the startup path. Preserves the account histories, then marks the migration done for older - * builds (once the session pass also finished), then imports the shared history until it settles. - * Never rejects; whatever fails retries on a later launch. + * Off the startup path. Preserves the account histories, then runs the session pass, which marks + * the migration done for older builds, then imports the shared history until it settles. The + * session pass waits for the copies so an older build never sees the marker while an account + * history has no copy, and never sees copied sessions without the marker. Never rejects; whatever + * fails retries on a later launch. */ -export async function settleLegacyHistory(paths: LegacyHistoryMigrationPaths): Promise { +export async function settleLegacyHistory( + paths: LegacyHistoryMigrationPaths, + migrateSessions: (() => void) | null +): Promise { try { const text = await readTextIfPresent(paths.statePath) let state = text === null ? {} : parseLegacyHistoryState(text) if (!state.historiesPreserved) { - await preserveLegacyHistories(paths.accountsRoot, paths.runtimeHistoryPath) + const preserved = new Set(state.preservedAccounts) + await preserveLegacyHistories( + paths.accountsRoot, + paths.runtimeHistoryPath, + preserved, + async (accountId) => { + preserved.add(accountId) + state = { ...state, preservedAccounts: [...preserved] } + await writeTextAtomically(paths.statePath, `${JSON.stringify(state)}\n`) + } + ) state = { ...state, historiesPreserved: true } await writeTextAtomically(paths.statePath, `${JSON.stringify(state)}\n`) } + try { + migrateSessions?.() + } catch (error) { + console.warn('[codex-runtime-home] Failed to migrate legacy Codex sessions:', error) + } await writeMarkerOnceSessionsDone(paths) if (!state.historyImportSettled) { await retryLegacyHistoryImport(paths, state) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 173d5e5ae868..5ff565ae804d 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { + chmodSync, existsSync, lstatSync, mkdirSync, @@ -291,6 +292,34 @@ describe('CodexRuntimeHomeService', () => { ) }) + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'copies no sessions and leaves the migration unmarked until every account history has its copy', + async () => { + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'rollout.jsonl'), '{}', 'utf-8') + chmodSync(join(managedHomePath, 'history.jsonl'), 0o000) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + await constructService() + await vi.waitFor( + () => + expect(warn).toHaveBeenCalledWith( + '[codex-runtime-home] Failed to migrate legacy Codex prompt history:', + expect.anything() + ), + { timeout: WAIT_MS } + ) + } finally { + warn.mockRestore() + chmodSync(join(managedHomePath, 'history.jsonl'), 0o644) + } + + expect(existsSync(join(getRuntimeCodexHomePath(), 'sessions', 'rollout.jsonl'))).toBe(false) + expect(existsSync(migrationMarkerPath())).toBe(false) + } + ) + it('imports history even when a session copy fails', async () => { const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') blockSessionCopies(managedHomePath) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 24df61dc0dd9..3677dfce6fbd 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -64,17 +64,21 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return } - // Started first and independent of the session copies, so one that fails can't hold it back. - void settleLegacyHistory({ - accountsRoot: this.getManagedAccountsRoot(), - runtimeHistoryPath: join(this.getRuntimeHomePath(), 'history.jsonl'), - statePath: join(this.getRuntimeMetadataDir(), 'migration-v1-history.json'), - sessionsStatePath: this.getSessionsMigratedStatePath(), - markerPath: this.getMigrationMarkerPath() - }) - if (sessionsDone) { - return - } + void settleLegacyHistory( + { + accountsRoot: this.getManagedAccountsRoot(), + runtimeHistoryPath: join(this.getRuntimeHomePath(), 'history.jsonl'), + statePath: join(this.getRuntimeMetadataDir(), 'migration-v1-history.json'), + sessionsStatePath: this.getSessionsMigratedStatePath(), + markerPath: this.getMigrationMarkerPath() + }, + sessionsDone ? null : () => this.migrateLegacySessionsAndMarkDone() + ) + } + + // Synchronous end to end, so no quit lands between the session copies and the marker older + // builds read: without it they would rerun their overwriting migration. + protected migrateLegacySessionsAndMarkDone(): void { const managedHomes = this.getLegacyManagedHomes() for (const managedHomePath of managedHomes) { const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( @@ -84,12 +88,9 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa this.migrateLegacySessions(managedHomePath, accountId) } } - // The history migration turns this into the marker older builds read, once it has preserved - // every account history: only then can't their account removal take the only copy. - writeFileAtomically( - this.getSessionsMigratedStatePath(), - `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` - ) + const record = `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` + writeFileAtomically(this.getSessionsMigratedStatePath(), record) + writeFileAtomically(this.getMigrationMarkerPath(), record) } protected getSessionsMigratedStatePath(): string { From 93613424d32da14994969d4d07f75eb563e124a6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:37:33 -0800 Subject: [PATCH 22/30] fix(codex): copy histories, sessions and the marker in one synchronous step at startup Running the session pass after an async step let account removal or history sharing reach a home first. The migration is synchronous again, as on main: each account history gets its copy, then the sessions, then migration-v1.json, all before anything can remove or share an account. Only the shared-history import stays async. The removal dialog says again that the account's Codex folder is deleted, apart from its history. --- config/main-blocking-helper-baseline.txt | 2 +- config/main-sync-fs-baseline.txt | 2 +- .../legacy-host/legacy-history-migration.ts | 192 ++---------------- .../runtime-home-legacy-migration.test.ts | 39 ++-- .../runtime-home-service-legacy-migration.ts | 164 +++++++++++---- .../accounts-pane-removal-dialogs.tsx | 2 +- src/renderer/src/i18n/locales/en.json | 2 +- src/renderer/src/i18n/locales/zh.json | 2 +- 8 files changed, 172 insertions(+), 233 deletions(-) diff --git a/config/main-blocking-helper-baseline.txt b/config/main-blocking-helper-baseline.txt index dbd945e3d1ca..443a078202d1 100644 --- a/config/main-blocking-helper-baseline.txt +++ b/config/main-blocking-helper-baseline.txt @@ -269,7 +269,7 @@ 4 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 19 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts -3 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +2 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 11 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts # Codex launch prep from #43365 already merged; unblocks main, async follow-up owed 9 src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts 8 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 456a436fa589..caefbc1e5e68 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -127,7 +127,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -14 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +19 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts index 8337565677e2..a3bc0ebe6507 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -1,18 +1,5 @@ import { randomUUID } from 'node:crypto' -import { constants } from 'node:fs' -import { - access, - copyFile, - lstat, - readFile, - readdir, - realpath, - rename, - rm, - stat, - writeFile -} from 'node:fs/promises' -import { join } from 'node:path' +import { readFile, rename, rm, writeFile } from 'node:fs/promises' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { importLegacyHistoriesIfSharedAbsent, @@ -24,9 +11,7 @@ export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 /** How long a given-up import waits before trying again with unchanged account histories. */ export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 -type LegacyHistoryState = { - /** Every account history has a copy in the runtime home. */ - historiesPreserved?: boolean +export type LegacyHistoryState = { /** Accounts whose history has its copy, so a retry doesn't copy them again. */ preservedAccounts?: string[] /** The shared history was created, or already existed, so nothing is owed. */ @@ -37,26 +22,19 @@ type LegacyHistoryState = { historyImportGaveUpAt?: number } -/** Where the legacy history migration reads and records its work. */ -export type LegacyHistoryMigrationPaths = { +/** Where the shared history import reads and records its attempts. */ +export type LegacyHistoryImportPaths = { accountsRoot: string runtimeHistoryPath: string statePath: string - /** Written with the marker once the session pass finishes. */ - sessionsStatePath: string - /** The only marker older builds read. */ - markerPath: string } -function parseLegacyHistoryState(text: string): LegacyHistoryState { +export function parseLegacyHistoryState(text: string): LegacyHistoryState { const parsed: unknown = JSON.parse(text) const state: LegacyHistoryState = {} if (!parsed || typeof parsed !== 'object') { return state } - if ('historiesPreserved' in parsed && parsed.historiesPreserved === true) { - state.historiesPreserved = true - } if ('preservedAccounts' in parsed && Array.isArray(parsed.preservedAccounts)) { state.preservedAccounts = parsed.preservedAccounts.filter( (accountId): accountId is string => typeof accountId === 'string' @@ -98,154 +76,12 @@ async function writeTextAtomically(path: string, text: string): Promise { } } -async function realpathIfPresent(path: string): Promise { - try { - return await realpath(path) - } catch (error) { - const code = errnoCodeOrUnknown(error) - if (code === 'ENOENT' || code === 'ENOTDIR') { - return null - } - throw error - } -} - -/** - * Exclusive create never replaces or writes through a name. A regular file already holding the same - * bytes counts as the copy; a link there does not, since it isn't a copy of its own. - */ -async function copyIntoFreeName(source: string, targetPath: string): Promise { - try { - await copyFile(source, targetPath, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE) - return true - } catch (error) { - if (errnoCodeOrUnknown(error) !== 'EEXIST') { - throw error - } - } - try { - return ( - (await lstat(targetPath)).isFile() && - (await readFile(targetPath)).equals(await readFile(source)) - ) - } catch { - return false - } -} - -// The shared history only when it is a regular file in the runtime home: an account history that -// is that file needs no copy, but one the shared history links to does. -async function sharedHistoryFile(runtimeHistoryPath: string): Promise { - const stats = await lstat(runtimeHistoryPath).catch((error: unknown) => { - if (errnoCodeOrUnknown(error) === 'ENOENT') { - return null - } - throw error - }) - return stats?.isFile() ? realpath(runtimeHistoryPath) : null -} - -// Every account's own history, copied into the runtime home where no Orca path deletes it, so an -// older build's account removal can never take the only copy. -async function preserveLegacyHistories( - accountsRoot: string, - runtimeHistoryPath: string, - alreadyPreserved: ReadonlySet, - recordPreserved: (accountId: string) => Promise -): Promise { - const accounts = await readdir(accountsRoot, { withFileTypes: true }).catch((error: unknown) => { - if (errnoCodeOrUnknown(error) === 'ENOENT') { - return [] - } - throw error - }) - const sharedHistory = await sharedHistoryFile(runtimeHistoryPath) - const copiedSources = new Set() - const names = accounts.filter((entry) => entry.isDirectory()).map((entry) => entry.name) - for (const accountId of names.sort()) { - if (alreadyPreserved.has(accountId)) { - continue - } - const source = await realpathIfPresent(join(accountsRoot, accountId, 'home', 'history.jsonl')) - if (!source || !(await stat(source)).isFile()) { - continue - } - if (source !== sharedHistory && !copiedSources.has(source)) { - const base = runtimeHistoryPath.replace(/\.jsonl$/, '') - for (let attempt = 0; ; attempt++) { - const suffix = attempt === 0 ? '' : `-${attempt}` - if (await copyIntoFreeName(source, `${base}.orca-legacy-${accountId}${suffix}.jsonl`)) { - break - } - } - copiedSources.add(source) - } - await recordPreserved(accountId) - } -} - -// Repairs a marker lost to a crash right after the session pass. -async function writeMarkerOnceSessionsDone(paths: LegacyHistoryMigrationPaths): Promise { - const sessionsState = await readTextIfPresent(paths.sessionsStatePath) - if (sessionsState === null) { - return - } - try { - await access(paths.markerPath) - } catch { - await writeTextAtomically(paths.markerPath, sessionsState) - } -} - -/** - * Off the startup path. Preserves the account histories, then runs the session pass, which marks - * the migration done for older builds, then imports the shared history until it settles. The - * session pass waits for the copies so an older build never sees the marker while an account - * history has no copy, and never sees copied sessions without the marker. Never rejects; whatever - * fails retries on a later launch. - */ -export async function settleLegacyHistory( - paths: LegacyHistoryMigrationPaths, - migrateSessions: (() => void) | null -): Promise { - try { - const text = await readTextIfPresent(paths.statePath) - let state = text === null ? {} : parseLegacyHistoryState(text) - if (!state.historiesPreserved) { - const preserved = new Set(state.preservedAccounts) - await preserveLegacyHistories( - paths.accountsRoot, - paths.runtimeHistoryPath, - preserved, - async (accountId) => { - preserved.add(accountId) - state = { ...state, preservedAccounts: [...preserved] } - await writeTextAtomically(paths.statePath, `${JSON.stringify(state)}\n`) - } - ) - state = { ...state, historiesPreserved: true } - await writeTextAtomically(paths.statePath, `${JSON.stringify(state)}\n`) - } - try { - migrateSessions?.() - } catch (error) { - console.warn('[codex-runtime-home] Failed to migrate legacy Codex sessions:', error) - } - await writeMarkerOnceSessionsDone(paths) - if (!state.historyImportSettled) { - await retryLegacyHistoryImport(paths, state) - } - } catch (error) { - console.warn('[codex-runtime-home] Failed to migrate legacy Codex prompt history:', error) - } -} - /** * After a few failed launches, a change to the account histories or a day's wait earns another * attempt, so a failure that clears (permissions, a mount) still imports. */ async function retryLegacyHistoryImport( - paths: LegacyHistoryMigrationPaths, + paths: LegacyHistoryImportPaths, state: LegacyHistoryState ): Promise { if ((state.historyImportAttempts ?? 0) >= MAX_HISTORY_IMPORT_ATTEMPTS) { @@ -276,3 +112,19 @@ async function retryLegacyHistoryImport( } await writeTextAtomically(paths.statePath, `${JSON.stringify(state)}\n`) } + +/** + * Off the startup path: imports the shared history until it settles, retrying on later launches. + * Never rejects. + */ +export async function settleLegacyHistoryImport(paths: LegacyHistoryImportPaths): Promise { + try { + const text = await readTextIfPresent(paths.statePath) + const state = text === null ? {} : parseLegacyHistoryState(text) + if (!state.historyImportSettled) { + await retryLegacyHistoryImport(paths, state) + } + } catch (error) { + console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error) + } +} diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 5ff565ae804d..e329173259f5 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -92,10 +92,6 @@ function preservedHistoryPath(accountId: string): string { return join(getRuntimeCodexHomePath(), `history.orca-legacy-${accountId}.jsonl`) } -function sessionsMigratedStatePath(): string { - return join(testState.userDataDir, 'codex-runtime-home', 'migration-v1-sessions.json') -} - function historyStatePath(): string { return join(testState.userDataDir, 'codex-runtime-home', 'migration-v1-history.json') } @@ -258,6 +254,22 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}\n') }) + it('copies the history, the sessions and the marker before the service is constructed', async () => { + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'rollout.jsonl'), '{}', 'utf-8') + + await constructService() + + // Nothing can remove or share the account before this: it all happened in the constructor. + expect(readFileSync(preservedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') + expect( + readFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'rollout.jsonl'), 'utf-8') + ).toBe('{}') + expect(existsSync(migrationMarkerPath())).toBe(true) + await waitForHistorySettled() + }) + it('makes a real copy when the shared history and the preserved name only link to the account history', async () => { const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) @@ -278,12 +290,8 @@ describe('CodexRuntimeHomeService', () => { mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) writeFileSync(preservedHistoryPath('account-1'), '{"id":"legacy-1"}\n', 'utf-8') mkdirSync(join(historyStatePath(), '..'), { recursive: true }) - writeFileSync(sessionsMigratedStatePath(), '{}', 'utf-8') - writeFileSync( - historyStatePath(), - JSON.stringify({ historiesPreserved: true, historyImportAttempts: 1 }), - 'utf-8' - ) + writeFileSync(migrationMarkerPath(), '{}', 'utf-8') + writeFileSync(historyStatePath(), JSON.stringify({ historyImportAttempts: 1 }), 'utf-8') await startService() @@ -299,19 +307,10 @@ describe('CodexRuntimeHomeService', () => { mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) writeFileSync(join(managedHomePath, 'sessions', 'rollout.jsonl'), '{}', 'utf-8') chmodSync(join(managedHomePath, 'history.jsonl'), 0o000) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) try { await constructService() - await vi.waitFor( - () => - expect(warn).toHaveBeenCalledWith( - '[codex-runtime-home] Failed to migrate legacy Codex prompt history:', - expect.anything() - ), - { timeout: WAIT_MS } - ) + await waitForImportOutcomes(['failed']) } finally { - warn.mockRestore() chmodSync(join(managedHomePath, 'history.jsonl'), 0o644) } diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 3677dfce6fbd..7e78e780966a 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -3,9 +3,11 @@ import { constants, copyFileSync, existsSync, + lstatSync, mkdirSync, readFileSync, readdirSync, + realpathSync, statSync } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' @@ -15,7 +17,11 @@ import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-mi import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' -import { settleLegacyHistory } from './legacy-history-migration' +import { + parseLegacyHistoryState, + settleLegacyHistoryImport, + type LegacyHistoryState +} from './legacy-history-migration' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { @@ -58,27 +64,50 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - const sessionsDone = existsSync(this.getSessionsMigratedStatePath()) - // Migrated by an older build. - if (!sessionsDone && existsSync(this.getMigrationMarkerPath())) { + const historyStatePath = join(this.getRuntimeMetadataDir(), 'migration-v1-history.json') + const migrated = existsSync(this.getMigrationMarkerPath()) + // Migrated by an older build, which merged the account histories itself. + if (migrated && !existsSync(historyStatePath)) { return } - - void settleLegacyHistory( - { + try { + if (!migrated) { + this.migrateLegacyManagedState(historyStatePath) + } + } finally { + // Independent of the session copies, so one that fails can't hold the import back. + void settleLegacyHistoryImport({ accountsRoot: this.getManagedAccountsRoot(), runtimeHistoryPath: join(this.getRuntimeHomePath(), 'history.jsonl'), - statePath: join(this.getRuntimeMetadataDir(), 'migration-v1-history.json'), - sessionsStatePath: this.getSessionsMigratedStatePath(), - markerPath: this.getMigrationMarkerPath() - }, - sessionsDone ? null : () => this.migrateLegacySessionsAndMarkDone() - ) + statePath: historyStatePath + }) + } } - // Synchronous end to end, so no quit lands between the session copies and the marker older - // builds read: without it they would rerun their overwriting migration. - protected migrateLegacySessionsAndMarkDone(): void { + /** + * One synchronous step at startup, before anything can remove or share an account: every account + * history gets its copy, then the sessions are copied, then the marker older builds read is + * written. No quit lands between them, so an older build never sees copied sessions without the + * marker (it would rerun its overwriting migration), nor the marker while an account history has + * no copy (its account removal would take the only one). A failure throws before the marker, and + * the step retries next launch. + */ + protected migrateLegacyManagedState(historyStatePath: string): void { + let state: LegacyHistoryState = {} + try { + state = parseLegacyHistoryState(readFileSync(historyStatePath, 'utf-8')) + } catch { + // Absent or unreadable: copies already made are found again as identical files. + } + const preserved = new Set(state.preservedAccounts) + this.preserveLegacyHistories(preserved, (accountId) => { + preserved.add(accountId) + state = { ...state, preservedAccounts: [...preserved] } + this.writeMigrationRecord(historyStatePath, state) + }) + // Present from here on: later launches owe the import until it settles. + this.writeMigrationRecord(historyStatePath, state) + const managedHomes = this.getLegacyManagedHomes() for (const managedHomePath of managedHomes) { const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( @@ -88,33 +117,86 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa this.migrateLegacySessions(managedHomePath, accountId) } } - const record = `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` - writeFileAtomically(this.getSessionsMigratedStatePath(), record) - writeFileAtomically(this.getMigrationMarkerPath(), record) + this.writeMigrationRecord(this.getMigrationMarkerPath(), { + completedAt: Date.now(), + migratedHomeCount: managedHomes.length + }) } - protected getSessionsMigratedStatePath(): string { - return join(this.getRuntimeMetadataDir(), 'migration-v1-sessions.json') + // Each account's own history, copied into the runtime home, where no Orca path deletes it. + protected preserveLegacyHistories( + alreadyPreserved: ReadonlySet, + recordPreserved: (accountId: string) => void + ): void { + const accountIds = this.listLegacyAccountIds() + if (accountIds.length === 0) { + return + } + const runtimeHistoryPath = join(this.getRuntimeHomePath(), 'history.jsonl') + mkdirSync(this.getRuntimeHomePath(), { recursive: true }) + // An account history that is the shared history itself needs no copy; one it links to does. + const sharedHistory = this.legacyHistorySource(runtimeHistoryPath, { followLink: false }) + const copiedSources = new Set() + for (const accountId of accountIds) { + if (alreadyPreserved.has(accountId)) { + continue + } + const historyPath = join(this.getManagedAccountsRoot(), accountId, 'home', 'history.jsonl') + const source = this.legacyHistorySource(historyPath, { followLink: true }) + if (!source) { + continue + } + if (source !== sharedHistory && !copiedSources.has(source)) { + this.copyLegacyFilePreservingConflicts(source, runtimeHistoryPath, accountId, { + preservedNameOnly: true + }) + copiedSources.add(source) + } + recordPreserved(accountId) + } } - protected getLegacyManagedHomes(): string[] { - const managedAccountsRoot = this.getManagedAccountsRoot() - if (!existsSync(managedAccountsRoot)) { - return [] + // Every account folder, ownership marker or not, sorted. + protected listLegacyAccountIds(): string[] { + try { + return readdirSync(this.getManagedAccountsRoot(), { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort() + } catch (error) { + if (errnoCodeOrUnknown(error) === 'ENOENT') { + return [] + } + throw error } + } - const accountEntries = readdirSync(managedAccountsRoot, { withFileTypes: true }) - const managedHomes: string[] = [] - for (const entry of accountEntries) { - if (!entry.isDirectory()) { - continue + // The real path of a regular history file, or null when there is none (or, without followLink, + // when the name is a link). + protected legacyHistorySource(path: string, options: { followLink: boolean }): string | null { + try { + if (!options.followLink && !lstatSync(path).isFile()) { + return null } - const managedHomePath = join(managedAccountsRoot, entry.name, 'home') - if (existsSync(join(managedHomePath, '.orca-managed-home'))) { - managedHomes.push(managedHomePath) + const source = realpathSync(path) + return statSync(source).isFile() ? source : null + } catch (error) { + const code = errnoCodeOrUnknown(error) + if (code === 'ENOENT' || code === 'ENOTDIR') { + return null } + throw error } - return managedHomes.sort() + } + + protected writeMigrationRecord(path: string, record: object): void { + writeFileAtomically(path, `${JSON.stringify(record)}\n`) + } + + protected getLegacyManagedHomes(): string[] { + return this.listLegacyAccountIds() + .map((accountId) => join(this.getManagedAccountsRoot(), accountId, 'home')) + .filter((managedHomePath) => existsSync(join(managedHomePath, '.orca-managed-home'))) } protected migrateLegacySessions(managedHomePath: string, accountId: string): void { @@ -146,17 +228,20 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } /** - * Copies to `targetPath` unless it already holds these bytes; when it holds others, copies beside - * it under the next free preserved name. Returns where the legacy bytes now are. + * Copies to `targetPath` unless it already holds these bytes; when it holds others (or with + * preservedNameOnly), copies beside it under the next free preserved name. Returns where the + * legacy bytes now are. */ protected copyLegacyFilePreservingConflicts( legacyFilePath: string, targetPath: string, - accountId: string + accountId: string, + options: { preservedNameOnly?: boolean } = {} ): { path: string; preserved: boolean } { let legacyContents: Buffer | null = null const readLegacy = (): Buffer => (legacyContents ??= readFileSync(legacyFilePath)) if ( + !options.preservedNameOnly && this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath, readLegacy) !== 'conflict' ) { return { path: targetPath, preserved: false } @@ -186,7 +271,10 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } const legacyContents = readLegacy() try { - return readFileSync(targetPath).equals(legacyContents) ? 'identical' : 'conflict' + // A link there is not a copy of its own, whatever it reaches. + return lstatSync(targetPath).isFile() && readFileSync(targetPath).equals(legacyContents) + ? 'identical' + : 'conflict' } catch { // A dangling link or directory at this name still occupies it. return 'conflict' diff --git a/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx b/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx index ff0e26bce8f1..f589778bfc83 100644 --- a/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx +++ b/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx @@ -57,7 +57,7 @@ export function renderAccountsRemovalDialogs( {t( 'settings.accounts.codexRemoveHome', - "Orca deletes this account's sign-in and MCP logins on {{host}}. Its Codex history, sessions and prompts, stays in the account's folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", + "Orca deletes this account's Codex folder on {{host}}, including its sign-in and MCP logins. Its Codex history (sessions and prompt history) stays in the account's folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", { host: accountRuntimeSentenceLabel } )} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index e2e198bf4127..c214e71c662d 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1200,7 +1200,7 @@ "followSymlinkedDirectories": "Follow symlinked directories", "followSymlinkedDirectoriesDescription": "Search linked folders in Quick Open and expand local linked folders in File Explorer.", "accounts": { - "codexRemoveHome": "Orca deletes this account's sign-in and MCP logins on {{host}}. Its Codex history, sessions and prompts, stays in the account's folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", + "codexRemoveHome": "Orca deletes this account's Codex folder on {{host}}, including its sign-in and MCP logins. Its Codex history (sessions and prompt history) stays in the account's folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", "claudeRemoveProfile": "Orca deletes this account's own Claude folder and the sign-in saved in it on {{host}}. Your System default login and chat history shared with it stay. If it is selected, the next Claude you start uses System default." }, "sourceControl": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 42aeafb5dd3c..1f22259515cf 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -576,7 +576,7 @@ "followSymlinkedDirectories": "跟随符号链接目录", "followSymlinkedDirectoriesDescription": "在快速打开中搜索链接文件夹,并在文件资源管理器中展开本地链接文件夹", "accounts": { - "codexRemoveHome": "Orca 会删除此账户在 {{host}} 上的登录信息和 MCP 登录。它的 Codex 历史记录(会话和提示)会保留在该账户的文件夹中。此操作无法撤销。如果此账户被选中,你下次启动的 Codex 将使用系统默认", + "codexRemoveHome": "Orca 会删除此账户在 {{host}} 上的 Codex 文件夹,包括其中的登录信息和 MCP 登录。它的 Codex 历史记录(会话和提示历史)会保留在该账户的文件夹中。此操作无法撤销。如果此账户被选中,你下次启动的 Codex 将使用系统默认", "claudeRemoveProfile": "Orca 会删除此账户在 {{host}} 上自己的 Claude 文件夹及其中保存的登录信息,你的系统默认登录以及与其共享的聊天记录会保留。如果此账户被选中,你下次启动的 Claude 将使用系统默认" }, "sourceControl": { From f53e6d691276c32fa1a6ff18eed6cf237a10cffd Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:56:20 -0800 Subject: [PATCH 23/30] fix(codex): remove only listed login files beside a linked history; mark the migration even when a session copy fails A home whose history.jsonl is a link loses only its login files (auth.json, .credentials.json, config.toml and Codex's encrypted stores), never the file the link reaches, and removal stops if the link can't be checked. A session that fails to copy stays in its account home, which every build's removal keeps, so the marker is written and the session pass retries on later launches. A link-loop history counts as none, and an unowned folder that fails is skipped. The removal dialog no longer promises what happens to history, since older remote hosts still delete it. --- .../codex-managed-home-lifecycle.test.ts | 23 +++- .../codex-managed-home-lifecycle.ts | 23 ++-- .../linked-history-login-removal.ts | 60 +++++++++ .../legacy-host/legacy-history-migration.ts | 5 + .../legacy-prompt-history-import.ts | 6 +- .../runtime-home-legacy-migration.test.ts | 32 ++++- .../runtime-home-service-legacy-migration.ts | 114 ++++++++++-------- .../accounts-pane-removal-dialogs.tsx | 2 +- src/renderer/src/i18n/locales/en.json | 2 +- src/renderer/src/i18n/locales/zh.json | 2 +- 10 files changed, 198 insertions(+), 71 deletions(-) create mode 100644 src/main/codex-accounts/managed-homes/linked-history-login-removal.ts diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index e3b5932d5868..e9c6a7cc2e9a 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -84,7 +84,14 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { await f.lifecycle.safeRemove(f.home, 'a') - expect(readdirSync(f.home).sort()).toEqual(['..backup', 'bridge', 'history.jsonl', 'middle']) + expect(readdirSync(f.home).sort()).toEqual([ + '..backup', + 'bridge', + 'history.jsonl', + 'middle', + 'secrets' + ]) + expect(readdirSync(join(f.home, 'secrets'))).toEqual([]) expect(readFileSync(join(f.home, 'history.jsonl'), 'utf8')).toBe('{"text":"only prompt"}\n') }) @@ -101,6 +108,20 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { expect(readdirSync(f.home).sort()).toEqual(['PROMPTS.saved', 'history.jsonl']) }) + it('keeps a linked prompt history that lives beside the logins it removes', async () => { + const f = fixture() + mkdirSync(join(f.home, 'secrets')) + writeFileSync(join(f.home, 'secrets', 'prompts.jsonl'), '{"text":"only prompt"}\n') + writeFileSync(join(f.home, 'secrets', 'mcp_oauth.age'), 'sealed') + symlinkSync(join('secrets', 'prompts.jsonl'), join(f.home, 'history.jsonl')) + writeFileSync(join(f.home, 'config.toml'), '[mcp_servers.x.http_headers]\n') + + await f.lifecycle.safeRemove(f.home, 'a') + + expect(readdirSync(f.home).sort()).toEqual(['history.jsonl', 'secrets']) + expect(readdirSync(join(f.home, 'secrets'))).toEqual(['prompts.jsonl']) + }) + it('removes a home that never shared history entirely', async () => { const f = fixture() writeFileSync(join(f.home, 'auth.json'), '{}') diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index d73f704edcbf..af1c606b8d02 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -23,6 +23,10 @@ import { } from '../../codex/history/shared-store/codex-account-history-cleanup-manifest' import { ManagedCodexHomeTemporarilyUnavailableError } from './host-codex-managed-home-ownership' import type { CodexManagedHomePath } from './codex-managed-home-path' +import { + LINKED_HISTORY_REMOVAL_SCRIPT, + removeLoginsBesideLinkedHistory +} from './linked-history-login-removal' const WSL_MANAGED_HOME_TIMEOUT_MS = 5_000 @@ -40,19 +44,11 @@ const KEPT_HISTORY = [ HISTORY_CLEANUP_MANIFEST, PRE_SHARE_DATABASES_DIR ] -// The sign-in and MCP logins, in files or Codex's encrypted store: all that removal deletes from a -// home whose history.jsonl is a link, since what the link reaches inside the home can't be told -// apart from private state by name. -const LOGIN_ENTRIES = ['auth.json', '.credentials.json', 'secrets'] const KEEP_ON_REMOVAL_SCRIPT = [ 'set -u', 'home=$1', - 'linked_history=0', - 'if [ -L "$home/history.jsonl" ]; then linked_history=1; fi', + ...LINKED_HISTORY_REMOVAL_SCRIPT, 'kept() {', - ' if [ "$linked_history" = 1 ]; then', - ` case "\${1##*/}" in ${LOGIN_ENTRIES.join(' | ')}) return 1 ;; *) return 0 ;; esac`, - ' fi', ' case "${1##*/}" in', ' *.orca-profile-merge) return 0 ;;', ` ${KEPT_HISTORY.join(' | ')}) return 0 ;;`, @@ -82,11 +78,12 @@ const KEEP_ON_REMOVAL_SCRIPT = [ async function removeManagedHomeKeepingSharedHistory(home: string): Promise { const entries = await readdir(home, { withFileTypes: true }) const sharedOnce = entries.some((entry) => entry.name === HISTORY_CLEANUP_MANIFEST) - const linkedHistory = entries.some( - (entry) => entry.name === 'history.jsonl' && entry.isSymbolicLink() - ) + if (entries.some((entry) => entry.name === 'history.jsonl' && entry.isSymbolicLink())) { + await removeLoginsBesideLinkedHistory(home) + return true + } const kept = (entry: Dirent): boolean => - (linkedHistory ? !LOGIN_ENTRIES.includes(entry.name) : KEPT_HISTORY.includes(entry.name)) || + KEPT_HISTORY.includes(entry.name) || entry.name.endsWith(MERGE_PENDING_SUFFIX) || (sharedOnce && entry.isFile() && CODEX_DATABASE_FILE.test(entry.name)) for (const entry of entries.filter((candidate) => !kept(candidate))) { diff --git a/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts b/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts new file mode 100644 index 000000000000..97af9e441a52 --- /dev/null +++ b/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts @@ -0,0 +1,60 @@ +import { lstat, rm, stat } from 'node:fs/promises' +import { join } from 'node:path' +import { errnoCodeOrUnknown } from '../../../shared/errors/errno-code' + +/** + * The sign-in, MCP logins (including tokens set in config.toml) and Codex's encrypted credential + * stores. A home whose history.jsonl is a link loses only these files on removal: what the link + * reaches can't be told apart from private state by name, so nothing else is removed. + */ +const LOGIN_FILES = [ + 'auth.json', + '.credentials.json', + 'config.toml', + 'secrets/codex_auth.age', + 'secrets/mcp_oauth.age', + 'secrets/gateway_oauth.age', + 'secrets/local.age' +] + +/** Skips a login file that is the file the history link reaches; throws if the link can't be checked. */ +export async function removeLoginsBesideLinkedHistory(home: string): Promise { + const history = await stat(join(home, 'history.jsonl'), { bigint: true }).catch( + (error: unknown) => { + // A dangling link reaches no file, so it can't be one of these. + const code = errnoCodeOrUnknown(error) + if (code === 'ENOENT' || code === 'ENOTDIR') { + return null + } + throw error + } + ) + for (const name of LOGIN_FILES) { + const path = join(home, name) + const file = await lstat(path, { bigint: true }).catch(() => null) + if (!file || file.isDirectory()) { + continue + } + if (history && file.dev === history.dev && file.ino === history.ino) { + continue + } + // Removes a link itself, never what it points to. + await rm(path, { force: true }) + } +} + +/** The same for a WSL home, as bash lines run with the home in $home; exits after removing. */ +export const LINKED_HISTORY_REMOVAL_SCRIPT = [ + 'if [ -L "$home/history.jsonl" ]; then', + ' if [ ! -e "$home/history.jsonl" ] && ! readlink -f -- "$home/history.jsonl" >/dev/null 2>&1; then', + ' exit 1', + ' fi', + ` for name in ${LOGIN_FILES.join(' ')}; do`, + ' file="$home/$name"', + ' if [ -d "$file" ] || { [ ! -e "$file" ] && [ ! -L "$file" ]; }; then continue; fi', + ' if [ ! -L "$file" ] && [ "$file" -ef "$home/history.jsonl" ]; then continue; fi', + ' rm -f -- "$file" || exit 1', + ' done', + ' exit 0', + 'fi' +] diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts index a3bc0ebe6507..5900781fd42b 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -14,6 +14,8 @@ export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 export type LegacyHistoryState = { /** Accounts whose history has its copy, so a retry doesn't copy them again. */ preservedAccounts?: string[] + /** A session copy failed; later launches run the session pass again. */ + sessionsPending?: boolean /** The shared history was created, or already existed, so nothing is owed. */ historyImportSettled?: boolean historyImportAttempts?: number @@ -40,6 +42,9 @@ export function parseLegacyHistoryState(text: string): LegacyHistoryState { (accountId): accountId is string => typeof accountId === 'string' ) } + if ('sessionsPending' in parsed && parsed.sessionsPending === true) { + state.sessionsPending = true + } if ('historyImportSettled' in parsed && parsed.historyImportSettled === true) { state.historyImportSettled = true } diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 21f1ce1869a7..82cacc163c42 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -40,11 +40,11 @@ async function listAccountHistories(accountsRoot: string): Promise { const paths: string[] = [] for (const account of accounts.filter((entry) => entry.isDirectory())) { const historyPath = join(accountsRoot, account.name, 'home', 'history.jsonl') - // Followed through a link, as Codex reads it. Only an absent file (or no home folder) means no - // history; any other error retries rather than skip an account. + // Followed through a link, as Codex reads it. Only an absent file, no home folder or a link loop + // means no history; any other error retries rather than skip an account. const stats = await stat(historyPath).catch((error: unknown) => { const code = errnoCodeOrUnknown(error) - if (code === 'ENOENT' || code === 'ENOTDIR') { + if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP') { return null } throw error diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index e329173259f5..4c6d1ceb06fa 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -7,6 +7,7 @@ import { mkdirSync, readlinkSync, readFileSync, + rmSync, symlinkSync, writeFileSync } from 'node:fs' @@ -319,7 +320,7 @@ describe('CodexRuntimeHomeService', () => { } ) - it('imports history even when a session copy fails', async () => { + it('imports history and marks the migration done when a session copy fails, then retries the sessions', async () => { const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') blockSessionCopies(managedHomePath) @@ -329,7 +330,34 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( '{"id":"a-1"}\n' ) - expect(existsSync(migrationMarkerPath())).toBe(false) + // The uncopied session stays in the account home, which every build's removal keeps. + expect(existsSync(migrationMarkerPath())).toBe(true) + expect(readFileSync(historyStatePath(), 'utf-8')).toContain('"sessionsPending":true') + + rmSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested')) + vi.resetModules() + await constructService() + + expect( + readFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested', 'rollout.jsonl'), 'utf-8') + ).toBe('{}') + expect(readFileSync(historyStatePath(), 'utf-8')).toContain('"sessionsPending":false') + }) + + it('migrates owned accounts past a folder it does not own whose history is a link loop', async () => { + const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') + mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'rollout.jsonl'), '{}', 'utf-8') + const orphanHome = join(testState.userDataDir, 'codex-accounts', 'orphan', 'home') + mkdirSync(orphanHome, { recursive: true }) + symlinkSync('history.jsonl', join(orphanHome, 'history.jsonl')) + + await startService() + + expect( + readFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'rollout.jsonl'), 'utf-8') + ).toBe('{}') + expect(existsSync(migrationMarkerPath())).toBe(true) }) it('leaves a shared history Codex creates during the import as it is', async () => { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 7e78e780966a..ad55d08d03b3 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -10,7 +10,7 @@ import { realpathSync, statSync } from 'node:fs' -import { dirname, extname, join, parse, relative } from 'node:path' +import { basename, dirname, extname, join, relative } from 'node:path' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-migration' @@ -23,6 +23,8 @@ import { type LegacyHistoryState } from './legacy-history-migration' +type LegacyMigrationMarker = { completedAt: number; migratedHomeCount: number } + export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { const settings = this.store.getSettings() @@ -71,8 +73,14 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return } try { - if (!migrated) { - this.migrateLegacyManagedState(historyStatePath) + let state: LegacyHistoryState = {} + try { + state = parseLegacyHistoryState(readFileSync(historyStatePath, 'utf-8')) + } catch { + // Absent or unreadable: copies already made are found again as identical files. + } + if (!migrated || state.sessionsPending) { + this.migrateLegacyManagedState(historyStatePath, state, migrated) } } finally { // Independent of the session copies, so one that fails can't hold the import back. @@ -87,72 +95,76 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa /** * One synchronous step at startup, before anything can remove or share an account: every account * history gets its copy, then the sessions are copied, then the marker older builds read is - * written. No quit lands between them, so an older build never sees copied sessions without the - * marker (it would rerun its overwriting migration), nor the marker while an account history has - * no copy (its account removal would take the only one). A failure throws before the marker, and - * the step retries next launch. + * written. No quit lands between them. An older build never sees the marker while an account + * history has no copy (its account removal would take the only one), and never sees copied + * sessions without it (it would rerun its overwriting migration). A session that fails to copy + * stays in its account home, which every build's removal keeps, and is retried on later launches. */ - protected migrateLegacyManagedState(historyStatePath: string): void { - let state: LegacyHistoryState = {} - try { - state = parseLegacyHistoryState(readFileSync(historyStatePath, 'utf-8')) - } catch { - // Absent or unreadable: copies already made are found again as identical files. - } - const preserved = new Set(state.preservedAccounts) - this.preserveLegacyHistories(preserved, (accountId) => { - preserved.add(accountId) - state = { ...state, preservedAccounts: [...preserved] } - this.writeMigrationRecord(historyStatePath, state) - }) - // Present from here on: later launches owe the import until it settles. - this.writeMigrationRecord(historyStatePath, state) - + protected migrateLegacyManagedState( + historyStatePath: string, + state: LegacyHistoryState, + migrated: boolean + ): void { const managedHomes = this.getLegacyManagedHomes() + if (!migrated) { + const preserved = new Set(state.preservedAccounts) + this.preserveLegacyHistories(managedHomes, preserved, (accountId) => { + preserved.add(accountId) + state = { ...state, preservedAccounts: [...preserved] } + this.writeMigrationRecord(historyStatePath, state) + }) + } + let sessionsPending = false for (const managedHomePath of managedHomes) { - const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( - /[\\/]/ - )[0] - if (accountId) { - this.migrateLegacySessions(managedHomePath, accountId) + try { + this.migrateLegacySessions(managedHomePath, basename(dirname(managedHomePath))) + } catch (error) { + sessionsPending = true + console.warn('[codex-runtime-home] Failed to migrate legacy Codex sessions:', error) } } + // Present from here on: later launches owe the import until it settles. + this.writeMigrationRecord(historyStatePath, { ...state, sessionsPending }) this.writeMigrationRecord(this.getMigrationMarkerPath(), { completedAt: Date.now(), migratedHomeCount: managedHomes.length }) } - // Each account's own history, copied into the runtime home, where no Orca path deletes it. + // Each account's own history, copied into the runtime home, where no Orca path deletes it. A + // folder Orca doesn't own can't be removed through Orca, so one that fails is skipped. protected preserveLegacyHistories( + managedHomes: readonly string[], alreadyPreserved: ReadonlySet, recordPreserved: (accountId: string) => void ): void { - const accountIds = this.listLegacyAccountIds() - if (accountIds.length === 0) { - return - } + const managedAccounts = new Set(managedHomes.map((home) => basename(dirname(home)))) const runtimeHistoryPath = join(this.getRuntimeHomePath(), 'history.jsonl') mkdirSync(this.getRuntimeHomePath(), { recursive: true }) // An account history that is the shared history itself needs no copy; one it links to does. const sharedHistory = this.legacyHistorySource(runtimeHistoryPath, { followLink: false }) const copiedSources = new Set() - for (const accountId of accountIds) { + for (const accountId of this.listLegacyAccountIds()) { if (alreadyPreserved.has(accountId)) { continue } - const historyPath = join(this.getManagedAccountsRoot(), accountId, 'home', 'history.jsonl') - const source = this.legacyHistorySource(historyPath, { followLink: true }) - if (!source) { - continue - } - if (source !== sharedHistory && !copiedSources.has(source)) { - this.copyLegacyFilePreservingConflicts(source, runtimeHistoryPath, accountId, { - preservedNameOnly: true - }) - copiedSources.add(source) + try { + const historyPath = join(this.getManagedAccountsRoot(), accountId, 'home', 'history.jsonl') + const source = this.legacyHistorySource(historyPath, { followLink: true }) + if (!source) { + continue + } + if (source !== sharedHistory && !copiedSources.has(source)) { + this.copyLegacyFilePreservingConflicts(source, runtimeHistoryPath, accountId, true) + copiedSources.add(source) + } + recordPreserved(accountId) + } catch (error) { + if (managedAccounts.has(accountId)) { + throw error + } + console.warn('[codex-runtime-home] Skipped an unowned legacy Codex history:', error) } - recordPreserved(accountId) } } @@ -182,14 +194,18 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return statSync(source).isFile() ? source : null } catch (error) { const code = errnoCodeOrUnknown(error) - if (code === 'ENOENT' || code === 'ENOTDIR') { + // A link loop holds no history either. + if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP') { return null } throw error } } - protected writeMigrationRecord(path: string, record: object): void { + protected writeMigrationRecord( + path: string, + record: LegacyHistoryState | LegacyMigrationMarker + ): void { writeFileAtomically(path, `${JSON.stringify(record)}\n`) } @@ -236,12 +252,12 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa legacyFilePath: string, targetPath: string, accountId: string, - options: { preservedNameOnly?: boolean } = {} + preservedNameOnly = false ): { path: string; preserved: boolean } { let legacyContents: Buffer | null = null const readLegacy = (): Buffer => (legacyContents ??= readFileSync(legacyFilePath)) if ( - !options.preservedNameOnly && + !preservedNameOnly && this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath, readLegacy) !== 'conflict' ) { return { path: targetPath, preserved: false } diff --git a/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx b/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx index f589778bfc83..62069f9b1920 100644 --- a/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx +++ b/src/renderer/src/components/settings/accounts/accounts-pane-removal-dialogs.tsx @@ -57,7 +57,7 @@ export function renderAccountsRemovalDialogs( {t( 'settings.accounts.codexRemoveHome', - "Orca deletes this account's Codex folder on {{host}}, including its sign-in and MCP logins. Its Codex history (sessions and prompt history) stays in the account's folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", + "Orca deletes this account's Codex folder on {{host}}, including its sign-in and MCP logins. This cannot be undone. If it is selected, the next Codex you start uses System default.", { host: accountRuntimeSentenceLabel } )} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index c214e71c662d..fef510689844 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1200,7 +1200,7 @@ "followSymlinkedDirectories": "Follow symlinked directories", "followSymlinkedDirectoriesDescription": "Search linked folders in Quick Open and expand local linked folders in File Explorer.", "accounts": { - "codexRemoveHome": "Orca deletes this account's Codex folder on {{host}}, including its sign-in and MCP logins. Its Codex history (sessions and prompt history) stays in the account's folder. This cannot be undone. If it is selected, the next Codex you start uses System default.", + "codexRemoveHome": "Orca deletes this account's Codex folder on {{host}}, including its sign-in and MCP logins. This cannot be undone. If it is selected, the next Codex you start uses System default.", "claudeRemoveProfile": "Orca deletes this account's own Claude folder and the sign-in saved in it on {{host}}. Your System default login and chat history shared with it stay. If it is selected, the next Claude you start uses System default." }, "sourceControl": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 1f22259515cf..b6a52f6f0fa7 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -576,7 +576,7 @@ "followSymlinkedDirectories": "跟随符号链接目录", "followSymlinkedDirectoriesDescription": "在快速打开中搜索链接文件夹,并在文件资源管理器中展开本地链接文件夹", "accounts": { - "codexRemoveHome": "Orca 会删除此账户在 {{host}} 上的 Codex 文件夹,包括其中的登录信息和 MCP 登录。它的 Codex 历史记录(会话和提示历史)会保留在该账户的文件夹中。此操作无法撤销。如果此账户被选中,你下次启动的 Codex 将使用系统默认", + "codexRemoveHome": "Orca 会删除此账户在 {{host}} 上的 Codex 文件夹,包括其中的登录信息和 MCP 登录。此操作无法撤销。如果此账户被选中,你下次启动的 Codex 将使用系统默认", "claudeRemoveProfile": "Orca 会删除此账户在 {{host}} 上自己的 Claude 文件夹及其中保存的登录信息,你的系统默认登录以及与其共享的聊天记录会保留。如果此账户被选中,你下次启动的 Claude 将使用系统默认" }, "sourceControl": { From 3cc96acaf62a3f731cb934ffb68028b925745efd Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:25:22 -0800 Subject: [PATCH 24/30] fix(codex): leave a linked secrets folder's files alone; reuse one temp name for the history import Removal beside a linked history deleted secrets/*.age through a secrets folder linked to another home. Those files now stay when secrets is a link. The history import and its state writes use one fixed temp name, cleared before each attempt, so a restart mid-import never leaves copies behind. --- .../codex-managed-home-lifecycle.test.ts | 14 ++++++++++++++ .../managed-homes/linked-history-login-removal.ts | 6 ++++++ .../legacy-host/legacy-history-migration.ts | 5 +++-- .../legacy-host/legacy-prompt-history-import.ts | 5 +++-- .../runtime-home-legacy-migration.test.ts | 12 ++++++++++++ 5 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index e9c6a7cc2e9a..c5ab3f2fe639 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -122,6 +122,20 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { expect(readdirSync(join(f.home, 'secrets'))).toEqual(['prompts.jsonl']) }) + it('leaves the files of a linked secrets folder to the home it points to', async () => { + const f = fixture() + const otherSecrets = join(f.accountsRoot, 'other-secrets') + mkdirSync(otherSecrets) + writeFileSync(join(otherSecrets, 'codex_auth.age'), 'sealed') + symlinkSync(otherSecrets, join(f.home, 'secrets')) + writeFileSync(join(f.home, 'prompts.jsonl'), '{"text":"only prompt"}\n') + symlinkSync('prompts.jsonl', join(f.home, 'history.jsonl')) + + await f.lifecycle.safeRemove(f.home, 'a') + + expect(readdirSync(otherSecrets)).toEqual(['codex_auth.age']) + }) + it('removes a home that never shared history entirely', async () => { const f = fixture() writeFileSync(join(f.home, 'auth.json'), '{}') diff --git a/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts b/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts index 97af9e441a52..722d67c64a08 100644 --- a/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts +++ b/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts @@ -29,7 +29,12 @@ export async function removeLoginsBesideLinkedHistory(home: string): Promise null))?.isSymbolicLink() for (const name of LOGIN_FILES) { + if (secretsLinked && name.startsWith('secrets/')) { + continue + } const path = join(home, name) const file = await lstat(path, { bigint: true }).catch(() => null) if (!file || file.isDirectory()) { @@ -50,6 +55,7 @@ export const LINKED_HISTORY_REMOVAL_SCRIPT = [ ' exit 1', ' fi', ` for name in ${LOGIN_FILES.join(' ')}; do`, + ' case "$name" in secrets/*) if [ -L "$home/secrets" ]; then continue; fi ;; esac', ' file="$home/$name"', ' if [ -d "$file" ] || { [ ! -e "$file" ] && [ ! -L "$file" ]; }; then continue; fi', ' if [ ! -L "$file" ] && [ "$file" -ef "$home/history.jsonl" ]; then continue; fi', diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts index 5900781fd42b..65d62e786b17 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -1,4 +1,3 @@ -import { randomUUID } from 'node:crypto' import { readFile, rename, rm, writeFile } from 'node:fs/promises' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { @@ -72,7 +71,9 @@ async function readTextIfPresent(path: string): Promise { } async function writeTextAtomically(path: string, text: string): Promise { - const tmpPath = `${path}.${process.pid}.${randomUUID()}.tmp` + // One fixed name, cleared first, so a quit mid-write leaves nothing behind for good. + const tmpPath = `${path}.tmp` + await rm(tmpPath, { force: true }) try { await writeFile(tmpPath, text, { encoding: 'utf-8', flag: 'wx' }) await rename(tmpPath, path) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 82cacc163c42..778cb5566fd6 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,4 +1,3 @@ -import { randomUUID } from 'node:crypto' import { link, lstat, open, readFile, readdir, rm, stat } from 'node:fs/promises' import { dirname, join } from 'node:path' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' @@ -124,7 +123,9 @@ async function publishWithoutOverwrite( contents: string, targetPath: string ): Promise { - const tmpPath = `${targetPath}.${process.pid}.${randomUUID()}.tmp` + // One fixed name, cleared first: an attempt a quit cut short never leaves a copy behind for good. + const tmpPath = `${targetPath}.orca-import.tmp` + await rm(tmpPath, { force: true }) try { const handle = await open(tmpPath, 'wx', 0o600) try { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 4c6d1ceb06fa..1acd66b60285 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -360,6 +360,18 @@ describe('CodexRuntimeHomeService', () => { expect(existsSync(migrationMarkerPath())).toBe(true) }) + it('clears the temp copy an interrupted import left behind', async () => { + const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') + mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) + writeFileSync(`${runtimeHistoryPath}.orca-import.tmp`, '{"id":"half', 'utf-8') + writeHistory('account-1', '{"id":"legacy-1"}\n') + + await startService() + + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') + expect(existsSync(`${runtimeHistoryPath}.orca-import.tmp`)).toBe(false) + }) + it('leaves a shared history Codex creates during the import as it is', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') From 96cf8ec91f41b45fd8ca4ece3d3ec0c65a3e32e2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:13:02 -0800 Subject: [PATCH 25/30] fix(codex): remove nothing from a home whose history is a link; copy histories again on every retry Deleting login files beside a linked history kept meeting link chains that reach the history. A home whose history.jsonl is a link, which Orca never creates, now keeps everything, sign-in included. Preservation no longer skips accounts recorded by an earlier attempt, so a history that changed since gets a fresh copy instead of leaving a stale one. --- .../codex-managed-home-lifecycle.test.ts | 62 ++--------------- .../codex-managed-home-lifecycle.ts | 10 ++- .../linked-history-login-removal.ts | 66 ------------------- .../legacy-host/legacy-history-migration.ts | 7 -- .../runtime-home-legacy-migration.test.ts | 28 ++++++++ .../runtime-home-service-legacy-migration.ts | 19 ++---- 6 files changed, 43 insertions(+), 149 deletions(-) delete mode 100644 src/main/codex-accounts/managed-homes/linked-history-login-removal.ts diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index c5ab3f2fe639..57ce747fd606 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -69,73 +69,25 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { expect(readFileSync(join(f.home, 'sessions', 'rollout.jsonl'), 'utf8')).toBe('only copy\n') }) - it('deletes only the logins from a home whose prompt history is a link', async () => { + it('removes nothing from a home whose prompt history is a link', async () => { const f = fixture() - mkdirSync(join(f.home, '..backup')) - writeFileSync(join(f.home, '..backup', 'prompts.jsonl'), '{"text":"only prompt"}\n') - mkdirSync(join(f.home, 'middle')) - symlinkSync(join('..', '..backup'), join(f.home, 'middle', 'next')) - symlinkSync(join('middle', 'next'), join(f.home, 'bridge')) - symlinkSync(join('bridge', 'prompts.jsonl'), join(f.home, 'history.jsonl')) - writeFileSync(join(f.home, 'auth.json'), '{}') - writeFileSync(join(f.home, '.credentials.json'), '{}') mkdirSync(join(f.home, 'secrets')) - writeFileSync(join(f.home, 'secrets', 'codex_auth.age'), 'sealed') + writeFileSync(join(f.home, 'secrets', 'codex_auth.age'), '{"text":"only prompt"}\n') + symlinkSync(join('secrets', 'codex_auth.age'), join(f.home, 'auth.json')) + symlinkSync('auth.json', join(f.home, 'history.jsonl')) + writeFileSync(join(f.home, 'config.toml'), '') await f.lifecycle.safeRemove(f.home, 'a') expect(readdirSync(f.home).sort()).toEqual([ - '..backup', - 'bridge', + 'auth.json', + 'config.toml', 'history.jsonl', - 'middle', 'secrets' ]) - expect(readdirSync(join(f.home, 'secrets'))).toEqual([]) expect(readFileSync(join(f.home, 'history.jsonl'), 'utf8')).toBe('{"text":"only prompt"}\n') }) - it('deletes only the logins when the prompt history is a link it cannot follow', async () => { - const f = fixture() - const outside = join(f.accountsRoot, 'outside') - mkdirSync(outside) - writeFileSync(join(f.home, 'PROMPTS.saved'), '{"text":"only prompt"}\n') - symlinkSync(join(outside, 'gone', 'link'), join(f.home, 'history.jsonl')) - writeFileSync(join(f.home, 'auth.json'), '{}') - - await f.lifecycle.safeRemove(f.home, 'a') - - expect(readdirSync(f.home).sort()).toEqual(['PROMPTS.saved', 'history.jsonl']) - }) - - it('keeps a linked prompt history that lives beside the logins it removes', async () => { - const f = fixture() - mkdirSync(join(f.home, 'secrets')) - writeFileSync(join(f.home, 'secrets', 'prompts.jsonl'), '{"text":"only prompt"}\n') - writeFileSync(join(f.home, 'secrets', 'mcp_oauth.age'), 'sealed') - symlinkSync(join('secrets', 'prompts.jsonl'), join(f.home, 'history.jsonl')) - writeFileSync(join(f.home, 'config.toml'), '[mcp_servers.x.http_headers]\n') - - await f.lifecycle.safeRemove(f.home, 'a') - - expect(readdirSync(f.home).sort()).toEqual(['history.jsonl', 'secrets']) - expect(readdirSync(join(f.home, 'secrets'))).toEqual(['prompts.jsonl']) - }) - - it('leaves the files of a linked secrets folder to the home it points to', async () => { - const f = fixture() - const otherSecrets = join(f.accountsRoot, 'other-secrets') - mkdirSync(otherSecrets) - writeFileSync(join(otherSecrets, 'codex_auth.age'), 'sealed') - symlinkSync(otherSecrets, join(f.home, 'secrets')) - writeFileSync(join(f.home, 'prompts.jsonl'), '{"text":"only prompt"}\n') - symlinkSync('prompts.jsonl', join(f.home, 'history.jsonl')) - - await f.lifecycle.safeRemove(f.home, 'a') - - expect(readdirSync(otherSecrets)).toEqual(['codex_auth.age']) - }) - it('removes a home that never shared history entirely', async () => { const f = fixture() writeFileSync(join(f.home, 'auth.json'), '{}') diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index af1c606b8d02..a50639ef6505 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -23,10 +23,6 @@ import { } from '../../codex/history/shared-store/codex-account-history-cleanup-manifest' import { ManagedCodexHomeTemporarilyUnavailableError } from './host-codex-managed-home-ownership' import type { CodexManagedHomePath } from './codex-managed-home-path' -import { - LINKED_HISTORY_REMOVAL_SCRIPT, - removeLoginsBesideLinkedHistory -} from './linked-history-login-removal' const WSL_MANAGED_HOME_TIMEOUT_MS = 5_000 @@ -47,7 +43,8 @@ const KEPT_HISTORY = [ const KEEP_ON_REMOVAL_SCRIPT = [ 'set -u', 'home=$1', - ...LINKED_HISTORY_REMOVAL_SCRIPT, + // What a linked history reaches can't be told apart from private state, so nothing is removed. + 'if [ -L "$home/history.jsonl" ]; then exit 0; fi', 'kept() {', ' case "${1##*/}" in', ' *.orca-profile-merge) return 0 ;;', @@ -78,8 +75,9 @@ const KEEP_ON_REMOVAL_SCRIPT = [ async function removeManagedHomeKeepingSharedHistory(home: string): Promise { const entries = await readdir(home, { withFileTypes: true }) const sharedOnce = entries.some((entry) => entry.name === HISTORY_CLEANUP_MANIFEST) + // A hand-made link Orca never creates: what it reaches can't be told apart from private state, so + // the whole home stays, sign-in included, rather than risk the history. if (entries.some((entry) => entry.name === 'history.jsonl' && entry.isSymbolicLink())) { - await removeLoginsBesideLinkedHistory(home) return true } const kept = (entry: Dirent): boolean => diff --git a/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts b/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts deleted file mode 100644 index 722d67c64a08..000000000000 --- a/src/main/codex-accounts/managed-homes/linked-history-login-removal.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { lstat, rm, stat } from 'node:fs/promises' -import { join } from 'node:path' -import { errnoCodeOrUnknown } from '../../../shared/errors/errno-code' - -/** - * The sign-in, MCP logins (including tokens set in config.toml) and Codex's encrypted credential - * stores. A home whose history.jsonl is a link loses only these files on removal: what the link - * reaches can't be told apart from private state by name, so nothing else is removed. - */ -const LOGIN_FILES = [ - 'auth.json', - '.credentials.json', - 'config.toml', - 'secrets/codex_auth.age', - 'secrets/mcp_oauth.age', - 'secrets/gateway_oauth.age', - 'secrets/local.age' -] - -/** Skips a login file that is the file the history link reaches; throws if the link can't be checked. */ -export async function removeLoginsBesideLinkedHistory(home: string): Promise { - const history = await stat(join(home, 'history.jsonl'), { bigint: true }).catch( - (error: unknown) => { - // A dangling link reaches no file, so it can't be one of these. - const code = errnoCodeOrUnknown(error) - if (code === 'ENOENT' || code === 'ENOTDIR') { - return null - } - throw error - } - ) - // A linked secrets folder belongs to wherever it points: its files are not this account's. - const secretsLinked = (await lstat(join(home, 'secrets')).catch(() => null))?.isSymbolicLink() - for (const name of LOGIN_FILES) { - if (secretsLinked && name.startsWith('secrets/')) { - continue - } - const path = join(home, name) - const file = await lstat(path, { bigint: true }).catch(() => null) - if (!file || file.isDirectory()) { - continue - } - if (history && file.dev === history.dev && file.ino === history.ino) { - continue - } - // Removes a link itself, never what it points to. - await rm(path, { force: true }) - } -} - -/** The same for a WSL home, as bash lines run with the home in $home; exits after removing. */ -export const LINKED_HISTORY_REMOVAL_SCRIPT = [ - 'if [ -L "$home/history.jsonl" ]; then', - ' if [ ! -e "$home/history.jsonl" ] && ! readlink -f -- "$home/history.jsonl" >/dev/null 2>&1; then', - ' exit 1', - ' fi', - ` for name in ${LOGIN_FILES.join(' ')}; do`, - ' case "$name" in secrets/*) if [ -L "$home/secrets" ]; then continue; fi ;; esac', - ' file="$home/$name"', - ' if [ -d "$file" ] || { [ ! -e "$file" ] && [ ! -L "$file" ]; }; then continue; fi', - ' if [ ! -L "$file" ] && [ "$file" -ef "$home/history.jsonl" ]; then continue; fi', - ' rm -f -- "$file" || exit 1', - ' done', - ' exit 0', - 'fi' -] diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts index 65d62e786b17..9e6f399a0cba 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -11,8 +11,6 @@ export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 export type LegacyHistoryState = { - /** Accounts whose history has its copy, so a retry doesn't copy them again. */ - preservedAccounts?: string[] /** A session copy failed; later launches run the session pass again. */ sessionsPending?: boolean /** The shared history was created, or already existed, so nothing is owed. */ @@ -36,11 +34,6 @@ export function parseLegacyHistoryState(text: string): LegacyHistoryState { if (!parsed || typeof parsed !== 'object') { return state } - if ('preservedAccounts' in parsed && Array.isArray(parsed.preservedAccounts)) { - state.preservedAccounts = parsed.preservedAccounts.filter( - (accountId): accountId is string => typeof accountId === 'string' - ) - } if ('sessionsPending' in parsed && parsed.sessionsPending === true) { state.sessionsPending = true } diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 1acd66b60285..a886bfd7388b 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -271,6 +271,34 @@ describe('CodexRuntimeHomeService', () => { await waitForHistorySettled() }) + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'copies a history again on retry when it changed after an earlier attempt', + async () => { + const firstHome = writeHistory('account-1', '{"id":"a-1"}\n') + const blockedHistory = join(writeHistory('account-2', '{"id":"b-1"}\n'), 'history.jsonl') + chmodSync(blockedHistory, 0o000) + try { + await constructService() + await waitForImportOutcomes(['failed']) + } finally { + chmodSync(blockedHistory, 0o644) + } + expect(existsSync(migrationMarkerPath())).toBe(false) + writeFileSync(join(firstHome, 'history.jsonl'), '{"id":"a-1"}\n{"id":"a-2"}\n', 'utf-8') + + vi.resetModules() + await startService() + + expect( + readFileSync( + join(getRuntimeCodexHomePath(), 'history.orca-legacy-account-1-1.jsonl'), + 'utf-8' + ) + ).toBe('{"id":"a-1"}\n{"id":"a-2"}\n') + expect(existsSync(migrationMarkerPath())).toBe(true) + } + ) + it('makes a real copy when the shared history and the preserved name only link to the account history', async () => { const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index ad55d08d03b3..18e37c18d39d 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -107,12 +107,9 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa ): void { const managedHomes = this.getLegacyManagedHomes() if (!migrated) { - const preserved = new Set(state.preservedAccounts) - this.preserveLegacyHistories(managedHomes, preserved, (accountId) => { - preserved.add(accountId) - state = { ...state, preservedAccounts: [...preserved] } - this.writeMigrationRecord(historyStatePath, state) - }) + // Every retry copies again: an unchanged history is found identical, a changed one gets a + // fresh copy, so no copy is ever stale. + this.preserveLegacyHistories(managedHomes) } let sessionsPending = false for (const managedHomePath of managedHomes) { @@ -133,11 +130,7 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa // Each account's own history, copied into the runtime home, where no Orca path deletes it. A // folder Orca doesn't own can't be removed through Orca, so one that fails is skipped. - protected preserveLegacyHistories( - managedHomes: readonly string[], - alreadyPreserved: ReadonlySet, - recordPreserved: (accountId: string) => void - ): void { + protected preserveLegacyHistories(managedHomes: readonly string[]): void { const managedAccounts = new Set(managedHomes.map((home) => basename(dirname(home)))) const runtimeHistoryPath = join(this.getRuntimeHomePath(), 'history.jsonl') mkdirSync(this.getRuntimeHomePath(), { recursive: true }) @@ -145,9 +138,6 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa const sharedHistory = this.legacyHistorySource(runtimeHistoryPath, { followLink: false }) const copiedSources = new Set() for (const accountId of this.listLegacyAccountIds()) { - if (alreadyPreserved.has(accountId)) { - continue - } try { const historyPath = join(this.getManagedAccountsRoot(), accountId, 'home', 'history.jsonl') const source = this.legacyHistorySource(historyPath, { followLink: true }) @@ -158,7 +148,6 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa this.copyLegacyFilePreservingConflicts(source, runtimeHistoryPath, accountId, true) copiedSources.add(source) } - recordPreserved(accountId) } catch (error) { if (managedAccounts.has(accountId)) { throw error From 0c37e1d1a3fcef47a8a121fe885e58e6be0fc626 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:39:57 -0800 Subject: [PATCH 26/30] refactor(codex): main's migration marker, capped session retries, Windows FAT counts as no hard links Downgrades and hand-made history links are out of scope, so the preserved history copies and the marker ordering built for them go: migration-v1.json is written after the session pass, as on main. A failed session pass retries three times, then once a day, and a retry never adds a second preserved copy, so disk stays flat while a failure persists. EISDIR from link() on Windows (FAT, exFAT) settles as no hard links. Import temp copies get unique names, and leftovers are removed. --- config/main-sync-fs-baseline.txt | 2 +- .../codex-managed-home-lifecycle.test.ts | 19 -- .../codex-managed-home-lifecycle.ts | 7 - .../legacy-host/legacy-history-migration.ts | 28 ++- .../legacy-prompt-history-import.ts | 55 +++--- .../runtime-home-legacy-migration.test.ts | 179 ++++-------------- .../runtime-home-service-legacy-migration.ts | 161 ++++++---------- 7 files changed, 146 insertions(+), 305 deletions(-) diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index caefbc1e5e68..90ebd5fc1ef4 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -127,7 +127,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -19 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +16 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts index 57ce747fd606..6864a2d058a1 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.test.ts @@ -69,25 +69,6 @@ describe('CodexManagedHomeLifecycle.safeRemove', () => { expect(readFileSync(join(f.home, 'sessions', 'rollout.jsonl'), 'utf8')).toBe('only copy\n') }) - it('removes nothing from a home whose prompt history is a link', async () => { - const f = fixture() - mkdirSync(join(f.home, 'secrets')) - writeFileSync(join(f.home, 'secrets', 'codex_auth.age'), '{"text":"only prompt"}\n') - symlinkSync(join('secrets', 'codex_auth.age'), join(f.home, 'auth.json')) - symlinkSync('auth.json', join(f.home, 'history.jsonl')) - writeFileSync(join(f.home, 'config.toml'), '') - - await f.lifecycle.safeRemove(f.home, 'a') - - expect(readdirSync(f.home).sort()).toEqual([ - 'auth.json', - 'config.toml', - 'history.jsonl', - 'secrets' - ]) - expect(readFileSync(join(f.home, 'history.jsonl'), 'utf8')).toBe('{"text":"only prompt"}\n') - }) - it('removes a home that never shared history entirely', async () => { const f = fixture() writeFileSync(join(f.home, 'auth.json'), '{}') diff --git a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index a50639ef6505..efc80c2c5159 100644 --- a/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -43,8 +43,6 @@ const KEPT_HISTORY = [ const KEEP_ON_REMOVAL_SCRIPT = [ 'set -u', 'home=$1', - // What a linked history reaches can't be told apart from private state, so nothing is removed. - 'if [ -L "$home/history.jsonl" ]; then exit 0; fi', 'kept() {', ' case "${1##*/}" in', ' *.orca-profile-merge) return 0 ;;', @@ -75,11 +73,6 @@ const KEEP_ON_REMOVAL_SCRIPT = [ async function removeManagedHomeKeepingSharedHistory(home: string): Promise { const entries = await readdir(home, { withFileTypes: true }) const sharedOnce = entries.some((entry) => entry.name === HISTORY_CLEANUP_MANIFEST) - // A hand-made link Orca never creates: what it reaches can't be told apart from private state, so - // the whole home stays, sign-in included, rather than risk the history. - if (entries.some((entry) => entry.name === 'history.jsonl' && entry.isSymbolicLink())) { - return true - } const kept = (entry: Dirent): boolean => KEPT_HISTORY.includes(entry.name) || entry.name.endsWith(MERGE_PENDING_SUFFIX) || diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts index 9e6f399a0cba..0315d4c22eaa 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -11,8 +11,9 @@ export const MAX_HISTORY_IMPORT_ATTEMPTS = 3 export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 export type LegacyHistoryState = { - /** A session copy failed; later launches run the session pass again. */ - sessionsPending?: boolean + /** Failed session passes; after a few, the pass waits a day between tries. */ + sessionPassAttempts?: number + sessionPassFailedAt?: number /** The shared history was created, or already existed, so nothing is owed. */ historyImportSettled?: boolean historyImportAttempts?: number @@ -21,6 +22,22 @@ export type LegacyHistoryState = { historyImportGaveUpAt?: number } +/** Like the import: a few tries, then once a day, so a lasting failure isn't redone every launch. */ +export function legacySessionPassDue(state: LegacyHistoryState): boolean { + return ( + (state.sessionPassAttempts ?? 0) < MAX_HISTORY_IMPORT_ATTEMPTS || + Date.now() - (state.sessionPassFailedAt ?? 0) >= HISTORY_IMPORT_RETRY_INTERVAL_MS + ) +} + +export function recordLegacySessionPassFailure(state: LegacyHistoryState): LegacyHistoryState { + return { + ...state, + sessionPassAttempts: (state.sessionPassAttempts ?? 0) + 1, + sessionPassFailedAt: Date.now() + } +} + /** Where the shared history import reads and records its attempts. */ export type LegacyHistoryImportPaths = { accountsRoot: string @@ -34,8 +51,11 @@ export function parseLegacyHistoryState(text: string): LegacyHistoryState { if (!parsed || typeof parsed !== 'object') { return state } - if ('sessionsPending' in parsed && parsed.sessionsPending === true) { - state.sessionsPending = true + if ('sessionPassAttempts' in parsed && typeof parsed.sessionPassAttempts === 'number') { + state.sessionPassAttempts = parsed.sessionPassAttempts + } + if ('sessionPassFailedAt' in parsed && typeof parsed.sessionPassFailedAt === 'number') { + state.sessionPassFailedAt = parsed.sessionPassFailedAt } if ('historyImportSettled' in parsed && parsed.historyImportSettled === true) { state.historyImportSettled = true diff --git a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts index 778cb5566fd6..8bc0223b2d72 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -1,7 +1,9 @@ +import { randomUUID } from 'node:crypto' import { link, lstat, open, readFile, readdir, rm, stat } from 'node:fs/promises' -import { dirname, join } from 'node:path' +import { basename, dirname, join } from 'node:path' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { track } from '../../../telemetry/client' +import { isHardLinkUnsupportedError } from '../../../codex/history/rollouts/codex-rollout-copy' import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas' type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number] @@ -55,22 +57,6 @@ async function listAccountHistories(accountsRoot: string): Promise { return paths.sort() } -const PRESERVED_HISTORY_NAME = /^history\.orca-legacy-.+\.jsonl$/ - -// The account histories the migration preserved in the runtime home, which outlive the accounts. -async function listPreservedHistories(runtimeHome: string): Promise { - const entries = await readdir(runtimeHome, { withFileTypes: true }).catch((error: unknown) => { - if (errnoCodeOrUnknown(error) === 'ENOENT') { - return [] - } - throw error - }) - return entries - .filter((entry) => entry.isFile() && PRESERVED_HISTORY_NAME.test(entry.name)) - .map((entry) => join(runtimeHome, entry.name)) - .sort() -} - /** * Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one * is created from the account histories, which are only read, and never over one Codex creates @@ -80,10 +66,7 @@ export async function importLegacyHistoriesIfSharedAbsent( accountsRoot: string, runtimeHistoryPath: string ): Promise { - const accountHistoryPaths = [ - ...(await listAccountHistories(accountsRoot)), - ...(await listPreservedHistories(dirname(runtimeHistoryPath))) - ] + const accountHistoryPaths = await listAccountHistories(accountsRoot) if (accountHistoryPaths.length === 0) { return } @@ -116,16 +99,12 @@ async function publishLegacyHistoriesIfAbsent( return publishWithoutOverwrite(`${[...seenLines].join('\n')}\n`, runtimeHistoryPath) } -// exFAT, FAT32 and some network or FUSE mounts refuse hard links. -const HARD_LINK_UNSUPPORTED = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV']) - async function publishWithoutOverwrite( contents: string, targetPath: string ): Promise { - // One fixed name, cleared first: an attempt a quit cut short never leaves a copy behind for good. - const tmpPath = `${targetPath}.orca-import.tmp` - await rm(tmpPath, { force: true }) + await removeStaleImportCopies(targetPath) + const tmpPath = `${targetPath}.${process.pid}.${randomUUID()}${IMPORT_COPY_SUFFIX}` try { const handle = await open(tmpPath, 'wx', 0o600) try { @@ -140,6 +119,23 @@ async function publishWithoutOverwrite( } } +const IMPORT_COPY_SUFFIX = '.orca-import.tmp' + +// Copies an attempt a quit cut short left behind. Only regular files: removing one only drops that +// name, even when it is a hard link to the published history. +async function removeStaleImportCopies(targetPath: string): Promise { + const prefix = `${basename(targetPath)}.` + for (const entry of await readdir(dirname(targetPath), { withFileTypes: true })) { + if ( + entry.isFile() && + entry.name.startsWith(prefix) && + entry.name.endsWith(IMPORT_COPY_SUFFIX) + ) { + await rm(join(dirname(targetPath), entry.name), { force: true }) + } + } +} + // A hard link publishes only into a free name: one Codex created meanwhile stays as it is. async function linkIntoFreeName( tmpPath: string, @@ -154,8 +150,9 @@ async function linkIntoFreeName( return 'skipped_existing' } // No safe way to publish without replacing: every other way leaves a name Codex can append - // into mid-write. The account histories stay in their homes, so nothing is lost. - if (HARD_LINK_UNSUPPORTED.has(code)) { + // into mid-write. The account histories stay in their homes, so nothing is lost, and the import + // settles rather than retry on a filesystem that won't change. + if (isHardLinkUnsupportedError(error)) { return 'skipped_no_hard_links' } throw error diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index a886bfd7388b..b03f66731cd3 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -1,12 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { - chmodSync, existsSync, - lstatSync, mkdirSync, readlinkSync, readFileSync, + readdirSync, rmSync, symlinkSync, writeFileSync @@ -89,10 +88,6 @@ async function waitForHistorySettled(): Promise { ) } -function preservedHistoryPath(accountId: string): string { - return join(getRuntimeCodexHomePath(), `history.orca-legacy-${accountId}.jsonl`) -} - function historyStatePath(): string { return join(testState.userDataDir, 'codex-runtime-home', 'migration-v1-history.json') } @@ -234,121 +229,7 @@ describe('CodexRuntimeHomeService', () => { ) }) - it('preserves each account history in the runtime home before marking the migration done', async () => { - const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') - writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}\n', 'utf-8') - writeFileSync(preservedHistoryPath('account-1'), '{"id":"older-copy"}\n', 'utf-8') - writeHistory('account-1', '{"id":"legacy-1"}\n') - - await startService() - - // An older build sees only this marker: it must not rerun its overwriting migration, and its - // account removal must not take the only copy of these prompts. - expect(existsSync(migrationMarkerPath())).toBe(true) - expect(readFileSync(preservedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"older-copy"}\n') - expect( - readFileSync( - join(getRuntimeCodexHomePath(), 'history.orca-legacy-account-1-1.jsonl'), - 'utf-8' - ) - ).toBe('{"id":"legacy-1"}\n') - expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}\n') - }) - - it('copies the history, the sessions and the marker before the service is constructed', async () => { - const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') - mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) - writeFileSync(join(managedHomePath, 'sessions', 'rollout.jsonl'), '{}', 'utf-8') - - await constructService() - - // Nothing can remove or share the account before this: it all happened in the constructor. - expect(readFileSync(preservedHistoryPath('account-1'), 'utf-8')).toBe('{"id":"legacy-1"}\n') - expect( - readFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'rollout.jsonl'), 'utf-8') - ).toBe('{}') - expect(existsSync(migrationMarkerPath())).toBe(true) - await waitForHistorySettled() - }) - - it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( - 'copies a history again on retry when it changed after an earlier attempt', - async () => { - const firstHome = writeHistory('account-1', '{"id":"a-1"}\n') - const blockedHistory = join(writeHistory('account-2', '{"id":"b-1"}\n'), 'history.jsonl') - chmodSync(blockedHistory, 0o000) - try { - await constructService() - await waitForImportOutcomes(['failed']) - } finally { - chmodSync(blockedHistory, 0o644) - } - expect(existsSync(migrationMarkerPath())).toBe(false) - writeFileSync(join(firstHome, 'history.jsonl'), '{"id":"a-1"}\n{"id":"a-2"}\n', 'utf-8') - - vi.resetModules() - await startService() - - expect( - readFileSync( - join(getRuntimeCodexHomePath(), 'history.orca-legacy-account-1-1.jsonl'), - 'utf-8' - ) - ).toBe('{"id":"a-1"}\n{"id":"a-2"}\n') - expect(existsSync(migrationMarkerPath())).toBe(true) - } - ) - - it('makes a real copy when the shared history and the preserved name only link to the account history', async () => { - const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') - mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) - symlinkSync(join(managedHomePath, 'history.jsonl'), preservedHistoryPath('account-1')) - symlinkSync( - join(managedHomePath, 'history.jsonl'), - join(getRuntimeCodexHomePath(), 'history.jsonl') - ) - - await startService() - - const copyPath = join(getRuntimeCodexHomePath(), 'history.orca-legacy-account-1-1.jsonl') - expect(lstatSync(copyPath).isFile()).toBe(true) - expect(readFileSync(copyPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') - }) - - it('imports from the preserved history once the account folder is gone', async () => { - mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) - writeFileSync(preservedHistoryPath('account-1'), '{"id":"legacy-1"}\n', 'utf-8') - mkdirSync(join(historyStatePath(), '..'), { recursive: true }) - writeFileSync(migrationMarkerPath(), '{}', 'utf-8') - writeFileSync(historyStatePath(), JSON.stringify({ historyImportAttempts: 1 }), 'utf-8') - - await startService() - - expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( - '{"id":"legacy-1"}\n' - ) - }) - - it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( - 'copies no sessions and leaves the migration unmarked until every account history has its copy', - async () => { - const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') - mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) - writeFileSync(join(managedHomePath, 'sessions', 'rollout.jsonl'), '{}', 'utf-8') - chmodSync(join(managedHomePath, 'history.jsonl'), 0o000) - try { - await constructService() - await waitForImportOutcomes(['failed']) - } finally { - chmodSync(join(managedHomePath, 'history.jsonl'), 0o644) - } - - expect(existsSync(join(getRuntimeCodexHomePath(), 'sessions', 'rollout.jsonl'))).toBe(false) - expect(existsSync(migrationMarkerPath())).toBe(false) - } - ) - - it('imports history and marks the migration done when a session copy fails, then retries the sessions', async () => { + it('imports history even when a session copy fails, and retries the sessions next launch', async () => { const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') blockSessionCopies(managedHomePath) @@ -358,46 +239,70 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( '{"id":"a-1"}\n' ) - // The uncopied session stays in the account home, which every build's removal keeps. - expect(existsSync(migrationMarkerPath())).toBe(true) - expect(readFileSync(historyStatePath(), 'utf-8')).toContain('"sessionsPending":true') + expect(existsSync(migrationMarkerPath())).toBe(false) + expect(readFileSync(historyStatePath(), 'utf-8')).toContain('"sessionPassAttempts":1') rmSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested')) vi.resetModules() - await constructService() + await startService() expect( readFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'nested', 'rollout.jsonl'), 'utf-8') ).toBe('{}') - expect(readFileSync(historyStatePath(), 'utf-8')).toContain('"sessionsPending":false') + expect(existsSync(migrationMarkerPath())).toBe(true) }) - it('migrates owned accounts past a folder it does not own whose history is a link loop', async () => { + it('waits a day before another session pass after three failed ones', async () => { const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) writeFileSync(join(managedHomePath, 'sessions', 'rollout.jsonl'), '{}', 'utf-8') - const orphanHome = join(testState.userDataDir, 'codex-accounts', 'orphan', 'home') - mkdirSync(orphanHome, { recursive: true }) - symlinkSync('history.jsonl', join(orphanHome, 'history.jsonl')) + mkdirSync(join(historyStatePath(), '..'), { recursive: true }) + writeFileSync( + historyStatePath(), + // Failed later than any test clock: the day hasn't passed. + JSON.stringify({ sessionPassAttempts: 3, sessionPassFailedAt: Number.MAX_SAFE_INTEGER }), + 'utf-8' + ) await startService() - expect( - readFileSync(join(getRuntimeCodexHomePath(), 'sessions', 'rollout.jsonl'), 'utf-8') - ).toBe('{}') - expect(existsSync(migrationMarkerPath())).toBe(true) + expect(existsSync(join(getRuntimeCodexHomePath(), 'sessions', 'rollout.jsonl'))).toBe(false) + expect(existsSync(migrationMarkerPath())).toBe(false) + }) + + it('adds no second preserved copy when a retried session pass meets a changed session', async () => { + const runtimeSessionsDir = join(getRuntimeCodexHomePath(), 'sessions') + mkdirSync(runtimeSessionsDir, { recursive: true }) + writeFileSync(join(runtimeSessionsDir, 'session.json'), '{"runtime":1}', 'utf-8') + const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') + mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'session.json'), '{"legacy":1}', 'utf-8') + blockSessionCopies(writeHistory('account-2', '{"id":"b-1"}\n')) + await constructService() + await waitForImportOutcomes(['imported']) + writeFileSync(join(managedHomePath, 'sessions', 'session.json'), '{"legacy":2}', 'utf-8') + + vi.resetModules() + await constructService() + + expect(readdirSync(runtimeSessionsDir).sort()).toEqual([ + 'nested', + 'session.json', + 'session.orca-legacy-account-1.json' + ]) }) - it('clears the temp copy an interrupted import left behind', async () => { + it('removes the copy an interrupted import left behind', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') + const leftover = `${runtimeHistoryPath}.4242.0b6f3c1e-2d4a-4b8e-9f10-7a6c5d4e3f21.orca-import.tmp` mkdirSync(getRuntimeCodexHomePath(), { recursive: true }) - writeFileSync(`${runtimeHistoryPath}.orca-import.tmp`, '{"id":"half', 'utf-8') + writeFileSync(leftover, '{"id":"half', 'utf-8') writeHistory('account-1', '{"id":"legacy-1"}\n') await startService() expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"legacy-1"}\n') - expect(existsSync(`${runtimeHistoryPath}.orca-import.tmp`)).toBe(false) + expect(existsSync(leftover)).toBe(false) }) it('leaves a shared history Codex creates during the import as it is', async () => { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 18e37c18d39d..13ca24703e45 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -7,10 +7,9 @@ import { mkdirSync, readFileSync, readdirSync, - realpathSync, statSync } from 'node:fs' -import { basename, dirname, extname, join, relative } from 'node:path' +import { dirname, extname, join, parse, relative } from 'node:path' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code' import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-migration' @@ -18,7 +17,9 @@ import { normalizeCodexRuntimeSelection } from '../../account-management/runtime import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' import { + legacySessionPassDue, parseLegacyHistoryState, + recordLegacySessionPassFailure, settleLegacyHistoryImport, type LegacyHistoryState } from './legacy-history-migration' @@ -72,15 +73,15 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa if (migrated && !existsSync(historyStatePath)) { return } + let state: LegacyHistoryState = {} try { - let state: LegacyHistoryState = {} - try { - state = parseLegacyHistoryState(readFileSync(historyStatePath, 'utf-8')) - } catch { - // Absent or unreadable: copies already made are found again as identical files. - } - if (!migrated || state.sessionsPending) { - this.migrateLegacyManagedState(historyStatePath, state, migrated) + state = parseLegacyHistoryState(readFileSync(historyStatePath, 'utf-8')) + } catch { + // Absent or unreadable: nothing recorded yet. + } + try { + if (!migrated && legacySessionPassDue(state)) { + this.migrateLegacySessionsAndMarkDone(historyStatePath, state) } } finally { // Independent of the session copies, so one that fails can't hold the import back. @@ -92,105 +93,34 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } } - /** - * One synchronous step at startup, before anything can remove or share an account: every account - * history gets its copy, then the sessions are copied, then the marker older builds read is - * written. No quit lands between them. An older build never sees the marker while an account - * history has no copy (its account removal would take the only one), and never sees copied - * sessions without it (it would rerun its overwriting migration). A session that fails to copy - * stays in its account home, which every build's removal keeps, and is retried on later launches. - */ - protected migrateLegacyManagedState( + protected migrateLegacySessionsAndMarkDone( historyStatePath: string, - state: LegacyHistoryState, - migrated: boolean + state: LegacyHistoryState ): void { + // A retry never adds a second preserved copy, so disk stays flat while a failure persists. + const retry = (state.sessionPassAttempts ?? 0) > 0 const managedHomes = this.getLegacyManagedHomes() - if (!migrated) { - // Every retry copies again: an unchanged history is found identical, a changed one gets a - // fresh copy, so no copy is ever stale. - this.preserveLegacyHistories(managedHomes) - } - let sessionsPending = false - for (const managedHomePath of managedHomes) { - try { - this.migrateLegacySessions(managedHomePath, basename(dirname(managedHomePath))) - } catch (error) { - sessionsPending = true - console.warn('[codex-runtime-home] Failed to migrate legacy Codex sessions:', error) + try { + for (const managedHomePath of managedHomes) { + const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( + /[\\/]/ + )[0] + if (accountId) { + this.migrateLegacySessions(managedHomePath, accountId, retry) + } } + } catch (error) { + this.writeMigrationRecord(historyStatePath, recordLegacySessionPassFailure(state)) + throw error } // Present from here on: later launches owe the import until it settles. - this.writeMigrationRecord(historyStatePath, { ...state, sessionsPending }) + this.writeMigrationRecord(historyStatePath, state) this.writeMigrationRecord(this.getMigrationMarkerPath(), { completedAt: Date.now(), migratedHomeCount: managedHomes.length }) } - // Each account's own history, copied into the runtime home, where no Orca path deletes it. A - // folder Orca doesn't own can't be removed through Orca, so one that fails is skipped. - protected preserveLegacyHistories(managedHomes: readonly string[]): void { - const managedAccounts = new Set(managedHomes.map((home) => basename(dirname(home)))) - const runtimeHistoryPath = join(this.getRuntimeHomePath(), 'history.jsonl') - mkdirSync(this.getRuntimeHomePath(), { recursive: true }) - // An account history that is the shared history itself needs no copy; one it links to does. - const sharedHistory = this.legacyHistorySource(runtimeHistoryPath, { followLink: false }) - const copiedSources = new Set() - for (const accountId of this.listLegacyAccountIds()) { - try { - const historyPath = join(this.getManagedAccountsRoot(), accountId, 'home', 'history.jsonl') - const source = this.legacyHistorySource(historyPath, { followLink: true }) - if (!source) { - continue - } - if (source !== sharedHistory && !copiedSources.has(source)) { - this.copyLegacyFilePreservingConflicts(source, runtimeHistoryPath, accountId, true) - copiedSources.add(source) - } - } catch (error) { - if (managedAccounts.has(accountId)) { - throw error - } - console.warn('[codex-runtime-home] Skipped an unowned legacy Codex history:', error) - } - } - } - - // Every account folder, ownership marker or not, sorted. - protected listLegacyAccountIds(): string[] { - try { - return readdirSync(this.getManagedAccountsRoot(), { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name) - .sort() - } catch (error) { - if (errnoCodeOrUnknown(error) === 'ENOENT') { - return [] - } - throw error - } - } - - // The real path of a regular history file, or null when there is none (or, without followLink, - // when the name is a link). - protected legacyHistorySource(path: string, options: { followLink: boolean }): string | null { - try { - if (!options.followLink && !lstatSync(path).isFile()) { - return null - } - const source = realpathSync(path) - return statSync(source).isFile() ? source : null - } catch (error) { - const code = errnoCodeOrUnknown(error) - // A link loop holds no history either. - if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP') { - return null - } - throw error - } - } - protected writeMigrationRecord( path: string, record: LegacyHistoryState | LegacyMigrationMarker @@ -199,12 +129,26 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected getLegacyManagedHomes(): string[] { - return this.listLegacyAccountIds() - .map((accountId) => join(this.getManagedAccountsRoot(), accountId, 'home')) - .filter((managedHomePath) => existsSync(join(managedHomePath, '.orca-managed-home'))) + const managedAccountsRoot = this.getManagedAccountsRoot() + if (!existsSync(managedAccountsRoot)) { + return [] + } + + const accountEntries = readdirSync(managedAccountsRoot, { withFileTypes: true }) + const managedHomes: string[] = [] + for (const entry of accountEntries) { + if (!entry.isDirectory()) { + continue + } + const managedHomePath = join(managedAccountsRoot, entry.name, 'home') + if (existsSync(join(managedHomePath, '.orca-managed-home'))) { + managedHomes.push(managedHomePath) + } + } + return managedHomes.sort() } - protected migrateLegacySessions(managedHomePath: string, accountId: string): void { + protected migrateLegacySessions(managedHomePath: string, accountId: string, retry = false): void { const legacySessionsRoot = join(managedHomePath, 'sessions') if (!existsSync(legacySessionsRoot)) { return @@ -219,7 +163,8 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa const copy = this.copyLegacyFilePreservingConflicts( legacyFilePath, runtimeFilePath, - accountId + accountId, + retry ) if (copy.preserved) { this.appendMigrationDiagnostic({ @@ -233,20 +178,20 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } /** - * Copies to `targetPath` unless it already holds these bytes; when it holds others (or with - * preservedNameOnly), copies beside it under the next free preserved name. Returns where the - * legacy bytes now are. + * Copies to `targetPath` unless it already holds these bytes; when it holds others, copies beside + * it under the next free preserved name. A retry stops at a taken preserved name instead: an + * earlier attempt already kept a copy, and the source stays in its account home. Returns where + * the legacy bytes now are. */ protected copyLegacyFilePreservingConflicts( legacyFilePath: string, targetPath: string, accountId: string, - preservedNameOnly = false + retry = false ): { path: string; preserved: boolean } { let legacyContents: Buffer | null = null const readLegacy = (): Buffer => (legacyContents ??= readFileSync(legacyFilePath)) if ( - !preservedNameOnly && this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath, readLegacy) !== 'conflict' ) { return { path: targetPath, preserved: false } @@ -254,7 +199,7 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa for (let attempt = 0; ; attempt++) { const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath, readLegacy) - if (result !== 'conflict') { + if (result !== 'conflict' || retry) { return { path: preservedPath, preserved: result === 'copied' } } } From b5e6170ad14579659eac1bf279eb9bf6329e51bc Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:31:07 -0800 Subject: [PATCH 27/30] fix(codex): keep session conflict copies only from a session pass that succeeds A retry that stopped at a taken preserved name could mark the migration done while a session had changed since its copy. Conflict copies are now made after every account's sessions copied: a failing pass adds none, so disk stays flat, and the pass that succeeds keeps each conflict's latest bytes. --- config/main-sync-fs-baseline.txt | 2 +- .../runtime-home-legacy-migration.test.ts | 16 ++-- .../runtime-home-service-legacy-migration.ts | 83 ++++++++++--------- 3 files changed, 56 insertions(+), 45 deletions(-) diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 90ebd5fc1ef4..28016d2a0cba 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -127,7 +127,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -16 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +17 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index b03f66731cd3..3bc3bc334a31 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -270,7 +270,7 @@ describe('CodexRuntimeHomeService', () => { expect(existsSync(migrationMarkerPath())).toBe(false) }) - it('adds no second preserved copy when a retried session pass meets a changed session', async () => { + it('keeps no conflict copy while a session pass fails, then the latest bytes once it succeeds', async () => { const runtimeSessionsDir = join(getRuntimeCodexHomePath(), 'sessions') mkdirSync(runtimeSessionsDir, { recursive: true }) writeFileSync(join(runtimeSessionsDir, 'session.json'), '{"runtime":1}', 'utf-8') @@ -281,15 +281,19 @@ describe('CodexRuntimeHomeService', () => { await constructService() await waitForImportOutcomes(['imported']) writeFileSync(join(managedHomePath, 'sessions', 'session.json'), '{"legacy":2}', 'utf-8') + vi.resetModules() + await constructService() + + expect(readdirSync(runtimeSessionsDir).sort()).toEqual(['nested', 'session.json']) + rmSync(join(runtimeSessionsDir, 'nested')) vi.resetModules() await constructService() - expect(readdirSync(runtimeSessionsDir).sort()).toEqual([ - 'nested', - 'session.json', - 'session.orca-legacy-account-1.json' - ]) + expect( + readFileSync(join(runtimeSessionsDir, 'session.orca-legacy-account-1.json'), 'utf-8') + ).toBe('{"legacy":2}') + expect(existsSync(migrationMarkerPath())).toBe(true) }) it('removes the copy an interrupted import left behind', async () => { diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 13ca24703e45..5626c2d9ba38 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -24,6 +24,8 @@ import { type LegacyHistoryState } from './legacy-history-migration' +type LegacySessionConflict = { legacyFilePath: string; runtimeFilePath: string; accountId: string } + type LegacyMigrationMarker = { completedAt: number; migratedHomeCount: number } export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { @@ -93,20 +95,36 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } } + /** + * Copies the sessions, then keeps each one that conflicts with a runtime file beside it, then + * marks the migration done. The conflict copies wait until every account's sessions copied: a + * pass that fails adds none, so disk stays flat while a failure persists, and the pass that + * succeeds keeps each conflict's latest bytes. + */ protected migrateLegacySessionsAndMarkDone( historyStatePath: string, state: LegacyHistoryState ): void { - // A retry never adds a second preserved copy, so disk stays flat while a failure persists. - const retry = (state.sessionPassAttempts ?? 0) > 0 const managedHomes = this.getLegacyManagedHomes() try { + const conflicts: LegacySessionConflict[] = [] for (const managedHomePath of managedHomes) { const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( /[\\/]/ )[0] if (accountId) { - this.migrateLegacySessions(managedHomePath, accountId, retry) + this.migrateLegacySessions(managedHomePath, accountId, conflicts) + } + } + for (const conflict of conflicts) { + const preserved = this.preserveLegacySessionConflict(conflict) + if (preserved.copied) { + this.appendMigrationDiagnostic({ + type: 'session-conflict', + accountId: conflict.accountId, + runtimeFilePath: conflict.runtimeFilePath, + preservedPath: preserved.path + }) } } } catch (error) { @@ -148,7 +166,12 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return managedHomes.sort() } - protected migrateLegacySessions(managedHomePath: string, accountId: string, retry = false): void { + // Copies each session into a free runtime name; one whose name holds other bytes is collected. + protected migrateLegacySessions( + managedHomePath: string, + accountId: string, + conflicts: LegacySessionConflict[] = [] + ): void { const legacySessionsRoot = join(managedHomePath, 'sessions') if (!existsSync(legacySessionsRoot)) { return @@ -160,47 +183,31 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa const relativePath = relative(legacySessionsRoot, legacyFilePath) const runtimeFilePath = join(runtimeSessionsRoot, relativePath) mkdirSync(dirname(runtimeFilePath), { recursive: true }) - const copy = this.copyLegacyFilePreservingConflicts( - legacyFilePath, - runtimeFilePath, - accountId, - retry - ) - if (copy.preserved) { - this.appendMigrationDiagnostic({ - type: 'session-conflict', - accountId, - runtimeFilePath, - preservedPath: copy.path - }) + let legacyContents: Buffer | null = null + const readLegacy = (): Buffer => (legacyContents ??= readFileSync(legacyFilePath)) + if ( + this.copyLegacyFileWithoutOverwrite(legacyFilePath, runtimeFilePath, readLegacy) === + 'conflict' + ) { + conflicts.push({ legacyFilePath, runtimeFilePath, accountId }) } } } - /** - * Copies to `targetPath` unless it already holds these bytes; when it holds others, copies beside - * it under the next free preserved name. A retry stops at a taken preserved name instead: an - * earlier attempt already kept a copy, and the source stays in its account home. Returns where - * the legacy bytes now are. - */ - protected copyLegacyFilePreservingConflicts( - legacyFilePath: string, - targetPath: string, - accountId: string, - retry = false - ): { path: string; preserved: boolean } { + // Copies beside the runtime file under the next free preserved name, or stops at one already + // holding these bytes. Never replaces or writes through a name. + protected preserveLegacySessionConflict(conflict: LegacySessionConflict): { + path: string + copied: boolean + } { + const { legacyFilePath, runtimeFilePath, accountId } = conflict let legacyContents: Buffer | null = null const readLegacy = (): Buffer => (legacyContents ??= readFileSync(legacyFilePath)) - if ( - this.copyLegacyFileWithoutOverwrite(legacyFilePath, targetPath, readLegacy) !== 'conflict' - ) { - return { path: targetPath, preserved: false } - } for (let attempt = 0; ; attempt++) { - const preservedPath = this.getPreservedLegacySessionPath(targetPath, accountId, attempt) - const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, preservedPath, readLegacy) - if (result !== 'conflict' || retry) { - return { path: preservedPath, preserved: result === 'copied' } + const path = this.getPreservedLegacySessionPath(runtimeFilePath, accountId, attempt) + const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, path, readLegacy) + if (result !== 'conflict') { + return { path, copied: result === 'copied' } } } } From 2e64257e06f30500a54e35ca78d9f1c52b851604 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:29:37 -0800 Subject: [PATCH 28/30] fix(codex): a failing session pass removes the conflict copies it made Copies kept beside conflicting runtime files are all or none: if keeping one fails, the copies this pass created are removed, so retries never pile up snapshots of sessions that keep changing. --- config/main-sync-fs-baseline.txt | 2 +- .../runtime-home-legacy-migration.test.ts | 38 +++++++++++++++++- .../runtime-home-service-legacy-migration.ts | 40 ++++++++++++++----- 3 files changed, 66 insertions(+), 14 deletions(-) diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 28016d2a0cba..9e4922429bbf 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -127,7 +127,7 @@ 23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts 2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts -17 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +18 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts 1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts 14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts 1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 3bc3bc334a31..120b2c5511cd 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -106,11 +106,26 @@ async function removeAccountHome(managedHomePath: string): Promise { } const fsHooks = vi.hoisted( - (): { afterRead: Map void>; linkError: NodeJS.ErrnoException | null } => ({ + (): { + afterRead: Map void> + linkError: NodeJS.ErrnoException | null + failedCopies: Set + } => ({ afterRead: new Map(), - linkError: null + linkError: null, + failedCopies: new Set() }) ) +vi.mock(import('node:fs'), async (importOriginal) => { + const actual = await importOriginal() + const copyFileSync = (...args: Parameters): void => { + if (fsHooks.failedCopies.has(String(args[1]))) { + throw Object.assign(new Error('copy failed'), { code: 'EIO' }) + } + actual.copyFileSync(...args) + } + return { ...actual, default: { ...actual, copyFileSync }, copyFileSync } +}) vi.mock(import('node:fs/promises'), async (importOriginal) => { const actual = await importOriginal() // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: forwards every overload unchanged. @@ -144,6 +159,7 @@ describe('CodexRuntimeHomeService', () => { afterEach(() => { fsHooks.afterRead.clear() fsHooks.linkError = null + fsHooks.failedCopies.clear() trackMock.mockClear() teardownRuntimeHomeTest() }) @@ -296,6 +312,24 @@ describe('CodexRuntimeHomeService', () => { expect(existsSync(migrationMarkerPath())).toBe(true) }) + it('leaves no conflict copy behind when keeping another conflict fails', async () => { + const runtimeSessionsDir = join(getRuntimeCodexHomePath(), 'sessions') + mkdirSync(runtimeSessionsDir, { recursive: true }) + writeFileSync(join(runtimeSessionsDir, 'a.json'), '{"runtime":"a"}', 'utf-8') + writeFileSync(join(runtimeSessionsDir, 'b.json'), '{"runtime":"b"}', 'utf-8') + const managedHomePath = writeHistory('account-1', '{"id":"a-1"}\n') + mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) + writeFileSync(join(managedHomePath, 'sessions', 'a.json'), '{"legacy":"a"}', 'utf-8') + writeFileSync(join(managedHomePath, 'sessions', 'b.json'), '{"legacy":"b"}', 'utf-8') + fsHooks.failedCopies.add(join(runtimeSessionsDir, 'b.orca-legacy-account-1.json')) + + await constructService() + await waitForImportOutcomes(['imported']) + + expect(readdirSync(runtimeSessionsDir).sort()).toEqual(['a.json', 'b.json']) + expect(existsSync(migrationMarkerPath())).toBe(false) + }) + it('removes the copy an interrupted import left behind', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') const leftover = `${runtimeHistoryPath}.4242.0b6f3c1e-2d4a-4b8e-9f10-7a6c5d4e3f21.orca-import.tmp` diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 5626c2d9ba38..ad9e07e66b38 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -7,6 +7,7 @@ import { mkdirSync, readFileSync, readdirSync, + rmSync, statSync } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' @@ -116,17 +117,7 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa this.migrateLegacySessions(managedHomePath, accountId, conflicts) } } - for (const conflict of conflicts) { - const preserved = this.preserveLegacySessionConflict(conflict) - if (preserved.copied) { - this.appendMigrationDiagnostic({ - type: 'session-conflict', - accountId: conflict.accountId, - runtimeFilePath: conflict.runtimeFilePath, - preservedPath: preserved.path - }) - } - } + this.preserveLegacySessionConflicts(conflicts) } catch (error) { this.writeMigrationRecord(historyStatePath, recordLegacySessionPassFailure(state)) throw error @@ -194,6 +185,33 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } } + // All or none: a failure removes the copies this pass made, so failing passes never pile copies + // up. Codex never writes these names, and each was created exclusively by this pass. + protected preserveLegacySessionConflicts(conflicts: readonly LegacySessionConflict[]): void { + const created: { conflict: LegacySessionConflict; path: string }[] = [] + try { + for (const conflict of conflicts) { + const preserved = this.preserveLegacySessionConflict(conflict) + if (preserved.copied) { + created.push({ conflict, path: preserved.path }) + } + } + } catch (error) { + for (const { path } of created) { + rmSync(path, { force: true }) + } + throw error + } + for (const { conflict, path } of created) { + this.appendMigrationDiagnostic({ + type: 'session-conflict', + accountId: conflict.accountId, + runtimeFilePath: conflict.runtimeFilePath, + preservedPath: path + }) + } + } + // Copies beside the runtime file under the next free preserved name, or stops at one already // holding these bytes. Never replaces or writes through a name. protected preserveLegacySessionConflict(conflict: LegacySessionConflict): { From 29ca9efb8799aba5cd92f5ada263f599626c6a3d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:24:58 -0800 Subject: [PATCH 29/30] test(codex): skip the linked account history test on Windows --- .../runtime-home-legacy-migration.test.ts | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index 120b2c5511cd..24d1d14260e0 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -209,26 +209,30 @@ describe('CodexRuntimeHomeService', () => { expect(trackedImportOutcomes()).toEqual(['imported']) }) - it('imports a linked account history and ignores an account folder without a home folder', async () => { - const elsewhere = join(testState.userDataDir, 'elsewhere-history.jsonl') - writeFileSync(elsewhere, '{"id":"linked-1"}\n', 'utf-8') - const managedHomePath = createManagedAuth( - testState.userDataDir, - 'account-1', - '{"account":"managed"}\n' - ) - symlinkSync(elsewhere, join(managedHomePath, 'history.jsonl')) - const orphan = join(testState.userDataDir, 'codex-accounts', 'orphan') - mkdirSync(orphan, { recursive: true }) - writeFileSync(join(orphan, 'home'), 'not a folder', 'utf-8') + // File symlinks need Developer Mode or elevation on Windows. + it.skipIf(process.platform === 'win32')( + 'imports a linked account history and ignores an account folder without a home folder', + async () => { + const elsewhere = join(testState.userDataDir, 'elsewhere-history.jsonl') + writeFileSync(elsewhere, '{"id":"linked-1"}\n', 'utf-8') + const managedHomePath = createManagedAuth( + testState.userDataDir, + 'account-1', + '{"account":"managed"}\n' + ) + symlinkSync(elsewhere, join(managedHomePath, 'history.jsonl')) + const orphan = join(testState.userDataDir, 'codex-accounts', 'orphan') + mkdirSync(orphan, { recursive: true }) + writeFileSync(join(orphan, 'home'), 'not a folder', 'utf-8') - await startService() + await startService() - expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( - '{"id":"linked-1"}\n' - ) - expect(readFileSync(elsewhere, 'utf-8')).toBe('{"id":"linked-1"}\n') - }) + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + '{"id":"linked-1"}\n' + ) + expect(readFileSync(elsewhere, 'utf-8')).toBe('{"id":"linked-1"}\n') + } + ) it('never writes an existing shared history, and account removal keeps the account history', async () => { const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') From 992489f7ec1d230473ddf71a77f9f48d977d28dc Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:40:29 -0800 Subject: [PATCH 30/30] test(codex): check session copies and the shared history right after startup --- .../runtime-home-legacy-migration.test.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index a1348c83d829..aafda10a64d4 100644 --- a/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -203,7 +203,10 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(runtimeHistoryPath, '{"id":"shared-1"}', 'utf-8') const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') - await startService() + await constructService() + // Startup itself must not rewrite it, before the import settles. + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}') + await waitForHistorySettled() await removeAccountHome(managedHomePath) expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe('{"id":"shared-1"}') @@ -296,15 +299,14 @@ describe('CodexRuntimeHomeService', () => { ) mkdirSync(join(managedHomePath, 'sessions'), { recursive: true }) writeFileSync(join(managedHomePath, 'sessions', 'session.json'), '{"turns":[1,2]}', 'utf-8') - const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('../../runtime-home-service') - new CodexRuntimeHomeService(store as never) - await waitForHistorySettled() + // Session copies finish during construction; check them before the history import settles. + await constructService() expect(readFileSync(occupiedPreservedPath, 'utf-8')).toBe('{"turns":["kept"]}') expect( readFileSync(join(runtimeSessionsDir, 'session.orca-legacy-account-1-1.json'), 'utf-8') ).toBe('{"turns":[1,2]}') + await waitForHistorySettled() }) })