diff --git a/cli/README.md b/cli/README.md index 882976fd..d6ec29a5 100644 --- a/cli/README.md +++ b/cli/README.md @@ -29,6 +29,8 @@ Choose a supported coding agent from your terminal and control its sessions remo - `hapi claude` - Start a Claude Code session (passes through Claude CLI flags). - `hapi codex` - Start Codex mode. See `src/codex/runCodex.ts`. - `hapi codex resume ` - Resume a Codex conversation by its native thread ID. For a HAPI session ID, use `hapi resume `. +- `hapi attach --socket /absolute/private/engine.sock` - Experimental macOS foreground bridge to an already-loaded external Codex thread. Independent of owned `hapi codex`; no server launch, native config injection or automatic Runner discovery. `--list` lists eligible loaded threads; `--new-view` explicitly replaces a history-rewrite-frozen projection. +- `hapi detach ` - Disconnect an attached worker only; leave the external server, turn and native queue intact. See [external bridge limits and acceptance status](../docs/guide/codex-shared-sessions.md#experimental-external-desktop-bridge-macos). - `hapi cursor` - Start Cursor Agent mode. See `src/cursor/runCursor.ts`. Supports `hapi cursor resume `, `hapi cursor --continue`, `--mode plan|ask`, `--yolo`, `--model`. Local and remote modes supported; new remote sessions use `agent acp`. Pre-ACP sessions retain the legacy `agent -p` stream-json resume path. diff --git a/cli/src/agent/sessionFactory.test.ts b/cli/src/agent/sessionFactory.test.ts index c5484a3d..5a2076a0 100644 --- a/cli/src/agent/sessionFactory.test.ts +++ b/cli/src/agent/sessionFactory.test.ts @@ -110,6 +110,18 @@ describe('bootstrapExistingSession', () => { delete process.env[HAPI_SESSION_ID_ENV] }) + it.each([false, true])('refuses unsafe attached session bootstrap before creating a socket (diverged=%s)', async diverged => { + const session = createSession(); + const codexRuntime = { kind: 'attached', bindingId: '11111111-1111-4111-8111-111111111111', state: 'detached' } as const; + session.metadata = { ...session.metadata!, codexRuntime, conversationHistoryDiverged: diverged }; + getSessionMock.mockResolvedValue(session); + getOrCreateMachineMock.mockResolvedValue({ id: 'machine-1' }); + readSettingsMock.mockResolvedValue({ machineId: 'machine-1' }); + await expect(bootstrapExistingSession({ sessionId: session.id, flavor: 'codex', workingDirectory: '/tmp/project', + ...(diverged ? { metadataOverrides: { codexRuntime } } : {}) })).rejects.toThrow(diverged ? 'history changed' : 'hapi attach'); + expect(sessionSyncClientMock).not.toHaveBeenCalled(); + }); + it('refuses local Codex resume of a CLI-archived source with a pending fork before creating a socket or changing metadata', async () => { const session = createSession() session.metadata = { ...session.metadata!, lifecycleState: 'archived', archivedBy: 'cli', diff --git a/cli/src/agent/sessionFactory.ts b/cli/src/agent/sessionFactory.ts index 99cedae9..984e8117 100644 --- a/cli/src/agent/sessionFactory.ts +++ b/cli/src/agent/sessionFactory.ts @@ -162,6 +162,7 @@ function pickExistingSessionMetadata(metadata: Metadata | null | undefined): Par if (metadata.claudeSessionId !== undefined) preserved.claudeSessionId = metadata.claudeSessionId if (metadata.claudeSessionIdHistory !== undefined) preserved.claudeSessionIdHistory = metadata.claudeSessionIdHistory if (metadata.codexSessionId !== undefined) preserved.codexSessionId = metadata.codexSessionId + if (metadata.codexRuntime !== undefined) preserved.codexRuntime = metadata.codexRuntime if (metadata.codexSourceSessionId !== undefined) preserved.codexSourceSessionId = metadata.codexSourceSessionId if (metadata.geminiSessionId !== undefined) preserved.geminiSessionId = metadata.geminiSessionId if (metadata.opencodeSessionId !== undefined) preserved.opencodeSessionId = metadata.opencodeSessionId @@ -405,6 +406,14 @@ export async function bootstrapExistingSession(options: { }) const sessionInfo = await api.getSession(options.sessionId) + if (sessionInfo.metadata?.codexRuntime?.kind === 'attached') { + if (options.metadataOverrides?.codexRuntime?.kind !== 'attached') { + throw new Error('Externally attached Codex sessions require hapi attach, not an owned cold resume') + } + if (sessionInfo.metadata.conversationHistoryDiverged) { + throw new Error('Native history changed; use hapi attach --new-view to create a fresh projection') + } + } // Shared Codex cold-resume calls bootstrap while holding native ownership. // The source reservation outlives the native fork through child startup. if (options.flavor === 'codex' && sessionInfo.metadata?.codexArchivedFork) { diff --git a/cli/src/codex/shared/attached.frontend.integration.test.ts b/cli/src/codex/shared/attached.frontend.integration.test.ts new file mode 100644 index 00000000..36e79d01 --- /dev/null +++ b/cli/src/codex/shared/attached.frontend.integration.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { createServer } from 'node:http'; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { CodexAppServerClient } from '../codexAppServerClient'; +import { initializeSharedClient } from './launch'; +import { record } from './gateway'; + +// Real CLI worker -> native externally owned server + real isolated Hub. +// No desktop UI automation, account tokens, or real model requests. +describe.skipIf(process.env.HAPI_RUN_SHARED_CODEX_TESTS !== '1' || process.platform !== 'darwin')('external attachment full stack', () => { + it('exchanges mobile/native input, detaches without engine shutdown and reattaches the same Hub row', async () => { + const home = await mkdtemp('/tmp/hapi-attached-e2e-'); await chmod(home, 0o700); + const cwd = join(home, 'work'); const ch = join(home, 'codex'); const hh = join(home, 'hapi'); + await Promise.all([cwd, ch, hh].map(path => mkdir(path))); + const endpoint = `unix://${join(home, 'engine.sock')}`; + const requests: Record[] = []; + const model = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on('data', chunk => { chunks.push(Buffer.from(chunk)); }); + request.on('end', () => { + if (!request.url?.endsWith('/responses')) { response.writeHead(404).end(); return; } + requests.push(record(JSON.parse(Buffer.concat(chunks).toString()))); + const id = randomUUID(); + const item = { type: 'message', role: 'assistant', id: randomUUID(), content: [{ type: 'output_text', text: `MOCK_RESPONSE_${requests.length}` }] }; + const events = [{ type: 'response.created', response: { id } }, { type: 'response.output_item.done', item }, + { type: 'response.completed', response: { id, usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } }]; + response.writeHead(200, { 'Content-Type': 'text/event-stream' }); + response.end(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join('')); + }); + }); + await new Promise(resolve => model.listen(0, '127.0.0.1', resolve)); + const port = (model.address() as { port: number }).port; + await writeFile(join(ch, 'config.toml'), `model = "mock-model" +model_provider = "isolated" +approval_policy = "on-request" +sandbox_mode = "read-only" +check_for_update_on_startup = false +[model_providers.isolated] +name = "Isolated mock" +base_url = "http://127.0.0.1:${port}/v1" +wire_api = "responses" +requires_openai_auth = false +supports_websockets = false +request_max_retries = 0 +stream_max_retries = 0 +[analytics] +enabled = false +[feedback] +enabled = false +[projects."${cwd}"] +trust_level = "trusted" +`); + const env: NodeJS.ProcessEnv = { PATH: process.env.PATH, HOME: home, CODEX_HOME: ch, HAPI_HOME: hh, + HAPI_API_URL: process.env.HAPI_API_URL, CLI_API_TOKEN: process.env.CLI_API_TOKEN, HAPI_INVOKED_CWD: cwd, + LANG: 'en_US.UTF-8', NO_PROXY: 'localhost,127.0.0.1', no_proxy: 'localhost,127.0.0.1', DEBUG: '1' }; + let logs = ''; + const children: ChildProcess[] = []; + const track = (child: ChildProcess) => { + children.push(child); child.stdout?.on('data', data => { logs += data.toString(); }); child.stderr?.on('data', data => { logs += data.toString(); }); + return child; + }; + const engine = track(spawn(process.env.HAPI_CODEX_APP_SERVER_BIN ?? 'codex', ['app-server', '--listen', endpoint], { cwd, env })); + const cli = (args: string[]) => track(spawn(process.env.HAPI_BUN_EXEC!, ['--cwd', resolve('.'), resolve('src/index.ts'), ...args], { cwd, env })); + const client = new CodexAppServerClient({ endpoint }); client.setServerRequestHandler(() => {}); + const eventually = async (read: () => Promise, accept: (value: T) => boolean): Promise => { + const deadline = Date.now() + 15_000; + while (Date.now() < deadline) { + const value = await read(); if (accept(value)) return value; + await new Promise(resolve => setTimeout(resolve, 60)); + } + throw new Error(`External full-stack timeout\n${logs}`); + }; + const base = env.HAPI_API_URL!; + const auth = await fetch(`${base}/api/auth`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ accessToken: env.CLI_API_TOKEN }) }); + const jwt = String(record(await auth.json()).token); + const api = async (path: string, body?: unknown): Promise & { status: number }> => { + const response = await fetch(`${base}/api${path}`, { method: body === undefined ? 'GET' : 'POST', + headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, ...record(await response.json()) }; + }; + try { + await eventually(() => readFile(join(ch, 'config.toml'), 'utf8').then(async () => readdir(home)), names => names.includes('engine.sock')); + await initializeSharedClient(client); + const started = record(await client.request('thread/start', { cwd, developerInstructions: 'EXTERNAL_OWNER_SENTINEL' })); + const threadId = String(record(started.thread).id); + await client.request('thread/metadata/update', { threadId, gitInfo: { sha: null } }); + const worker = cli(['attach', threadId, '--socket', endpoint]); + const runtime = await eventually(async () => { + for (const name of await readdir(join(hh, 'codex-runtimes')).catch(() => [] as string[])) { + if (!name.endsWith('.json')) continue; + const value = record(JSON.parse(await readFile(join(hh, 'codex-runtimes', name), 'utf8'))); + if (Object.values(record(value.sessions)).some(binding => record(binding).active)) return value; + } + return {}; + }, value => Boolean(value.id)); + expect(runtime.kind).toBe('attached'); expect(runtime.serverPid).toBeUndefined(); + const sessionId = Object.keys(record(runtime.sessions))[0]; const detail = () => api(`/sessions/${sessionId}`); + await eventually(detail, value => record(value.session).active === true); + expect(record(record((await detail()).session).metadata).codexRuntime).toMatchObject({ kind: 'attached' }); + await api(`/sessions/${sessionId}/messages`, { text: 'FROM_MOBILE', localId: randomUUID() }); + await eventually(() => api(`/sessions/${sessionId}/messages`), value => JSON.stringify(value).includes('MOCK_RESPONSE_1')); + expect(JSON.stringify(requests[0])).toContain('FROM_MOBILE'); + expect(JSON.stringify(requests[0])).toContain('EXTERNAL_OWNER_SENTINEL'); + expect(JSON.stringify(requests[0])).not.toContain('mcp__hapi'); + await client.request('turn/start', { threadId, input: [{ type: 'text', text: 'FROM_DESKTOP_PROTOCOL' }] }); + await eventually(() => api(`/sessions/${sessionId}/messages`), value => JSON.stringify(value).includes('MOCK_RESPONSE_2')); + const detach = cli(['detach', sessionId]); + await eventually(async () => detach.exitCode, code => code !== null); expect(detach.exitCode).toBe(0); + await eventually(async () => worker.exitCode, code => code !== null); expect(worker.exitCode).toBe(0); + await eventually(detail, value => record(value.session).active === false); + expect(engine.exitCode).toBeNull(); + expect(record(await client.request('thread/loaded/list', {})).data).toContain(threadId); + const refused = await api(`/sessions/${sessionId}/resume`, {}); + expect(refused.status).toBeGreaterThanOrEqual(400); + const second = cli(['attach', threadId, '--socket', endpoint]); + await eventually(detail, value => record(value.session).active === true); + await eventually(async () => logs, value => value.split('Attached HAPI session:').length === 3); + second.kill('SIGTERM'); + await eventually(async () => second.exitCode, code => code !== null); expect(second.exitCode).toBe(0); + expect(engine.exitCode).toBeNull(); + expect(requests).toHaveLength(2); + } finally { + await client.disconnect(); + // Fixture cleanup only: production attach never owns these PIDs. + for (const child of children.reverse()) { + if (child.exitCode !== null || child.signalCode !== null) continue; + child.kill('SIGTERM'); + await Promise.race([new Promise(resolve => child.once('exit', () => resolve())), new Promise(resolve => setTimeout(resolve, 2_000))]); + if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); + } + model.closeAllConnections(); await new Promise(resolve => model.close(() => resolve())); + await rm(home, { recursive: true, force: true, maxRetries: 3 }); + } + }, 90_000); +}); diff --git a/cli/src/codex/shared/attached.test.ts b/cli/src/codex/shared/attached.test.ts new file mode 100644 index 00000000..5a215e45 --- /dev/null +++ b/cli/src/codex/shared/attached.test.ts @@ -0,0 +1,47 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createServer } from 'node:net'; +import { chmod, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { AttachedOptionsSchema, assertAttachableRoot, requireLoadedThread, validateAttachedEndpoint } from './attached'; +import type { CodexAppServerClient } from '../codexAppServerClient'; + +const cleanup: Array<() => Promise> = []; +afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); +describe('explicit external attachment preflight', () => { + it.each(['ws://localhost:1', 'unix://relative.sock', '/tmp/socket', 'unix:///tmp/a\n'])('rejects non-local or malformed endpoint %s', async endpoint => { + await expect(validateAttachedEndpoint(endpoint)).rejects.toThrow('Attach requires'); + }); + it.skipIf(process.platform === 'win32')('accepts a private same-user socket and official-style symlink, refuses unsafe modes and files', async () => { + const home = await mkdtemp(join(tmpdir(), 'hapi-attach-preflight-')); + cleanup.push(() => rm(home, { recursive: true, force: true })); + await chmod(home, 0o700); + const path = join(home, 'engine.sock'); const server = createServer(); + await new Promise((resolve, reject) => { server.once('error', reject); server.listen(path, resolve); }); + cleanup.push(() => new Promise(resolve => server.close(() => resolve()))); + await chmod(path, 0o600); + const link = join(home, 'daemon.sock'); await symlink(path, link); + expect(await validateAttachedEndpoint(`unix://${link}`)).toBe(`unix://${await realpath(path)}`); + await chmod(path, 0o660); + await expect(validateAttachedEndpoint(`unix://${path}`)).rejects.toThrow('same-user'); + await chmod(path, 0o600); await chmod(home, 0o777); + await expect(validateAttachedEndpoint(`unix://${path}`)).rejects.toThrow('same-user'); + await chmod(home, 0o700); const regular = join(home, 'file'); await writeFile(regular, ''); + await expect(validateAttachedEndpoint(`unix://${regular}`)).rejects.toThrow('same-user'); + }); + it('paginates loaded threads without ever sending a resume or start', async () => { + const request = vi.fn().mockResolvedValueOnce({ data: ['other'], nextCursor: 'next' }).mockResolvedValueOnce({ data: ['root'] }); + await requireLoadedThread({ request } as unknown as CodexAppServerClient, 'root'); + expect(request.mock.calls).toEqual([['thread/loaded/list', { cursor: undefined }], ['thread/loaded/list', { cursor: 'next' }]]); + request.mockResolvedValue({ data: [] }); + await expect(requireLoadedThread({ request } as unknown as CodexAppServerClient, 'absent')).rejects.toThrow('not loaded'); + }); + it('only accepts persistent roots and strict non-injecting options', () => { + const thread = { id: 'root', cwd: '/tmp/work', source: 'vscode' }; + expect(assertAttachableRoot(thread, 'root')).toBe('/tmp/work'); + for (const change of [{ id: 'other' }, { cwd: 'relative' }, { parentThreadId: 'parent' }, { ephemeral: true }, { source: { subAgent: {} } }]) { + expect(() => assertAttachableRoot({ ...thread, ...change }, 'root')).toThrow(); + } + expect(() => AttachedOptionsSchema.parse({ endpoint: 'unix:///tmp/a', threadId: 'root', permissionMode: 'yolo' })).toThrow(); + }); +}); diff --git a/cli/src/codex/shared/attached.ts b/cli/src/codex/shared/attached.ts new file mode 100644 index 00000000..3956f03b --- /dev/null +++ b/cli/src/codex/shared/attached.ts @@ -0,0 +1,218 @@ +import { lstat, readlink, realpath, stat } from 'node:fs/promises'; +import { basename, dirname, isAbsolute, join, resolve } from 'node:path'; +import { createHash, randomUUID } from 'node:crypto'; +import { z } from 'zod'; +import { ApiClient } from '@/api/api'; +import type { ApiSessionClient } from '@/api/apiSession'; +import { bootstrapExistingSession, bootstrapSession } from '@/agent/sessionFactory'; +import { configuration } from '@/configuration'; +import { getProcessStartMarker } from '@/utils/process'; +import { notifyRunnerSessionStarted } from '@/runner/controlClient'; +import { CodexAppServerClient } from '../codexAppServerClient'; +import { record, string } from './gateway'; +import { checkSharedCapabilities } from './launch'; +import { SharedCodexRoot } from './root'; +import { findAttachedBinding, runtimeAuthHash, runtimeDirectory, saveRuntime, withThreadOwnership, type CodexRuntimeRecord } from './registry'; +import { startAttachedControl } from './attachedControl'; +import { AttachedHistoryChangedError, validateAttachedHistory } from './attachedHistory'; + +export const AttachedOptionsSchema = z.object({ + endpoint: z.string().min(1), threadId: z.string().min(1), newView: z.boolean().optional(), + startedBy: z.enum(['runner', 'terminal']).optional() +}).strict(); +export type AttachedOptions = z.infer; +export type AttachedReady = { sessionId: string; runtime: CodexRuntimeRecord }; +type StopReason = 'detached' | 'unavailable' | 'history-changed' | 'archived'; + +/** Explicitly trusted, same-user local UDS only. Official daemon symlinks are supported. */ +export async function validateAttachedEndpoint(endpoint: string): Promise { + if (!endpoint.startsWith('unix://') || !isAbsolute(endpoint.slice(7)) || /[\0\r\n]/.test(endpoint)) { + throw new Error('Attach requires unix:///absolute/socket/path; TCP and remote endpoints are not supported'); + } + // Bun/macOS realpath(socket) can return EOPNOTSUPP. Canonicalize the + // directory and explicitly follow leaf symlinks instead; never ignore + // errors or weaken the final socket/owner/mode checks. + let path = endpoint.slice(7); + for (let hops = 0; ; hops++) { + if (hops >= 40) throw new Error('Too many attached socket symlinks'); + path = join(await realpath(dirname(path)), basename(path)); + if (!(await lstat(path)).isSymbolicLink()) break; + path = resolve(dirname(path), await readlink(path)); + } + const socket = await stat(path); const parent = await stat(dirname(path)); + const uid = process.getuid?.(); + if (uid === undefined || !socket.isSocket() || socket.uid !== uid || (socket.mode & 0o077) !== 0 || parent.uid !== uid || (parent.mode & 0o022) !== 0) { + throw new Error('Attach requires a same-user Unix socket in a non-writable-by-others directory'); + } + return `unix://${path}`; +} + +export async function requireLoadedThread(client: CodexAppServerClient, threadId: string): Promise { + let cursor: string | undefined; + do { + const page = z.object({ data: z.array(z.string()), nextCursor: z.string().nullish() }).parse(await client.request('thread/loaded/list', { cursor })); + if (page.data.includes(threadId)) return; + cursor = page.nextCursor ?? undefined; + } while (cursor); + throw new Error('Thread is not loaded in the external engine. Open it in the owning desktop first; HAPI will not cold-resume it.'); +} + +export function assertAttachableRoot(thread: Record, threadId: string): string { + const source = thread.source; + if (thread.id !== threadId || thread.parentThreadId || thread.ephemeral === true + || typeof source === 'object' && source !== null || typeof source === 'string' && /subagent/i.test(source)) { + throw new Error('Only persistent user-root threads can be explicitly attached'); + } + const cwd = string(thread.cwd); + if (!cwd || !isAbsolute(cwd)) throw new Error('Native thread has no absolute working directory'); + return cwd; +} + +/** One independent bridge worker. It never starts, configures, archives or kills the external engine. */ +export async function runAttachedRuntime(raw: AttachedOptions, onReady?: (ready: AttachedReady) => void, signal?: AbortSignal): Promise { + const options = AttachedOptionsSchema.parse(raw); + signal?.throwIfAborted(); + const endpoint = await validateAttachedEndpoint(options.endpoint); + const observer = new CodexAppServerClient({ endpoint }); + observer.setServerRequestHandler(() => {}); + let root: SharedCodexRoot | undefined; + let session: ApiSessionClient | undefined; + let control: Awaited> | undefined; + let runtime: CodexRuntimeRecord | undefined; + const lifecycle: { reason: StopReason } = { reason: 'detached' }; + let stopping = false; + let finish!: () => void; + const stopped = new Promise(resolve => { finish = resolve; }); + const stop = (next: StopReason = 'detached') => { + if (next === 'history-changed' || !stopping) lifecycle.reason = next; + stopping = true; root?.stopAccepting(); finish(); + }; + const onSignal = () => stop(); + const assertRunning = () => { signal?.throwIfAborted(); if (stopping) throw new Error('Attached worker is stopping'); }; + signal?.addEventListener('abort', onSignal, { once: true }); + for (const event of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.on(event, onSignal); + observer.setTransportAbandonedHandler(() => stop('unavailable')); + try { + await observer.connect(); + const initialized = await observer.initialize({ clientInfo: { name: 'hapi_attached_observer', version: '1' }, capabilities: { experimentalApi: true } }); + const homePath = string(record(initialized).codexHome); + if (!homePath || !isAbsolute(homePath)) throw new Error('External engine did not report CODEX_HOME'); + const home = await realpath(homePath); + const homeStat = await stat(home); + if (!homeStat.isDirectory() || homeStat.uid !== process.getuid?.() || (homeStat.mode & 0o022) !== 0) { + throw new Error('External CODEX_HOME must be owned by this user and not writable by others'); + } + await checkSharedCapabilities(observer); + await requireLoadedThread(observer, options.threadId); + const thread = record(record(await observer.request('thread/read', { threadId: options.threadId, includeTurns: false })).thread); + const cwd = await realpath(assertAttachableRoot(thread, options.threadId)); + if (!(await stat(cwd)).isDirectory()) throw new Error('Native working directory is not a directory'); + const id = randomUUID(); const marker = getProcessStartMarker(process.pid); + if (!marker) throw new Error('Cannot verify attached worker process generation'); + runtime = { id, kind: 'attached', pid: process.pid, marker, endpoint: '', nativeEndpoint: endpoint, attachedAt: Date.now(), + command: '', args: [], codexHome: home, hub: configuration.apiUrl, authHash: runtimeAuthHash(), sessions: {} }; + await withThreadOwnership(home, options.threadId, id, async () => { + assertRunning(); + let existing = await findAttachedBinding(home, options.threadId); + let bindingId: string = randomUUID(); + if (existing) { + const session = await (await ApiClient.create()).getSession(existing); + if (session.metadata?.codexRuntime?.kind !== 'attached' || session.metadata.codexSessionId !== options.threadId || session.metadata.path !== cwd) { + throw new Error('Attached binding identity mismatch'); + } + if (options.newView) { + if (!session.metadata.conversationHistoryDiverged) throw new Error('--new-view is only for a view frozen after a native history rewrite'); + runtime!.supersedes = existing; + existing = undefined; + } else { + if (session.metadata.conversationHistoryDiverged) throw new AttachedHistoryChangedError(); + bindingId = session.metadata.codexRuntime.bindingId; + } + } else if (options.newView) throw new Error('No previous attached view to replace'); + const bootstrapOptions = { flavor: 'codex', startedBy: options.startedBy ?? 'terminal', workingDirectory: cwd, + exportSessionEnv: false, reportStarted: false, metadataOverrides: { + codexRuntime: { kind: 'attached', bindingId, state: 'attached' }, + ...(typeof thread.name === 'string' ? { name: thread.name } : {}), + capabilities: { terminal: false, concurrentClients: true, conversationHistory: { + forkCurrent: false, forkAtMessage: false, forkLatestCompleted: false, rewindToMessage: false + } } + } + } as const; + const bootstrap = existing + ? await bootstrapExistingSession({ ...bootstrapOptions, sessionId: existing }) + : await bootstrapSession({ ...bootstrapOptions, agentState: { controlledByUser: false } }); + session = bootstrap.session; + const verifyHubBinding = async () => { + if (!await bootstrap.session.flushMetadata()) throw new Error('Cannot persist attached runtime metadata'); + const persisted = await (await ApiClient.create()).getSession(bootstrap.session.sessionId); + if (persisted.metadata?.codexRuntime?.kind !== 'attached' || persisted.metadata.codexRuntime.bindingId !== bindingId) { + throw new Error('Hub does not preserve attached runtime identity; update CLI, Hub and Runner together'); + } + }; + // Check before exposing the native ID: older hubs must not dedupe + // this row into an owned session or offer an owned resume fallback. + await verifyHubBinding(); assertRunning(); + root = new SharedCodexRoot(bootstrap, { + attached: true, directory: join(runtimeDirectory(), 'queues'), generation: id, endpoint, + settingsFor: () => undefined, + beforeSubscribe: threadId => requireLoadedThread(observer, threadId), + create: async () => { throw new Error('Create external threads in the owning desktop'); }, + end: async (_root, _archive, why) => { stop(why ?? 'detached'); }, + validateHistory: async (threadId, history) => { + const key = createHash('sha256').update(threadId).digest('hex'); + try { await validateAttachedHistory(join(runtimeDirectory(), 'attached-history', `${bootstrap.session.sessionId}-${key}.json`), history); } + catch (error) { + if (error instanceof AttachedHistoryChangedError) { + bootstrap.session.updateMetadata(metadata => ({ ...metadata, conversationHistoryDiverged: true })); + stop('history-changed'); + } else stop('unavailable'); + throw error; + } + } + }); + assertRunning(); + await root.prepare(); assertRunning(); + await root.bind(options.threadId, { thread }, true); assertRunning(); + control = await startAttachedControl(root.session.sessionId, () => stop()); + runtime!.endpoint = control.endpoint; runtime!.token = control.token; + runtime!.sessions[root.session.sessionId] = { threadId: options.threadId, namespace: bootstrap.sessionInfo.namespace, active: true }; + await saveRuntime(runtime!); assertRunning(); + await verifyHubBinding(); assertRunning(); + await root.activate(); assertRunning(); + if (!await root.session.flush()) throw new Error('Cannot confirm attached session readiness'); + assertRunning(); + await notifyRunnerSessionStarted(root.session.sessionId, { ...bootstrap.metadata, hostStartMarker: marker }); + assertRunning(); + onReady?.({ sessionId: root.session.sessionId, runtime: runtime! }); + }, undefined, 'attached'); + await stopped; + } catch (error) { + // Signals/detach are successful even while startup is still awaiting + // native or Hub I/O. Actual startup/validation failures remain errors. + if (!stopping) { lifecycle.reason = 'unavailable'; throw error; } + if (lifecycle.reason !== 'detached') throw error; + } finally { + stopping = true; root?.stopAccepting(); + signal?.removeEventListener('abort', onSignal); + for (const event of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.off(event, onSignal); + observer.setTransportAbandonedHandler(null); + await control?.close(); + await observer.disconnect(); + if (root) { + const state = lifecycle.reason === 'archived' ? 'detached' : lifecycle.reason; + root.session.updateMetadata(metadata => metadata.codexRuntime ? ({ ...metadata, + codexRuntime: { ...metadata.codexRuntime, state } }) : metadata); + // Deliberately NOT suspend(): queued input belongs to the native engine. + await root.close(lifecycle.reason === 'archived'); + } else if (session) { + session.updateMetadata(metadata => metadata.codexRuntime ? ({ ...metadata, + codexRuntime: { ...metadata.codexRuntime, state: 'unavailable' } }) : metadata); + session.sendSessionDeath(undefined, { preserveUploads: true }); + await session.flush(); session.close(); + } + if (runtime && Object.keys(runtime.sessions).length) { + for (const binding of Object.values(runtime.sessions)) binding.active = false; + await saveRuntime(runtime); + } + } +} diff --git a/cli/src/codex/shared/attachedControl.test.ts b/cli/src/codex/shared/attachedControl.test.ts new file mode 100644 index 00000000..61af16bb --- /dev/null +++ b/cli/src/codex/shared/attachedControl.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; +import { attachedRuntimeControl, startAttachedControl } from './attachedControl'; +import type { CodexRuntimeRecord } from './registry'; + +describe('attached worker control', () => { + it('authenticates local detach and refuses native proxying or remote control endpoints', async () => { + let detached = false; + const control = await startAttachedControl('sid', () => { detached = true; }); + try { + expect((await fetch(`${control.endpoint}/detach/sid`, { method: 'POST' })).status).toBe(401); + expect((await fetch(`${control.endpoint}/native-rpc`, { method: 'POST', headers: { Authorization: `Bearer ${control.token}` } })).status).toBe(404); + expect(detached).toBe(false); + const runtime: CodexRuntimeRecord = { id: 'test', pid: process.pid, marker: 'test', kind: 'attached', + command: '', args: [], codexHome: '/tmp/test', hub: 'test', authHash: 'test', endpoint: control.endpoint, + token: control.token, sessions: { sid: { threadId: 'native', namespace: 'test', active: true } } }; + await expect(attachedRuntimeControl(runtime, 'hapi/attach', 'sid')).rejects.toThrow('only support detach'); + await expect(attachedRuntimeControl({ ...runtime, endpoint: 'http://example.com' }, 'hapi/detach', 'sid')).rejects.toThrow('Invalid'); + expect(await attachedRuntimeControl(runtime, 'hapi/stopSession', 'sid')).toEqual({ success: true }); + expect(detached).toBe(true); + } finally { await control.close(); } + }); +}); diff --git a/cli/src/codex/shared/attachedControl.ts b/cli/src/codex/shared/attachedControl.ts new file mode 100644 index 00000000..dbb0a8c8 --- /dev/null +++ b/cli/src/codex/shared/attachedControl.ts @@ -0,0 +1,39 @@ +import { createServer } from 'node:http'; +import { randomBytes, timingSafeEqual } from 'node:crypto'; +import type { CodexRuntimeRecord } from './registry'; + +/** Local bridge control only; never proxies native RPCs or approvals. */ +export async function startAttachedControl(sessionId: string, detach: () => void): Promise<{ + endpoint: string; token: string; close(): Promise; +}> { + const token = randomBytes(32).toString('hex'); + const server = createServer((request, response) => { + const actual = Buffer.from(request.headers.authorization ?? ''); + const expected = Buffer.from(`Bearer ${token}`); + if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) { response.writeHead(401).end(); return; } + if (request.method !== 'POST' || request.url !== `/detach/${encodeURIComponent(sessionId)}`) { response.writeHead(404).end(); return; } + // Let the acknowledgement leave before closing this connection. + response.once('finish', detach); + response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: true })); + }); + await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); }); + const address = server.address(); + if (!address || typeof address === 'string') { server.close(); throw new Error('No attached control address'); } + return { endpoint: `http://127.0.0.1:${address.port}`, token, async close() { + server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())); + } }; +} + +export async function attachedRuntimeControl(runtime: CodexRuntimeRecord, method: string, sessionId: string): Promise { + if (!['hapi/stopSession', 'hapi/detach'].includes(method)) throw new Error('Attached workers only support detach, not native terminal attachment'); + if (runtime.kind !== 'attached' || !runtime.sessions[sessionId]?.active || !runtime.token) throw new Error('No active attached binding'); + const url = new URL(runtime.endpoint); + if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) { + throw new Error('Invalid attached control endpoint'); + } + const response = await fetch(`${url.origin}/detach/${encodeURIComponent(sessionId)}`, { + method: 'POST', headers: { Authorization: `Bearer ${runtime.token}` }, signal: AbortSignal.timeout(10_000) + }); + if (!response.ok) throw new Error(`Attached detach failed (${response.status})`); + return response.json(); +} diff --git a/cli/src/codex/shared/attachedHistory.test.ts b/cli/src/codex/shared/attachedHistory.test.ts new file mode 100644 index 00000000..35bb27d6 --- /dev/null +++ b/cli/src/codex/shared/attachedHistory.test.ts @@ -0,0 +1,48 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { AttachedHistoryChangedError, validateAttachedHistory } from './attachedHistory'; + +const homes: string[] = []; +afterEach(async () => { await Promise.all(homes.splice(0).map(home => rm(home, { recursive: true, force: true }))); }); +async function checkpoint() { + const home = await mkdtemp(join(tmpdir(), 'hapi-attached-history-')); homes.push(home); + return join(home, 'checkpoints', 'history.json'); +} +const turn = (id: string, text = id, status = 'completed') => ({ id, status, items: [{ id, type: 'agentMessage', text }] }); + +describe('attached completed-history checkpoint', () => { + it('accepts appends and changing in-progress items, sealing terminal content privately', async () => { + const file = await checkpoint(); + await validateAttachedHistory(file, { turns: [turn('a'), turn('b', 'partial', 'inProgress')] }); + await validateAttachedHistory(file, { turns: [turn('a'), turn('b', 'more', 'inProgress')] }); + expect(JSON.parse(await readFile(file, 'utf8'))).toEqual([expect.objectContaining({ id: 'a', hash: expect.any(String) }), { id: 'b', hash: null }]); + await validateAttachedHistory(file, { turns: [turn('a'), turn('b'), turn('c', 'stopped', 'interrupted')] }); + expect(JSON.parse(await readFile(file, 'utf8'))).toHaveLength(3); + expect((await stat(file)).mode & 0o777).toBe(0o600); + }); + it('does not forget a turn observed before detaching midway through generation', async () => { + const file = await checkpoint(); + await validateAttachedHistory(file, { turns: [turn('a'), turn('b', 'partial', 'inProgress')] }); + await expect(validateAttachedHistory(file, { turns: [turn('a')] })).rejects.toBeInstanceOf(AttachedHistoryChangedError); + }); + it.each(['truncate', 'rewrite', 'reorder', 'replace'] as const)('refuses %s, including mutations missed while detached', async kind => { + const file = await checkpoint(); + await validateAttachedHistory(file, { turns: [turn('a'), turn('b')] }); + const turns = { truncate: [turn('a')], rewrite: [turn('a', 'edited'), turn('b')], + reorder: [turn('b'), turn('a')], replace: [turn('a'), turn('new')] }[kind]; + await expect(validateAttachedHistory(file, { turns })).rejects.toBeInstanceOf(AttachedHistoryChangedError); + expect(JSON.parse(await readFile(file, 'utf8'))).toHaveLength(2); + }); + it('fails closed on malformed native history and corrupt checkpoint files', async () => { + const file = await checkpoint(); + await expect(validateAttachedHistory(file, {})).rejects.toThrow('verify'); + await expect(validateAttachedHistory(file, { turns: [{ id: 'a', status: 'completed' }] })).rejects.toThrow('verify'); + await expect(validateAttachedHistory(file, { turns: [turn('a'), turn('a')] })).rejects.toThrow('Ambiguous'); + await validateAttachedHistory(file, { turns: [turn('a')] }); + await writeFile(file, '{'); + await expect(validateAttachedHistory(file, { turns: [turn('a')] })).rejects.toThrow(); + expect(await readFile(file, 'utf8')).toBe('{'); + }); +}); diff --git a/cli/src/codex/shared/attachedHistory.ts b/cli/src/codex/shared/attachedHistory.ts new file mode 100644 index 00000000..f03009a0 --- /dev/null +++ b/cli/src/codex/shared/attachedHistory.ts @@ -0,0 +1,37 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; +import { z } from 'zod'; +import { record, string } from './gateway'; + +const SnapshotSchema = z.array(z.object({ id: z.string(), hash: z.string().nullable() })); +export class AttachedHistoryChangedError extends Error { + constructor() { super('Native history changed outside HAPI; use hapi attach --new-view for a fresh projection'); } +} + +/** Durable observed-prefix guard, including rewrites missed while detached. */ +export async function validateAttachedHistory(file: string, thread: unknown): Promise { + const turns = record(thread).turns; + if (!Array.isArray(turns)) throw new Error('Cannot verify attached native history'); + const current = turns.map(record).map(turn => { + const id = string(turn.id); + if (!id || !Array.isArray(turn.items) || !['completed', 'interrupted', 'failed', 'inProgress'].includes(String(turn.status))) { + throw new Error('Cannot verify native turn'); + } + // Active items may legitimately change. Fence their turn identity now, + // and seal their content once terminal, rather than forgetting them + // when the worker detaches midway through generation. + return { id, hash: turn.status === 'inProgress' ? null : createHash('sha256').update(JSON.stringify(turn.items)).digest('hex') }; + }); + if (new Set(current.map(turn => turn.id)).size !== current.length) throw new Error('Ambiguous native turn IDs'); + let previous: z.infer = []; + try { previous = SnapshotSchema.parse(JSON.parse(await readFile(file, 'utf8'))); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } + if (previous.some((turn, index) => current[index]?.id !== turn.id || turn.hash !== null && current[index]?.hash !== turn.hash)) { + throw new AttachedHistoryChangedError(); + } + await mkdir(dirname(file), { recursive: true, mode: 0o700 }); + const temporary = `${file}.${randomUUID()}.tmp`; + await writeFile(temporary, JSON.stringify(current), { mode: 0o600 }); + await rename(temporary, file); +} diff --git a/cli/src/codex/shared/external.integration.test.ts b/cli/src/codex/shared/external.integration.test.ts new file mode 100644 index 00000000..e9977558 --- /dev/null +++ b/cli/src/codex/shared/external.integration.test.ts @@ -0,0 +1,450 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { createServer, type Server } from 'node:http'; +import { access, chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { createHash, randomUUID } from 'node:crypto'; +import { EventEmitter } from 'node:events'; +import type { Metadata, AgentState } from '@/api/types'; +import type { ApiSessionClient } from '@/api/apiSession'; +import type { SessionBootstrapResult } from '@/agent/sessionFactory'; +import { CodexAppServerClient } from '../codexAppServerClient'; +import { initializeSharedClient } from './launch'; +import { record } from './gateway'; + +type Packet = { method: string; params: unknown }; +type ServerRequest = Packet & { id: string | number }; +type Peer = { client: CodexAppServerClient; notifications: Packet[]; requests: ServerRequest[] }; + +const hub = vi.hoisted(() => ({ home: '', stripRuntime: false, sessions: new Map() })); +class BridgeSession extends EventEmitter { + readonly sessionId: string; metadata: Metadata; state: AgentState = {}; + messages: unknown[]; private seen: Set; dead = false; + user?: (message: { content: { text: string } }, id?: string) => void; + rpc = new Map Promise>(); + rpcHandlerManager = { registerHandler: (method: string, handler: (params: unknown) => Promise) => { this.rpc.set(method, handler); } }; + constructor(cwd: string, overrides: Partial, previous?: BridgeSession) { + super(); this.sessionId = previous?.sessionId ?? randomUUID(); this.messages = previous?.messages ?? []; this.seen = previous?.seen ?? new Set(); + this.metadata = { path: cwd, host: 'test', machineId: 'test', hostPid: process.pid, ...previous?.metadata, ...overrides }; + } + getMetadata() { return this.metadata; } + updateMetadata(fn: (value: Metadata) => Metadata) { this.metadata = fn(this.metadata); } + updateAgentState(fn: (value: AgentState) => AgentState) { this.state = fn(this.state); } + onUserMessage(fn: BridgeSession['user']) { this.user = fn; } + onCancelQueuedMessage() {} onRetryQueuedMessage() {} onReconnect() {} + sendAgentMessage(body: unknown, id?: string) { if (!id || !this.seen.has(id)) this.messages.push(body); if (id) this.seen.add(id); } + sendUserMessage(text: string) { this.messages.push({ user: text }); } + sendSessionEvent() {} emitMessagesConsumed() {} emitSteerIndeterminate() {} syncNativeQueuedMessage() {} + async setSteerDeliveryState() { return true; } + keepAlive() {} emitSessionReady() {} isPending() { return false; } + sendSessionDeath() { this.dead = true; } async flush() { return true; } async flushMetadata() { return true; } close() {} +} +vi.mock('@/configuration', () => ({ resolveHapiHomeDir: () => hub.home, + configuration: { get happyHomeDir() { return hub.home; }, apiUrl: 'http://mock-hub', cliApiToken: 'test' } })); +vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn((...args: unknown[]) => { if (process.env.HAPI_TEST_DEBUG) console.error(...args); }), warn: vi.fn(), info: vi.fn() } })); +vi.mock('@/runner/controlClient', () => ({ notifyRunnerSessionStarted: vi.fn(async () => ({})) })); +vi.mock('@/api/api', () => ({ ApiClient: { create: async () => ({ getSession: async (id: string) => { + const session = hub.sessions.get(id); if (!session) throw new Error('Session not found'); + return { id, namespace: 'test', metadata: hub.stripRuntime ? { ...session.metadata, codexRuntime: undefined } : session.metadata }; +} }) } })); +vi.mock('@/agent/sessionFactory', () => { + const bootstrap = async (options: { workingDirectory: string; metadataOverrides: Partial; sessionId?: string }): Promise => { + const session = new BridgeSession(options.workingDirectory, options.metadataOverrides, options.sessionId ? hub.sessions.get(options.sessionId) : undefined); + hub.sessions.set(session.sessionId, session); + return { session: session as unknown as ApiSessionClient, workingDirectory: options.workingDirectory, metadata: session.metadata, + sessionInfo: { id: session.sessionId, namespace: 'test' } } as SessionBootstrapResult; + }; + return { bootstrapSession: bootstrap, bootstrapExistingSession: bootstrap }; +}); + +// P0 for externally owned engines: neither client goes through HAPI's gateway. +// This verifies the native multi-client protocol, NOT the ChatGPT GUI. The real +// binary uses a blank home and a local Responses mock, never user credentials. +describe.skipIf(process.env.HAPI_RUN_SHARED_CODEX_TESTS !== '1' || process.platform === 'win32')('external Codex engine protocol', () => { + let home: string; + let cwd: string; + let endpoint: string; + let engine: ChildProcess | undefined; + let model: Server | undefined; + let engineLog: string; + let peers: Peer[]; + let modelRequests: Record[]; + let answer: (request: Record) => Promise>; + const releases: Array<() => void> = []; + const workers: Array<{ abort: AbortController; running: Promise }> = []; + + const message = (text: string) => ({ type: 'message', role: 'assistant', id: `msg_${randomUUID()}`, + content: [{ type: 'output_text', text }] }); + const gate = () => { + let release!: () => void; + const waiting = new Promise(resolve => { release = resolve; }); + releases.push(release); + return { waiting, release }; + }; + const connect = async (): Promise => { + const peer: Peer = { client: new CodexAppServerClient({ endpoint }), notifications: [], requests: [] }; + peers.push(peer); + peer.client.setNotificationHandler((method, params) => { peer.notifications.push({ method, params }); }); + // Observe without automatically replying: any error response would also + // compete with the actual desktop/mobile answer upstream. + peer.client.setServerRequestHandler(request => { peer.requests.push(request); }); + await initializeSharedClient(peer.client); + return peer; + }; + const start = async (peer: Peer) => { + const response = record(await peer.client.request('thread/start', { cwd, developerInstructions: 'EXTERNAL_OWNER_SENTINEL' })); + const threadId = String(record(response.thread).id); + // The owning frontend persists an empty thread's metadata before it can + // be resumed by another client. The bridge must not inject this itself. + await peer.client.request('thread/metadata/update', { threadId, gitInfo: { sha: null } }); + return threadId; + }; + const turn = async (peer: Peer, threadId: string, text: string) => { + const response = record(await peer.client.request('turn/start', { threadId, input: [{ type: 'text', text }] })); + return String(record(response.turn).id); + }; + const completed = async (peer: Peer, turnId: string) => { + await vi.waitFor(() => expect(peer.notifications).toContainEqual(expect.objectContaining({ method: 'turn/completed', + params: expect.objectContaining({ turn: expect.objectContaining({ id: turnId, status: 'completed' }) }) })), { timeout: 15_000 }); + }; + const attach = async (threadId: string, newView = false) => { + const { runAttachedRuntime } = await import('./attached'); + const abort = new AbortController(); + let ready!: (value: import('./attached').AttachedReady) => void; + const readiness = new Promise(resolve => { ready = resolve; }); + const running = runAttachedRuntime({ endpoint, threadId, newView }, ready, abort.signal); + void running.catch(() => {}); + workers.push({ abort, running }); + const result = await Promise.race([readiness, running.then(() => { throw new Error('Bridge stopped before readiness'); })]); + return { ...result, abort, running, web: hub.sessions.get(result.sessionId)! }; + }; + + beforeEach(async () => { + peers = []; modelRequests = []; engineLog = ''; + home = await mkdtemp('/tmp/hapi-external-'); + hub.home = join(home, 'hapi'); hub.sessions.clear(); hub.stripRuntime = false; + await chmod(home, 0o700); + cwd = join(home, 'work'); + const codexHome = join(home, 'codex'); + await Promise.all([mkdir(cwd), mkdir(codexHome)]); + endpoint = `unix://${join(home, 'engine.sock')}`; + answer = async () => message('EXTERNAL_MOCK_DONE'); + model = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on('data', chunk => { chunks.push(Buffer.from(chunk)); }); + request.on('end', () => { + void (async () => { + if (!request.url?.endsWith('/responses')) { response.writeHead(404).end(); return; } + const body = record(JSON.parse(Buffer.concat(chunks).toString())); + modelRequests.push(body); + const item = await answer(body); + const id = `resp_${randomUUID()}`; + const events = [{ type: 'response.created', response: { id } }, { type: 'response.output_item.done', item }, + { type: 'response.completed', response: { id, usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } }]; + response.writeHead(200, { 'Content-Type': 'text/event-stream' }); + response.end(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join('')); + })().catch(error => { response.writeHead(500).end(String(error)); }); + }); + }); + await new Promise(resolve => model!.listen(0, '127.0.0.1', resolve)); + const port = (model.address() as { port: number }).port; + await writeFile(join(codexHome, 'config.toml'), `model = "mock-model" +model_provider = "isolated_mock" +approval_policy = "on-request" +sandbox_mode = "read-only" +check_for_update_on_startup = false +[model_providers.isolated_mock] +name = "Isolated external protocol mock" +base_url = "http://127.0.0.1:${port}/v1" +wire_api = "responses" +requires_openai_auth = false +supports_websockets = false +request_max_retries = 0 +stream_max_retries = 0 +[analytics] +enabled = false +[feedback] +enabled = false +[projects."${cwd}"] +trust_level = "trusted" +`); + engine = spawn(process.env.HAPI_CODEX_APP_SERVER_BIN ?? 'codex', ['app-server', '--listen', endpoint], { + cwd, stdio: ['ignore', 'pipe', 'pipe'], + env: { PATH: process.env.PATH, HOME: home, CODEX_HOME: codexHome, LANG: 'en_US.UTF-8', RUST_LOG: 'warn', + NO_PROXY: '127.0.0.1,localhost', no_proxy: '127.0.0.1,localhost' } + }); + engine.stdout?.on('data', data => { engineLog += data.toString(); }); + engine.stderr?.on('data', data => { engineLog += data.toString(); }); + engine.on('error', error => { engineLog += String(error); }); + await vi.waitFor(async () => { + if (engine?.exitCode !== null || engine?.signalCode !== null) throw new Error(`External engine exited: ${engineLog}`); + await access(join(home, 'engine.sock')); + }, { timeout: 15_000 }); + }); + + afterEach(async () => { + for (const release of releases.splice(0)) release(); + for (const worker of workers) worker.abort.abort(); + await Promise.allSettled(workers.splice(0).map(worker => worker.running)); + await Promise.all(peers.map(peer => peer.client.disconnect())); + // Only the fixture owns this PID. An attached runtime must never do this. + if (engine?.pid && engine.exitCode === null && engine.signalCode === null) { + engine.kill('SIGTERM'); + try { await vi.waitFor(() => expect(engine!.exitCode !== null || engine!.signalCode !== null).toBe(true), { timeout: 5_000 }); } + catch { engine.kill('SIGKILL'); await new Promise(resolve => engine!.once('exit', () => resolve())); } + } + engine = undefined; + if (model) { model.closeAllConnections(); await new Promise(resolve => model!.close(() => resolve())); } + model = undefined; + await rm(home, { recursive: true, force: true, maxRetries: 3 }); + }); + + it('attaches to a loaded thread, detaches during generation, reconnects and exchanges native turns', async () => { + const desktop = await connect(); + const threadId = await start(desktop); + const bridge = await connect(); + const loaded = record(await bridge.client.request('thread/loaded/list', {})); + expect(loaded.data).toContain(threadId); + const settings = record(await bridge.client.request('thread/resume', { threadId })); + expect(settings.approvalPolicy).toBe('on-request'); + expect(settings.sandbox).toMatchObject({ type: 'readOnly' }); + expect(modelRequests).toHaveLength(0); + + const hold = gate(); + answer = async () => { await hold.waiting; return message('EXTERNAL_MOCK_DONE'); }; + const firstTurn = await turn(desktop, threadId, 'FROM_DESKTOP'); + await vi.waitFor(() => expect(modelRequests).toHaveLength(1), { timeout: 15_000 }); + await bridge.client.disconnect(); + expect(engine!.exitCode).toBeNull(); + hold.release(); + await completed(desktop, firstTurn); + + await initializeSharedClient(bridge.client); + const history = record(await bridge.client.request('thread/resume', { threadId })); + expect(record(history.thread).id).toBe(threadId); + const turns = record(history.thread).turns as Array<{ id: string }>; + expect(turns.map(value => value.id)).toEqual([firstTurn]); + expect(JSON.stringify(history)).toContain('EXTERNAL_MOCK_DONE'); + const secondTurn = await turn(bridge, threadId, 'FROM_BRIDGE'); + await Promise.all([completed(desktop, secondTurn), completed(bridge, secondTurn)]); + expect(modelRequests).toHaveLength(2); + expect(JSON.stringify(modelRequests)).toContain('EXTERNAL_OWNER_SENTINEL'); + }, 45_000); + + it('broadcasts pending questions and accepts one native answer without a gateway arbiter', async () => { + const desktop = await connect(); const bridge = await connect(); + const threadId = await start(desktop); + await bridge.client.request('thread/resume', { threadId }); + await desktop.client.request('thread/settings/update', { threadId, collaborationMode: { + mode: 'plan', settings: { model: 'mock-model', reasoning_effort: null, developer_instructions: null } + } }); + answer = async () => modelRequests.length === 1 ? { type: 'function_call', call_id: 'external_question', name: 'request_user_input', + arguments: JSON.stringify({ questions: [{ id: 'client', header: 'Client', question: 'Which client answers?', options: [ + { label: 'Desktop', description: 'Desktop wins' }, { label: 'Bridge', description: 'Bridge wins' } + ] }] }) } : message('QUESTION_DONE'); + const turnId = await turn(desktop, threadId, 'ASK_EXTERNAL_QUESTION'); + await vi.waitFor(() => { + expect(desktop.requests).toHaveLength(1); expect(bridge.requests).toHaveLength(1); + }, { timeout: 15_000 }); + const pending = desktop.requests[0]; + expect(pending.method).toBe('item/tool/requestUserInput'); + expect(bridge.requests[0].id).toBe(pending.id); + desktop.client.respond(pending.id, { answers: { client: { answers: ['Desktop'] } } }); + await vi.waitFor(() => expect(bridge.notifications).toContainEqual({ method: 'serverRequest/resolved', + params: { threadId, requestId: pending.id } })); + // A late losing answer must not re-execute the tool or start a new turn. + bridge.client.respond(pending.id, { answers: { client: { answers: ['Bridge'] } } }); + await Promise.all([completed(desktop, turnId), completed(bridge, turnId)]); + expect(modelRequests).toHaveLength(2); + const outputs = (modelRequests[1].input as Array>).filter(item => item.type === 'function_call_output'); + expect(JSON.stringify(outputs)).toContain('Desktop'); + expect(JSON.stringify(outputs)).not.toContain('Bridge'); + }, 45_000); + + it('replays a pending command approval on reconnect and accepts a bridge denial', async () => { + const desktop = await connect(); const bridge = await connect(); + const threadId = await start(desktop); + await bridge.client.request('thread/resume', { threadId }); + answer = async () => modelRequests.length === 1 ? { type: 'function_call', call_id: 'external_approval', name: 'exec_command', + arguments: JSON.stringify({ cmd: 'printf EXTERNAL_SHOULD_NOT_RUN', sandbox_permissions: 'require_escalated', + justification: 'Isolated approval replay test; decline this command' }) } : message('APPROVAL_DONE'); + const turnId = await turn(desktop, threadId, 'ASK_EXTERNAL_APPROVAL'); + await vi.waitFor(() => { + expect(desktop.requests).toHaveLength(1); expect(bridge.requests).toHaveLength(1); + }, { timeout: 15_000 }); + const pending = bridge.requests[0]; + expect(pending.method).toBe('item/commandExecution/requestApproval'); + await bridge.client.disconnect(); + bridge.requests = []; + await initializeSharedClient(bridge.client); + await bridge.client.request('thread/resume', { threadId }); + await vi.waitFor(() => expect(bridge.requests).toContainEqual(pending)); + bridge.client.respond(pending.id, { decision: 'decline' }); + await vi.waitFor(() => expect(desktop.notifications).toContainEqual({ method: 'serverRequest/resolved', + params: { threadId, requestId: pending.id } })); + await Promise.all([completed(desktop, turnId), completed(bridge, turnId)]); + expect(modelRequests).toHaveLength(2); + const outputs = (modelRequests[1].input as Array>).filter(item => item.type === 'function_call_output'); + expect(JSON.stringify(outputs)).toMatch(/reject|deni|declin/i); + }, 45_000); + + it('keeps native queued input when the submitting bridge disconnects', async () => { + const desktop = await connect(); const bridge = await connect(); + const threadId = await start(desktop); + await bridge.client.request('thread/resume', { threadId }); + const hold = gate(); + answer = async () => { await hold.waiting; return message('QUEUE_DONE'); }; + const firstTurn = await turn(desktop, threadId, 'DESKTOP_GENERATING'); + await vi.waitFor(() => expect(modelRequests).toHaveLength(1), { timeout: 15_000 }); + const clientUserMessageId = randomUUID(); + await bridge.client.request('thread/queue/add', { threadId, clientUserMessageId, input: [{ type: 'text', text: 'BRIDGE_QUEUED' }] }); + await bridge.client.disconnect(); + const queued = record(await desktop.client.request('thread/queue/list', { threadId })); + expect(queued.data).toContainEqual(expect.objectContaining({ clientUserMessageId })); + hold.release(); + await completed(desktop, firstTurn); + await vi.waitFor(() => expect(modelRequests).toHaveLength(2), { timeout: 15_000 }); + await vi.waitFor(() => expect(desktop.notifications.filter(packet => packet.method === 'turn/completed')).toHaveLength(2), { timeout: 15_000 }); + expect(JSON.stringify(modelRequests[1])).toContain('BRIDGE_QUEUED'); + expect(record(await desktop.client.request('thread/queue/list', { threadId })).data).toEqual([]); + await initializeSharedClient(bridge.client); + const history = record(await bridge.client.request('thread/resume', { threadId })); + expect(record(history.thread).turns).toHaveLength(2); + expect(engine!.exitCode).toBeNull(); + }, 45_000); + + it('observes desktop forks and archives made directly on the native endpoint', async () => { + const desktop = await connect(); const bridge = await connect(); + const threadId = await start(desktop); + await bridge.client.request('thread/resume', { threadId }); + const turnId = await turn(desktop, threadId, 'BEFORE_FORK'); + await completed(bridge, turnId); + const fork = record(await desktop.client.request('thread/fork', { threadId })); + const childId = String(record(fork.thread).id); + expect(childId).not.toBe(threadId); + await vi.waitFor(() => expect(bridge.notifications).toContainEqual(expect.objectContaining({ method: 'thread/started', + params: expect.objectContaining({ thread: expect.objectContaining({ id: childId }) }) }))); + await desktop.client.request('thread/archive', { threadId: childId }); + await vi.waitFor(() => expect(bridge.notifications).toContainEqual({ method: 'thread/archived', params: { threadId: childId } })); + const loaded = record(await bridge.client.request('thread/loaded/list', {})); + expect(loaded.data).toContain(threadId); + expect(loaded.data).not.toContain(childId); + expect(engine!.exitCode).toBeNull(); + }, 45_000); + + it('bridges an external engine without injection, preserves native work on detach and reuses the HAPI identity', async () => { + const desktop = await connect(); const threadId = await start(desktop); + const calls = vi.spyOn(CodexAppServerClient.prototype, 'request'); + try { + const bridge = await attach(threadId); + expect(bridge.runtime).toMatchObject({ kind: 'attached', command: '', args: [] }); + expect(bridge.runtime.serverPid).toBeUndefined(); + expect(bridge.web.metadata.capabilities).toMatchObject({ terminal: false, concurrentClients: true, + conversationHistory: { forkCurrent: false, forkAtMessage: false, forkLatestCompleted: false, rewindToMessage: false } }); + expect(calls.mock.calls.some(([method]) => ['thread/start', 'thread/metadata/update'].includes(method))).toBe(false); + // Invalid-ID capability probes do not carry settings, MCP or instructions. + expect(calls.mock.calls.filter(([method]) => method === 'thread/settings/update') + .every(([, params]) => record(params).threadId === '__hapi_capability_probe__')).toBe(true); + expect(calls.mock.calls.filter(([method]) => method === 'thread/resume') + .every(([, params]) => Object.keys(record(params)).every(key => ['threadId', 'excludeTurns'].includes(key)))).toBe(true); + expect(modelRequests).toHaveLength(0); + + const hold = gate(); answer = async () => { await hold.waiting; return message('BRIDGED_DONE'); }; + const turnId = await turn(desktop, threadId, 'DESKTOP_ACTIVE'); + await vi.waitFor(() => expect(modelRequests).toHaveLength(1), { timeout: 15_000 }); + bridge.web.user?.({ content: { text: 'MOBILE_QUEUED' } }, 'mobile-queued'); + await vi.waitFor(async () => expect(JSON.stringify(await desktop.client.request('thread/queue/list', { threadId }))).toContain('MOBILE_QUEUED')); + const { runtimeControl } = await import('./frontend'); + await runtimeControl(bridge.runtime, 'hapi/detach', bridge.sessionId); + await bridge.running; + expect(bridge.web.dead).toBe(true); + expect(bridge.web.metadata.codexRuntime?.state).toBe('detached'); + expect(JSON.stringify(await desktop.client.request('thread/queue/list', { threadId }))).toContain('MOBILE_QUEUED'); + expect(engine!.exitCode).toBeNull(); + hold.release(); await completed(desktop, turnId); + await vi.waitFor(() => expect(desktop.notifications.filter(packet => packet.method === 'turn/completed')).toHaveLength(2), { timeout: 15_000 }); + + const reattached = await attach(threadId); + expect(reattached.sessionId).toBe(bridge.sessionId); + expect(reattached.web.messages).toContainEqual(expect.objectContaining({ type: 'message', message: 'BRIDGED_DONE' })); + expect(reattached.web.metadata.codexRuntime?.bindingId).toBe(bridge.web.metadata.codexRuntime?.bindingId); + const lastTurn = await turn(desktop, threadId, 'DESKTOP_AFTER_REATTACH'); + await completed(desktop, lastTurn); + await vi.waitFor(() => expect(reattached.web.messages.filter(value => record(value).type === 'message')).toHaveLength(3)); + expect(modelRequests).toHaveLength(3); + } finally { calls.mockRestore(); } + }, 60_000); + + it('refuses an unloaded external thread before creating a HAPI session or sending resume', async () => { + const { runAttachedRuntime } = await import('./attached'); + const calls = vi.spyOn(CodexAppServerClient.prototype, 'request'); + try { + await expect(runAttachedRuntime({ endpoint, threadId: randomUUID() })).rejects.toThrow('not loaded'); + expect(hub.sessions.size).toBe(0); + expect(calls.mock.calls.some(([method]) => method === 'thread/resume')).toBe(false); + expect(modelRequests).toHaveLength(0); + } finally { calls.mockRestore(); } + }, 30_000); + + it('fails before exposing the native ID if an old Hub strips the attached marker', async () => { + const desktop = await connect(); const threadId = await start(desktop); + hub.stripRuntime = true; + const { runAttachedRuntime } = await import('./attached'); + const calls = vi.spyOn(CodexAppServerClient.prototype, 'request'); + try { + await expect(runAttachedRuntime({ endpoint, threadId })).rejects.toThrow('does not preserve'); + const session = [...hub.sessions.values()][0]; + expect(session.dead).toBe(true); + expect(session.metadata.codexSessionId).toBeUndefined(); + expect(calls.mock.calls.some(([method]) => method === 'thread/resume')).toBe(false); + expect(modelRequests).toHaveLength(0); + } finally { calls.mockRestore(); } + }, 30_000); + + it('ends only the bridge when the desktop archives its root, keeping sibling threads and engine alive', async () => { + const desktop = await connect(); const threadId = await start(desktop); const sibling = await start(desktop); + const bridge = await attach(threadId); + await desktop.client.request('thread/archive', { threadId }); + await bridge.running; + expect(bridge.web.metadata.lifecycleState).toBe('archived'); + expect(engine!.exitCode).toBeNull(); + expect(record(await desktop.client.request('thread/loaded/list', {})).data).toContain(sibling); + }, 30_000); + + it('freezes a mismatched durable view and only --new-view creates a distinct, reusable projection', async () => { + const desktop = await connect(); const threadId = await start(desktop); + const bridge = await attach(threadId); + const turnId = await turn(desktop, threadId, 'CHECKPOINT_BASELINE'); await completed(desktop, turnId); + const checkpoint = join(hub.home, 'codex-runtimes', 'attached-history', `${bridge.sessionId}-${createHash('sha256').update(threadId).digest('hex')}.json`); + await vi.waitFor(async () => expect(JSON.parse(await readFile(checkpoint, 'utf8'))).toContainEqual(expect.objectContaining({ id: turnId, hash: expect.any(String) }))); + bridge.abort.abort(); await bridge.running; + // Simulate a durable checkpoint whose native prefix no longer exists + // (the same admission path as a rewrite missed while detached). + await writeFile(checkpoint, JSON.stringify([{ id: 'previous-native-turn', hash: 'previous-content' }])); + const { runAttachedRuntime } = await import('./attached'); + await expect(runAttachedRuntime({ endpoint, threadId })).rejects.toThrow('Native history changed'); + expect(hub.sessions.get(bridge.sessionId)!.metadata).toMatchObject({ conversationHistoryDiverged: true, + codexRuntime: { state: 'history-changed' } }); + const replacement = await attach(threadId, true); + expect(replacement.sessionId).not.toBe(bridge.sessionId); + expect(replacement.web.metadata.codexRuntime?.bindingId).not.toBe(bridge.web.metadata.codexRuntime?.bindingId); + expect(replacement.web.messages).toContainEqual(expect.objectContaining({ type: 'message', message: 'EXTERNAL_MOCK_DONE' })); + replacement.abort.abort(); await replacement.running; + const again = await attach(threadId); + expect(again.sessionId).toBe(replacement.sessionId); + expect(modelRequests).toHaveLength(1); expect(engine!.exitCode).toBeNull(); + }, 45_000); + + it('freezes immediately on a real native revert while leaving the external engine alive', async context => { + const desktop = await connect(); const threadId = await start(desktop); + const turnId = await turn(desktop, threadId, 'BEFORE_NATIVE_REVERT'); await completed(desktop, turnId); + const native = record(record(await desktop.client.request('thread/read', { threadId, includeTurns: false })).thread); + if (native.historyMode !== 'paginated') context.skip('Native binary predates paginated thread/revert'); + const bridge = await attach(threadId); + await desktop.client.request('thread/revert', { threadId, beforeTurnId: turnId }); + await bridge.running; + expect(bridge.web.metadata).toMatchObject({ conversationHistoryDiverged: true, codexRuntime: { state: 'history-changed' } }); + expect(bridge.web.messages).toContainEqual(expect.objectContaining({ type: 'message', message: 'EXTERNAL_MOCK_DONE' })); + expect(engine!.exitCode).toBeNull(); + }, 30_000); +}); diff --git a/cli/src/codex/shared/frontend.ts b/cli/src/codex/shared/frontend.ts index 22574059..29bf4c79 100644 --- a/cli/src/codex/shared/frontend.ts +++ b/cli/src/codex/shared/frontend.ts @@ -11,6 +11,10 @@ import { runSharedRuntime, type RuntimeReady } from './runtime'; export async function runtimeControl(runtime: CodexRuntimeRecord, method: string, sessionId: string): Promise { if (!runtimeAlive(runtime)) throw new Error('Shared runtime is not alive'); + if (runtime.kind === 'attached') { + const { attachedRuntimeControl } = await import('./attachedControl'); + return attachedRuntimeControl(runtime, method, sessionId); + } const client = new CodexAppServerClient({ endpoint: runtime.endpoint, token: runtime.token }); client.setServerRequestHandler(() => {}); try { await initializeSharedClient(client); return await client.request(method, { sessionId }); } @@ -18,6 +22,7 @@ export async function runtimeControl(runtime: CodexRuntimeRecord, method: string } export async function attachSharedSession(runtime: CodexRuntimeRecord, sessionId: string, args: string[] = [], signal?: AbortSignal): Promise { + if (runtime.kind === 'attached') throw new Error('This is an external bridge, not an owned terminal runtime. Use hapi attach to manage it.'); const session = await (await ApiClient.create()).getSession(sessionId); if (runtime.sessions[sessionId]?.namespace !== session.namespace) throw new Error('Shared runtime namespace mismatch'); const { threadId } = z.object({ threadId: z.string() }).parse(await runtimeControl(runtime, 'hapi/attach', sessionId)); @@ -54,6 +59,7 @@ export async function runSharedCodex(raw: SharedLaunchOptions): Promise { if (options.existingSessionId && !options.reservedSessionId) { const api = await ApiClient.create(); const session = await api.getSession(options.existingSessionId); + if (session.metadata?.codexRuntime?.kind === 'attached') throw new Error('Use hapi attach for this external thread; owned resume is disabled'); const runtime = await findRuntime(session.id); if (runtime) { if (options.startedBy === 'runner') throw new Error('Shared session is already running; attach instead of spawning another execution'); diff --git a/cli/src/codex/shared/registry.test.ts b/cli/src/codex/shared/registry.test.ts index d702cfa8..888d4875 100644 --- a/cli/src/codex/shared/registry.test.ts +++ b/cli/src/codex/shared/registry.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os'; const state = vi.hoisted(() => ({ home: '', auth: 'token', processes: new Map() })); vi.mock('@/configuration', () => ({ configuration: { get happyHomeDir() { return state.home; }, apiUrl: 'hub', get cliApiToken() { return state.auth; } } })); vi.mock('@/utils/process', () => ({ isProcessAlive: (pid: number) => state.processes.has(pid), getProcessStartMarker: (pid: number) => state.processes.get(pid) })); -import { findRuntime, readRuntimes, runtimeAlive, runtimeAuthHash, runtimeMayBeAlive, saveRuntime, withThreadOwnership, type CodexRuntimeRecord } from './registry'; +import { findAttachedBinding, findColdBinding, findRuntime, readRuntimes, runtimeAlive, runtimeAuthHash, runtimeMayBeAlive, saveRuntime, withThreadOwnership, type CodexRuntimeRecord } from './registry'; const directories: string[] = []; afterEach(async () => { state.processes.clear(); state.auth = 'token'; await Promise.all(directories.splice(0).map(path => rm(path, { recursive: true, force: true }))); }); @@ -85,3 +85,43 @@ describe('shared runtime ownership', () => { await expect(readRuntimes({ strict: true })).rejects.toThrow('Cannot verify'); }); }); + +async function attachedFixture(): Promise { + const owner = await fixture(); + return { ...owner, kind: 'attached', command: '', serverPid: undefined, serverMarker: undefined, + nativeEndpoint: 'unix:///private/engine.sock', attachedAt: Date.now() }; +} +describe('external bridge ownership', () => { + it('never permits owned cold resume of an attached thread, even after detach or worker death', async () => { + const owner = await attachedFixture(); owner.sessions.sid.active = false; await saveRuntime(owner); + expect(await findColdBinding(owner.codexHome, 'thread')).toBeUndefined(); + await expect(withThreadOwnership(owner.codexHome, 'thread', 'new', async () => {})).rejects.toThrow('use hapi attach'); + expect(await withThreadOwnership(owner.codexHome, 'different', 'new', async () => 'independent')).toBe('independent'); + }); + it('rejects implicit migration of a detached owned binding into an attached view', async () => { + const owner = await fixture(); owner.sessions.sid.active = false; await saveRuntime(owner); + await expect(withThreadOwnership(owner.codexHome, 'thread', 'new', async () => {}, undefined, 'attached')).rejects.toThrow('no automatic migration'); + }); + it('excludes a live or unverifiable attached generation across HAPI homes, but allows a dead worker to reattach', async () => { + const owner = await attachedFixture(); state.processes.set(owner.pid, owner.marker); await saveRuntime(owner); + state.home = join(directories[0], 'another-hapi'); + const attach = () => withThreadOwnership(owner.codexHome, 'thread', 'new', async () => 'ok', undefined, 'attached'); + await expect(attach()).rejects.toThrow('another Codex runtime'); + state.processes.set(owner.pid, undefined); await expect(attach()).rejects.toThrow('another Codex runtime'); + state.processes.clear(); expect(await attach()).toBe('ok'); + expect(runtimeMayBeAlive({ ...owner, serverPid: 9999 }, new Map([[9999, 'external']]))).toBe(false); + }); + it('reattaches one stable view and only retires it after an explicit new-view reservation is saved', async () => { + const owner = await attachedFixture(); owner.sessions.sid.active = false; await saveRuntime(owner); + expect(await findAttachedBinding(owner.codexHome, 'thread')).toBe('sid'); + state.auth = 'other-namespace'; expect(await findAttachedBinding(owner.codexHome, 'thread')).toBeUndefined(); + state.auth = 'token'; + await saveRuntime({ ...owner, id: 'replacement', supersedes: 'sid', sessions: { fresh: { ...owner.sessions.sid } } }); + expect(await findAttachedBinding(owner.codexHome, 'thread')).toBe('fresh'); + expect(await findColdBinding(owner.codexHome, 'thread')).toBeUndefined(); + }); + it('fails closed if an attached record contains an owned process or executable', async () => { + const owner = await attachedFixture(); await saveRuntime({ ...owner, serverPid: 2222 }); + await expect(readRuntimes({ strict: true })).rejects.toThrow('Cannot verify'); + }); +}); diff --git a/cli/src/codex/shared/registry.ts b/cli/src/codex/shared/registry.ts index 190593e5..5315a036 100644 --- a/cli/src/codex/shared/registry.ts +++ b/cli/src/codex/shared/registry.ts @@ -11,12 +11,14 @@ import { withSettingsFileLock } from '@hapi/protocol/settingsFileLock'; const RuntimeSchema = z.object({ id: z.string(), pid: z.number().int().positive(), marker: z.string(), + kind: z.literal('attached').optional(), nativeEndpoint: z.string().optional(), attachedAt: z.number().optional(), supersedes: z.string().optional(), serverPid: z.number().int().positive().optional(), serverMarker: z.string().optional(), endpoint: z.string(), token: z.string().optional(), command: z.string(), args: z.array(z.string()), codexHome: z.string(), hub: z.string(), authHash: z.string(), pendingCreations: z.array(z.string()).optional(), sessions: z.record(z.string(), z.object({ threadId: z.string(), namespace: z.string(), active: z.boolean() })) -}); +}).refine(value => value.kind !== 'attached' || (!value.serverPid && !value.serverMarker && value.command === '' && value.args.length === 0), + 'An attached worker must not record an owned server or executable'); export type CodexRuntimeRecord = z.infer; export function runtimeDirectory(): string { @@ -48,7 +50,7 @@ function generationMayBeAlive(pid: number, marker?: string, snapshot?: ReadonlyM } export function runtimeMayBeAlive(owner: CodexRuntimeRecord, snapshot?: ReadonlyMap | WindowsProcessTable | null): boolean { return generationMayBeAlive(owner.pid, owner.marker, snapshot) - || Boolean(owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker, snapshot)); + || Boolean(owner.kind !== 'attached' && owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker, snapshot)); } export async function readRuntimes(options?: { strict?: boolean }): Promise { @@ -83,7 +85,7 @@ export async function saveRuntime(record: CodexRuntimeRecord): Promise { /** The store-wide lock spans cold resume, not merely registry writes. */ export async function withThreadOwnership(home: string, threadId: string, ownId: string, work: () => Promise, - onPreflightRejected?: (error: unknown) => Promise): Promise { + onPreflightRejected?: (error: unknown) => Promise, intent: 'owned' | 'attached' = 'owned'): Promise { const directory = join(home, 'hapi-runtime-owners'); await mkdir(directory, { recursive: true, mode: 0o700 }); return withSettingsFileLock(join(directory, 'ownership'), async () => { @@ -93,8 +95,16 @@ export async function withThreadOwnership(home: string, threadId: string, own if (owner.pendingCreations?.length && runtimeMayBeAlive(owner)) { throw new Error(`Codex runtime ${owner.id} has an unconfirmed creation. Inspect/stop that runtime before cold resume; its thread ID may be unknown.`); } - const match = Object.entries(owner.sessions).find(([, session]) => session.threadId === threadId && session.active); + const match = Object.entries(owner.sessions).find(([, session]) => session.threadId === threadId + && (session.active || owner.kind === 'attached' || intent === 'attached')); if (!match) continue; + if (owner.kind === 'attached' && intent === 'owned') { + throw new Error('Externally attached thread: use hapi attach, never cold-resume it into an owned runtime'); + } + if (owner.kind !== 'attached' && intent === 'attached') { + throw new Error('Thread has an owned HAPI binding. Fork it in the external desktop before attaching; no automatic migration.'); + } + if (!match[1].active) continue; const orphanAlive = owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker); if (generationMayBeAlive(owner.pid, owner.marker) || orphanAlive) { throw new Error(`Thread belongs to another Codex runtime. Use hapi resume ${match[0]}.${orphanAlive && !runtimeAlive(owner) ? ' Its wrapper exited; stop the orphaned runtime before recovery.' : ''}`); @@ -117,9 +127,21 @@ export async function findRuntime(sessionId: string): Promise { for (const owner of await readRuntimes()) { + if (owner.kind === 'attached') continue; if (owner.codexHome !== home || owner.hub !== configuration.apiUrl || owner.authHash !== runtimeAuthHash()) continue; const match = Object.entries(owner.sessions).find(([, session]) => session.threadId === threadId); if (match) return match[0]; } return undefined; } + +export async function findAttachedBinding(home: string, threadId: string): Promise { + const owners = (await readRuntimes({ strict: true })).filter(owner => owner.kind === 'attached' && owner.codexHome === home + && owner.hub === configuration.apiUrl && owner.authHash === runtimeAuthHash()); + const retired = new Set(owners.map(owner => owner.supersedes).filter(id => id !== undefined)); + for (const owner of owners) { + const match = Object.entries(owner.sessions).find(([id, binding]) => binding.threadId === threadId && !retired.has(id)); + if (match) return match[0]; + } + return undefined; +} diff --git a/cli/src/codex/shared/root.test.ts b/cli/src/codex/shared/root.test.ts index c71a796f..a5796741 100644 --- a/cli/src/codex/shared/root.test.ts +++ b/cli/src/codex/shared/root.test.ts @@ -9,6 +9,8 @@ import { SharedCodexRoot, latestCompletedForkCutoff, type RootHost } from './roo import { codexPlanProposalId } from './plan'; import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; import { asyncQuestionsForItem } from './asyncQuestions'; +import { CodexAppServerClient } from '../codexAppServerClient'; +import { buildHapiMcpBridge } from '../utils/buildHapiMcpBridge'; type NativeTurn = { id: string; status: string; items: unknown[] }; type NativeRequest = { id: string | number; method: string; params: unknown }; @@ -50,9 +52,9 @@ vi.mock('../codexAppServerClient', () => ({ }, isIndeterminateError: () => false })); -vi.mock('../utils/buildHapiMcpBridge', () => ({ buildHapiMcpBridge: async () => ({ +vi.mock('../utils/buildHapiMcpBridge', () => ({ buildHapiMcpBridge: vi.fn(async () => ({ mcpServers: {}, server: { stop() {} } -}) })); +})) })); const cleanups: Array<() => Promise> = []; afterEach(async () => { @@ -60,10 +62,12 @@ afterEach(async () => { finally { vi.useRealTimers(); } }); -async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; create?: RootHost['create'] }) { +async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; create?: RootHost['create']; + attached?: boolean; beforeSubscribe?: RootHost['beforeSubscribe']; validateHistory?: RootHost['validateHistory'] }) { const directory = await mkdtemp(join(tmpdir(), 'hapi-shared-root-')); let state: AgentState = { steeringActive: true }; let metadata: Metadata = { path: directory, host: 'test', flavor: 'codex' }; + if (opts?.attached) metadata.codexRuntime = { kind: 'attached', bindingId: '11111111-1111-4111-8111-111111111111', state: 'attached' }; let reconnect: (() => void) | null = null; const updateState = vi.fn((fn: (value: AgentState) => AgentState) => { state = fn(state); }); const rpc = new Map Promise>(); @@ -91,11 +95,12 @@ async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; cr const root = new SharedCodexRoot({ session, workingDirectory: directory } as SessionBootstrapResult, { directory, generation: 'test', endpoint: 'mock', settingsFor: () => undefined, create: opts?.create ?? (async () => { throw new Error('Unexpected root creation'); }), + attached: opts?.attached, beforeSubscribe: opts?.beforeSubscribe, validateHistory: opts?.validateHistory, end } satisfies RootHost); cleanups.push(async () => { await root.close(false); await rm(directory, { recursive: true, force: true }); }); await root.prepare(); - await root.bind('thread', { model: 'mock', thread: { turns: [] } }, false); + await root.bind('thread', { model: 'mock', thread: { turns: [] } }, opts?.attached ?? false); const native = root.client as unknown as { initialized: boolean; thread: { id: string; turns: NativeTurn[] }; @@ -115,6 +120,66 @@ async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; cr }; } +describe('externally attached root', () => { + it('skips MCP, instructions and initial settings injection, and disables lifecycle actions', async () => { + const builds = vi.mocked(buildHapiMcpBridge).mock.calls.length; + const calls = vi.spyOn(CodexAppServerClient.prototype, 'request'); + const beforeSubscribe = vi.fn(async () => {}); + const end = vi.fn(async () => {}); + try { + const f = await fixture({ attached: true, end, beforeSubscribe }); + await f.root.activate({ permissionMode: 'yolo', model: 'must-not-inject' }); + expect(vi.mocked(buildHapiMcpBridge).mock.calls).toHaveLength(builds); + expect(beforeSubscribe).toHaveBeenCalledWith('thread'); + expect(calls).toHaveBeenCalledWith('thread/resume', { threadId: 'thread' }); + expect(calls.mock.calls.some(([method]) => ['thread/start', 'thread/settings/update', 'thread/metadata/update'].includes(method))).toBe(false); + expect(() => f.root.config({})).toThrow('cannot inject'); + expect(f.metadata().capabilities).toMatchObject({ terminal: false, conversationHistory: { + forkCurrent: false, forkAtMessage: false, forkLatestCompleted: false, rewindToMessage: false } }); + await expect(f.rpc.get(RPC_METHODS.ClearConversation)!({})).rejects.toThrow('owning desktop'); + await expect(f.rpc.get(RPC_METHODS.ForkConversation)!({})).rejects.toThrow('owning desktop'); + await f.root.close(false); + expect(calls.mock.calls.some(([method]) => ['thread/archive', 'thread/queue/delete', 'turn/interrupt'].includes(method))).toBe(false); + } finally { calls.mockRestore(); } + }); + it.each(['thread/reverted', 'thread/rolledBack'])('freezes immediately on native %s', async method => { + const end = vi.fn(async () => {}); const f = await fixture({ attached: true, end }); + await f.root.activate(); + f.native.notify(method, { threadId: 'thread' }); + expect(f.metadata().conversationHistoryDiverged).toBe(true); + expect(f.metadata().codexRuntime?.state).toBe('history-changed'); + expect(end).toHaveBeenCalledWith(f.root, false, 'history-changed'); + await expect(f.rpc.get(RPC_METHODS.SetSessionConfig)!({ model: 'changed' })).rejects.toThrow('stopping'); + }); + it.each(['thread/deleted', 'thread/closed'])('detaches on native %s without archiving the engine', async method => { + const end = vi.fn(async () => {}); const f = await fixture({ attached: true, end }); + await f.root.activate(); f.native.notify(method, { threadId: 'thread' }); await f.drain(); + expect(end).toHaveBeenCalledWith(f.root, false, 'unavailable'); + }); + it('fails closed on unverifiable native history and never reconnects a lost engine', async () => { + const end = vi.fn(async () => {}); const f = await fixture({ attached: true, end }); + await f.root.activate(); + const request = vi.spyOn(f.root.client, 'request').mockRejectedValue(new Error('read unavailable')); + await expect(f.root.refresh()).rejects.toThrow('read unavailable'); + expect(end).toHaveBeenCalledWith(f.root, false, 'unavailable'); + request.mockRestore(); + const other = await fixture({ attached: true, end }); await other.root.activate(); + other.native.initialized = false; other.native.abandoned(); + expect(end).toHaveBeenCalledWith(other.root, false, 'unavailable'); + expect(other.native.initialized).toBe(false); + }); + it('revalidates history before an explicit native control instead of relying only on rewrite notifications', async () => { + let changed = false; + const validateHistory = vi.fn(async () => { if (changed) throw new Error('changed history'); }); + const end = vi.fn(async () => {}); const f = await fixture({ attached: true, end, validateHistory }); + await f.root.activate(); changed = true; + const request = vi.spyOn(f.root.client, 'request'); + await expect(f.rpc.get(RPC_METHODS.SetSessionConfig)!({ model: 'must-not-apply' })).rejects.toThrow('changed history'); + expect(request.mock.calls.some(([method]) => method === 'thread/settings/update')).toBe(false); + expect(end).toHaveBeenCalledWith(f.root, false, 'unavailable'); + }); +}); + describe('native readiness after Hub reconnect', () => { it('replays readiness only after an activated root revalidates native history', async () => { const f = await fixture() diff --git a/cli/src/codex/shared/root.ts b/cli/src/codex/shared/root.ts index 71fea285..d6362868 100644 --- a/cli/src/codex/shared/root.ts +++ b/cli/src/codex/shared/root.ts @@ -28,9 +28,12 @@ import { planImplementationMessageId, planProposalForItem, planProposalForTurn } type RuntimeSettings = NonNullable[2]>; export type RootHost = { directory: string; generation: string; endpoint: string; token?: string; + attached?: boolean; + beforeSubscribe?(threadId: string): Promise; + validateHistory?(threadId: string, thread: unknown): Promise; settingsFor(threadId: string): Record | undefined; create(method: 'thread/start' | 'thread/fork', params: Record, parent?: SharedCodexRoot): Promise; - end(root: SharedCodexRoot, nativeArchive?: boolean): Promise; + end(root: SharedCodexRoot, nativeArchive?: boolean, reason?: 'unavailable' | 'history-changed' | 'archived'): Promise; }; const SettingsSchema = z.object({ permissionMode: z.enum(['default', 'read-only', 'autoReview', 'yolo']).optional(), @@ -85,6 +88,10 @@ export class SharedCodexRoot { this.session = bootstrap.session; this.client = new CodexAppServerClient({ endpoint: host.endpoint, token: host.token, cwd: bootstrap.workingDirectory }); this.client.setNotificationHandler((method, params) => { + if (this.host.attached && ['thread/reverted', 'thread/rolledBack'].includes(method) + && (record(params).threadId === this.threadId || this.children.has(String(record(params).threadId)))) { + this.invalidateHistory(); return; + } if (method === 'serverRequest/resolved') { this.permissions?.resolved(string(record(params).threadId) ?? '', record(params).requestId); return; } @@ -97,7 +104,7 @@ export class SharedCodexRoot { } if (method === 'turn/completed' && (!this.currentTurn || record(record(params).turn).id === this.currentTurn)) { this.turnRevision++; this.currentTurn = undefined; this.interrupted = record(record(params).turn).status === 'interrupted'; - if (record(record(params).turn).status === 'completed') this.session.updateMetadata(metadata => ({ ...metadata, + if (!this.host.attached && record(record(params).turn).status === 'completed') this.session.updateMetadata(metadata => ({ ...metadata, capabilities: { ...metadata.capabilities, conversationHistory: { ...metadata.capabilities?.conversationHistory, forkLatestCompleted: true } } })); this.publishSteering(); @@ -119,13 +126,23 @@ export class SharedCodexRoot { } const receivedAt = Date.now(); const modelAtReceipt = record(params).threadId === this.threadId ? this.settings.model ?? undefined : undefined; - this.notifications = this.notifications.then(() => this.notification(method, params, modelAtReceipt, receivedAt)).catch(error => logger.debug('[Codex shared] projection', error)); + this.notifications = this.notifications.then(() => this.notification(method, params, modelAtReceipt, receivedAt)).catch(error => { + logger.debug('[Codex shared] projection', error); + this.failAttached(); + }); + }); + this.client.setTransportAbandonedHandler(() => { + if (this.host.attached) { + this.stopAccepting(); + void this.host.end(this, false, 'unavailable').catch(error => logger.debug('[Codex attached] disconnect', error)); + } else void this.reconnect(); }); - this.client.setTransportAbandonedHandler(() => { void this.reconnect(); }); this.session.onUserMessage((message, localId) => { this.work = this.work.catch(() => {}).then(async () => { await this.bound; if (this.closed || this.stopping) return; + if (this.host.attached) await this.refresh(); + if (this.closed || this.stopping) return; const id = localId ?? randomUUID(); const text = formatMessageWithAttachments(message.content.text, message.content.attachments); const resolved = text.trim().startsWith('/') ? await this.queue.command(id, () => this.command(text)) : text; @@ -158,7 +175,7 @@ export class SharedCodexRoot { // it only after native revalidation and completed activation. if (wasActivated && this.heartbeat && !this.closed && !this.stopping && this.client.isInitialized()) this.session.emitSessionReady(); }) - .catch(error => logger.debug('[Codex shared] hub resync', error)); + .catch(error => { logger.debug('[Codex shared] hub resync', error); this.failAttached(); }); }); } @@ -180,7 +197,7 @@ export class SharedCodexRoot { async prepare(): Promise { // Descendants share this bridge. The projection applies successful // root title calls so a child cannot rename the parent session. - this.bridge = await buildHapiMcpBridge(this.session, { exportSessionEnv: false, emitTitleSummary: false, + if (!this.host.attached) this.bridge = await buildHapiMcpBridge(this.session, { exportSessionEnv: false, emitTitleSummary: false, skillLookup: { workingDirectory: this.bootstrap.workingDirectory, flavor: 'codex' } }); await initializeSharedClient(this.client); this.asyncQuestions = new SharedCodexAsyncQuestions(this.session, (threadId, text, id) => this.submitQuestionAnswer(threadId, text, id)); @@ -191,6 +208,11 @@ export class SharedCodexRoot { if (this.closed || this.stopping) throw new Error('Codex execution is stopping'); const operation = (async () => { const thread = threadId === this.threadId ? undefined : await this.readThread(threadId); + if (this.host.attached) { + if (thread) await this.host.validateHistory?.(threadId, thread); + else await this.refresh(); + if (this.closed || this.stopping) throw new Error('Codex execution is stopping'); + } const turnId = threadId === this.threadId ? this.currentTurn : string((Array.isArray(thread?.turns) ? thread.turns.map(record) : []).find(turn => turn.status === 'inProgress')?.id); const params = { threadId, clientUserMessageId, input: buildUserInputFromMessage(text) }; @@ -200,12 +222,17 @@ export class SharedCodexRoot { try { await operation; } finally { this.controls.delete(operation); } } private async projectHistory(projection: SharedCodexProjection, thread: unknown): Promise { + await this.host.validateHistory?.(projection.threadId, thread); this.asyncQuestions.history(projection.threadId, thread); await projection.history(thread); } private async receiveRequest(request: { id: string | number; method: string; params: unknown }): Promise { await this.bound; if (this.closed || this.stopping) return; + if (this.host.attached) { + try { await this.refresh(); } catch { return; } + if (this.closed || this.stopping) return; + } const threadId = string(record(request.params).threadId); // App-server automatically subscribes every initialized connection to // newly created threads, including siblings. Never answer their calls. @@ -228,6 +255,7 @@ export class SharedCodexRoot { return false; } config(params: Record): Record { + if (this.host.attached) throw new Error('An attached runtime cannot inject native configuration'); return { ...params, cwd: params.cwd ?? this.bootstrap.workingDirectory, developerInstructions: params.developerInstructions ?? getCodexSystemPrompt(), config: { ...record(params.config), 'mcp_servers.hapi': this.bridge.mcpServers.hapi, @@ -250,23 +278,27 @@ export class SharedCodexRoot { async () => record(await this.client.request('thread/read', { threadId, includeTurns: false })).thread, (threadId, item) => this.asyncQuestions.observeItem(threadId, item)); this.session.updateMetadata(metadata => ({ ...metadata, codexSessionId: threadId, capabilities: { - ...metadata.capabilities, concurrentClients: true, terminal: true, + ...metadata.capabilities, concurrentClients: true, terminal: !this.host.attached, // In-place rewind needs a native + hub commit barrier. Do not // advertise a destructive operation we cannot make atomic yet. - conversationHistory: { forkCurrent: true, forkAtMessage: true, forkLatestCompleted: false, rewindToMessage: false } + conversationHistory: { forkCurrent: !this.host.attached, forkAtMessage: !this.host.attached, forkLatestCompleted: false, rewindToMessage: false } } })); this.session.updateAgentState(state => ({ ...state, controlledByUser: false, startingMode: undefined, codexPlanProposalId: null, codexCompactionPendingMessageIds: [], requests: {}, completedRequests: { ...state.completedRequests, ...Object.fromEntries(Object.entries(state.requests ?? {}).map(([id, request]) => [id, { ...request, completedAt: Date.now(), status: 'canceled' as const }])) } })); // 空会话的首次订阅保留完整响应,以兼容原生历史源文件的初始化。 - if (subscribe) response = record(await this.client.request('thread/resume', { threadId })); + if (subscribe) { + await this.host.beforeSubscribe?.(threadId); + response = record(await this.client.request('thread/resume', { threadId })); + } this.acceptSettings(response); this.acceptSettings(this.host.settingsFor(threadId) ?? {}); - await this.projectHistory(this.projection, response.thread); await this.refresh(); await this.refreshChildren(true); + if (!this.host.attached) await this.projectHistory(this.projection, response.thread); + await this.refresh(); await this.refreshChildren(true); } async activate(options: SharedLaunchOptions = {}): Promise { // Restored input cannot run before the cold-resume settings are applied. - await this.initialSettings(options); + if (!this.host.attached) await this.initialSettings(options); if (this.stopping) throw new Error('Codex execution is stopping'); this.registerControls(); this.ready(); this.heartbeat = setInterval(() => this.alive(), 2_000); this.alive(); this.session.emitSessionReady(); @@ -322,13 +354,17 @@ export class SharedCodexRoot { this.publishPlan(); } private async notification(method: string, params: unknown, modelAtReceipt?: string, receivedAt = Date.now()): Promise { - if (!this.threadId || this.closed) return; + // Native broadcasts can arrive while bind() is loading the local + // ledger, before a projection exists. bind's full read reconciles them. + if (!this.threadId || !this.projection || this.closed || this.host.attached && this.stopping) return; const p = record(params); if (method === 'thread/started') { const thread = record(p.thread); const id = string(thread.id); if (id) this.ancestry.set(id, string(thread.parentThreadId) ?? null); } const eventThread = string(p.threadId) ?? string(record(p.thread).id); + if (this.host.attached && ['thread/reverted', 'thread/rolledBack'].includes(method) + && eventThread && await this.ownsThread(eventThread)) { this.invalidateHistory(); return; } if (eventThread && eventThread !== this.threadId) { if (!await this.ownsThread(eventThread)) return; let projection = this.children.get(eventThread); @@ -338,13 +374,19 @@ export class SharedCodexRoot { (threadId, item) => this.asyncQuestions.observeItem(threadId, item)); this.children.set(eventThread, projection); } + if (this.host.attached && ['turn/started', 'turn/completed'].includes(method)) { + await this.projectHistory(projection, await this.readThread(eventThread)); + } await projection.notification(method, params); return; } if (method === 'turn/completed') this.session.sendSessionEvent({ type: 'ready' }); if (method === 'thread/name/updated' && (typeof p.threadName === 'string' || p.threadName === null)) { const name = p.threadName ?? undefined; this.session.updateMetadata(metadata => ({ ...metadata, name })); } - if (method === 'thread/archived') { await this.host.end(this, false); return; } + if (method === 'thread/archived') { await this.host.end(this, false, 'archived'); return; } + if (this.host.attached && ['thread/closed', 'thread/deleted'].includes(method)) { + this.stopAccepting(); await this.host.end(this, false, 'unavailable'); return; + } // Process these in notification order: queue removal can precede turn/started. // Older unknown input must not acquire a later turn's compaction status. if (method === 'turn/started') { @@ -363,9 +405,25 @@ export class SharedCodexRoot { if (method === 'thread/queue/changed') { for (const id of await this.queue.reconcile()) this.dequeuedInputs.add(id); } - await this.projection.notification(method, params, modelAtReceipt, receivedAt); this.publishCompaction(); this.alive(); + if (this.host.attached && method === 'turn/started' && !this.stopping) await this.refresh(); + await this.projection.notification(method, params, modelAtReceipt, receivedAt); + if (this.host.attached && method === 'turn/completed' && !this.stopping) await this.refresh(); + this.publishCompaction(); this.alive(); + } + private invalidateHistory(): void { + this.stopAccepting(); + this.session.updateMetadata(metadata => ({ ...metadata, conversationHistoryDiverged: true, + codexRuntime: { kind: 'attached', bindingId: metadata.codexRuntime?.bindingId ?? this.session.sessionId, state: 'history-changed' } })); + this.notice('Native history changed outside HAPI. This view is frozen; use hapi attach --new-view for a fresh projection.'); + void this.host.end(this, false, 'history-changed').catch(error => logger.debug('[Codex attached] history change', error)); + } + private failAttached(): void { + if (!this.host.attached || this.stopping) return; + this.stopAccepting(); + void this.host.end(this, false, 'unavailable').catch(error => logger.debug('[Codex attached] validation failed', error)); } private lazyHistory(): boolean { + if (this.host.attached) return false; return !!this.threadId && (process.env.HAPI_CODEX_LAZY_HISTORY_IDS ?? '') .split(',').map(id => id.trim()).includes(this.threadId); } @@ -392,7 +450,8 @@ export class SharedCodexRoot { return thread; } refresh(): Promise { - return this.refreshing ??= this.refreshNow().finally(() => { this.refreshing = undefined; }); + return this.refreshing ??= this.refreshNow().catch(error => { this.failAttached(); throw error; }) + .finally(() => { this.refreshing = undefined; }); } private async refreshNow(): Promise { if (!this.threadId || this.closed || !this.client.isInitialized()) return; @@ -406,8 +465,8 @@ export class SharedCodexRoot { const id = string(last?.id); this.latestTurn = id && last ? { id, status: string(last.status) ?? 'unknown', planId: planProposalForTurn(this.threadId, last) } : undefined; } - const canForkLatest = turns.some(turn => turn.status === 'completed') - || (this.lazyHistory() && this.session.getMetadata()?.capabilities?.conversationHistory?.forkLatestCompleted === true); + const canForkLatest = !this.host.attached && (turns.some(turn => turn.status === 'completed') + || (this.lazyHistory() && this.session.getMetadata()?.capabilities?.conversationHistory?.forkLatestCompleted === true)); // Starting a later turn does not invalidate completed-history evidence. // Only a stale demotion must defer to newer completion notifications. if ((canForkLatest || revision === this.turnRevision) @@ -445,11 +504,17 @@ export class SharedCodexRoot { for (const [id, projection] of this.children) { // Replaying a completed/unloaded child must not start its engine. try { - if (subscribe && loaded.has(id)) await this.client.request('thread/resume', { threadId: id, excludeTurns: true }); + if (subscribe && loaded.has(id)) { + await this.host.beforeSubscribe?.(id); + await this.client.request('thread/resume', { threadId: id, excludeTurns: true }); + } if (replayHistory) { projection.reset(); await this.projectHistory(projection, await this.readThread(id)); } - } catch (error) { logger.debug('[Codex shared] child history unavailable', { id, error }); } + } catch (error) { + if (this.host.attached) throw error; + logger.debug('[Codex shared] child history unavailable', { id, error }); + } } } nativeQueueDeleted(nativeId: string): Promise { return this.queue.deleted(nativeId); } @@ -565,6 +630,13 @@ export class SharedCodexRoot { const rpc = { registerHandler: (method: string, handler: (raw: unknown) => Promise) => { this.session.rpcHandlerManager.registerHandler(method, async (raw: unknown) => { if (this.stopping) throw new Error('Codex execution is stopping; resume when inactive'); + if (this.host.attached && ([RPC_METHODS.ClearConversation, RPC_METHODS.ForkConversation, RPC_METHODS.RewindConversation] as string[]).includes(method)) { + throw new Error('Create/fork/revert this external thread in its owning desktop; HAPI only attaches'); + } + if (this.host.attached && method !== RPC_METHODS.KillSession) { + await this.refresh(); + if (this.stopping) throw new Error('Codex execution is stopping'); + } const pending = handler(raw); this.controls.add(pending); try { return await pending; } finally { this.controls.delete(pending); } }); @@ -676,6 +748,7 @@ export class SharedCodexRoot { } private notice(message: string): void { this.session.sendSessionEvent({ type: 'message', message }); } private async newConversation(): Promise { + if (this.host.attached) throw new Error('Create new conversations in the owning desktop, then attach them explicitly'); const child = await this.host.create('thread/start', this.freshParams()); await child.initialSettings({ collaborationMode: this.settings.collaborationMode }); return child; } @@ -685,7 +758,8 @@ export class SharedCodexRoot { const child = await this.newConversation(); this.notice(`New conversation: /sessions/${child.session.sessionId}`); return null; } if (command === '/compact') { await this.client.request('thread/compact/start', { threadId: this.threadId }); return null; } - if (command === '/exit') { this.notice('/exit closes a native terminal, not this Web view. Use End session to archive this conversation.'); return null; } + if (command === '/exit') { this.notice(this.host.attached ? 'Use hapi detach to disconnect HAPI without stopping the external thread.' + : '/exit closes a native terminal, not this Web view. Use End session to archive this conversation.'); return null; } if (!command.startsWith('/')) return text; const slash = resolveCodexSlashCommand(text, { commands: await listSlashCommands('codex', this.bootstrap.workingDirectory), permissionMode: this.settings.permissionMode === 'yolo' || this.settings.permissionMode === 'read-only' || this.settings.permissionMode === 'autoReview' ? this.settings.permissionMode : 'default', @@ -729,7 +803,9 @@ export class SharedCodexRoot { return this.closing ??= (async () => { this.stopAccepting(); this.closed = true; clearInterval(this.heartbeat); this.permissions?.close(); this.asyncQuestions?.close(); - await this.client.disconnect(); await this.notifications; await this.queue?.flush(); this.bridge?.server.stop(); + await this.client.disconnect(); + if (this.host.attached) { await this.work.catch(() => {}); await Promise.allSettled([...this.controls]); } + await this.notifications; await this.queue?.flush(); this.bridge?.server.stop(); if (archived) this.session.updateMetadata(metadata => ({ ...metadata, lifecycleState: 'archived', lifecycleStateSince: Date.now() })); // Inactive is resumable; uploads referenced by pending input must survive. this.session.sendSessionDeath(undefined, { preserveUploads: !archived }); diff --git a/cli/src/commands/attach.test.ts b/cli/src/commands/attach.test.ts new file mode 100644 index 00000000..53b664e0 --- /dev/null +++ b/cli/src/commands/attach.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { parseAttachArgs } from './attach'; + +describe('attach arguments', () => { + it('requires an explicit endpoint and native thread, or read-only list', () => { + expect(parseAttachArgs(['thread', '--socket', '/tmp/a.sock'])).toEqual({ threadId: 'thread', endpoint: 'unix:///tmp/a.sock', list: false, newView: false }); + expect(parseAttachArgs(['--socket', 'unix:///tmp/a.sock', '--new-view', 'thread']).newView).toBe(true); + expect(parseAttachArgs(['--list', '--socket', '/tmp/a.sock']).list).toBe(true); + }); + it.each([[], ['thread'], ['--socket'], ['--socket', '/tmp/a'], ['thread', 'other', '--socket', '/tmp/a'], + ['thread', '--socket', '/tmp/a', '--permission-mode', 'yolo'], ['--list', 'thread', '--socket', '/tmp/a'], + ['--list', '--new-view', '--socket', '/tmp/a'], ['thread', '--socket', '/tmp/a', '--socket', '/tmp/b'], + ['thread', '--socket', '/tmp/a', '-c', 'model=x']].map(args => ({ args })))('rejects ambiguous or injecting args $args', ({ args }) => { + expect(() => parseAttachArgs(args)).toThrow(); + }); +}); diff --git a/cli/src/commands/attach.ts b/cli/src/commands/attach.ts new file mode 100644 index 00000000..631aa723 --- /dev/null +++ b/cli/src/commands/attach.ts @@ -0,0 +1,87 @@ +import type { CommandDefinition } from './types'; +import { initializeToken } from '@/ui/tokenInit'; +import { authAndSetupMachineIfNeeded } from '@/ui/auth'; +import { maybeAutoStartServer } from '@/utils/autoStartServer'; +import { CodexAppServerClient } from '@/codex/codexAppServerClient'; +import { initializeSharedClient } from '@/codex/shared/launch'; +import { assertAttachableRoot, runAttachedRuntime, validateAttachedEndpoint, type AttachedOptions } from '@/codex/shared/attached'; +import { findRuntime } from '@/codex/shared/registry'; +import { runtimeControl } from '@/codex/shared/frontend'; +import { record, string } from '@/codex/shared/gateway'; + +const HELP = `Experimental external Codex bridge (explicit external endpoint required). + hapi attach --socket /absolute/path.sock [--new-view] + hapi attach --socket /absolute/path.sock --list + hapi detach + +The thread must already be loaded in the external app-server. Runs in the +foreground; Ctrl-C, detach and End session disconnect HAPI only. No app-server, +desktop configuration, login item or launchctl setting is created or changed.`; + +export function parseAttachArgs(args: string[]): AttachedOptions & { list: boolean } { + let endpoint: string | undefined; let threadId: string | undefined; let newView = false; let list = false; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '--socket') { + if (endpoint) throw new Error('Duplicate --socket'); + const path = args[++i]; + if (!path || path.startsWith('-')) throw new Error('Missing --socket path'); + endpoint = path.startsWith('unix://') ? path : `unix://${path}`; + } else if (arg === '--new-view') newView = true; + else if (arg === '--list') list = true; + else if (arg.startsWith('-') || threadId) throw new Error(`Unexpected attach argument: ${arg}`); + else threadId = arg; + } + if (!endpoint || list && (threadId || newView) || !list && !threadId) throw new Error(HELP); + return { endpoint, threadId: threadId ?? '', newView, list }; +} + +async function listLoaded(endpoint: string): Promise { + const client = new CodexAppServerClient({ endpoint: await validateAttachedEndpoint(endpoint) }); + client.setServerRequestHandler(() => {}); + try { + await initializeSharedClient(client); + let cursor: string | undefined; + do { + const page = record(await client.request('thread/loaded/list', { cursor })); + for (const id of Array.isArray(page.data) ? page.data : []) { + if (typeof id !== 'string') continue; + const thread = record(record(await client.request('thread/read', { threadId: id, includeTurns: false })).thread); + try { assertAttachableRoot(thread, id); } catch { continue; } + console.log(JSON.stringify({ threadId: id, name: thread.name ?? null, cwd: thread.cwd })); + } + cursor = string(page.nextCursor); + } while (cursor); + } finally { await client.disconnect(); } +} + +export const attachCommand: CommandDefinition = { + name: 'attach', requiresRuntimeAssets: false, + run: async ({ commandArgs }) => { + if (commandArgs.includes('--help') || commandArgs.includes('-h')) { console.log(HELP); return; } + try { + if (process.platform !== 'darwin') throw new Error('External desktop attachment is currently supported only on macOS'); + const { list, ...options } = parseAttachArgs(commandArgs); + if (list) return await listLoaded(options.endpoint); + await initializeToken(); await maybeAutoStartServer(); await authAndSetupMachineIfNeeded(); + await runAttachedRuntime(options, ({ sessionId }) => { + console.log(`Attached HAPI session: ${sessionId}\nCtrl-C detaches HAPI only; the external thread keeps running.`); + }); + } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; } + } +}; + +export const detachCommand: CommandDefinition = { + name: 'detach', requiresRuntimeAssets: false, + run: async ({ commandArgs }) => { + if (commandArgs.includes('--help') || commandArgs.includes('-h')) { console.log(HELP); return; } + try { + if (commandArgs.length !== 1 || commandArgs[0].startsWith('-')) throw new Error('Usage: hapi detach '); + await initializeToken(); + const runtime = await findRuntime(commandArgs[0]); + if (!runtime || runtime.kind !== 'attached') throw new Error('No live attached worker for this session; owned runtimes are not detached by this command'); + await runtimeControl(runtime, 'hapi/detach', commandArgs[0]); + console.log('HAPI detached; the external app-server and native queue were left intact.'); + } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; } + } +}; diff --git a/cli/src/commands/help.ts b/cli/src/commands/help.ts index 83fe2b7c..63a5dd34 100644 --- a/cli/src/commands/help.ts +++ b/cli/src/commands/help.ts @@ -18,6 +18,8 @@ ${agents} Commands: hapi auth Manage authentication hapi resume [id] Choose or resume an existing HAPI session + hapi attach … Experimental bridge to an external Codex thread + hapi detach Detach HAPI without stopping the external engine hapi hub [--relay] Start the API + web hub hapi server Alias for hapi hub hapi runner Manage the background runner diff --git a/cli/src/commands/registry.ts b/cli/src/commands/registry.ts index c07f791d..9b3deb74 100644 --- a/cli/src/commands/registry.ts +++ b/cli/src/commands/registry.ts @@ -19,6 +19,8 @@ const removedGeminiCommand: CommandDefinition = { const commandMap = new Map Promise>([ ['agy', async () => (await import('./agy')).agyCommand], ['auth', async () => (await import('./auth')).authCommand], + ['attach', async () => (await import('./attach')).attachCommand], + ['detach', async () => (await import('./attach')).detachCommand], ['claude', async () => (await import('./claude')).claudeCommand], ['connect', async () => (await import('./connect')).connectCommand], ['codex', async () => (await import('./codex')).codexCommand], diff --git a/docs/guide/codex-shared-sessions.md b/docs/guide/codex-shared-sessions.md index c70934a7..3c3c012d 100644 --- a/docs/guide/codex-shared-sessions.md +++ b/docs/guide/codex-shared-sessions.md @@ -19,6 +19,83 @@ has since changed. A compatible runner is required when one is already running. Update CLI, Runner and Hub together: the Hub must preserve shared pending input on execution exit rather than applying the legacy session-end queue sweep. +## Experimental external desktop bridge (macOS) + +An **owned** execution (`hapi codex`) and an **attached** worker can coexist. +They are independent: the attached worker connects to an explicitly selected, +externally owned app-server and never starts or stops that server. This path is +off by default; starting HAPI or its Runner does not discover or adopt desktop +threads. + +```bash +# The desktop/owner must already expose a compatible WebSocket-over-Unix socket. +hapi attach --socket /absolute/private/engine.sock --list +hapi attach --socket /absolute/private/engine.sock +# In another shell; this is the HAPI ID printed by attach, not the native ID: +hapi detach +``` + +`attach` is a **foreground worker**, not a launcher for the official App. The +socket must belong to the current user, have owner-only permissions, and be in +a same-user directory not writable by others. Official daemon-style symlinks +are supported. TCP/remote endpoints and configuration/permission injection +flags are rejected. The worker reads the server's actual `CODEX_HOME`; it does +not use a different local engine as a fallback. Update CLI, Hub and Runner +together; startup refuses a Hub that drops the attached identity marker. + +Only persistent user-root threads **already loaded in that external engine** +are eligible. There is a loaded-thread preflight immediately before subscription; +current native protocols do not offer an atomic "subscribe only if still loaded" +operation, so an external unload racing that check is not fully fenced. HAPI +does not intentionally cold-resume an unloaded desktop thread. A thread with an +owned HAPI binding cannot be implicitly migrated into an attached binding; fork +it in the external owner and attach the new thread instead. + +- Messages, native queue, explicit settings changes, approvals and questions + use the external engine. HAPI does **not** inject its system instructions, + MCP server, environment variables or default permission settings at attach. +- Ctrl-C, `hapi detach`, and **End session** disconnect the HAPI worker only. + They do not interrupt the native turn, delete native queued input, archive the + native thread, or kill the App/server. **Stop** remains an explicit turn + interrupt. A native archive ends the bridge and archives its HAPI view. +- Native transport loss ends the worker; it never launches a replacement + engine. Run `hapi attach` again after the owner has restored the thread. + Reattachment in the same HAPI home, Hub and auth namespace reuses the HAPI + session and projection identity. An inactive attached view cannot use + ordinary `hapi resume`, Runner resume-on-send, or an archived-history fork. +- Terminal attachment and HAPI create/fork/rewind actions are unavailable for + these views. Create/fork/revert in the owning desktop, then attach explicitly. +- A native revert notification or a changed history checkpoint freezes + the old HAPI view. Checkpoints fence observed turn IDs and seal completed + content, including changes missed while detached. Use + `hapi attach --socket --new-view` to explicitly + create a fresh HAPI projection; old transcripts/queues are not merged into it. + Unverifiable history/checkpoints fail closed rather than silently resetting. + +Private local state uses the existing runtime registry and native-store +ownership directory, plus `$HAPI_HOME/codex-runtimes/attached-history` for history +checkpoints. Only HAPI's local detach control endpoint is registered; the +external PID is never recorded as owned. Native endpoints/tokens are not +published in session metadata or SSE. + +**Acceptance boundary:** isolated native-protocol and CLI → Hub integration +tests use blank homes and a local mock model; those automated tests alone are +not GUI acceptance. On 2026-11-16, a separate manual desktop smoke test with +ChatGPT App **26.1111.21308** (build 27194) and its bundled Codex +**0.169.0-alpha.11.1** verified WebSocket initialization, desktop-origin messages +mirrored into HAPI, HAPI-origin messages processed by the same engine, desktop +messages after HAPI detached, and reattachment to the same HAPI session with +detached-period history backfilled. The upgraded binary also passed all 12 +external-engine protocol and CLI → Hub integration tests. The GUI smoke test +used an isolated App profile and a local Responses mock, without copying account +credentials; production login, real-model requests and long-running desktop +use remain unverified. The earlier App 26.908.31748 frontend startup failure +did not recur in this upgraded test. + +This phase does **not** configure `launchctl`, login items, a production App +launcher or automatic Runner attachment, and does not change your original App +configuration. It requires a separately configured, compatible external endpoint. + ## Lifecycle - **Terminal-created execution**: the original terminal owns its lifetime. diff --git a/hub/src/sync/attachedCodex.test.ts b/hub/src/sync/attachedCodex.test.ts new file mode 100644 index 00000000..32b7ce22 --- /dev/null +++ b/hub/src/sync/attachedCodex.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'bun:test' +import { randomUUID } from 'node:crypto' +import type { Metadata } from '@hapi/protocol/types' +import { Store } from '../store' +import { RpcRegistry } from '../socket/rpcRegistry' +import { SessionCache } from './sessionCache' +import { SyncEngine } from './syncEngine' +import type { RpcGateway } from './rpcGateway' + +const metadata: Metadata = { path: '/tmp/work', host: 'test', machineId: 'machine', flavor: 'codex', codexSessionId: 'native-root' } +const attached = (bindingId = randomUUID()): NonNullable => ({ kind: 'attached', bindingId, state: 'detached' }) + +describe('external Codex binding safety', () => { + it.each([true, false])('never sends an inactive attached view to Runner, including an empty startup row (nativeId=%s)', async hasId => { + const store = new Store(':memory:') + const engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) + try { + const session = engine.getOrCreateSession('external', { ...metadata, codexSessionId: hasId ? 'native-root' : undefined, codexRuntime: attached() }, null, 'default') + const rpc = (engine as unknown as { rpcGateway: RpcGateway }).rpcGateway + let spawned = false + rpc.spawnSession = async () => { spawned = true; throw new Error('must not spawn') } + expect(engine.resolveLocalResumeTarget(session.id, 'default')).toMatchObject({ type: 'error', code: 'resume_unavailable' }) + expect(await engine.resumeSession(session.id, 'default')).toMatchObject({ type: 'error', code: 'resume_unavailable' }) + expect(await engine.forkConversation(session.id, 'default')).toMatchObject({ type: 'error', message: expect.stringContaining('owning desktop') }) + expect(spawned).toBe(false) + engine.handleSessionAlive({ sid: session.id, time: Date.now() }) + expect(await engine.resumeSession(session.id, 'default')).toEqual({ type: 'success', sessionId: session.id }) + } finally { engine.stop() } + }) + it('never deduplicates owned, attached, and post-rewrite epochs into one transcript', async () => { + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit() {} } as never) + const owned = cache.getOrCreateSession('owned', metadata, null, 'default') + const first = cache.getOrCreateSession('attached', { ...metadata, codexRuntime: attached() }, null, 'default') + const second = cache.getOrCreateSession('new-view', { ...metadata, codexRuntime: attached() }, null, 'default') + for (const session of [owned, first, second]) { + store.messages.addMessage(session.id, { text: session.id }, `message-${session.id}`) + await cache.deduplicateByAgentSessionId(session.id) + } + for (const session of [owned, first, second]) { + expect(cache.getSession(session.id)).toBeDefined() + expect(store.messages.getMessages(session.id, 100)).toHaveLength(1) + } + }) +}); diff --git a/hub/src/sync/sessionCache.ts b/hub/src/sync/sessionCache.ts index 5991b0b3..959bc59f 100644 --- a/hub/src/sync/sessionCache.ts +++ b/hub/src/sync/sessionCache.ts @@ -29,11 +29,14 @@ type RuntimeConfigKey = 'permissionMode' | 'model' | 'modelReasoningEffort' | 'e * Rows without a machine keep the id-only match. Pi and OpenCode are * scoped strictly by their dedupe key instead. */ -function isRecordedOnAnotherMachine( +function isDistinctNativeIdentity( field: string, a: NonNullable, b: NonNullable ): boolean { + // An attached projection is not an owned engine or another post-rewrite + // view of the same native thread. Never merge their transcripts/queues. + if (field === 'codexSessionId' && a.codexRuntime?.bindingId !== b.codexRuntime?.bindingId) return true if (field !== 'codexSessionId' && field !== 'claudeSessionId') return false return typeof a.machineId === 'string' && typeof b.machineId === 'string' @@ -2805,7 +2808,7 @@ export class SessionCache { if (!existing.metadata) continue if (existing.metadata[agentId.field] !== agentId.value) continue if (machineScoped && existing.metadata.machineId !== agentId.machineId) continue - if (isRecordedOnAnotherMachine(agentId.field, passMetadata, existing.metadata)) continue + if (isDistinctNativeIdentity(agentId.field, passMetadata, existing.metadata)) continue candidates.push({ id: existingId, session: existing }) } diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index b69ec7e1..98fa2319 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -2408,6 +2408,9 @@ export class SyncEngine { > { try { const metadata = source.metadata + if (metadata?.codexRuntime?.kind === 'attached') { + throw new Error('Fork external threads in the owning desktop, then use hapi attach') + } if (metadata?.flavor !== 'codex' || !metadata.codexSessionId || !metadata.machineId || !metadata.path) { throw new Error('Inactive fork requires a Codex session with native history and a machine binding') } @@ -4189,6 +4192,9 @@ export class SyncEngine { const session = access.session const metadata = session.metadata + if (metadata?.codexRuntime?.kind === 'attached') { + return { type: 'error', message: 'Externally attached Codex session: run hapi attach on its machine; owned cold resume is disabled', code: 'resume_unavailable' } + } if (!metadata || typeof metadata.path !== 'string' || metadata.path.length === 0) { return { type: 'error', message: 'Session metadata missing path', code: 'resume_unavailable' } } @@ -4579,6 +4585,7 @@ export class SyncEngine { /** Inactive session with directory path but no agent thread and no prior user turn. */ private canFreshSpawnNeverStartedSession(session: Session, sessionId: string, namespace: string): boolean { const metadata = session.metadata + if (metadata?.codexRuntime?.kind === 'attached') return false if (!metadata || typeof metadata.path !== 'string' || metadata.path.length === 0) { return false } diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index 2831f836..e649f640 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -97,6 +97,12 @@ export const MetadataSchema = z.object({ // session as a branch of `` instead of an unrelated duplicate. forkedFrom: z.string().optional(), codexSessionId: z.string().optional(), + // A bridge to an externally owned app-server, never an owned cold-resume target. + codexRuntime: z.object({ + kind: z.literal('attached'), + bindingId: z.string().uuid(), + state: z.enum(['attached', 'detached', 'unavailable', 'history-changed']) + }).optional(), // 原始 Codex thread id。导入 Codex 历史后,HAPI 会 fork 出自己的续写 thread; // codexSessionId 保存 fork 后的 thread,codexSourceSessionId 保留来源 thread 便于同步/展示。 codexSourceSessionId: z.string().optional(),