diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ed00bb3..5724c57c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ Anything that changes what the dashboard, the admin or a widget can do gets a li ## Unreleased +### Added +- Add read-only Codex account quotas, token usage, selected local chats and observed turns. Enable account reads or select history sources in the admin screen privacy settings; both start off. History selection explains that titles and labels reach subscribed widgets. A chat opens only after exact-ID validation against the local desktop catalog. Account email is not sent to widgets. Removing a history source or disabling account reads also removes its cached fields if the next Codex read fails. + ### Changed - **Clock in the compact bar.** Show an accent-coloured clock icon beside the time, matching the weather icon. - **The system tiles show useful Mac capacity.** Disk usage uses the APFS data volume and shows available space; memory shows available RAM and swap. diff --git a/README.md b/README.md index fc477ec5..ddcb9b28 100644 --- a/README.md +++ b/README.md @@ -288,6 +288,8 @@ What the installer checks, what a consent record is and how an update asks again How to obtain each credential, what is stored where, and what is never logged: **[docs/connections.md](docs/connections.md)**. +The optional [Codex provider](docs/codex.md) reads selected local account and chat data after an explicit opt-in. Its dashboard widgets are distributed separately. + ## Backup **/admin → Screen → Backup** downloads the whole dashboard — the configuration and the background diff --git a/docs/codex.md b/docs/codex.md new file mode 100644 index 00000000..69b7ba23 --- /dev/null +++ b/docs/codex.md @@ -0,0 +1,58 @@ +# Codex account, history and observed turns + +The `codex` channel provides read-only account quotas, token usage and selected local chats. The `codex-live` channel reports observed turns and direct subagents for those selected chats. Both channels are disabled by default and require an installed Codex CLI. Widgets belong in the registry. + +## Enable the data you want + +In the admin's screen privacy settings, enable **Codex account usage** for account, quota and token reads. Select one or more **Codex history sources** for bounded local history reads. The available sources are `cli`, `vscode`, `exec`, `appServer`, `subAgent`, `subAgentReview`, `subAgentCompact`, `subAgentThreadSpawn`, `subAgentOther` and `unknown`. The broad `subAgent` selection includes its subtypes. An unknown source requires explicit selection. + +These settings take effect on the next provider poll without a restart. An unconfigured subscribed channel keeps a 60-second polling cadence, so a new opt-in is picked up at its next scheduled poll. Turning account reads off clears the displayed account data. Removing every history source clears selected history and live observations. Older dashboard configurations migrate with both settings off. No widget installation grants consent to read Codex account data. + +`buildApp` registers the provider beside the Claude providers and passes callbacks for `privacy.codexAccount` and `privacy.codexHistorySources`. Constructing the provider does not start a child process or read the desktop catalog. A subscribed channel starts reading only after its corresponding opt-in. The helper must be able to find `codex` on its inherited `PATH`; the provider does not scan other installations or edit Codex configuration. + +## Read-only process boundary + +The adapter discovers candidate methods from the installed CLI's generated `ClientRequest.json` schema and caches the capability result briefly. Schema presence alone does not establish account access; a runtime method-not-found response marks that method unsupported for that poll. + +A separate stdio app-server child runs for each account or history poll and closes when the poll ends. It does not attach to the desktop daemon, its control socket or a proxy. Only these methods are permitted: + +| Method | Fixed request constraints | +|---|---| +| `account/read` | `refreshToken: false` | +| `account/rateLimits/read` | `supportsLunaReserve: false`, `excludeResetCreditDetails: true` | +| `account/usage/read` | Empty parameters | +| `thread/list` | Explicit sources, `useStateDbOnly: true`, `archived: false`, `sortKey: updated_at`, limit 50 | + +Initialization is adapter-owned. Conversation creation, resume, turns, login, logout and account-changing actions are refused before transport use. Server-initiated approval and external auth-token refresh requests are refused. Child arguments disable hooks and analytics. The child environment contains only process lookup, home, temporary-directory, locale and system-directory variables. Provider credentials and arbitrary parent variables are excluded. Stderr and protocol error text never enter snapshots or logs. + +`refreshToken: false` forbids a requested refresh on `account/read`. This change does not prove that CLI startup has no incidental authentication side effects. The short-lived child avoids keeping a second app server beside the desktop app. Timeout or disconnect rejects pending reads; a stopped poll cannot publish its result. + +The request constraints came from the installed CLI 0.159.2 schema. Earlier or later CLIs may change `experimentalApi`, `supportsLunaReserve` or `explicitGatewayOauth`, reject fields or lack methods. The provider reports `unsupported` or `offline` and does not retry with less restrictive requests. Durable errors back off for five minutes; only transient `offline` errors retry after 15 seconds. + +## Snapshot and local chat opening + +`CodexSnapshot` is exported by `server/src/providers/codex.ts`; the detailed types are in `server/src/codex/snapshot.ts`. Each account, quota, usage and history section carries data, update time, freshness and a fixed error reason. A failed refresh preserves last valid data as stale. Authentication rejection clears account data. A detected account or workspace identity change clears prior quota and usage data. No credential, workspace ID or account email is sent to a widget. `account.data` contains only authentication type and, for ChatGPT authentication, plan type. It is not a per-chat account binding. + +History returns at most one page of 50 non-archived, non-ephemeral records. A cursor and `truncated` disclose an incomplete page. Rollout paths, working directories, prompt previews and turn bodies are excluded. Stored status and source do not prove live desktop activity. + +A card's `codex/open` command accepts an exact thread UUID only from a loopback widget command. It requires a selected history record updated within 120 seconds and validates that ID against the desktop-owned local chat catalog before opening. The catalog check requires a local host and a non-removed record. The provider validates again immediately before using `/usr/bin/open` on `codex://threads/`. It never guesses from a title, launches `codex resume` or sends a prompt. A user verified this deep link on their Mac, but it is not claimed as a stable public API. CLI terminal focus is unavailable because no process-to-terminal mapping has been demonstrated. + +The local catalog validator uses one read-only SQLite query for an entire page and `PRAGMA query_only`. It currently reads `sqlite/codex-dev.db`. A missing database, changed schema, lock timeout or foreign ID fails closed. The desktop database schema is not a stable public API, so catalog changes may disable navigation while account and history reads continue. + +## Observed turns and direct subagents + +The `codex-live` provider polls selected history IDs every five seconds. One read-only SQLite query selects the parent records and non-archived direct children, up to 300 combined records. Journal reads are bounded to local session files and accept only regular files whose first record identifies the exact thread. Full working directories, rollout paths, prompts, reasoning and tool arguments are excluded from snapshots. + +The reader examines at most 16 MiB on a cold file read and 512 KiB of new data on later reads, with at most four journal files open concurrently. It currently joins journals through `state_5.sqlite`. This versioned, undocumented schema may change in a Codex update; `codex-live` can then go quiet or report unknown observations while account and app-server history still work. It projects lifecycle state, last observed model and effort, branch, a working-directory basename, agent role and direct-child count. A missing start remains unknown. Inactivity for 90 seconds changes an unfinished observation to unknown; silence does not prove continued work. Saved desktop project names and IDs are deferred to a separate change, so the directory basename is only a label. + +## Verification + +From the cloned repository root: + +```bash +pnpm --filter server exec vitest run test/codex-adapter.test.ts test/codex-provider.test.ts test/codex-local-chats.test.ts test/codex-observations.test.ts test/config-migration.test.ts --configLoader runner +pnpm typecheck +pnpm test +``` + +The tests use injected transports, clocks and disposable local databases. They do not authenticate a real account, prove that Codex startup never refreshes credentials, navigate the desktop app or verify the native dashboard. Those runtime checks remain separate. diff --git a/docs/writing-widgets.md b/docs/writing-widgets.md index 38a1a168..e56d3826 100644 --- a/docs/writing-widgets.md +++ b/docs/writing-widgets.md @@ -279,7 +279,8 @@ document.documentElement.style.setProperty('--h', Fremkit.size.px.height + 'px') `system`, `processes`, `volume`, `spotify`, `mutedeck`, `clipboard`, `shortcuts`, `cleanshot`, `network`, `battery`, `service-status`, `config`, `claude-sessions`, `claude-usage`, -`claude-account`, `dock`, `docker-local`, `local-models`, plus one per connection: `azure-devops:`, +`claude-account`, `codex`, `codex-live`, `dock`, `docker-local`, `local-models`, +plus one per connection: `azure-devops:`, `bambu:`, `github:`, `synology:`, and `calendar:` for an ICS connection. diff --git a/server/src/app.ts b/server/src/app.ts index d11c751d..817f472a 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -37,6 +37,8 @@ import { ClaudeTracker } from './claude/tracker.js' import { ClaudeUsage } from './claude/usage.js' import { claudeRoutes } from './claude/routes.js' import { createClaudeSessionsProvider, createClaudeUsageProvider, createClaudeAccountProvider } from './claude/providers.js' +import { createCodexProvider } from './providers/codex.js' +import { createLocalChatValidator } from './codex/local-chats.js' import { createAttention } from './claude/attention.js' import { DockState } from './dock/state.js' import { dockRoutes } from './dock/routes.js' @@ -153,6 +155,13 @@ export async function buildApp(opts: AppOptions): Promise { filePath: join(opts.dataDir, 'claude-account.json'), enabled: () => store.get().privacy.claudeAccountUsage, })) + const codex = createCodexProvider({ + enabled: () => store.get().privacy.codexAccount || store.get().privacy.codexHistorySources.length > 0, + accountEnabled: () => store.get().privacy.codexAccount, + historySources: () => store.get().privacy.codexHistorySources, + }, { isLocalChat: createLocalChatValidator() }) + registry.register(codex) + registry.register(codex.sessions) registry.register(createDockProvider(dock)) // These two act on the user's behalf — opening an application, knocking on a host — so they // resolve what to act on from the saved dashboard rather than from the widget's message. diff --git a/server/src/codex/adapter.ts b/server/src/codex/adapter.ts new file mode 100644 index 00000000..8c96143c --- /dev/null +++ b/server/src/codex/adapter.ts @@ -0,0 +1,372 @@ +import { spawn, execFile } from 'node:child_process' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir, homedir } from 'node:os' +import { join } from 'node:path' +import { z } from 'zod' +import { HistorySourceSchema } from './sources.js' + +export type CodexFailure = 'offline' | 'unauthorized' | 'unsupported' | 'invalid' | 'refused' | 'unconfigured' +/** Fixed reason codes only. Child stderr, protocol error messages and credentials never escape. */ +export class CodexError extends Error { + constructor(public readonly reason: CodexFailure) { + super(reason) + this.name = 'CodexError' + } +} +const requestSchemas: Record = { + 'account/read': z.object({ refreshToken: z.literal(false) }).strict(), + 'account/rateLimits/read': z + .object({ supportsLunaReserve: z.literal(false), excludeResetCreditDetails: z.literal(true) }) + .strict(), + 'account/usage/read': z.object({}).strict(), + 'thread/list': z + .object({ + sourceKinds: z.array(HistorySourceSchema).min(1).max(10), + useStateDbOnly: z.literal(true), + limit: z.number().int().min(1).max(50), + sortKey: z.literal('updated_at'), + archived: z.literal(false), + }) + .strict(), +} +export interface ReadTransport { + write(line: string): void + onLine(fn: (line: string) => void): void + onClose(fn: () => void): void + close(): void +} +export interface CodexClient { + request(method: string, params: unknown): Promise + supports(method: string): boolean + close(): void +} +interface ClientOptions { + methods: ReadonlySet + connect: () => Promise + timeoutMs?: number +} +interface Pending { + method: string + resolve(value: unknown): void + reject(error: CodexError): void + timer: ReturnType +} + +/** Dedicated child connection. Never connects to a daemon, proxy, socket or desktop process. */ +export class CodexReadClient implements CodexClient { + private wire?: ReadTransport + private ready?: Promise + private pending = new Map() + private unsupported = new Set() + private id = 0 + private generation = 0 + constructor(private readonly options: ClientOptions) {} + supports(method: string): boolean { + return this.options.methods.has(method) && !this.unsupported.has(method) + } + async request(method: string, params: unknown): Promise { + const schema = Object.hasOwn(requestSchemas, method) ? requestSchemas[method] : undefined + const parsed = schema?.safeParse(params) + if (!parsed?.success) throw new CodexError('refused') + if (!this.supports(method) || !this.supports('initialize')) throw new CodexError('unsupported') + await this.initialize() + return this.send(method, parsed.data) + } + private initialize(): Promise { + if (this.ready) return this.ready + const generation = this.generation + this.ready = (async () => { + const wire = await this.options.connect() + if (generation !== this.generation) { + wire.close() + throw new CodexError('offline') + } + this.wire = wire + wire.onLine((line) => { + if (this.wire === wire) this.receive(line) + }) + wire.onClose(() => { + if (this.wire === wire) this.close() + }) + await this.send('initialize', { + clientInfo: { name: 'fremkit_readonly', title: 'Fremkit', version: '1.0.0' }, + capabilities: { experimentalApi: true, explicitGatewayOauth: true, requestAttestation: false }, + }) + if (this.wire !== wire) throw new CodexError('offline') + wire.write(JSON.stringify({ method: 'initialized', params: {} }) + '\n') + })().catch(() => { + if (generation === this.generation) this.close() + throw new CodexError('offline') + }) + return this.ready + } + private send(method: string, params: unknown): Promise { + const wire = this.wire + if (!wire) return Promise.reject(new CodexError('offline')) + const id = ++this.id + return new Promise((resolve, reject) => { + const timer = setTimeout(() => this.close(), this.options.timeoutMs ?? 15000) + this.pending.set(id, { method, resolve, reject, timer }) + try { + wire.write(JSON.stringify({ id, method, params }) + '\n') + } catch { + this.close() + } + }) + } + private receive(line: string): void { + if (Buffer.byteLength(line) > 4 * 1024 * 1024) { + this.close() + return + } + let raw: unknown + try { + raw = JSON.parse(line) + } catch { + this.close() + return + } + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + this.close() + return + } + const m = raw as Record + // Deny all server-initiated requests, including approval and token-refresh requests. + if (typeof m.method === 'string') { + if (m.id !== undefined && (typeof m.id === 'string' || typeof m.id === 'number')) { + try { + this.wire?.write( + JSON.stringify({ + id: m.id, + error: { code: -32601, message: 'Read-only client' }, + }) + '\n', + ) + } catch { + this.close() + } + } + return + } + if (typeof m.id !== 'number') return + const pending = this.pending.get(m.id) + if (!pending) return + this.pending.delete(m.id) + clearTimeout(pending.timer) + if (m.error && typeof m.error === 'object') { + const e = m.error as Record + const message = typeof e.message === 'string' ? e.message : '' + const reason: CodexFailure = + e.code === -32601 + ? 'unsupported' + : e.code === 401 || + e.code === 403 || + /unauthorized|not authenticated|authentication required|not logged in|sign in|invalid.*token|expired.*token/i.test( + message, + ) + ? 'unauthorized' + : 'offline' + if (reason === 'unsupported') this.unsupported.add(pending.method) + pending.reject(new CodexError(reason)) + } else if ('result' in m) pending.resolve(m.result) + else pending.reject(new CodexError('invalid')) + } + close(): void { + const wire = this.wire + this.wire = undefined + this.ready = undefined + this.generation++ + for (const pending of this.pending.values()) { + clearTimeout(pending.timer) + pending.reject(new CodexError('offline')) + } + this.pending.clear() + wire?.close() + } +} + +/** Allowlist prevents unknown provider credentials and loader variables from leaking. */ +export function safeChildEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const out: NodeJS.ProcessEnv = {} + for (const key of [ + 'PATH', + 'HOME', + 'CODEX_HOME', + 'TMPDIR', + 'TMP', + 'TEMP', + 'LANG', + 'LC_ALL', + 'SYSTEMROOT', + 'WINDIR', + ]) { + if (env[key] !== undefined) out[key] = env[key] + } + return out +} +const childArgs = [ + 'app-server', + '--listen', + 'stdio://', + '-c', + 'features.hooks=false', + '-c', + 'features.codex_hooks=false', + '-c', + 'analytics.enabled=false', +] +export interface StdioOptions { + binary?: string + env?: NodeJS.ProcessEnv + spawn?: typeof spawn +} +export function createStdioTransport(options: StdioOptions = {}): ReadTransport { + const child = (options.spawn ?? spawn)(options.binary ?? 'codex', childArgs, { + env: safeChildEnv(options.env ?? process.env), + shell: false, + cwd: homedir(), + stdio: ['pipe', 'pipe', 'pipe'], + }) + let ended = false + let exited = false + let stopping = false + let buffer = '' + let onLine: (line: string) => void = () => {} + let onClose = () => {} + let killTimer: ReturnType | undefined + const finish = () => { + if (ended) return + ended = true + onClose() + } + child.on('error', () => { + exited = true + clearTimeout(killTimer) + finish() + }) + child.on('close', () => { + exited = true + clearTimeout(killTimer) + finish() + }) + child.stdin!.on('error', finish) + child.stdout!.on('error', finish) + child.stderr!.on('error', () => {}) + child.stderr!.resume() + child.stdout!.setEncoding('utf8') + const transport: ReadTransport = { + write(line) { + if (ended || stopping) throw new CodexError('offline') + child.stdin!.write(line) + }, + onLine(fn) { + onLine = fn + }, + onClose(fn) { + onClose = fn + if (ended) fn() + }, + close() { + if (exited || stopping) return + stopping = true + child.stdin!.end() + child.kill('SIGTERM') + killTimer = setTimeout(() => { + if (!exited) child.kill('SIGKILL') + }, 1000) + killTimer.unref() + }, + } + child.stdout!.on('data', (chunk: string) => { + buffer += chunk + if (Buffer.byteLength(buffer) > 4 * 1024 * 1024) { + transport.close() + finish() + return + } + let newline: number + while ((newline = buffer.indexOf('\n')) >= 0) { + const line = buffer.slice(0, newline) + buffer = buffer.slice(newline + 1) + if (line.trim()) onLine(line) + } + }) + return transport +} + +/** Schema presence is a candidate capability, not account access. */ +export function methodsFromSchema(schema: unknown): Set { + const found = new Set() + if (!schema || typeof schema !== 'object') return found + const root = schema as Record + const variants = Array.isArray(root.oneOf) ? root.oneOf : [root] + for (const variant of variants) { + const v = variant as { properties?: { method?: { enum?: unknown[] } } } + for (const m of v?.properties?.method?.enum ?? []) if (typeof m === 'string') found.add(m) + } + return found +} +export type SchemaRunner = ( + file: string, + args: string[], + options: { env: NodeJS.ProcessEnv }, +) => Promise +const runSchema: SchemaRunner = (file, args, options) => + new Promise((resolve, reject) => { + execFile( + file, + args, + { ...options, cwd: homedir(), timeout: 15000, maxBuffer: 1024 * 1024, shell: false }, + (error) => (error ? reject(new CodexError('unsupported')) : resolve()), + ) + }) +export async function discoverMethods( + options: { binary?: string; env?: NodeJS.ProcessEnv; run?: SchemaRunner } = {}, +): Promise> { + const dir = await mkdtemp(join(tmpdir(), 'fremkit-codex-schema-')) + try { + await (options.run ?? runSchema)( + options.binary ?? 'codex', + [ + 'app-server', + 'generate-json-schema', + '--experimental', + '--out', + dir, + '-c', + 'features.hooks=false', + '-c', + 'features.codex_hooks=false', + ], + { env: safeChildEnv(options.env ?? process.env) }, + ) + const methods = methodsFromSchema(JSON.parse(await readFile(join(dir, 'ClientRequest.json'), 'utf8'))) + if (!methods.has('initialize')) throw new CodexError('unsupported') + return methods + } catch { + throw new CodexError('unsupported') + } finally { + await rm(dir, { recursive: true, force: true }) + } +} +const methodsCache = new Map> }>() +export async function createLocalCodexClient( + options: StdioOptions & { run?: SchemaRunner } = {}, +): Promise { + // Installed CLI capabilities rarely change while Fremkit runs. Recheck periodically, and + // never cache injected schema runners used by tests or host integrations. + const env = safeChildEnv(options.env ?? process.env) + const key = JSON.stringify([options.binary ?? 'codex', env.PATH ?? '', env.CODEX_HOME ?? '']) + let cached = !options.run && !options.spawn ? methodsCache.get(key) : undefined + if (!cached || cached.until < Date.now()) { + cached = { until: Date.now() + 10 * 60_000, methods: discoverMethods(options) } + if (!options.run && !options.spawn) methodsCache.set(key, cached) + } + let methods: Set + try { + methods = await cached.methods + } catch { + methodsCache.delete(key) + throw new CodexError('unsupported') + } + return new CodexReadClient({ methods, connect: async () => createStdioTransport(options) }) +} diff --git a/server/src/codex/config.ts b/server/src/codex/config.ts new file mode 100644 index 00000000..b7314093 --- /dev/null +++ b/server/src/codex/config.ts @@ -0,0 +1,6 @@ +import { isAbsolute } from 'node:path' +import { z } from 'zod' + +/** Optional trusted host override for an installed Codex CLI. */ +export const CodexBinarySchema = z.string().min(1).max(4096) + .refine(isAbsolute).refine(value => !value.includes('\0')) diff --git a/server/src/codex/local-chats.ts b/server/src/codex/local-chats.ts new file mode 100644 index 00000000..bbbdddce --- /dev/null +++ b/server/src/codex/local-chats.ts @@ -0,0 +1,38 @@ +import { execFile } from 'node:child_process' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { ThreadIdSchema } from './snapshot.js' + +export interface LocalChatValidator { + (threadId: string): Promise + validateMany?: (threadIds: string[]) => Promise> +} + +/** Desktop-owned catalog membership, independent of source, title and thread status. */ +export function createLocalChatValidator(options: { databasePath?: string } = {}): LocalChatValidator { + const databasePath = options.databasePath ?? join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'sqlite', 'codex-dev.db') + const validateMany = async (threadIds: string[]): Promise> => { + const ids = [...new Set(threadIds.filter(id => ThreadIdSchema.safeParse(id).success))].slice(0, 50) + if (!ids.length) return new Set() + // UUID validation excludes SQL delimiters. The child sees one bounded page, not thread content. + const quoted = ids.map(id => `'${id}'`).join(',') + const query = `SELECT DISTINCT t.thread_id AS id FROM local_thread_catalog AS t + JOIN local_thread_catalog_hosts AS h ON h.host_id=t.host_id + WHERE t.host_id='local' AND h.host_kind='local' AND t.missing_candidate=0 + AND t.thread_id IN (${quoted});` + return new Promise(resolve => { + execFile('/usr/bin/sqlite3', ['-readonly', '-json', '-batch', '-cmd', 'PRAGMA query_only=ON;', '-cmd', '.timeout 1000', databasePath, query], + { timeout: 2000, maxBuffer: 8192, shell: false }, (error, stdout) => { + if (error) return resolve(new Set()) + try { + const rows: unknown = JSON.parse(stdout || '[]') + if (!Array.isArray(rows)) return resolve(new Set()) + resolve(new Set(rows.flatMap(row => row && typeof row === 'object' && 'id' in row && typeof row.id === 'string' && ids.includes(row.id) ? [row.id] : []))) + } catch { resolve(new Set()) } + }) + }) + } + const validate: LocalChatValidator = async id => (await validateMany([id])).has(id) + validate.validateMany = validateMany + return validate +} diff --git a/server/src/codex/observations.ts b/server/src/codex/observations.ts new file mode 100644 index 00000000..074c4165 --- /dev/null +++ b/server/src/codex/observations.ts @@ -0,0 +1,264 @@ +import { execFile } from 'node:child_process' +import { constants } from 'node:fs' +import { open, realpath } from 'node:fs/promises' +import { homedir } from 'node:os' +import { basename, join, sep } from 'node:path' +import { z } from 'zod' +import { ThreadIdSchema, type History } from './snapshot.js' +import type { Provider } from '../providers/types.js' + +const MAX_ROWS = 300 +const TAIL_BYTES = 512 * 1024 +const INITIAL_BYTES = 16 * 1024 * 1024 +const FRESH_MS = 90_000 +const text = z.string().max(4096).nullable() +const Row = z.object({ + id: ThreadIdSchema, + parentId: ThreadIdSchema.nullable(), + rollout: text, + model: text, + effort: text, + cwd: text, + branch: text, + nickname: text, + role: text, + agentPath: text, + childCount: z.number().int().nonnegative(), +}) +type Row = z.infer +export interface TurnObservation { + state: 'working' | 'waiting' | 'done' | 'interrupted' | 'error' | 'unknown' + turnId: string | null + startedAt: number | null + finishedAt: number | null + lastEventAt: number | null + model: string | null + effort: string | null + durationMs: number | null +} +export interface SessionObservation extends TurnObservation { + id: string + parentId: string | null + project: string | null + branch: string | null + modelSource: 'turn' | 'stored' | null + nickname: string | null + role: string | null + agentName: string | null + subagents: SessionObservation[] + subagentCount: number + agentsTruncated: boolean +} +export interface SessionsSnapshot { + sessions: SessionObservation[] + updatedAt: number | null + error: 'offline' | 'unconfigured' | 'invalid' | null + truncated: boolean +} +const emptyTurn = (): TurnObservation => ({ state: 'unknown', turnId: null, startedAt: null, finishedAt: null, lastEventAt: null, model: null, effort: null, durationMs: null }) +const number = (v: unknown): number | null => typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null +const milliseconds = (v: unknown): number | null => { const n = number(v); return n === null ? null : n < 1e12 ? n * 1000 : n } +const label = (v: unknown): string | null => typeof v === 'string' && v.length <= 200 ? v : null +const object = (v: unknown): Record | null => + v !== null && typeof v === 'object' && !Array.isArray(v) ? v as Record : null + +/** Project lifecycle/model fields only. Prompt, reasoning and tool arguments are discarded. */ +export function parseTurnRecords(raw: string, previous: TurnObservation = emptyTurn()): TurnObservation { + let result = { ...previous } + for (const line of raw.split('\n')) { + if (!line || line.length > TAIL_BYTES) continue + let decoded: unknown + try { decoded = JSON.parse(line) } catch { continue } + const record = object(decoded) + const p = object(record?.payload) + const at = Date.parse(typeof record?.timestamp === 'string' ? record.timestamp : '') + if (!record || !p || !Number.isFinite(at)) continue + if (record.type === 'event_msg' && p.type === 'task_started') { + result = { ...emptyTurn(), state: 'working', turnId: label(p.turn_id), startedAt: milliseconds(p.started_at) ?? at, lastEventAt: at } + } else if (record.type === 'turn_context') { + // A turn context without a retained start records a model, but cannot establish runtime state. + if (!result.turnId || !p.turn_id || p.turn_id === result.turnId) { + result.model = label(p.model) + result.effort = label(p.effort ?? p.reasoning_effort) + } + } else if (record.type === 'event_msg' && + (p.type === 'task_complete' || p.type === 'turn_aborted' || p.type === 'error')) { + if (result.turnId && p.turn_id && p.turn_id !== result.turnId) continue + result.state = p.type === 'task_complete' ? 'done' : p.type === 'turn_aborted' ? 'interrupted' : 'error' + result.turnId = label(p.turn_id) ?? result.turnId + result.finishedAt = milliseconds(p.completed_at) ?? at + result.startedAt = milliseconds(p.started_at) ?? result.startedAt + result.durationMs = number(p.duration_ms) ?? + (result.startedAt === null ? null : Math.max(0, result.finishedAt - result.startedAt)) + result.lastEventAt = at + } else if (record.type === 'event_msg' || record.type === 'response_item') { + if (result.state === 'working' || result.state === 'waiting') { + result.lastEventAt = at + if (record.type === 'response_item' && p.type === 'function_call' && + typeof p.name === 'string' && /request_user_input(?:_async)?$/.test(p.name)) result.state = 'waiting' + // New model output after a wait demonstrates that execution resumed. + else if (result.state === 'waiting' && record.type === 'response_item' && + (p.type === 'reasoning' || p.type === 'function_call' || p.type === 'custom_tool_call')) result.state = 'working' + } + } + } + return result +} +export function freshTurn(turn: TurnObservation, now: number): TurnObservation { + if (['working', 'waiting'].includes(turn.state) && (!turn.lastEventAt || now < turn.lastEventAt || now - turn.lastEventAt > FRESH_MS)) return { ...turn, state: 'unknown' } + return { ...turn } +} +interface Cache { id: string; ino: number; size: number; mtime: number; turn: TurnObservation } +export function createSessionReader(options: { codexHome?: string; query?: (sql: string) => Promise } = {}) { + const home = options.codexHome ?? process.env.CODEX_HOME ?? join(homedir(), '.codex') + const cache = new Map() + const query = options.query ?? ((sql: string) => new Promise((resolve, reject) => { + execFile('/usr/bin/sqlite3', [ + '-readonly', '-json', '-batch', '-cmd', 'PRAGMA query_only=ON;', + '-cmd', '.timeout 1000', join(home, 'state_5.sqlite'), sql, + ], { timeout: 2500, maxBuffer: 512 * 1024, shell: false }, (error, stdout) => { + if (error) return reject(Error('offline')) + try { resolve(JSON.parse(stdout || '[]')) } catch { reject(Error('invalid')) } + }) + })) + async function tail(row: Row): Promise { + if (!row.rollout) return emptyTurn() + let file: Awaited> | undefined + try { + const [root, path] = await Promise.all([realpath(home), realpath(row.rollout)]) + if (![join(root, 'sessions') + sep, join(root, 'archived_sessions') + sep].some(base => path.startsWith(base))) return emptyTurn() + file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK) + const info = await file.stat() + if (!info.isFile()) return emptyTurn() + const old = cache.get(path) + if (!old || old.ino !== info.ino || old.id !== row.id) { + const head = Buffer.alloc(Math.min(65_536, info.size)) + const read = await file.read(head, 0, head.length, 0) + const end = head.subarray(0, read.bytesRead).indexOf(10) + if (end < 0) return emptyTurn() + const first = object(JSON.parse(head.subarray(0, end).toString('utf8'))) + if (first?.type !== 'session_meta' || object(first.payload)?.id !== row.id) return emptyTurn() + } + if (old && old.id === row.id && old.ino === info.ino && old.size === info.size && old.mtime === info.mtimeMs) return { ...old.turn } + const contiguous = !!old && old.id === row.id && old.ino === info.ino && old.size <= info.size && info.size - old.size <= TAIL_BYTES + const limit = contiguous ? TAIL_BYTES : INITIAL_BYTES + const offset = contiguous ? old!.size : Math.max(0, info.size - limit) + const buffer = Buffer.alloc(Math.min(limit, info.size - offset)) + const { bytesRead } = await file.read(buffer, 0, buffer.length, offset) + // Advance only through complete bytes, preserving partial JSON and UTF-8 for the next read. + const consumed = buffer.subarray(0, bytesRead).lastIndexOf(10) + 1 + let raw = buffer.subarray(0, consumed).toString('utf8') + if (!contiguous && offset > 0) raw = raw.slice(raw.indexOf('\n') + 1) + const turn = parseTurnRecords(raw, contiguous ? old!.turn : emptyTurn()) + cache.set(path, { id: row.id, ino: info.ino, size: offset + consumed, mtime: info.mtimeMs, turn }) + if (cache.size > 200) cache.delete(cache.keys().next().value!) + return { ...turn } + } catch { + return emptyTurn() + } finally { + await file?.close() + } + } + return async (ids: string[], now: number): Promise<{ sessions: SessionObservation[]; truncated: boolean }> => { + const selected = [...new Set(ids.filter(id => ThreadIdSchema.safeParse(id).success))].slice(0, 50) + if (!selected.length) return { sessions: [], truncated: false } + const list = selected.map(id => `'${id}'`).join(',') + const priority = selected.map((id, i) => `WHEN '${id}' THEN ${i}`).join(' ') + // Only UUIDs enter SQL. Read direct children of selected history, not every thread. + const sql = `SELECT t.id, e.parent_thread_id AS parentId, t.rollout_path AS rollout, + t.model, t.reasoning_effort AS effort, t.cwd, t.git_branch AS branch, + t.agent_nickname AS nickname, t.agent_role AS role, t.agent_path AS agentPath, + (SELECT COUNT(*) FROM thread_spawn_edges ce JOIN threads ct ON ct.id=ce.child_thread_id + WHERE ce.parent_thread_id=t.id AND ct.archived=0) AS childCount + FROM threads t LEFT JOIN thread_spawn_edges e ON e.child_thread_id=t.id + WHERE t.id IN (${list}) OR (e.parent_thread_id IN (${list}) AND t.archived=0) + ORDER BY (t.id IN (${list})) DESC, + CASE COALESCE(e.parent_thread_id,t.id) ${priority} ELSE 50 END, + t.updated_at DESC LIMIT ${MAX_ROWS + 1};` + const parsed = z.array(Row).max(MAX_ROWS + 1).parse(await query(sql)) + const truncated = parsed.length > MAX_ROWS + const rows = parsed.slice(0, MAX_ROWS) + const observe = async (row: Row): Promise => { + const observed = freshTurn(await tail(row), now) + const turnModel = observed.model + return { + ...observed, + id: row.id, + parentId: row.parentId, + project: row.cwd ? basename(row.cwd) : null, + branch: label(row.branch), + model: turnModel ?? label(row.model), + effort: observed.effort ?? label(row.effort), + modelSource: turnModel ? 'turn' : row.model ? 'stored' : null, + nickname: label(row.nickname), + role: label(row.role), + agentName: row.agentPath ? basename(row.agentPath) : null, + subagents: [], + subagentCount: row.childCount, + agentsTruncated: false, + } + } + const observations: SessionObservation[] = [] + // Bound concurrent cold reads: a large conversation cannot multiply file buffers by the row cap. + for (let i = 0; i < rows.length; i += 4) { + observations.push(...await Promise.all(rows.slice(i, i + 4).map(observe))) + } + const sessions = selected + .map(id => observations.find(session => session.id === id)) + .filter((session): session is SessionObservation => !!session) + .map(session => { + const subagents = observations.filter(child => child.parentId === session.id && child.id !== session.id) + return { ...session, subagents, agentsTruncated: subagents.length < session.subagentCount } + }) + return { sessions, truncated } + } +} + +/** Five-second local reads remain separate from slower account and network quota polling. */ +export function createCodexSessionsProvider(options: { + enabled: boolean | (() => boolean) + history: () => History | null + read?: ReturnType + now?: () => number +}): Provider { + const read = options.read ?? createSessionReader() + const now = options.now ?? Date.now + let generation = 0 + let inflight: Promise | undefined + let last: SessionsSnapshot = { sessions: [], updatedAt: null, error: 'unconfigured', truncated: false } + return { + channel: 'codex-live', + intervalMs: 5000, + stop() { + generation++ + inflight = undefined + last = { ...last, error: 'offline' } + }, + poll() { + const enabled = typeof options.enabled === 'function' ? options.enabled() : options.enabled + if (!enabled) { + generation++ + inflight = undefined + last = { sessions: [], updatedAt: null, error: 'unconfigured', truncated: false } + return Promise.resolve(last) + } + if (!inflight) { + const epoch = generation + const job = (async () => { + try { + const history = options.history() + if (!history) return { ...last, error: 'unconfigured' as const } + const value = await read(history.threads.map(thread => thread.id), now()) + if (epoch === generation) last = { ...value, updatedAt: now(), error: null } + } catch { + if (epoch === generation) last = { ...last, error: 'offline' } + } + return last + })() + inflight = job + void job.finally(() => { if (inflight === job) inflight = undefined }) + } + return inflight + }, + } +} diff --git a/server/src/codex/snapshot.ts b/server/src/codex/snapshot.ts new file mode 100644 index 00000000..80817897 --- /dev/null +++ b/server/src/codex/snapshot.ts @@ -0,0 +1,154 @@ +import { z } from 'zod' +import type { CodexFailure } from './adapter.js' +import type { HistorySource } from './sources.js' +const metric = z + .number() + .int() + .nonnegative() + .max(Number.MAX_SAFE_INTEGER) + .nullish() + .transform((v) => v ?? null) +const window = z + .object({ + usedPercent: z.number().int().nonnegative(), + windowDurationMins: metric, + resetsAt: metric, + }) + .transform((v) => ({ + ...v, + remainingPercent: Math.max(0, Math.min(100, 100 - v.usedPercent)), + })) +const bucket = z.object({ + limitId: z.string().max(200).nullish(), + limitName: z.string().max(200).nullish(), + primary: window.nullish().transform((v) => v ?? null), + secondary: window.nullish().transform((v) => v ?? null), +}) +export const QuotasSchema = z + .object({ + rateLimits: bucket, + rateLimitsByLimitId: z.record(z.string(), bucket).nullish(), + accountId: z.string().nullish(), + }) + .transform((v) => { + const multi = + v.rateLimitsByLimitId && Object.keys(v.rateLimitsByLimitId).length + ? Object.entries(v.rateLimitsByLimitId).slice(0, 50) + : [[v.rateLimits.limitId ?? 'codex', v.rateLimits] as const] + return { + buckets: multi.map(([id, b]) => ({ + id, + name: b.limitName ?? null, + primary: b.primary, + secondary: b.secondary, + })), + } + }) +export const UsageSchema = z.object({ + summary: z.object({ + lifetimeTokens: metric, + peakDailyTokens: metric, + currentStreakDays: metric, + longestStreakDays: metric, + longestRunningTurnSec: metric, + }), + dailyUsageBuckets: z + .array( + z.object({ + startDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + tokens: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), + }), + ) + .max(3660) + .nullish() + .transform((v) => v ?? null), +}) +export const AccountSchema = z.object({ + requiresOpenaiAuth: z.boolean(), + account: z + .object({ + type: z.enum(['chatgpt', 'apiKey', 'amazonBedrock']), + email: z.string().max(320).nullish(), + planType: z.string().max(100).nullish(), + }) + .nullish(), + workspaceRouting: z.object({ chatgptAccountId: z.string() }).nullish(), +}) +export const ThreadIdSchema = z + .string() + .regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i) +export const HistorySchema = z.object({ + data: z + .array( + z.object({ + id: ThreadIdSchema, + name: z.string().max(2000).nullish(), + source: z.union([z.string(), z.record(z.string(), z.unknown())]), + createdAt: z.number().int().nonnegative(), + updatedAt: z.number().int().nonnegative(), + ephemeral: z.boolean(), + }), + ) + .max(50), + nextCursor: z.string().max(4000).nullish(), +}) +export interface Quotas { + buckets: { id: string; name: string | null; primary: QuotaWindow | null; secondary: QuotaWindow | null }[] +} +export interface QuotaWindow { + usedPercent: number + remainingPercent: number + windowDurationMins: number | null + resetsAt: number | null +} +export type Usage = z.infer +export interface HistoryThread { + id: string + title: string | null + sourceKind: HistorySource + createdAt: number + updatedAt: number + liveActivity: null + navigation: 'localChat' | 'unavailable' +} +export interface History { + threads: HistoryThread[] + nextCursor: string | null + truncated: boolean +} +export interface SnapshotPart { + data: T | null + updatedAt: number | null + freshness: 'fresh' | 'stale' | 'unavailable' + error: CodexFailure | null +} +export interface CodexAccount { + type: 'chatgpt' | 'apiKey' | 'amazonBedrock' + planType: string | null +} +export interface CodexSnapshot { + sourceKind: 'localAppServer' + authMode: 'chatgpt' | 'apiKey' | 'amazonBedrock' | null + account: SnapshotPart + quotas: SnapshotPart + usage: SnapshotPart + history: SnapshotPart + checkedAt: number | null + error: CodexFailure | null +} +export const emptyPart = (error: CodexFailure = 'unconfigured'): SnapshotPart => ({ + data: null, + updatedAt: null, + freshness: 'unavailable', + error, +}) +export const emptySnapshot = (error: CodexFailure = 'unconfigured'): CodexSnapshot => ({ + sourceKind: 'localAppServer', + authMode: null, + account: emptyPart(error), + quotas: emptyPart(error), + usage: emptyPart(error), + history: emptyPart(error), + checkedAt: null, + error, +}) diff --git a/server/src/codex/sources.ts b/server/src/codex/sources.ts new file mode 100644 index 00000000..b6be9508 --- /dev/null +++ b/server/src/codex/sources.ts @@ -0,0 +1,16 @@ +import { z } from 'zod' + +export const HistorySourceSchema = z.enum([ + 'cli', + 'vscode', + 'exec', + 'appServer', + 'subAgent', + 'subAgentReview', + 'subAgentCompact', + 'subAgentThreadSpawn', + 'subAgentOther', + 'unknown', +]) + +export type HistorySource = z.infer diff --git a/server/src/config/migrate.ts b/server/src/config/migrate.ts index 9701de6a..746a2209 100644 --- a/server/src/config/migrate.ts +++ b/server/src/config/migrate.ts @@ -152,7 +152,7 @@ export function migrateConfig(raw: unknown): Config { connections: [], secrets: { backend: defaultSecretsBackend() }, locale: defaultLocale(), - privacy: { claudeAccountUsage: false, showAccountEmail: false }, + privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [] }, // A v1 config predates the marketplace by a long way; nothing can have been installed. marketplace: { installed: {} }, pages: v1.pages.map((p) => ({ diff --git a/server/src/config/schema.ts b/server/src/config/schema.ts index dbe62e5b..ad6bbf43 100644 --- a/server/src/config/schema.ts +++ b/server/src/config/schema.ts @@ -1,4 +1,5 @@ import { z } from 'zod' +import { HistorySourceSchema } from '../codex/sources.js' import { BUILTIN_THEME } from '../themes/theme.js' import { defaultSecretsBackend } from '../secrets/index.js' import { tr } from '../i18n.js' @@ -245,6 +246,8 @@ const PrivacySchema = z.object({ * `withAccountEmail()` from `privacy.ts` on every poll. */ showAccountEmail: z.boolean().default(false), + codexAccount: z.boolean().default(false), + codexHistorySources: z.array(HistorySourceSchema).max(10).default([]), }).prefault({}) /** @@ -349,7 +352,7 @@ export const DEFAULT_CONFIG: Config = { connections: [], secrets: { backend: defaultSecretsBackend() }, locale: defaultLocale(), - privacy: { claudeAccountUsage: false, showAccountEmail: false }, + privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [] }, marketplace: { installed: {} }, pages: [ { diff --git a/server/src/providers/codex.ts b/server/src/providers/codex.ts new file mode 100644 index 00000000..9efe8cdc --- /dev/null +++ b/server/src/providers/codex.ts @@ -0,0 +1,363 @@ +import { execFile } from 'node:child_process' +import { z } from 'zod' +import type { Provider } from './types.js' +import { + createCodexSessionsProvider, + type createSessionReader, + type SessionsSnapshot, +} from '../codex/observations.js' +import { CodexBinarySchema } from '../codex/config.js' +import type { LocalChatValidator } from '../codex/local-chats.js' +import { CodexError, createLocalCodexClient, type CodexClient, type CodexFailure } from '../codex/adapter.js' +import { HistorySourceSchema, type HistorySource } from '../codex/sources.js' +import { + AccountSchema, + HistorySchema, + QuotasSchema, + UsageSchema, + ThreadIdSchema, + emptySnapshot, + emptyPart, + type CodexSnapshot, + type SnapshotPart, + type History, +} from '../codex/snapshot.js' +export type { CodexSnapshot } from '../codex/snapshot.js' +const OptionsSchema = z + .object({ + binary: CodexBinarySchema.optional(), + enabled: z.boolean().default(false), + accountEnabled: z.boolean().default(false), + historySources: z.array(HistorySourceSchema).max(10).default([]), + }) + .strict() +export interface CodexProviderOptions { + binary?: string + enabled?: boolean | (() => boolean) + accountEnabled?: boolean | (() => boolean) + historySources?: HistorySource[] | (() => HistorySource[]) +} +function resolveOptions(options: CodexProviderOptions) { + try { + const enabled = typeof options.enabled === 'function' ? options.enabled() : (options.enabled ?? false) + const accountEnabled = + typeof options.accountEnabled === 'function' + ? options.accountEnabled() + : (options.accountEnabled ?? enabled) + const historySources = + typeof options.historySources === 'function' ? options.historySources() : (options.historySources ?? []) + return OptionsSchema.safeParse({ binary: options.binary, enabled, accountEnabled, historySources }) + } catch { + return OptionsSchema.safeParse({ enabled: 'invalid' }) + } +} +export interface CodexProviderDeps { + readSessions?: ReturnType + client?: CodexClient + clientFactory?: () => Promise + now?: () => number + /** Trusted host validation independent of sourceKind or title. Missing validator disables opens. */ + isLocalChat?: LocalChatValidator + openUrl?: (url: string) => Promise +} +const openUrl = (url: string): Promise => + new Promise((resolve, reject) => { + execFile('/usr/bin/open', [url], { timeout: 15000, shell: false }, (error) => { + if (error) reject(new CodexError('offline')) + else resolve() + }) + }) +const failure = (error: unknown): CodexFailure => + error instanceof CodexError ? error.reason : error instanceof z.ZodError ? 'invalid' : 'offline' +const stale = (part: SnapshotPart, error: CodexFailure): SnapshotPart => ({ + ...part, + freshness: part.data === null ? 'unavailable' : 'stale', + error, +}) +function normalizeSource(source: string | Record): HistorySource { + if (typeof source === 'string') { + const parsed = HistorySourceSchema.safeParse(source) + return parsed.success ? parsed.data : 'unknown' + } + if (!Object.hasOwn(source, 'subAgent')) return 'unknown' + if (source.subAgent === 'review') return 'subAgentReview' + if (source.subAgent === 'compact') return 'subAgentCompact' + if (source.subAgent && typeof source.subAgent === 'object') { + return Object.hasOwn(source.subAgent, 'thread_spawn') ? 'subAgentThreadSpawn' : 'subAgentOther' + } + return 'subAgentOther' +} +function selectedSource(source: HistorySource, sources: HistorySource[]): boolean { + return sources.includes(source) || (sources.includes('subAgent') && source.startsWith('subAgent')) +} +function selectedHistory(part: SnapshotPart, sources: HistorySource[]): SnapshotPart { + if (!sources.length) return emptyPart('unconfigured') + if (!part.data) return part + return { ...part, data: { ...part.data, threads: part.data.threads.filter((thread) => selectedSource(thread.sourceKind, sources)) } } +} +/** Opt-in core channel. The caller owns configuration and trusted local-chat validation. */ +export function createCodexProvider( + options: CodexProviderOptions = {}, + deps: CodexProviderDeps = {}, +): Provider & { sessions: Provider } { + const now = deps.now ?? Date.now + let last = emptySnapshot() + let client = deps.client + let inflight: Promise | undefined + let generation = 0 + let authIdentity: string | undefined + async function refresh(): Promise { + const parsed = resolveOptions(options) + if (!parsed.success) return emptySnapshot('invalid') + if (!parsed.data.enabled) return emptySnapshot() + const epoch = generation + const sources = parsed.data.historySources + const next: CodexSnapshot = { + ...last, + checkedAt: now(), + error: null, + history: selectedHistory(last.history, sources), + ...(!parsed.data.accountEnabled + ? { account: emptyPart(), quotas: emptyPart(), usage: emptyPart(), authMode: null } + : {}), + } + if (!parsed.data.accountEnabled) authIdentity = undefined + try { + if (!client) { + const created = deps.clientFactory + ? await deps.clientFactory() + : await createLocalCodexClient({ binary: parsed.data.binary }) + if (epoch !== generation) { + created.close() + return last + } + client = created + } + const api = client + async function read( + method: string, + params: unknown, + previous: SnapshotPart, + transform: (raw: unknown) => Promise | T, + ): Promise> { + try { + if (epoch !== generation) throw new CodexError('offline') + if (!api.supports(method)) throw new CodexError('unsupported') + const data = await transform(await api.request(method, params)) + return { data, updatedAt: now(), freshness: 'fresh', error: null } + } catch (error) { + return stale(previous, failure(error)) + } + } + let accountVerified = false + if (parsed.data.accountEnabled) + try { + if (!api.supports('account/read')) throw new CodexError('unsupported') + const auth = AccountSchema.parse(await api.request('account/read', { refreshToken: false })) + if (epoch !== generation) return last + next.authMode = auth.account?.type ?? null + if (!auth.account) throw new CodexError('unauthorized') + next.account = { + data: { + type: auth.account.type, + planType: auth.account.type === 'chatgpt' ? (auth.account.planType ?? null) : null, + }, + updatedAt: now(), + freshness: 'fresh', + error: null, + } + accountVerified = true + // Private workspace marker only; the public account display fields are projected above. + const identity = JSON.stringify([ + auth.account.type, + auth.account.email ?? null, + auth.account.planType ?? null, + auth.workspaceRouting?.chatgptAccountId ?? null, + ]) + if (authIdentity !== identity) { + next.quotas = emptyPart() + next.usage = emptyPart() + authIdentity = identity + } + if (auth.account.type !== 'chatgpt') throw new CodexError('unsupported') + next.quotas = await read( + 'account/rateLimits/read', + { supportsLunaReserve: false, excludeResetCreditDetails: true }, + next.quotas, + (raw) => QuotasSchema.parse(raw), + ) + if (next.quotas.error === 'unauthorized') throw new CodexError('unauthorized') + next.usage = await read('account/usage/read', {}, next.usage, (raw) => UsageSchema.parse(raw)) + if (next.usage.error === 'unauthorized') throw new CodexError('unauthorized') + } catch (error) { + const reason = failure(error) + if ( + reason === 'unauthorized' || + reason === 'invalid' || + (reason === 'unsupported' && !accountVerified) + ) + next.account = emptyPart(reason) + else if (!accountVerified) next.account = stale(next.account, reason) + if (reason === 'unauthorized' || reason === 'unsupported' || reason === 'invalid') { + next.authMode = reason === 'unauthorized' ? null : next.authMode + next.quotas = emptyPart(reason) + next.usage = emptyPart(reason) + authIdentity = undefined + } else { + next.quotas = stale(next.quotas, reason) + next.usage = stale(next.usage, reason) + } + } + else { + next.account = emptyPart() + next.quotas = emptyPart() + next.usage = emptyPart() + next.authMode = null + authIdentity = undefined + } + next.history = sources.length + ? await read( + 'thread/list', + { sourceKinds: sources, useStateDbOnly: true, limit: 50, sortKey: 'updated_at', archived: false }, + next.history, + async (raw) => { + const value = HistorySchema.parse(raw) + const selected = value.data.filter((thread) => { + const sourceKind = normalizeSource(thread.source) + return ( + !thread.ephemeral && + selectedSource(sourceKind, sources) + ) + }) + let localIds = new Set() + try { + if (deps.isLocalChat?.validateMany) + localIds = await deps.isLocalChat.validateMany(selected.map((thread) => thread.id)) + else if (deps.isLocalChat) { + const results = await Promise.all( + selected.map(async (thread) => ((await deps.isLocalChat!(thread.id)) ? thread.id : null)), + ) + localIds = new Set(results.filter((id): id is string => id !== null)) + } + } catch { + // Fail closed when the local catalog cannot validate the selected IDs. + } + const threads: History['threads'] = selected.map((thread) => ({ + id: thread.id, + title: thread.name ?? null, + sourceKind: normalizeSource(thread.source), + createdAt: thread.createdAt, + updatedAt: thread.updatedAt, + liveActivity: null, + navigation: localIds.has(thread.id) ? 'localChat' : 'unavailable', + })) + return { threads, nextCursor: value.nextCursor ?? null, truncated: !!value.nextCursor } + }, + ) + : emptyPart('unconfigured') + } catch (error) { + const reason = failure(error) + next.account = stale(next.account, reason) + next.quotas = stale(next.quotas, reason) + next.usage = stale(next.usage, reason) + next.history = sources.length ? stale(next.history, reason) : emptyPart('unconfigured') + } + // A poll owns its app-server child. Closing here avoids a second long-lived auth process + // alongside the desktop app; injected test clients remain under the caller's control. + if (!deps.client) { + client?.close() + client = undefined + } + next.error = + (parsed.data.accountEnabled ? (next.account.error ?? next.quotas.error ?? next.usage.error) : null) ?? + (parsed.data.historySources.length ? next.history.error : null) + if (epoch === generation && JSON.stringify(resolveOptions(options)) === JSON.stringify(parsed)) + last = next + return last + } + return { + sessions: createCodexSessionsProvider({ + enabled: () => { + const current = resolveOptions(options) + return current.success && current.data.enabled && current.data.historySources.length > 0 + }, + history: () => { + const current = resolveOptions(options) + return current.success && current.data.enabled + ? selectedHistory(last.history, current.data.historySources).data + : null + }, + read: deps.readSessions, + now, + }), + channel: 'codex', + get intervalMs() { + if (last.error === 'offline') return 15_000 + if (last.error && last.error !== 'unconfigured') return 300_000 + return 60_000 + }, + poll() { + const current = resolveOptions(options) + if (!current.success || !current.data.enabled) { + generation++ + client?.close() + client = deps.client + inflight = undefined + last = emptySnapshot(current.success ? 'unconfigured' : 'invalid') + return Promise.resolve(last) + } + if (!inflight) { + const running = refresh() + inflight = running + void running.finally(() => { + if (inflight === running) inflight = undefined + }) + } + return inflight + }, + stop() { + generation++ + client?.close() + client = deps.client + inflight = undefined + last = { + ...last, + account: stale(last.account, 'offline'), + history: stale(last.history, 'offline'), + } + }, + commands: { + open: async (payload, context) => { + const request = z + .object({ threadId: ThreadIdSchema, instanceId: z.string().min(1).max(200).optional() }) + .strict() + .safeParse(payload) + if (!context?.loopback || !request.success) return { ok: false, error: 'refused' } + const history = last.history + const epoch = generation + const thread = history.data?.threads.find((t) => t.id === request.data.threadId) + const parsed = resolveOptions(options) + if ( + !parsed.success || + !parsed.data.enabled || + history.freshness !== 'fresh' || + history.updatedAt === null || + now() - history.updatedAt > 120000 || + thread?.navigation !== 'localChat' || + !selectedSource(thread.sourceKind, parsed.data.historySources) || + !deps.isLocalChat + ) + return { ok: false, error: 'unavailable' } + try { + if (!(await deps.isLocalChat(thread.id))) return { ok: false, error: 'unavailable' } + if (epoch !== generation || last.history !== history || now() - history.updatedAt > 120000) + return { ok: false, error: 'unavailable' } + await (deps.openUrl ?? openUrl)(`codex://threads/${thread.id}`) + return { ok: true } + } catch { + return { ok: false, error: 'offline' } + } + }, + }, + } +} diff --git a/server/test/codex-adapter.test.ts b/server/test/codex-adapter.test.ts new file mode 100644 index 00000000..dc1421df --- /dev/null +++ b/server/test/codex-adapter.test.ts @@ -0,0 +1,125 @@ +import { describe, it, expect, vi } from 'vitest' +import { EventEmitter } from 'node:events' +import { PassThrough } from 'node:stream' +import { CodexReadClient, methodsFromSchema, safeChildEnv, createStdioTransport, discoverMethods } from '../src/codex/adapter.js' +import type { ReadTransport } from '../src/codex/adapter.js' +const methods = ['initialize', 'account/read', 'account/rateLimits/read', 'account/usage/read', 'thread/list'] +class Wire implements ReadTransport { + messages: Record[] = [] + line: (line: string) => void = () => {} + ended: () => void = () => {} + closed = false + respond = true + write(line: string) { + const m = JSON.parse(line); this.messages.push(m) + if (this.respond && m.id !== undefined) queueMicrotask(() => this.line(JSON.stringify({ id: m.id, result: {} }))) + } + onLine(fn: (line: string) => void) { this.line = fn } + onClose(fn: () => void) { this.ended = fn } + close() { this.closed = true; this.ended() } +} +function client(wire = new Wire(), supported = methods) { + return { wire, api: new CodexReadClient({ methods: new Set(supported), connect: async () => wire, timeoutMs: 30 }) } +} +describe('Codex read transport', () => { + it('extracts only schema method enums', () => { + expect([...methodsFromSchema({ oneOf: [{ properties: { method: { enum: ['account/read'] } } }, { properties: { method: { enum: ['turn/start'] } } }] })]).toEqual(['account/read', 'turn/start']) + expect([...methodsFromSchema({ properties: { method: { enum: [123] } } })]).toEqual([]) + }) + it('handshakes once and only sends constrained reads', async () => { + const { api, wire } = client() + await api.request('account/read', { refreshToken: false }); await api.request('account/usage/read', {}) + expect(wire.messages.map(m => m.method)).toEqual(['initialize', 'initialized', 'account/read', 'account/usage/read']) + expect(wire.messages[0]).toMatchObject({ params: { capabilities: { experimentalApi: true, explicitGatewayOauth: true, requestAttestation: false } } }) + api.close() + }) + it('rejects writes and unsafe parameters before connecting', async () => { + const { api, wire } = client() + for (const [method, params] of [['turn/start', {}], ['thread/resume', {}], ['account/rateLimitResetCredit/consume', {}], ['account/read', { refreshToken: true }], ['account/rateLimits/read', { supportsLunaReserve: true }], ['thread/list', { sourceKinds: [], useStateDbOnly: false }]] as const) { + await expect(api.request(method, params)).rejects.toMatchObject({ reason: 'refused' }) + } + expect(wire.messages).toEqual([]) + }) + it('reports methods missing in installed schema before connecting', async () => { + const { api, wire } = client(new Wire(), ['initialize']) + await expect(api.request('account/usage/read', {})).rejects.toMatchObject({ reason: 'unsupported' }); expect(wire.messages).toEqual([]) + }) + it('marks runtime missing methods unsupported and sanitizes auth errors', async () => { + const wire = new Wire(); const { api } = client(wire) + await api.request('account/read', { refreshToken: false }) + wire.write = line => { const m = JSON.parse(line); wire.messages.push(m); queueMicrotask(() => wire.line(JSON.stringify({ id: m.id, error: { code: m.method === 'account/usage/read' ? -32601 : 401, message: 'sensitive response' } }))) } + await expect(api.request('account/usage/read', {})).rejects.toMatchObject({ reason: 'unsupported' }) + await expect(api.request('account/read', { refreshToken: false })).rejects.toThrow('unauthorized') + expect(api.supports('account/usage/read')).toBe(false); api.close() + }) + it('rejects pending reads on disconnect and reconnects with a new handshake', async () => { + const wire = new Wire(); const { api } = client(wire) + await api.request('account/read', { refreshToken: false }); wire.respond = false + const pending = api.request('account/usage/read', {}); await Promise.resolve(); wire.ended() + await expect(pending).rejects.toMatchObject({ reason: 'offline' }) + wire.respond = true; await expect(api.request('account/usage/read', {})).resolves.toEqual({}) + expect(wire.messages.filter(m => m.method === 'initialize')).toHaveLength(2); api.close() + }) + it('times out initialization and closes its owned transport', async () => { + const wire = new Wire(); wire.respond = false; const { api } = client(wire) + await expect(api.request('account/read', { refreshToken: false })).rejects.toMatchObject({ reason: 'offline' }); expect(wire.closed).toBe(true) + }) + it('refuses unsolicited auth and approval requests', async () => { + const { api, wire } = client(); await api.request('account/read', { refreshToken: false }) + wire.line(JSON.stringify({ id: 'server-id', method: 'account/chatgptAuthTokens/refresh', params: {} })) + expect(wire.messages.at(-1)).toMatchObject({ id: 'server-id', error: { code: -32601 } }); api.close() + }) + it('allowlists environment without passing credentials or loader injection', () => { + expect(safeChildEnv({ PATH: '/usr/bin', HOME: '/home/example', CODEX_HOME: '/home/example/.codex', TMPDIR: '/tmp', OPENAI_API_KEY: 'placeholder', CLOUD_ACCESS_KEY: 'placeholder', TOKEN: 'placeholder', NODE_OPTIONS: '--require unsafe', DYLD_INSERT_LIBRARIES: 'unsafe' })).toEqual({ PATH: '/usr/bin', HOME: '/home/example', CODEX_HOME: '/home/example/.codex', TMPDIR: '/tmp' }) + }) + it('spawns a separate child with hooks off and closes only its process', () => { + const child = Object.assign(new EventEmitter(), { stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), kill: vi.fn(() => true) }) + const spawn = vi.fn(() => child) + const transport = createStdioTransport({ binary: 'codex', spawn: spawn as never, env: { PATH: '/usr/bin', OPENAI_API_KEY: 'placeholder' } }) + expect(spawn).toHaveBeenCalledWith('codex', ['app-server', '--listen', 'stdio://', '-c', 'features.hooks=false', '-c', 'features.codex_hooks=false', '-c', 'analytics.enabled=false'], expect.objectContaining({ shell: false, env: { PATH: '/usr/bin' }, stdio: ['pipe', 'pipe', 'pipe'] })) + const lines: string[] = []; transport.onLine(line => lines.push(line)); child.stdout.write('{"id":1'); child.stdout.write('}\n'); expect(lines).toEqual(['{"id":1}']) + transport.close(); expect(child.kill).toHaveBeenCalledWith('SIGTERM'); child.emit('close'); transport.close(); expect(child.kill).toHaveBeenCalledTimes(1) + }) + it('discovers capabilities using disposable output and filtered environment', async () => { + let directory = ''; const { writeFile, access } = await import('node:fs/promises'); const { join } = await import('node:path') + const run = vi.fn(async (_file: string, args: string[], options: { env: NodeJS.ProcessEnv }) => { + directory = args[args.indexOf('--out') + 1]; expect(options.env).toEqual({ PATH: '/usr/bin' }) + await writeFile(join(directory, 'ClientRequest.json'), JSON.stringify({ oneOf: [{ properties: { method: { enum: ['initialize', 'account/read'] } } }] })) + }) + expect([...await discoverMethods({ run, env: { PATH: '/usr/bin', OPENAI_API_KEY: 'placeholder' } })]).toEqual(['initialize', 'account/read']) + expect(run.mock.calls[0][1]).toContain('--experimental'); await expect(access(directory)).rejects.toThrow() + }) + it('refuses inherited object names instead of executing an unallowlisted method', async () => { + const { api } = client() + await expect(api.request('toString', {})).rejects.toMatchObject({ reason: 'refused' }) + }) + it('rejects a malformed protocol frame and closes the pending transport', async () => { + const { api, wire } = client(); await api.request('account/read', { refreshToken: false }); wire.respond = false + const pending = api.request('account/usage/read', {}); await Promise.resolve(); wire.line('not json') + await expect(pending).rejects.toMatchObject({ reason: 'offline' }); expect(wire.closed).toBe(true) + }) + it('terminates the owned child after an input stream error', () => { + const child = Object.assign(new EventEmitter(), { stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), kill: vi.fn(() => true) }) + const transport = createStdioTransport({ spawn: (() => child) as never }) + transport.onClose(() => transport.close()); child.stdin.emit('error', Error('pipe failure')) + expect(child.kill).toHaveBeenCalledWith('SIGTERM'); child.emit('close') + }) + it('sends the validated parameter copies despite caller mutation during initialization', async () => { + const wire = new Wire(); wire.respond = false + const { api } = client(wire) + const account = { refreshToken: false } + const history = { sourceKinds: ['appServer'], useStateDbOnly: true, limit: 50, sortKey: 'updated_at', archived: false } + const accountRead = api.request('account/read', account) + const historyRead = api.request('thread/list', history) + await Promise.resolve() + expect(wire.messages.map(m => m.method)).toEqual(['initialize']) + account.refreshToken = true + history.sourceKinds.push('cli'); history.useStateDbOnly = false + wire.respond = true + wire.line(JSON.stringify({ id: wire.messages[0].id, result: {} })) + await Promise.all([accountRead, historyRead]) + expect(wire.messages.find(m => m.method === 'account/read')?.params).toEqual({ refreshToken: false }) + expect(wire.messages.find(m => m.method === 'thread/list')?.params).toEqual({ sourceKinds: ['appServer'], useStateDbOnly: true, limit: 50, sortKey: 'updated_at', archived: false }) + api.close() + }) +}) diff --git a/server/test/codex-local-chats.test.ts b/server/test/codex-local-chats.test.ts new file mode 100644 index 00000000..89272a81 --- /dev/null +++ b/server/test/codex-local-chats.test.ts @@ -0,0 +1,48 @@ +import { execFileSync } from 'node:child_process' +import { mkdtemp, rm, stat } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { createLocalChatValidator } from '../src/codex/local-chats.js' +const A = '01900000-0000-7000-8000-000000000001' +const B = '01900000-0000-7000-8000-000000000002' +const C = '01900000-0000-7000-8000-000000000003' +const dirs: string[] = [] +afterEach(async () => { await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))) }) +async function database(sql: string) { + const dir = await mkdtemp(join(tmpdir(), 'codex-catalog-test-')); dirs.push(dir) + const path = join(dir, 'catalog.db') + execFileSync('/usr/bin/sqlite3', [path, sql]) + return path +} +const schema = `CREATE TABLE local_thread_catalog_hosts (host_id TEXT PRIMARY KEY, host_kind TEXT NOT NULL); +CREATE TABLE local_thread_catalog (host_id TEXT, thread_id TEXT, display_title TEXT, missing_candidate INTEGER NOT NULL); +INSERT INTO local_thread_catalog_hosts VALUES ('local','local'),('remote','ssh');` +describe('Codex desktop local catalog validation', () => { + it('proves same-title chats by UUID while rejecting foreign, removed and absent IDs', async () => { + const path = await database(`${schema} +INSERT INTO local_thread_catalog VALUES ('local','${A}','Same title',0),('local','${B}','Same title',0),('remote','${C}','Same title',0);`) + const valid = createLocalChatValidator({ databasePath: path }) + expect(await valid(A)).toBe(true); expect(await valid(B)).toBe(true); expect(await valid(C)).toBe(false) + expect(await valid('01900000-0000-7000-8000-000000000004')).toBe(false) + execFileSync('/usr/bin/sqlite3', [path, `UPDATE local_thread_catalog SET missing_candidate=1 WHERE thread_id='${A}';`]) + expect(await valid(A)).toBe(false) + expect(await valid("' OR 1=1 --")).toBe(false) + }) + it('requires the authoritative local host kind even when a host ID is local', async () => { + const path = await database(`${schema} INSERT INTO local_thread_catalog VALUES ('local','${A}','Same title',0); UPDATE local_thread_catalog_hosts SET host_kind='ssh' WHERE host_id='local';`) + expect(await createLocalChatValidator({ databasePath: path })(A)).toBe(false) + }) + it('checks a history page in one query and excludes IDs outside the local catalog', async () => { + const path = await database(`${schema} INSERT INTO local_thread_catalog VALUES ('local','${A}','A',0),('remote','${B}','B',0),('local','${C}','C',1);`) + const validator = createLocalChatValidator({ databasePath: path }) + expect(await validator.validateMany!([A, B, C, A, "' OR 1=1 --"])).toEqual(new Set([A])) + }) + it('fails closed for missing or unsupported databases without creating one', async () => { + const path = await database('CREATE TABLE unsupported (id TEXT);') + expect(await createLocalChatValidator({ databasePath: path })(A)).toBe(false) + const missing = join(dirs[0], 'missing.db') + expect(await createLocalChatValidator({ databasePath: missing })(A)).toBe(false) + await expect(stat(missing)).rejects.toMatchObject({ code: 'ENOENT' }) + }) +}) diff --git a/server/test/codex-observations.test.ts b/server/test/codex-observations.test.ts new file mode 100644 index 00000000..ca7679ee --- /dev/null +++ b/server/test/codex-observations.test.ts @@ -0,0 +1,349 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { appendFile, mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { execFileSync } from 'node:child_process' +import { + createCodexSessionsProvider, + createSessionReader, + freshTurn, + parseTurnRecords, +} from '../src/codex/observations.js' +import type { History } from '../src/codex/snapshot.js' + +const A = '00000000-0000-4000-8000-000000000001' +const B = '00000000-0000-4000-8000-000000000002' +const C = '00000000-0000-4000-8000-000000000003' +const now = 1800000000000 +const line = (type: string, payload: unknown, at = now) => + JSON.stringify({ timestamp: new Date(at).toISOString(), type, payload }) + '\n' +const started = line( + 'event_msg', + { + type: 'task_started', + turn_id: 'turn-a', + started_at: (now - 120000) / 1000, + }, + now - 120000, +) +const context = line( + 'turn_context', + { + turn_id: 'turn-a', + model: 'gpt-example', + effort: 'high', + cwd: '/private/project', + instructions: 'PRIVATE PROMPT', + }, + now - 119000, +) +const progress = line( + 'response_item', + { + type: 'function_call', + name: 'exec_command', + arguments: 'PRIVATE TOKEN', + }, + now, +) + +const dirs: string[] = [] +afterEach(async () => { + while (dirs.length) await rm(dirs.pop()!, { recursive: true, force: true }) +}) + +describe('Codex turn observations', () => { + it('tracks explicit start and per-turn model without exposing prompt/tool content', () => { + const turn = parseTurnRecords(started + context + progress) + expect(turn).toMatchObject({ + state: 'working', + startedAt: now - 120000, + model: 'gpt-example', + effort: 'high', + lastEventAt: now, + }) + expect(JSON.stringify(turn)).not.toMatch(/PRIVATE|instructions|arguments|cwd/) + }) + + it('uses observed completion duration and does not confuse another turn completion', () => { + const turn = parseTurnRecords( + started + + context + + line('event_msg', { + type: 'task_complete', + turn_id: 'other', + }), + ) + expect(turn.state).toBe('working') + const done = parseTurnRecords( + line('event_msg', { + type: 'task_complete', + turn_id: 'turn-a', + duration_ms: 120000, + completed_at: now / 1000, + }), + turn, + ) + expect(done).toMatchObject({ state: 'done', durationMs: 120000, finishedAt: now }) + }) + + it('marks silent unfinished turns unknown instead of reporting them active indefinitely', () => { + const turn = parseTurnRecords(started + context + progress) + expect(freshTurn(turn, now + 90001).state).toBe('unknown') + expect(freshTurn(turn, now).state).toBe('working') + expect(freshTurn(turn, now - 1).state).toBe('unknown') + }) + + it('recognizes user input waits, resumption, and interruption', () => { + let turn = parseTurnRecords( + started + + line('response_item', { + type: 'function_call', + name: 'functions.request_user_input_async', + }), + ) + expect(turn.state).toBe('waiting') + turn = parseTurnRecords(line('response_item', { type: 'reasoning', text: 'PRIVATE' }), turn) + expect(turn.state).toBe('working') + expect( + parseTurnRecords( + line('event_msg', { + type: 'turn_aborted', + turn_id: 'turn-a', + }), + turn, + ).state, + ).toBe('interrupted') + }) + + it('does not infer work or a start from a model/context or generic history update alone', () => { + expect(parseTurnRecords(context + progress)).toMatchObject({ + state: 'unknown', + startedAt: null, + model: 'gpt-example', + }) + expect(parseTurnRecords('broken\n')).toMatchObject({ state: 'unknown' }) + }) +}) + +async function fixture() { + const home = await mkdtemp(join(tmpdir(), 'codex-observation-')) + dirs.push(home) + await mkdir(join(home, 'sessions')) + const parent = join(home, 'sessions', 'parent.jsonl') + const child = join(home, 'sessions', 'child.jsonl') + await writeFile(parent, line('session_meta', { id: A }) + started + context + progress) + await writeFile( + child, + line('session_meta', { id: B }) + + started + + context + + line('event_msg', { + type: 'task_complete', + turn_id: 'turn-a', + duration_ms: 120000, + }), + ) + const database = join(home, 'state_5.sqlite') + execFileSync('/usr/bin/sqlite3', [ + database, + ` + CREATE TABLE threads (id TEXT, rollout_path TEXT, model TEXT, reasoning_effort TEXT, + cwd TEXT, git_branch TEXT, agent_nickname TEXT, agent_role TEXT, agent_path TEXT, + archived INTEGER, updated_at INTEGER); + CREATE TABLE thread_spawn_edges (parent_thread_id TEXT, child_thread_id TEXT); + INSERT INTO threads VALUES + ('${A}','${parent}','stored-model','low','/private/example-project','main',NULL,NULL,NULL,0,1), + ('${B}','${child}','stored-child','low','/private/example-project','main','Agent Example','worker','/root/check',0,1), + ('${C}',NULL,'unrelated','low','/private/other',NULL,NULL,NULL,NULL,0,1); + INSERT INTO thread_spawn_edges VALUES ('${A}','${B}'); + `, + ]) + return { home, parent, child, database } +} + +describe('Selected Codex local session reader', () => { + it('joins selected parent and direct child, sanitizes project paths and keeps unrelated threads private', async () => { + const f = await fixture() + const snapshot = await createSessionReader({ codexHome: f.home })([A], now) + expect(snapshot.sessions).toHaveLength(1) + expect(snapshot.sessions[0]).toMatchObject({ + id: A, + project: 'example-project', + branch: 'main', + model: 'gpt-example', + modelSource: 'turn', + state: 'working', + subagents: [ + { + id: B, + nickname: 'Agent Example', + role: 'worker', + agentName: 'check', + state: 'done', + }, + ], + }) + expect(JSON.stringify(snapshot)).not.toMatch(/rollout|\/private\/|unrelated|PRIVATE/) + expect(snapshot.truncated).toBe(false) + }) + + it('preserves a start through incremental updates and split UTF-8 JSON records', async () => { + const f = await fixture() + const read = createSessionReader({ codexHome: f.home }) + await read([A], now) + const next = line('response_item', { type: 'reasoning', text: 'privé' }, now + 1000) + const bytes = Buffer.from(next) + const split = bytes.indexOf(Buffer.from('é')) + 1 + await appendFile(f.parent, bytes.subarray(0, split)) + await read([A], now + 1000) + await appendFile(f.parent, bytes.subarray(split)) + const snapshot = await read([A], now + 1000) + expect(snapshot.sessions[0]).toMatchObject({ + state: 'working', + startedAt: now - 120000, + lastEventAt: now + 1000, + }) + }) + + it('recovers after an oversized record arrives in chunks before a completion event', async () => { + const f = await fixture() + const read = createSessionReader({ codexHome: f.home }) + await read([A], now) + const large = line('response_item', { type: 'message', content: 'x'.repeat(600000) }) + await appendFile(f.parent, large.slice(0, 400000)) + expect((await read([A], now)).sessions[0].state).toBe('working') + await appendFile(f.parent, large.slice(400000) + line('event_msg', { + type: 'task_complete', turn_id: 'turn-a', completed_at: now / 1000, + })) + const finished = await read([A], now) + expect(finished.sessions[0]).toMatchObject({ state: 'done', finishedAt: now }) + }) + + it('retains a turn start beyond a large recent output on initial observation', async () => { + const f = await fixture() + await appendFile( + f.parent, + line('response_item', { + type: 'message', + content: 'x'.repeat(3000000), + }) + progress, + ) + const snapshot = await createSessionReader({ codexHome: f.home })([A], now) + expect(snapshot.sessions[0]).toMatchObject({ state: 'working', startedAt: now - 120000 }) + }) + + it('refuses a rollout belonging to another ID and a path outside sessions', async () => { + const f = await fixture() + await writeFile(f.parent, line('session_meta', { id: C }) + started + progress) + let snapshot = await createSessionReader({ codexHome: f.home })([A], now) + expect(snapshot.sessions[0].state).toBe('unknown') + const outside = join(f.home, 'outside.jsonl') + await writeFile(outside, line('session_meta', { id: A }) + started + progress) + execFileSync('/usr/bin/sqlite3', [ + f.database, + `UPDATE threads SET rollout_path='${outside}' WHERE id='${A}';`, + ]) + snapshot = await createSessionReader({ codexHome: f.home })([A], now) + expect(snapshot.sessions[0].state).toBe('unknown') + }) + + it('prioritizes each selected parent and reports exact counts when detail rows are bounded', async () => { + const f = await fixture() + const inserts = Array.from({ length: 320 }, (_, i) => { + const id = '10000000-0000-4000-8000-' + String(i).padStart(12, '0') + return `INSERT INTO threads VALUES ('${id}',NULL,'child-model','low','/private/example',NULL,NULL,NULL,NULL,0,100);INSERT INTO thread_spawn_edges VALUES ('${C}','${id}');` + }).join('') + execFileSync('/usr/bin/sqlite3', [f.database, inserts]) + const snapshot = await createSessionReader({ codexHome: f.home })([A, C], now) + expect(snapshot.truncated).toBe(true) + expect(snapshot.sessions[0]).toMatchObject({ + id: A, + subagentCount: 1, + agentsTruncated: false, + subagents: [{ id: B }], + }) + expect(snapshot.sessions[1]).toMatchObject({ + id: C, + subagentCount: 320, + agentsTruncated: true, + }) + expect(snapshot.sessions[1].subagents).toHaveLength(297) + }) + + it('does not create a missing database or query invalid IDs', async () => { + const f = await fixture() + const missing = join(f.home, 'missing') + await expect(createSessionReader({ codexHome: missing })([A], now)).rejects.toThrow() + await expect(stat(join(missing, 'state_5.sqlite'))).rejects.toMatchObject({ code: 'ENOENT' }) + let queried = false + const read = createSessionReader({ + query: async () => { + queried = true + return [] + }, + }) + expect(await read(["bad' SQL"], now)).toEqual({ sessions: [], truncated: false }) + expect(queried).toBe(false) + }) +}) + +const selectedHistory = (): History => ({ + threads: [ + { + id: A, + title: 'Selected chat', + sourceKind: 'appServer', + createdAt: now - 120000, + updatedAt: now, + liveActivity: null, + navigation: 'localChat', + }, + ], + nextCursor: null, + truncated: false, +}) + +describe('Codex observations channel lifecycle', () => { + it('stays opt-in and keeps failures separate from history/account snapshots', async () => { + let reads = 0 + const disabled = createCodexSessionsProvider({ + enabled: false, + history: () => null, + read: async () => { + reads++ + throw Error('offline') + }, + }) + expect((await disabled.poll!()).error).toBe('unconfigured') + expect(reads).toBe(0) + + const provider = createCodexSessionsProvider({ + enabled: true, + history: selectedHistory, + read: async () => { + throw Error('PRIVATE') + }, + now: () => now, + }) + expect(await provider.poll!()).toMatchObject({ sessions: [], error: 'offline', updatedAt: null }) + expect(provider.intervalMs).toBe(5000) + }) + + it('does not publish a late read after the channel stops', async () => { + let release!: (value: { sessions: []; truncated: false }) => void + const provider = createCodexSessionsProvider({ + enabled: true, + history: selectedHistory, + read: () => + new Promise((resolve) => { + release = resolve + }), + now: () => now, + }) + const pending = provider.poll!() + provider.stop!() + release({ sessions: [], truncated: false }) + expect(await pending).toMatchObject({ updatedAt: null, error: 'offline' }) + }) +}) diff --git a/server/test/codex-provider.test.ts b/server/test/codex-provider.test.ts new file mode 100644 index 00000000..96593387 --- /dev/null +++ b/server/test/codex-provider.test.ts @@ -0,0 +1,650 @@ +import { describe, it, expect, vi } from 'vitest' +import * as codexAdapter from '../src/codex/adapter.js' +import { createCodexProvider } from '../src/providers/codex.js' +import { CodexError } from '../src/codex/adapter.js' +const A = '01900000-0000-7000-8000-000000000001', + B = '01900000-0000-7000-8000-000000000002', + C = '01900000-0000-7000-8000-000000000003' +function thread(id: string, source = 'appServer') { + return { + id, + name: 'Same title', + preview: 'private message', + source, + createdAt: 100, + updatedAt: 200, + cwd: '/path/to/project', + sessionId: id, + cliVersion: '0.159.2', + ephemeral: false, + modelProvider: 'openai', + projectId: null, + status: { type: 'active', activeFlags: [] }, + turns: [], + } +} +function harness( + auth: unknown = { + account: { type: 'chatgpt', email: 'example@example.com', planType: 'plus' }, + requiresOpenaiAuth: true, + }, + localIds = [A, B], +) { + const calls: { method: string; params: unknown }[] = [], + opens: string[] = [] + const values: Record = { + 'account/read': auth, + 'account/rateLimits/read': { + rateLimits: { primary: { usedPercent: 80, windowDurationMins: 300, resetsAt: 1000 }, secondary: null }, + rateLimitsByLimitId: { + codex: { + primary: { usedPercent: 0, windowDurationMins: null, resetsAt: null }, + secondary: { usedPercent: 110, windowDurationMins: 10080, resetsAt: 2000 }, + }, + }, + }, + 'account/usage/read': { + summary: { lifetimeTokens: null, peakDailyTokens: 0 }, + dailyUsageBuckets: [{ startDate: '2026-01-01', tokens: 0 }], + }, + 'thread/list': { data: [thread(A), thread(B), thread(C, 'cli')], nextCursor: 'next' }, + } + let t = 5000, + closed = 0 + const client = { + supports: () => true, + close: () => { + closed++ + }, + request: async (method: string, params: unknown) => { + calls.push({ method, params }) + const v = values[method] + if (v instanceof Error) throw v + return v + }, + } + const provider = createCodexProvider( + { enabled: true, historySources: ['appServer', 'cli'] }, + { + client, + now: () => t, + isLocalChat: async (id) => localIds.includes(id), + openUrl: async (url) => { + opens.push(url) + }, + }, + ) + return { + provider, + calls, + opens, + values, + tick: () => { + t += 1000 + }, + closed: () => closed, + } +} +describe('Codex provider snapshots', () => { + it('is opt-in and does not construct a client while unconfigured', async () => { + let built = 0 + const p = createCodexProvider( + {}, + { + clientFactory: async () => { + built++ + throw Error('unexpected') + }, + }, + ) + expect(await p.poll!()).toMatchObject({ + error: 'unconfigured', + quotas: { data: null }, + history: { data: null }, + }) + expect(p.intervalMs).toBe(60_000) + expect(built).toBe(0) + }) + it('reads live preferences on each poll and drops prior account data when disabled', async () => { + const h = harness() + let accountEnabled = false + let historySources: Array<'appServer'> = [] + const p = createCodexProvider( + { + enabled: () => accountEnabled || historySources.length > 0, + accountEnabled: () => accountEnabled, + historySources: () => historySources, + }, + { + client: { + supports: () => true, + close() {}, + request: async (method) => h.values[method], + }, + }, + ) + expect((await p.poll!()).account.data).toBeNull() + accountEnabled = true + expect((await p.poll!()).account.data).toEqual({ type: 'chatgpt', planType: 'plus' }) + historySources = ['appServer'] + expect((await p.poll!()).history.data?.threads).toHaveLength(2) + accountEnabled = false + expect((await p.poll!()).account.data).toBeNull() + historySources = [] + expect((await p.poll!()).history.data).toBeNull() + }) + it('removes revoked history sources even when the next list fails', async () => { + const h = harness() + let sources: Array<'appServer' | 'cli'> = ['appServer', 'cli'] + const provider = createCodexProvider( + { enabled: true, accountEnabled: false, historySources: () => sources }, + { + client: { supports: () => true, close() {}, request: async (method) => { + const value = h.values[method] + if (value instanceof Error) throw value + return value + } }, + isLocalChat: async () => true, + }, + ) + expect((await provider.poll!()).history.data?.threads.map((item) => item.id)).toContain(C) + sources = ['appServer'] + h.values['thread/list'] = new CodexError('offline') + const changed = await provider.poll!() + expect(changed.history.freshness).toBe('stale') + expect(changed.history.data?.threads.map((item) => item.id)).not.toContain(C) + expect(await provider.commands!.open({ threadId: C }, { loopback: true })).toMatchObject({ ok: false }) + }) + it('clears account sections before a new client fails after account reads are disabled', async () => { + const h = harness() + let accountEnabled = true + let factoryFails = false + const provider = createCodexProvider( + { enabled: true, accountEnabled: () => accountEnabled, historySources: ['appServer'] }, + { clientFactory: async () => { + if (factoryFails) throw new Error('unavailable') + return { supports: () => true, close() {}, request: async (method) => h.values[method] } + } }, + ) + expect((await provider.poll!()).account.data).not.toBeNull() + accountEnabled = false + factoryFails = true + const changed = await provider.poll!() + expect(changed.account.data).toBeNull() + expect(changed.quotas.data).toBeNull() + expect(changed.usage.data).toBeNull() + expect(changed.authMode).toBeNull() + }) + it('passes the configured absolute binary to its local client factory', async () => { + const h = harness() + const local = vi + .spyOn(codexAdapter, 'createLocalCodexClient') + .mockResolvedValue({ supports: () => true, close() {}, request: async (method) => h.values[method] }) + try { + const p = createCodexProvider({ enabled: true, binary: '/path/to/codex' }) + expect((await p.poll!()).usage.data?.summary.peakDailyTokens).toBe(0) + expect(local).toHaveBeenCalledWith({ binary: '/path/to/codex' }) + } finally { + local.mockRestore() + } + }) + it('retains an injected client factory override with configured binary', async () => { + const h = harness() + let builds = 0 + const p = createCodexProvider( + { enabled: true, binary: '/path/to/codex' }, + { + clientFactory: async () => { + builds++ + return { supports: () => true, close() {}, request: async (method) => h.values[method] } + }, + }, + ) + expect((await p.poll!()).usage.data?.summary.peakDailyTokens).toBe(0) + expect(builds).toBe(1) + }) + it('closes each owned app-server client after a poll', async () => { + const h = harness() + let built = 0 + let closed = 0 + const p = createCodexProvider( + { enabled: true, accountEnabled: true }, + { + clientFactory: async () => { + built++ + return { + supports: () => true, + request: async (method) => h.values[method], + close: () => { + closed++ + }, + } + }, + }, + ) + await p.poll!() + await p.poll!() + expect({ built, closed }).toEqual({ built: 2, closed: 2 }) + }) + it('backs off for durable errors instead of retrying every 15 seconds', async () => { + const h = harness() + h.values['account/read'] = new CodexError('unsupported') + const p = createCodexProvider( + { enabled: true, accountEnabled: true }, + { + client: { + supports: () => true, + request: async (method) => { + const value = h.values[method] + if (value instanceof Error) throw value + return value + }, + close() {}, + }, + }, + ) + expect((await p.poll!()).error).toBe('unsupported') + expect(p.intervalMs).toBe(300_000) + }) + it('preserves null and zero metrics, prefers multiple buckets and exposes only the account display fields', async () => { + const h = harness(), + s = await h.provider.poll!() + expect(s.quotas.data?.buckets).toEqual([ + { + id: 'codex', + name: null, + primary: { usedPercent: 0, remainingPercent: 100, windowDurationMins: null, resetsAt: null }, + secondary: { usedPercent: 110, remainingPercent: 0, windowDurationMins: 10080, resetsAt: 2000 }, + }, + ]) + expect(s.usage.data).toMatchObject({ + summary: { lifetimeTokens: null, peakDailyTokens: 0, currentStreakDays: null }, + dailyUsageBuckets: [{ startDate: '2026-01-01', tokens: 0 }], + }) + expect(s.account).toMatchObject({ + data: { type: 'chatgpt', planType: 'plus' }, + freshness: 'fresh', + error: null, + }) + expect(h.calls).toContainEqual({ method: 'account/read', params: { refreshToken: false } }) + expect(h.calls).toContainEqual({ + method: 'account/rateLimits/read', + params: { supportsLunaReserve: false, excludeResetCreditDetails: true }, + }) + }) + it('uses explicit DB-only history and retains IDs without claiming live activity', async () => { + const h = harness(), + s = await h.provider.poll!() + expect(h.calls).toContainEqual({ + method: 'thread/list', + params: { + sourceKinds: ['appServer', 'cli'], + useStateDbOnly: true, + limit: 50, + sortKey: 'updated_at', + archived: false, + }, + }) + expect(s.history.data).toMatchObject({ + nextCursor: 'next', + truncated: true, + threads: [ + { id: A, title: 'Same title', sourceKind: 'appServer', navigation: 'localChat', liveActivity: null }, + { id: B, navigation: 'localChat' }, + { id: C, sourceKind: 'cli', navigation: 'unavailable' }, + ], + }) + expect(JSON.stringify(s)).not.toContain('private message') + expect(JSON.stringify(s)).not.toContain('/path/to/project') + }) + it('does not list history unless sources are selected', async () => { + const h = harness() + const p = createCodexProvider( + { enabled: true }, + { + client: { + supports: () => true, + close() {}, + request: async (m: string) => { + h.calls.push({ method: m, params: {} }) + return h.values[m] + }, + }, + }, + ) + expect((await p.poll!()).history.error).toBe('unconfigured') + expect(h.calls.some((c) => c.method === 'thread/list')).toBe(false) + }) + it('retains last good data with original timestamps and stale state after interruption', async () => { + const h = harness(), + first = await h.provider.poll!() + h.tick() + h.values['account/usage/read'] = new CodexError('offline') + const s = await h.provider.poll!() + expect(s.usage).toEqual({ ...first.usage, freshness: 'stale', error: 'offline' }) + expect(s.quotas.updatedAt).toBe(6000) + expect(h.provider.intervalMs).toBe(15000) + }) + it('reports missing auth while still reading selected local history', async () => { + const h = harness({ account: null, requiresOpenaiAuth: true }), + s = await h.provider.poll!() + expect(s.quotas).toMatchObject({ data: null, freshness: 'unavailable', error: 'unauthorized' }) + expect(s.history.data?.threads).toHaveLength(3) + expect(h.calls.some((c) => c.method === 'account/usage/read')).toBe(false) + }) + it('clears prior account data when authentication disappears', async () => { + const h = harness() + await h.provider.poll!() + h.values['account/read'] = { account: null, requiresOpenaiAuth: true } + const s = await h.provider.poll!() + expect(s.quotas.data).toBeNull() + expect(s.usage.data).toBeNull() + }) + it('reports unsupported auth modes rather than zero usage', async () => { + const h = harness({ account: { type: 'apiKey' }, requiresOpenaiAuth: true }), + s = await h.provider.poll!() + expect(s.authMode).toBe('apiKey') + expect(s.usage.error).toBe('unsupported') + expect(s.usage.data).toBeNull() + }) + it('preserves independent successes when usage is unsupported or malformed', async () => { + const h = harness() + h.values['account/usage/read'] = new CodexError('unsupported') + expect((await h.provider.poll!()).usage.error).toBe('unsupported') + h.values['account/usage/read'] = { summary: { lifetimeTokens: -3 } } + expect((await h.provider.poll!()).usage.error).toBe('invalid') + }) + it('rejects invalid source selection without constructing a client', async () => { + const p = createCodexProvider( + { enabled: true, historySources: ['invalid'] as never }, + { + clientFactory: async () => { + throw Error('unexpected') + }, + }, + ) + expect((await p.poll!()).error).toBe('invalid') + }) + it('opens same-title validated local chats by ID without protocol calls', async () => { + const h = harness() + await h.provider.poll!() + const count = h.calls.length + expect(await h.provider.commands!.open({ threadId: A }, { loopback: true })).toEqual({ ok: true }) + expect(await h.provider.commands!.open({ threadId: B }, { loopback: true })).toEqual({ ok: true }) + expect(h.opens).toEqual([`codex://threads/${A}`, `codex://threads/${B}`]) + expect(h.calls).toHaveLength(count) + }) + it('refuses remote, unknown, stale, title-only and unvalidated CLI navigation', async () => { + const h = harness() + await h.provider.poll!() + for (const [payload, ctx] of [ + [{ threadId: A }, undefined], + [{ threadId: A }, { loopback: false }], + [{ title: 'Same title' }, { loopback: true }], + [{ threadId: 'new' }, { loopback: true }], + [{ threadId: C }, { loopback: true }], + [{ threadId: A, prompt: 'start' }, { loopback: true }], + ]) + expect(await h.provider.commands!.open(payload, ctx as never)).toMatchObject({ ok: false }) + h.values['thread/list'] = new CodexError('offline') + await h.provider.poll!() + expect(await h.provider.commands!.open({ threadId: A }, { loopback: true })).toMatchObject({ ok: false }) + expect(h.opens).toEqual([]) + }) + it('allows a CLI-origin record only when the desktop catalog proves the exact existing chat', async () => { + const h = harness(undefined, [A, B, C]) + const snapshot = await h.provider.poll!() + expect(snapshot.history.data?.threads.find((t) => t.id === C)).toMatchObject({ + sourceKind: 'cli', + navigation: 'localChat', + liveActivity: null, + }) + expect( + await h.provider.commands!.open({ threadId: C, instanceId: 'codex-widget-1' }, { loopback: true }), + ).toEqual({ ok: true }) + expect(h.opens).toEqual([`codex://threads/${C}`]) + }) + it('rejects foreign and absent UUIDs and ignores no extra command capabilities', async () => { + const h = harness() + h.values['thread/list'] = { data: [thread('01900000-0000-7000-8000-000000000004')], nextCursor: null } + await h.provider.poll!() + for (const payload of [ + { threadId: A }, + { threadId: '01900000-0000-7000-8000-000000000004' }, + { threadId: A, instanceId: '' }, + { threadId: A, instanceId: 'x'.repeat(201) }, + ]) { + expect(await h.provider.commands!.open(payload, { loopback: true })).toMatchObject({ ok: false }) + } + expect(h.opens).toEqual([]) + }) + it('closes only its client and serializes overlapping polls', async () => { + const h = harness() + const [a, b] = await Promise.all([h.provider.poll!(), h.provider.poll!()]) + expect(a).toEqual(b) + expect(h.calls.filter((c) => c.method === 'account/read')).toHaveLength(1) + h.provider.stop!() + expect(h.closed()).toBe(1) + }) + it('clears both account sections when a metric read rejects authentication', async () => { + const h = harness() + await h.provider.poll!() + h.values['account/usage/read'] = new CodexError('unauthorized') + const s = await h.provider.poll!() + expect(s.usage.data).toBeNull() + expect(s.quotas.data).toBeNull() + expect(s.authMode).toBeNull() + }) + it('does not retain the previous account data after account identity changes', async () => { + const h = harness() + await h.provider.poll!() + h.values['account/read'] = { + account: { type: 'chatgpt', email: 'other@example.com', planType: 'plus' }, + requiresOpenaiAuth: true, + } + h.values['account/usage/read'] = new CodexError('offline') + expect((await h.provider.poll!()).usage.data).toBeNull() + }) + it('does not restart reads after stop interrupts a pending authentication read', async () => { + let resolve!: (v: unknown) => void + const calls: string[] = [] + const p = createCodexProvider( + { enabled: true, historySources: ['appServer'] }, + { + client: { + supports: () => true, + close() {}, + request: async (method) => { + calls.push(method) + return new Promise((r) => { + resolve = r + }) + }, + }, + }, + ) + const pending = p.poll!() + await Promise.resolve() + p.stop!() + resolve({ account: { type: 'chatgpt' }, requiresOpenaiAuth: true }) + await pending + expect(calls).toEqual(['account/read']) + }) + it('disables navigation without an independent trusted local-chat validator', async () => { + const h = harness() + const p = createCodexProvider( + { enabled: true, historySources: ['appServer'] }, + { + client: { supports: () => true, close() {}, request: async (method) => h.values[method] }, + openUrl: async () => { + throw Error('must not open') + }, + }, + ) + expect((await p.poll!()).history.data?.threads.every((t) => t.navigation === 'unavailable')).toBe(true) + expect(await p.commands!.open({ threadId: A }, { loopback: true })).toEqual({ + ok: false, + error: 'unavailable', + }) + }) + it('normalizes subagent source objects and filters precisely selected kinds', async () => { + const h = harness() + h.values['thread/list'] = { + data: [ + { ...thread(A), source: { subAgent: 'review' } }, + { ...thread(B), source: { custom: 'external' } }, + ], + nextCursor: null, + } + const p = createCodexProvider( + { enabled: true, historySources: ['subAgentReview', 'unknown'] }, + { client: { supports: () => true, close() {}, request: async (method) => h.values[method] } }, + ) + expect((await p.poll!()).history.data?.threads.map((t) => t.sourceKind)).toEqual([ + 'subAgentReview', + 'unknown', + ]) + }) + it('cancels navigation when stop occurs during trusted revalidation', async () => { + const h = harness() + let resolve!: (value: boolean) => void + let defer = false + const p = createCodexProvider( + { enabled: true, historySources: ['appServer'] }, + { + client: { supports: () => true, close() {}, request: async (method) => h.values[method] }, + isLocalChat: async () => + defer + ? new Promise((r) => { + resolve = r + }) + : true, + openUrl: async (url) => { + h.opens.push(url) + }, + }, + ) + await p.poll!() + defer = true + const opening = p.commands!.open({ threadId: A }, { loopback: true }) + await Promise.resolve() + p.stop!() + resolve(true) + expect(await opening).toEqual({ ok: false, error: 'unavailable' }) + expect(h.opens).toEqual([]) + }) + it('refuses navigation when successful history has aged past its freshness bound', async () => { + const h = harness() + await h.provider.poll!() + for (let i = 0; i < 121; i++) h.tick() + expect(await h.provider.commands!.open({ threadId: A }, { loopback: true })).toEqual({ + ok: false, + error: 'unavailable', + }) + expect(h.opens).toEqual([]) + }) + it('clears stale metrics when the workspace account changes with the same email and plan', async () => { + const account = { type: 'chatgpt', email: 'example@example.com', planType: 'plus' } + const routing = { + chatgptAccountId: 'workspace-a', + backendOrigin: 'https://example.com', + accountRoutingOverride: 'NO_CONSTRAINT', + } + const h = harness({ account, requiresOpenaiAuth: true, workspaceRouting: routing }) + h.values['account/rateLimits/read'] = { + rateLimits: { primary: { usedPercent: 37, windowDurationMins: 300, resetsAt: 1000 } }, + } + h.values['account/usage/read'] = { summary: { lifetimeTokens: 123 }, dailyUsageBuckets: null } + const first = await h.provider.poll!() + expect(first.quotas.data?.buckets[0].primary?.usedPercent).toBe(37) + expect(first.usage.data?.summary.lifetimeTokens).toBe(123) + expect(JSON.stringify(first)).not.toContain('workspace-a') + h.values['account/read'] = { + account, + requiresOpenaiAuth: true, + workspaceRouting: { ...routing, chatgptAccountId: 'workspace-b' }, + } + h.values['account/rateLimits/read'] = new CodexError('offline') + h.values['account/usage/read'] = new CodexError('offline') + const next = await h.provider.poll!() + expect(next.quotas).toEqual({ data: null, updatedAt: null, freshness: 'unavailable', error: 'offline' }) + expect(next.usage).toEqual({ data: null, updatedAt: null, freshness: 'unavailable', error: 'offline' }) + expect(JSON.stringify(next)).not.toContain('workspace-b') + expect(JSON.stringify(next)).not.toContain('chatgptAccountId') + }) +}) + +describe('Codex connected account display', () => { + it('does not expose credentials or workspace identifiers with account display fields', async () => { + const h = harness({ + requiresOpenaiAuth: true, + account: { + type: 'chatgpt', + email: 'example@example.com', + planType: 'pro', + accessToken: 'PRIVATE_TOKEN', + }, + workspaceRouting: { chatgptAccountId: 'PRIVATE_WORKSPACE' }, + }) + const s = await h.provider.poll!() + expect(s.account.data).toEqual({ type: 'chatgpt', planType: 'pro' }) + expect(JSON.stringify(s)).not.toMatch( + /PRIVATE_TOKEN|PRIVATE_WORKSPACE|accessToken|chatgptAccountId|example@example.com/, + ) + }) + it('keeps last known account explicitly stale on a failed account read', async () => { + const h = harness(), + first = await h.provider.poll!() + h.tick() + h.values['account/read'] = new CodexError('offline') + expect((await h.provider.poll!()).account).toEqual({ + ...first.account, + freshness: 'stale', + error: 'offline', + }) + }) + it.each(['account/read', 'account/usage/read'])( + 'clears the account after unauthorized %s', + async (method) => { + const h = harness() + await h.provider.poll!() + h.values[method] = new CodexError('unauthorized') + expect((await h.provider.poll!()).account).toMatchObject({ + data: null, + freshness: 'unavailable', + error: 'unauthorized', + }) + }, + ) + it('replaces the identity and clears old metrics when switching accounts', async () => { + const h = harness() + await h.provider.poll!() + h.values['account/read'] = { + requiresOpenaiAuth: true, + account: { type: 'chatgpt', email: 'other@example.com', planType: 'pro' }, + } + h.values['account/usage/read'] = new CodexError('offline') + const s = await h.provider.poll!() + expect(s.account.data).toEqual({ type: 'chatgpt', planType: 'pro' }) + expect(s.usage.data).toBeNull() + }) + it('does not claim email identity for API key authentication', async () => { + const h = harness({ + requiresOpenaiAuth: true, + account: { type: 'apiKey', email: 'ignore@example.com', planType: 'ignore' }, + }) + expect((await h.provider.poll!()).account).toMatchObject({ + data: { type: 'apiKey', planType: null }, + freshness: 'fresh', + }) + }) + it('clears malformed account data rather than retaining a connected identity', async () => { + const h = harness() + await h.provider.poll!() + h.values['account/read'] = { + requiresOpenaiAuth: true, + account: { type: 'chatgpt', email: 'x'.repeat(321) }, + } + expect((await h.provider.poll!()).account).toMatchObject({ data: null, error: 'invalid' }) + }) +}) diff --git a/server/test/config-migration.test.ts b/server/test/config-migration.test.ts index c8aa32bb..933db54c 100644 --- a/server/test/config-migration.test.ts +++ b/server/test/config-migration.test.ts @@ -32,6 +32,19 @@ describe('migrateConfig', () => { const c2 = migrateConfig(v1) expect(migrateConfig(c2)).toEqual(c2) }) + it('keeps older dashboards opted out of Codex account and history reads', () => { + const old = migrateConfig(v1) + delete (old.privacy as Partial).codexAccount + delete (old.privacy as Partial).codexHistorySources + expect(migrateConfig(old).privacy).toMatchObject({ + codexAccount: false, + codexHistorySources: [], + }) + expect(migrateConfig(v1).privacy).toMatchObject({ + codexAccount: false, + codexHistorySources: [], + }) + }) it('rejects an unknown version with a clear message', () => { // Translated now, so match either language rather than the French wording. expect(() => migrateConfig({ ...v1, version: 7 })).toThrow(/(version de config inconnue|unknown config version).*7/) diff --git a/ui/src/admin/ScreenInspector.vue b/ui/src/admin/ScreenInspector.vue index 89b34efa..fe19d83f 100644 --- a/ui/src/admin/ScreenInspector.vue +++ b/ui/src/admin/ScreenInspector.vue @@ -62,6 +62,17 @@ const privacy = computed(() => s.state.config!.privacy) function setClaudeAccountUsage(on: boolean): void { s.apply((c) => { c.privacy.claudeAccountUsage = on }) } +const CODEX_SOURCES = ['appServer', 'vscode', 'cli', 'exec', 'subAgent', 'unknown'] as const +const CODEX_SUBAGENT_SOURCES = ['subAgentReview', 'subAgentCompact', 'subAgentThreadSpawn', 'subAgentOther'] as const +type CodexSource = typeof CODEX_SOURCES[number] | typeof CODEX_SUBAGENT_SOURCES[number] +function setCodexAccount(on: boolean): void { + s.apply((c) => { c.privacy.codexAccount = on }) +} +function setCodexSource(source: CodexSource, on: boolean): void { + s.apply((c) => { c.privacy.codexHistorySources = on + ? [...new Set([...c.privacy.codexHistorySources, source])] + : c.privacy.codexHistorySources.filter(value => value !== source) }) +} /** * Off, the server leaves the account e-mail out of every snapshot it publishes; this box does * not hide it in a widget, it decides whether any widget is sent it at all. @@ -274,12 +285,36 @@ function setBackground(patch: Partial): void { :label="t('admin.inspector.screen.accountEmail')" @update:model-value="setShowAccountEmail($event)" />

{{ t('admin.inspector.screen.accountEmail.hint') }}

+ +

{{ t('admin.inspector.screen.codexAccount.hint') }}

+

{{ t('admin.inspector.screen.codexSources') }}

+

{{ t('admin.inspector.screen.codexSources.hint') }}

+
+ +
+
+ {{ t('admin.inspector.screen.codexSources.subagents') }} +
+ +
+