diff --git a/config/main-blocking-helper-baseline.txt b/config/main-blocking-helper-baseline.txt index e09db6c65f3a..10fcd30b0235 100644 --- a/config/main-blocking-helper-baseline.txt +++ b/config/main-blocking-helper-baseline.txt @@ -264,7 +264,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 5ae0029979a5..ee39827003d9 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -125,7 +125,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/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-history-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts new file mode 100644 index 000000000000..0315d4c22eaa --- /dev/null +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-history-migration.ts @@ -0,0 +1,149 @@ +import { readFile, rename, rm, writeFile } from 'node:fs/promises' +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 + +export type LegacyHistoryState = { + /** 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 + /** The account histories' sizes and times when the import last gave up. */ + historyImportInputs?: string + 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 + runtimeHistoryPath: string + statePath: string +} + +export function parseLegacyHistoryState(text: string): LegacyHistoryState { + const parsed: unknown = JSON.parse(text) + const state: LegacyHistoryState = {} + if (!parsed || typeof parsed !== 'object') { + return state + } + 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 + } + 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 { + // 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) + } finally { + await rm(tmpPath, { force: true }) + } +} + +/** + * 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: LegacyHistoryImportPaths, + 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`) +} + +/** + * 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/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..8bc0223b2d72 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-prompt-history-import.ts @@ -0,0 +1,172 @@ +import { randomUUID } from 'node:crypto' +import { link, lstat, open, readFile, readdir, rm, stat } from 'node:fs/promises' +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] + +/** 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 parts.join('|') +} + +async function pathExists(path: string): Promise { + try { + await lstat(path) + return true + } catch (error) { + if (errnoCodeOrUnknown(error) === 'ENOENT') { + return false + } + throw error + } +} + +// 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 + }) + 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, 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' || code === 'ELOOP') { + return null + } + throw error + }) + if (stats?.isFile()) { + paths.push(historyPath) + } + } + return paths.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 + * meanwhile. Rejects on failure, so the migration retries on the next launch. + */ +export async function importLegacyHistoriesIfSharedAbsent( + accountsRoot: string, + runtimeHistoryPath: string +): Promise { + const accountHistoryPaths = await listAccountHistories(accountsRoot) + if (accountHistoryPaths.length === 0) { + return + } + let outcome: LegacyHistoryImportOutcome = 'failed' + try { + 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 publishWithoutOverwrite(`${[...seenLines].join('\n')}\n`, runtimeHistoryPath) +} + +async function publishWithoutOverwrite( + contents: string, + targetPath: string +): Promise { + await removeStaleImportCopies(targetPath) + const tmpPath = `${targetPath}.${process.pid}.${randomUUID()}${IMPORT_COPY_SUFFIX}` + try { + const handle = await open(tmpPath, 'wx', 0o600) + try { + await handle.writeFile(contents, 'utf-8') + await handle.sync() + } finally { + await handle.close() + } + return await linkIntoFreeName(tmpPath, targetPath) + } finally { + await rm(tmpPath, { force: true }) + } +} + +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, + targetPath: string +): Promise { + try { + await link(tmpPath, targetPath) + return 'imported' + } catch (error) { + const code = errnoCodeOrUnknown(error) + if (code === 'EEXIST') { + 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, and the import + // settles rather than retry on a filesystem that won't change. + if (isHardLinkUnsupportedError(error)) { + return 'skipped_no_hard_links' + } + throw error + } +} + +function trackLegacyHistoryImport(outcome: LegacyHistoryImportOutcome): void { + try { + track('codex_legacy_history_import', { + outcome, + platform: + process.platform === 'win32' || process.platform === 'linux' ? process.platform : 'darwin' + }) + } catch { + // 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 new file mode 100644 index 000000000000..aafda10a64d4 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -0,0 +1,312 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { + existsSync, + mkdirSync, + readFileSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync +} from 'node:fs' +import { join } from 'node:path' +import { createSettings } from '../runtime-home-settings-test-fixtures' +import { + createManagedAuth, + createStore, + getRuntimeCodexHomePath, + setupRuntimeHomeTest, + teardownRuntimeHomeTest, + testState +} from '../runtime-home-service-test-harness' + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.userDataDir + } +})) +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]: unknown[]) => + props && typeof props === 'object' && 'outcome' in props ? String(props.outcome) : '' + ) +} + +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 +} + +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 { + 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 waitForHistorySettled() +} + +// Settled: the history import landed or was skipped, so nothing more is owed. +async function waitForHistorySettled(): Promise { + await vi.waitFor( + () => + expect(readFileSync(historyStatePath(), 'utf-8')).toContain('"historyImportSettled":true'), + { timeout: WAIT_MS } + ) +} + +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 + +async function removeAccountHome(managedHomePath: string): Promise { + const { CodexManagedHomeLifecycle } = + await import('../../managed-homes/codex-managed-home-lifecycle') + const { CodexManagedHomePath } = await import('../../managed-homes/codex-managed-home-path') + await new CodexManagedHomeLifecycle(new CodexManagedHomePath()).safeRemove( + managedHomePath, + 'account-1' + ) +} + +const fsHooks = vi.hoisted( + (): { + afterRead: Map void> + linkError: NodeJS.ErrnoException | null + failedCopies: Set + } => ({ + afterRead: new Map(), + 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. + const readFile = (async (...args: Parameters) => { + const contents = await actual.readFile(...args) + fsHooks.afterRead.get(String(args[0]))?.() + return contents + }) as typeof actual.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) => { + const actual = await importOriginal() + return { + ...actual, + homedir: () => testState.fakeHomeDir + } +}) + +describe('CodexRuntimeHomeService', () => { + beforeEach(() => { + setupRuntimeHomeTest() + }) + + afterEach(() => { + fsHooks.afterRead.clear() + fsHooks.linkError = null + fsHooks.failedCopies.clear() + trackMock.mockClear() + teardownRuntimeHomeTest() + }) + + 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') + + await startService() + + expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( + '{"id":"a-1"}\n{"id":"both"}\n{"id":"b-1"}\n' + ) + expect(trackedImportOutcomes()).toEqual(['imported']) + }) + + // 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() + + 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') + const managedHomePath = writeHistory('account-1', '{"id":"legacy-1"}\n') + + 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"}') + expect(trackedImportOutcomes()).toEqual(['skipped_existing']) + expect(readFileSync(join(managedHomePath, 'history.jsonl'), 'utf-8')).toBe( + '{"id":"legacy-1"}\n' + ) + }) + + 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') + 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']) + + rmSync(join(runtimeSessionsDir, 'nested')) + vi.resetModules() + await constructService() + + expect( + readFileSync(join(runtimeSessionsDir, 'session.orca-legacy-account-1.json'), 'utf-8') + ).toBe('{"legacy":2}') + 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('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']) + }) + + 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(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' + ) + }) + + 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') + + // 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() + }) +}) 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..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 @@ -1,18 +1,33 @@ import { appendFileSync, + constants, copyFileSync, existsSync, + lstatSync, mkdirSync, readFileSync, readdirSync, + rmSync, statSync } from 'node:fs' 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' import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' 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' + +type LegacySessionConflict = { legacyFilePath: string; runtimeFilePath: string; accountId: string } + +type LegacyMigrationMarker = { completedAt: number; migratedHomeCount: number } export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { @@ -55,27 +70,71 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa } protected migrateLegacyManagedStateIfNeeded(): void { - if (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 } + let state: LegacyHistoryState = {} + try { + 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. + void settleLegacyHistoryImport({ + accountsRoot: this.getManagedAccountsRoot(), + runtimeHistoryPath: join(this.getRuntimeHomePath(), 'history.jsonl'), + statePath: historyStatePath + }) + } + } + /** + * 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 { const managedHomes = this.getLegacyManagedHomes() - for (const managedHomePath of managedHomes) { - const accountId = parse(relative(this.getManagedAccountsRoot(), managedHomePath)).dir.split( - /[\\/]/ - )[0] - if (!accountId) { - continue + 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, conflicts) + } } - this.migrateLegacyHistory(managedHomePath) - this.migrateLegacySessions(managedHomePath, accountId) + this.preserveLegacySessionConflicts(conflicts) + } 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) + this.writeMigrationRecord(this.getMigrationMarkerPath(), { + completedAt: Date.now(), + migratedHomeCount: managedHomes.length + }) + } - // Mark completion so later startups cannot replay stale managed-home state. - writeFileAtomically( - this.getMigrationMarkerPath(), - `${JSON.stringify({ completedAt: Date.now(), migratedHomeCount: managedHomes.length })}\n` - ) + protected writeMigrationRecord( + path: string, + record: LegacyHistoryState | LegacyMigrationMarker + ): void { + writeFileAtomically(path, `${JSON.stringify(record)}\n`) } protected getLegacyManagedHomes(): string[] { @@ -98,33 +157,12 @@ export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePa return managedHomes.sort() } - protected migrateLegacyHistory(managedHomePath: string): void { - const legacyHistoryPath = join(managedHomePath, 'history.jsonl') - if (!existsSync(legacyHistoryPath)) { - return - } - - 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) - for (const line of readFileSync(legacyHistoryPath, 'utf-8').split('\n')) { - if (!line || seenLines.has(line)) { - continue - } - seenLines.add(line) - mergedLines.push(line) - } - - if (mergedLines.length === 0) { - return - } - writeFileAtomically(runtimeHistoryPath, `${mergedLines.join('\n')}\n`) - } - - protected migrateLegacySessions(managedHomePath: string, accountId: string): 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 @@ -136,28 +174,88 @@ 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) - continue + let legacyContents: Buffer | null = null + const readLegacy = (): Buffer => (legacyContents ??= readFileSync(legacyFilePath)) + if ( + this.copyLegacyFileWithoutOverwrite(legacyFilePath, runtimeFilePath, readLegacy) === + 'conflict' + ) { + conflicts.push({ legacyFilePath, runtimeFilePath, accountId }) } + } + } - const legacyContents = readFileSync(legacyFilePath) - const runtimeContents = readFileSync(runtimeFilePath) - if (runtimeContents.equals(legacyContents)) { - continue + // 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 }) + } } - - const preservedPath = this.getPreservedLegacySessionPath(runtimeFilePath, accountId) - copyFileSync(legacyFilePath, preservedPath) + } 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, - runtimeFilePath, - preservedPath + 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): { + path: string + copied: boolean + } { + const { legacyFilePath, runtimeFilePath, accountId } = conflict + let legacyContents: Buffer | null = null + const readLegacy = (): Buffer => (legacyContents ??= readFileSync(legacyFilePath)) + for (let attempt = 0; ; attempt++) { + const path = this.getPreservedLegacySessionPath(runtimeFilePath, accountId, attempt) + const result = this.copyLegacyFileWithoutOverwrite(legacyFilePath, path, readLegacy) + if (result !== 'conflict') { + return { path, copied: result === 'copied' } + } + } + } + + /** Exclusive create never replaces or writes through a name, even one that appears after a check. */ + protected copyLegacyFileWithoutOverwrite( + legacyFilePath: string, + targetPath: string, + readLegacy: () => Buffer + ): 'copied' | 'identical' | 'conflict' { + try { + copyFileSync(legacyFilePath, targetPath, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE) + return 'copied' + } catch (error) { + if (errnoCodeOrUnknown(error) !== 'EEXIST') { + throw error + } + } + const legacyContents = readLegacy() + try { + // 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' + } + } + protected listFilesRecursively(rootPath: string): string[] { const stat = statSync(rootPath) if (!stat.isDirectory()) { @@ -185,10 +283,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..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 @@ -199,14 +199,19 @@ 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 migrateLegacySessions(managedHomePath: string, accountId: string): void protected abstract listFilesRecursively(rootPath: string): string[] 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, + readLegacy: () => Buffer + ): 'copied' | 'identical' | 'conflict' protected abstract appendMigrationDiagnostic(record: Record): void protected abstract captureSystemDefaultSnapshot(options: { force: boolean }): void 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 29cd34147b65..b435e15636b5 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 @@ -192,11 +192,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/ipc/telemetry.ts b/src/main/ipc/telemetry.ts index 86a96468cc62..9e874c87f166 100644 --- a/src/main/ipc/telemetry.ts +++ b/src/main/ipc/telemetry.ts @@ -33,6 +33,7 @@ const MAIN_OWNED_TELEMETRY_EVENTS = new Set([ 'browser_extensions_banner_assigned', 'app_starred_orca', 'codex_history_move_status', + 'codex_legacy_history_import', 'legacy_journal_retirement', 'daemon_adopted', 'daemon_async_io_health', 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..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, 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 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 6704be1036ae..39a18ffe5bbf 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1217,7 +1217,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 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 043fe8ce0f07..9853cf2392b8 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -586,7 +586,7 @@ "followSymlinkedDirectories": "跟随符号链接目录", "followSymlinkedDirectoriesDescription": "在快速打开中搜索链接文件夹,并在文件资源管理器中展开本地链接文件夹", "accounts": { - "codexRemoveHome": "Orca 会删除此账户在 {{host}} 上的 Codex 文件夹,包括其中的登录信息、MCP 登录以及仅保存在该文件夹中的 Codex 历史记录,此操作无法撤销。如果此账户被选中,你下次启动的 Codex 将使用系统默认", + "codexRemoveHome": "Orca 会删除此账户在 {{host}} 上的 Codex 文件夹,包括其中的登录信息和 MCP 登录。此操作无法撤销。如果此账户被选中,你下次启动的 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 new file mode 100644 index 000000000000..e3d02e249972 --- /dev/null +++ b/src/shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas.ts @@ -0,0 +1,18 @@ +import { z } from 'zod' + +/** Account histories are only read, whatever the outcome; `failed` retries on the next launch. */ +export const CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES = [ + 'imported', + 'skipped_existing', + 'nothing_to_import', + 'skipped_no_hard_links', + 'failed' +] as const + +/** 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), + 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 bae3e5c366ff..5e58187a784e 100644 --- a/src/shared/telemetry/telemetry-event-registry.ts +++ b/src/shared/telemetry/telemetry-event-registry.ts @@ -5,6 +5,7 @@ import { onboardingLanguageRequestedSchema } from './schemas/telemetry-onboarding-language-schemas' import { agentTokenUsageDailySchema } from './schemas/telemetry-agent-token-usage-schema' +import { codexLegacyHistoryImportSchema } from './schemas/telemetry-codex-legacy-history-event-schemas' import { legacyJournalRetirementSchema } from './schemas/telemetry-legacy-journal-retirement-schema' import { agentDashboardActiveSchema, @@ -264,6 +265,7 @@ export const eventSchemas = { wsl_usage_snapshot: wslUsageSnapshotSchema, + codex_legacy_history_import: codexLegacyHistoryImportSchema, legacy_journal_retirement: legacyJournalRetirementSchema, plugin_installed: pluginInstalledSchema,