feat(codex): attach HAPI to external desktop runtimes

Add explicit macOS attach/detach workers independent of owned runtimes. Preserve external engine lifetime, native queues and settings, and fence history rewrites with durable projection checkpoints.

Guard owned resume and deduplication paths, add protocol and CLI-to-Hub regression coverage, and document the isolated ChatGPT desktop GUI acceptance results.

Refs #2427
This commit is contained in:
weishu
2026-11-16 16:24:33 +08:00
parent b9a2869f4e
commit 8aebb908bf
25 changed files with 1508 additions and 32 deletions
@@ -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<string, unknown>[] = [];
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<void>(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 <T>(read: () => Promise<T>, accept: (value: T) => boolean): Promise<T> => {
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<Record<string, unknown> & { 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<void>(resolve => child.once('exit', () => resolve())), new Promise<void>(resolve => setTimeout(resolve, 2_000))]);
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
}
model.closeAllConnections(); await new Promise<void>(resolve => model.close(() => resolve()));
await rm(home, { recursive: true, force: true, maxRetries: 3 });
}
}, 90_000);
});
+47
View File
@@ -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<void>> = [];
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<void>((resolve, reject) => { server.once('error', reject); server.listen(path, resolve); });
cleanup.push(() => new Promise<void>(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();
});
});
+218
View File
@@ -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<typeof AttachedOptionsSchema>;
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<string> {
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<void> {
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<string, unknown>, 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<void> {
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<ReturnType<typeof startAttachedControl>> | undefined;
let runtime: CodexRuntimeRecord | undefined;
const lifecycle: { reason: StopReason } = { reason: 'detached' };
let stopping = false;
let finish!: () => void;
const stopped = new Promise<void>(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);
}
}
}
@@ -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(); }
});
});
+39
View File
@@ -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<void>;
}> {
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<void>((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<void>(resolve => server.close(() => resolve()));
} };
}
export async function attachedRuntimeControl(runtime: CodexRuntimeRecord, method: string, sessionId: string): Promise<unknown> {
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();
}
@@ -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('{');
});
});
+37
View File
@@ -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<void> {
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<typeof SnapshotSchema> = [];
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);
}
@@ -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<string, BridgeSession>() }));
class BridgeSession extends EventEmitter {
readonly sessionId: string; metadata: Metadata; state: AgentState = {};
messages: unknown[]; private seen: Set<string>; dead = false;
user?: (message: { content: { text: string } }, id?: string) => void;
rpc = new Map<string, (params: unknown) => Promise<unknown>>();
rpcHandlerManager = { registerHandler: (method: string, handler: (params: unknown) => Promise<unknown>) => { this.rpc.set(method, handler); } };
constructor(cwd: string, overrides: Partial<Metadata>, 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<Metadata>; sessionId?: string }): Promise<SessionBootstrapResult> => {
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<string, unknown>[];
let answer: (request: Record<string, unknown>) => Promise<Record<string, unknown>>;
const releases: Array<() => void> = [];
const workers: Array<{ abort: AbortController; running: Promise<void> }> = [];
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<void>(resolve => { release = resolve; });
releases.push(release);
return { waiting, release };
};
const connect = async (): Promise<Peer> => {
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<import('./attached').AttachedReady>(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<void>(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<void>(resolve => engine!.once('exit', () => resolve())); }
}
engine = undefined;
if (model) { model.closeAllConnections(); await new Promise<void>(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<Record<string, unknown>>).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<Record<string, unknown>>).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);
});
+6
View File
@@ -11,6 +11,10 @@ import { runSharedRuntime, type RuntimeReady } from './runtime';
export async function runtimeControl(runtime: CodexRuntimeRecord, method: string, sessionId: string): Promise<unknown> {
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<void> {
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<void> {
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');
+41 -1
View File
@@ -6,7 +6,7 @@ import { tmpdir } from 'node:os';
const state = vi.hoisted(() => ({ home: '', auth: 'token', processes: new Map<number, string | undefined>() }));
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<CodexRuntimeRecord> {
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');
});
});
+26 -4
View File
@@ -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<typeof RuntimeSchema>;
export function runtimeDirectory(): string {
@@ -48,7 +50,7 @@ function generationMayBeAlive(pid: number, marker?: string, snapshot?: ReadonlyM
}
export function runtimeMayBeAlive(owner: CodexRuntimeRecord, snapshot?: ReadonlyMap<number, string | null> | 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<CodexRuntimeRecord[]> {
@@ -83,7 +85,7 @@ export async function saveRuntime(record: CodexRuntimeRecord): Promise<void> {
/** The store-wide lock spans cold resume, not merely registry writes. */
export async function withThreadOwnership<T>(home: string, threadId: string, ownId: string, work: () => Promise<T>,
onPreflightRejected?: (error: unknown) => Promise<T>): Promise<T> {
onPreflightRejected?: (error: unknown) => Promise<T>, intent: 'owned' | 'attached' = 'owned'): Promise<T> {
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<T>(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<CodexRuntimeRecord
export async function findColdBinding(home: string, threadId: string): Promise<string | undefined> {
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<string | undefined> {
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;
}
+69 -4
View File
@@ -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<void>> = [];
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<string, (raw: unknown) => Promise<unknown>>();
@@ -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()
+97 -21
View File
@@ -28,9 +28,12 @@ import { planImplementationMessageId, planProposalForItem, planProposalForTurn }
type RuntimeSettings = NonNullable<Parameters<ApiSessionClient['keepAlive']>[2]>;
export type RootHost = {
directory: string; generation: string; endpoint: string; token?: string;
attached?: boolean;
beforeSubscribe?(threadId: string): Promise<void>;
validateHistory?(threadId: string, thread: unknown): Promise<void>;
settingsFor(threadId: string): Record<string, unknown> | undefined;
create(method: 'thread/start' | 'thread/fork', params: Record<string, unknown>, parent?: SharedCodexRoot): Promise<SharedCodexRoot>;
end(root: SharedCodexRoot, nativeArchive?: boolean): Promise<void>;
end(root: SharedCodexRoot, nativeArchive?: boolean, reason?: 'unavailable' | 'history-changed' | 'archived'): Promise<void>;
};
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<void> {
// 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<void> {
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<void> {
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<string, unknown>): Record<string, unknown> {
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<void> {
// 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<void> {
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<void> {
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<void> {
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<void> { return this.queue.deleted(nativeId); }
@@ -565,6 +630,13 @@ export class SharedCodexRoot {
const rpc = { registerHandler: (method: string, handler: (raw: unknown) => Promise<unknown>) => {
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<SharedCodexRoot> {
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 });