Keep managed Codex homes in sync

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo-H
2026-05-10 20:14:36 -04:00
co-authored by Orca
parent 9d94df635e
commit f6ea59bae8
5 changed files with 77 additions and 10 deletions
@@ -396,6 +396,8 @@ describe('CodexRuntimeHomeService', () => {
})
it('returns the managed home for managed Codex launch and rate-limit preparation', async () => {
const runtimeConfigPath = join(testState.fakeHomeDir, '.codex', 'config.toml')
writeFileSync(runtimeConfigPath, 'approval_policy = "trusted"\n', 'utf-8')
const managedHomePath = createManagedAuth(
testState.userDataDir,
'account-1',
@@ -424,7 +426,14 @@ describe('CodexRuntimeHomeService', () => {
const service = new CodexRuntimeHomeService(store as never)
expect(service.prepareForCodexLaunch()).toBe(managedHomePath)
expect(readFileSync(join(managedHomePath, 'config.toml'), 'utf-8')).toBe(
'approval_policy = "trusted"\n'
)
writeFileSync(runtimeConfigPath, 'approval_policy = "on-request"\n', 'utf-8')
expect(service.prepareForRateLimitFetch()).toBe(managedHomePath)
expect(readFileSync(join(managedHomePath, 'config.toml'), 'utf-8')).toBe(
'approval_policy = "on-request"\n'
)
})
it('does not overwrite auth.json when no managed account was ever active', async () => {
@@ -233,9 +233,21 @@ export class CodexRuntimeHomeService {
// refresh. Managed sessions must run from their account-owned home so old
// PTYs on account B cannot race a newly launched account A process through
// the shared ~/.codex runtime file.
this.syncCanonicalConfigIntoManagedHome(activeAccount.managedHomePath)
return activeAccount.managedHomePath
}
private syncCanonicalConfigIntoManagedHome(managedHomePath: string): void {
const canonicalConfigPath = join(homedir(), '.codex', 'config.toml')
if (!existsSync(canonicalConfigPath)) {
return
}
writeFileAtomically(
join(managedHomePath, 'config.toml'),
readFileSync(canonicalConfigPath, 'utf-8')
)
}
private runtimeAuthMatchesAccount(
runtimeAuthContents: string,
activeAccount: CodexManagedAccount,
+36 -2
View File
@@ -1,5 +1,39 @@
import { describe, expect, it } from 'vitest'
import { attributeCodexUsageEvent, parseCodexUsageRecord } from './scanner'
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, describe, expect, it } from 'vitest'
import { attributeCodexUsageEvent, listCodexSessionFiles, parseCodexUsageRecord } from './scanner'
const tempDirs: string[] = []
afterEach(() => {
delete process.env.CODEX_HOME
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
describe('listCodexSessionFiles', () => {
it('includes managed Codex account session roots alongside the default root', async () => {
const defaultHome = mkdtempSync(join(tmpdir(), 'orca-codex-default-'))
const managedHome = mkdtempSync(join(tmpdir(), 'orca-codex-managed-'))
tempDirs.push(defaultHome, managedHome)
const defaultSessions = join(defaultHome, 'sessions')
const managedSessions = join(managedHome, 'sessions')
mkdirSync(defaultSessions, { recursive: true })
mkdirSync(managedSessions, { recursive: true })
const defaultFile = join(defaultSessions, 'default.jsonl')
const managedFile = join(managedSessions, 'managed.jsonl')
writeFileSync(defaultFile, '{}\n', 'utf-8')
writeFileSync(managedFile, '{}\n', 'utf-8')
process.env.CODEX_HOME = defaultHome
await expect(listCodexSessionFiles([managedSessions])).resolves.toEqual([
defaultFile,
managedFile
])
})
})
describe('parseCodexUsageRecord', () => {
it('uses cumulative totals to avoid double-counting repeated token snapshots', () => {
+16 -7
View File
@@ -112,12 +112,20 @@ export function getCodexSessionsDirectory(): string {
return DEFAULT_CODEX_SESSIONS_DIR
}
export async function listCodexSessionFiles(): Promise<string[]> {
try {
return (await walkJsonlFiles(getCodexSessionsDirectory())).sort()
} catch {
return []
export async function listCodexSessionFiles(extraSessionDirs: string[] = []): Promise<string[]> {
const sessionDirs = [getCodexSessionsDirectory(), ...extraSessionDirs]
const files = new Set<string>()
for (const sessionDir of sessionDirs) {
try {
for (const file of await walkJsonlFiles(sessionDir)) {
files.add(file)
}
} catch {
// Missing or unreadable session roots are expected for accounts that have
// not launched Codex yet. Keep scanning the remaining roots.
}
}
return [...files].sort()
}
export async function getProcessedFileInfo(filePath: string): Promise<CodexUsageProcessedFile> {
@@ -766,13 +774,14 @@ export async function parseCodexUsageFile(
export async function scanCodexUsageFiles(
worktrees: CodexUsageWorktreeRef[],
previousProcessedFiles: CodexUsagePersistedFile[]
previousProcessedFiles: CodexUsagePersistedFile[],
extraSessionDirs: string[] = []
): Promise<{
processedFiles: CodexUsagePersistedFile[]
sessions: CodexUsageSession[]
dailyAggregates: CodexUsageDailyAggregate[]
}> {
const files = await listCodexSessionFiles()
const files = await listCodexSessionFiles(extraSessionDirs)
const previousByPath = new Map(previousProcessedFiles.map((file) => [file.path, file]))
const processedFiles: CodexUsagePersistedFile[] = []
const worktreesWithCanonicalPaths = await buildWorktreesWithCanonicalPaths(worktrees)
+4 -1
View File
@@ -267,7 +267,10 @@ export class CodexUsageStore {
const worktreeFingerprint = getWorktreeFingerprint(worktreesByRepo)
const result = await scanCodexUsageFiles(
createWorktreeRefs(repos, worktreesByRepo),
this.state.worktreeFingerprint === worktreeFingerprint ? this.state.processedFiles : []
this.state.worktreeFingerprint === worktreeFingerprint ? this.state.processedFiles : [],
this.store
.getSettings()
.codexManagedAccounts.map((account) => join(account.managedHomePath, 'sessions'))
)
this.state.processedFiles = result.processedFiles
this.state.sessions = result.sessions