diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fb5e6233..c0de2fe6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,7 @@ jobs: # Required by cli/src/utils/windowsProcessTree.pwsh.test.ts — image # inspect alone does not pull; silent skip was fake B1 coverage (#1911). - run: docker pull mcr.microsoft.com/powershell:latest - - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts session-list-fork-menu.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts session-activity.spec.ts cold-initial-tail.spec.ts scrollbar-auto-hide.spec.ts attachment-removal.spec.ts history-navigation-layout.spec.ts share-turn.spec.ts share-turn-blob-export.spec.ts composer-attachment-controls.spec.ts image-preview-back.spec.ts + - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts session-list-fork-menu.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts session-activity.spec.ts cold-initial-tail.spec.ts scrollbar-auto-hide.spec.ts attachment-removal.spec.ts history-navigation-layout.spec.ts share-turn.spec.ts share-turn-blob-export.spec.ts composer-attachment-controls.spec.ts image-preview-back.spec.ts opencode-fork-buttons.spec.ts - run: bun run test # Serial runner-integration suite: starts real detached runner/session diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.test.ts b/cli/src/agent/backends/acp/AcpSdkBackend.test.ts index aab7f4de..265027fc 100644 --- a/cli/src/agent/backends/acp/AcpSdkBackend.test.ts +++ b/cli/src/agent/backends/acp/AcpSdkBackend.test.ts @@ -1903,6 +1903,113 @@ describe('AcpSdkBackend', () => { expect(turn1.some((m) => m.type === 'plan')).toBe(true); }); + it('starts the suppression quiet window at operation completion when the previous turn was already idle', async () => { + backendStatics.UPDATE_QUIET_PERIOD_MS = 5; + backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 100; + backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 30; + backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 300; + backendStatics.LATE_FLUSH_INTERVAL_MS = 5; + backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 5; + backendStatics.LATE_FLUSH_WINDOW_MS = 30; + const backend = new AcpSdkBackend({ command: 'opencode', flavor: 'opencode', textChunkMode: 'delta' }); + const internal = backend as unknown as { + transport: unknown; + handleNotification(method: string, params: unknown): void; + sessionUpdateQueue: Promise; + lastSessionUpdateAt: number; + }; + internal.transport = { sendRequest: async () => ({ stopReason: 'end_turn' }), close: async () => {} }; + const updates: AgentMessage[] = []; + let timer: ReturnType | undefined; + let delivered!: () => void; + const notificationDelivered = new Promise(resolve => { delivered = resolve; }); + const emitPlan = (text: string) => internal.handleNotification('session/update', { + sessionId: 'session-1', update: { sessionUpdate: ACP_SESSION_UPDATE_TYPES.plan, + entries: [{ content: text, priority: 'medium', status: 'pending' }] } + }); + try { + await backend.prompt('session-1', [{ type: 'text', text: 'completed turn' }], update => updates.push(update)); + // No notification has arrived during a long idle period before reload. + internal.lastSessionUpdateAt = Date.now() - 1_000; + const idleActivity = backend.getLastSessionUpdateAt(); + const result = await backend.suppressUpdatesDuring(async () => { + timer = setTimeout(() => { emitPlan('late-reload-history'); delivered(); }, 15); + return 'loaded'; + }); + await notificationDelivered; + await internal.sessionUpdateQueue; + expect(result).toBe('loaded'); + expect(JSON.stringify(updates)).not.toContain('late-reload-history'); + expect(backend.getLastSessionUpdateAt()).toBeGreaterThan(idleActivity); + emitPlan('ordinary-update-after-reload'); + await internal.sessionUpdateQueue; + expect(JSON.stringify(updates)).toContain('ordinary-update-after-reload'); + } finally { + if (timer) clearTimeout(timer); + await backend.disconnect(); + } + }); + + it('restores suppression after a load failure without discarding metadata, usage or the next response', async () => { + backendStatics.UPDATE_QUIET_PERIOD_MS = 5; + backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 100; + backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 30; + backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 300; + backendStatics.LATE_FLUSH_INTERVAL_MS = 5; + backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 5; + backendStatics.LATE_FLUSH_WINDOW_MS = 30; + const retryOptions = (AcpSdkBackend as unknown as { INIT_RETRY_OPTIONS: { maxAttempts: number } }).INIT_RETRY_OPTIONS; + const originalMaxAttempts = retryOptions.maxAttempts; + retryOptions.maxAttempts = 1; + const backend = new AcpSdkBackend({ command: 'opencode', flavor: 'opencode', textChunkMode: 'delta' }); + const internal = backend as unknown as { + transport: unknown; + handleNotification(method: string, params: unknown): void; + sessionUpdateQueue: Promise; + messageHandler: unknown; + latestUsageUpdate: unknown; + }; + const emit = (update: unknown) => internal.handleNotification('session/update', { sessionId: 'session-1', update }); + let promptCount = 0; + internal.transport = { + close: async () => {}, + sendRequest: async (method: string) => { + if (method === 'session/load') { + emit({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'failed-load-replay' } }); + emit({ sessionUpdate: 'session_info_update', title: 'loaded-session-title' }); + emit({ sessionUpdate: 'usage_update', used: 4_200, size: 200_000 }); + throw new Error('fixture load rejection'); + } + if (++promptCount === 2) emit({ sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'normal-after-load-failure' } }); + return { stopReason: 'end_turn' }; + } + }; + const previous: AgentMessage[] = []; + const titles: unknown[] = []; + backend.setSessionInfoUpdateListener(update => titles.push(update)); + try { + await backend.prompt('session-1', [{ type: 'text', text: 'previous prompt' }], update => previous.push(update)); + const previousHandler = internal.messageHandler; + await expect(backend.suppressUpdatesDuring(() => backend.loadSession({ + sessionId: 'session-1', cwd: '/tmp/project', mcpServers: [] + }))).rejects.toThrow('fixture load rejection'); + await internal.sessionUpdateQueue; + expect(internal.messageHandler).toBe(previousHandler); + expect(JSON.stringify(previous)).not.toContain('failed-load-replay'); + expect(titles).toEqual([{ sessionId: 'session-1', title: 'loaded-session-title' }]); + expect(internal.latestUsageUpdate).toMatchObject({ contextTokens: 4_200, contextWindow: 200_000 }); + const next: AgentMessage[] = []; + await backend.prompt('session-1', [{ type: 'text', text: 'next prompt' }], update => next.push(update)); + expect(JSON.stringify(previous)).not.toContain('failed-load-replay'); + expect(JSON.stringify(next)).toContain('normal-after-load-failure'); + expect(JSON.stringify(next)).not.toContain('failed-load-replay'); + } finally { + retryOptions.maxAttempts = originalMaxAttempts; + await backend.disconnect(); + } + }); + it('drops updates enqueued while suppressed even if the queue drains after the handler is restored', async () => { // If handleSessionUpdate looked up this.messageHandler when the queued // microtask ran (instead of capturing it at enqueue), a compact-era diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.ts b/cli/src/agent/backends/acp/AcpSdkBackend.ts index ecf5737d..46457b8e 100644 --- a/cli/src/agent/backends/acp/AcpSdkBackend.ts +++ b/cli/src/agent/backends/acp/AcpSdkBackend.ts @@ -1107,9 +1107,12 @@ export class AcpSdkBackend implements AgentBackend { try { return await fn(); } finally { + // A load/compact can finish before its first notification. Measure + // quiet from completion too, not only the previous prompt's idle time. await this.waitForSessionUpdateQuiet( AcpSdkBackend.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS, - AcpSdkBackend.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS + AcpSdkBackend.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS, + Date.now() ); if (this.messageHandler === null) { this.messageHandler = previousHandler; @@ -1527,7 +1530,7 @@ export class AcpSdkBackend implements AgentBackend { } } - private async waitForSessionUpdateQuiet(quietMs: number, timeoutMs: number): Promise { + private async waitForSessionUpdateQuiet(quietMs: number, timeoutMs: number, quietBaseline = 0): Promise { if (quietMs <= 0 || timeoutMs <= 0) { return; } @@ -1535,7 +1538,7 @@ export class AcpSdkBackend implements AgentBackend { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { - const elapsedSinceUpdate = Date.now() - this.lastSessionUpdateAt; + const elapsedSinceUpdate = Date.now() - Math.max(this.lastSessionUpdateAt, quietBaseline); if (elapsedSinceUpdate >= quietMs) { return; } diff --git a/cli/src/agent/sessionFactory.test.ts b/cli/src/agent/sessionFactory.test.ts index 027f0bff..c5484a3d 100644 --- a/cli/src/agent/sessionFactory.test.ts +++ b/cli/src/agent/sessionFactory.test.ts @@ -250,6 +250,7 @@ describe('bootstrapExistingSession', () => { }) it('preserves existing native resume metadata when reactivating a session', async () => { + const checkpoint = { sessionId: 'native-child', messageIds: ['m1'], userMessageIds: ['m1'], localMessageIds: ['m2'], localPublicationPending: true as const } const session = createSession() const existingMetadata = session.metadata if (!existingMetadata) throw new Error('expected test session metadata') @@ -283,6 +284,8 @@ describe('bootstrapExistingSession', () => { tools: ['read_file'], slashCommands: ['/compact'], conversationHistoryPoints: { 'local-user-1': true }, + opencodeHistoryCheckpoint: checkpoint, + opencodeForkPending: true, conversationHistoryEntryIds: { 'local-user-1': 'pi-entry-1' }, capabilities: { terminal: true, @@ -332,6 +335,8 @@ describe('bootstrapExistingSession', () => { tools: ['read_file'], slashCommands: ['/compact'], conversationHistoryPoints: { 'local-user-1': true }, + opencodeHistoryCheckpoint: checkpoint, + opencodeForkPending: true, conversationHistoryEntryIds: { 'local-user-1': 'pi-entry-1' }, capabilities: { terminal: true, @@ -344,7 +349,9 @@ describe('bootstrapExistingSession', () => { acpManualTitle: true, codexSessionId: 'codex-thread-1', grokSessionId: 'grok-thread-1', - conversationHistoryEntryIds: { 'local-user-1': 'pi-entry-1' } + conversationHistoryEntryIds: { 'local-user-1': 'pi-entry-1' }, + opencodeHistoryCheckpoint: checkpoint, + opencodeForkPending: true })) expect(notifyRunnerSessionStartedMock).toHaveBeenCalledWith( 'hapi-session-1', diff --git a/cli/src/agent/sessionFactory.ts b/cli/src/agent/sessionFactory.ts index e6da974d..99cedae9 100644 --- a/cli/src/agent/sessionFactory.ts +++ b/cli/src/agent/sessionFactory.ts @@ -190,6 +190,10 @@ function pickExistingSessionMetadata(metadata: Metadata | null | undefined): Par if (metadata.conversationHistoryIndexes !== undefined) { preserved.conversationHistoryIndexes = metadata.conversationHistoryIndexes } + if (metadata.opencodeHistoryCheckpoint !== undefined) preserved.opencodeHistoryCheckpoint = metadata.opencodeHistoryCheckpoint + if (metadata.opencodeRewind !== undefined) preserved.opencodeRewind = metadata.opencodeRewind + if (metadata.opencodeWorkerId !== undefined) preserved.opencodeWorkerId = metadata.opencodeWorkerId + if (metadata.opencodeForkPending !== undefined) preserved.opencodeForkPending = metadata.opencodeForkPending if (metadata.conversationHistoryTurns !== undefined) { preserved.conversationHistoryTurns = metadata.conversationHistoryTurns } diff --git a/cli/src/api/api.extraHeaders.test.ts b/cli/src/api/api.extraHeaders.test.ts index 67f6f42a..84bd33ac 100644 --- a/cli/src/api/api.extraHeaders.test.ts +++ b/cli/src/api/api.extraHeaders.test.ts @@ -4,9 +4,14 @@ import { configuration } from '@/configuration' const axiosPostMock = vi.hoisted(() => vi.fn()) const ioMock = vi.hoisted(() => vi.fn()) +vi.mock('@/utils/time', async (original) => ({ + ...await original(), monotonicTimeMs: () => Date.now() +})) + vi.mock('axios', () => ({ default: { - post: axiosPostMock + post: axiosPostMock, + isAxiosError: (error: unknown) => Boolean((error as { isAxiosError?: boolean } | null)?.isAxiosError) } })) @@ -52,6 +57,48 @@ describe('API extra headers integration', () => { ioMock.mockReset() }) + it('waits for confirmed shutdown preparation using CLI authentication and extra headers', async () => { + configuration._setExtraHeaders({ Cookie: 'fixture' }) + let release!: () => void + axiosPostMock.mockImplementation((_url, body) => new Promise((resolve) => { + release = () => resolve({ data: { status: 'ready', preparationLease: body.preparationLease } }) + })) + const client = await ApiClient.create() + let done = false + const request = client.prepareOpenCodeSessionStop('session/1', 'machine-1', 123, 'gen-a').then(() => { done = true }) + await Promise.resolve() + expect(done).toBe(false) + expect(axiosPostMock).toHaveBeenCalledWith('https://hapi.example.com/cli/sessions/session%2F1/prepare-stop', + expect.objectContaining({ machineId: 'machine-1', pid: 123, processStartMarker: 'gen-a', + preparationLease: expect.objectContaining({ id: expect.any(String), expiresAt: expect.any(Number) }) }), + expect.objectContaining({ headers: expect.objectContaining({ Authorization: 'Bearer cli-token', Cookie: 'fixture' }) })) + release() + await request + expect(done).toBe(true) + }) + + it('propagates unconfirmed preparation but permits cleanup of a removed Hub row', async () => { + const client = await ApiClient.create() + axiosPostMock.mockResolvedValueOnce({ data: { error: 'drain failed' } }) + await expect(client.prepareOpenCodeSessionStop('session-1', 'machine-1', 123, 'gen-a')).rejects.toThrow('not confirmed') + axiosPostMock.mockRejectedValueOnce({ isAxiosError: true, response: { status: 503 } }) + await expect(client.prepareOpenCodeSessionStop('session-1', 'machine-1', 123, 'gen-a')).rejects.toMatchObject({ response: { status: 503 } }) + axiosPostMock.mockRejectedValueOnce({ isAxiosError: true, response: { status: 404 } }) + await expect(client.prepareOpenCodeSessionStop('session-1', 'machine-1', 123, 'gen-a')).resolves.toBeUndefined() + }) + + it('rejects a ready response received after its caller lease expired', async () => { + vi.useFakeTimers() + try { + const client = await ApiClient.create() + axiosPostMock.mockImplementation(async (_url, body) => { + vi.advanceTimersByTime(30000) + return { data: { status: 'ready', preparationLease: body.preparationLease } } + }) + await expect(client.prepareOpenCodeSessionStop('session-1', 'machine-1', 123, 'gen-a')).rejects.toThrow('lease was not confirmed') + } finally { vi.useRealTimers() } + }) + it('adds extra headers to REST requests', async () => { configuration._setExtraHeaders({ Cookie: 'CF_Authorization=token' diff --git a/cli/src/api/api.ts b/cli/src/api/api.ts index 4b1b7074..6347e94e 100644 --- a/cli/src/api/api.ts +++ b/cli/src/api/api.ts @@ -1,4 +1,6 @@ import axios from 'axios' +import { randomUUID } from 'node:crypto' +import { DEFAULT_RPC_TIMEOUT_MS, type SessionStopPreparationLease } from '@hapi/protocol/rpcMethods' import type { AgentState, ClearOpencodeSessionCallbackRequest, ClearOpencodeSessionResponse, CreateMachineResponse, CreateSessionResponse, RunnerState, Machine, MachineMetadata, Metadata, Session } from '@/api/types' import { applyHubSessionSummaryContract } from '@/modules/common/sessionSummaryInstruction' import type { LocalResumeTarget, LocalResumeTargetByAgentResponse, ResumableSession } from '@hapi/protocol' @@ -23,6 +25,7 @@ import { apiValidationError } from '@/utils/errorUtils' import { ApiMachineClient } from './apiMachine' import { ApiSessionClient, type ApiSessionClientOptions } from './apiSession' import { buildHubRequestHeaders } from './hubExtraHeaders' +import { monotonicTimeMs } from '@/utils/time' export class ApiClient { static async create(): Promise { @@ -38,6 +41,31 @@ export class ApiClient { }) } + async prepareOpenCodeSessionStop(sessionId: string, machineId: string, pid: number, processStartMarker: string): Promise { + const preparationLease = { id: randomUUID(), expiresAt: monotonicTimeMs() + DEFAULT_RPC_TIMEOUT_MS } + try { + const response = await axios.post<{ status: string; preparationLease?: SessionStopPreparationLease }>( + `${configuration.apiUrl}/cli/sessions/${encodeURIComponent(sessionId)}/prepare-stop`, + { machineId, pid, processStartMarker, preparationLease }, { headers: this.authHeaders(), timeout: 60_000 } + ) + if (response.data.status !== 'ready' && response.data.status !== 'not_required') { + throw new Error('Session shutdown preparation was not confirmed') + } + if (response.data.status === 'not_required') return + if (response.data.preparationLease?.id !== preparationLease.id + || response.data.preparationLease.expiresAt !== preparationLease.expiresAt + || monotonicTimeMs() >= preparationLease.expiresAt) { + throw new Error('Session shutdown preparation lease was not confirmed') + } + return preparationLease.expiresAt + } catch (error) { + // A removed Hub row has no transcript left to drain. Preserve the + // runner's existing orphan-process cleanup for that case. + if (axios.isAxiosError(error) && error.response?.status === 404) return + throw error + } + } + async getOrCreateSession(opts: { id?: string /** Bind a hub-preallocated stub (requires id). */ diff --git a/cli/src/api/apiSession.test.ts b/cli/src/api/apiSession.test.ts index a2e8b2a1..2545b49f 100644 --- a/cli/src/api/apiSession.test.ts +++ b/cli/src/api/apiSession.test.ts @@ -1,5 +1,14 @@ import { describe, expect, it, vi } from 'vitest' import type { Session } from './types' +import { mkdtempSync, readFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { spawnSync } from 'node:child_process' +import type { OpenCodeRewindOperation } from '@hapi/protocol/schemas' +import type { OpenCodeRewindReport } from '@hapi/protocol/apiTypes' +import { OpenCodeRewind, OpenCodeRuntimeGate } from '../opencode/rewind' +import { MessageQueue2 } from '../utils/MessageQueue2' +import { getProcessStartMarker } from '../utils/process' const socketHarness = vi.hoisted(() => ({ sockets: [] as Array<{ @@ -16,7 +25,8 @@ const socketHarness = vi.hoisted(() => ({ })) const axiosHarness = vi.hoisted(() => ({ - get: vi.fn() + get: vi.fn(), + post: vi.fn() })) vi.mock('socket.io-client', () => ({ @@ -92,6 +102,7 @@ vi.mock('socket.io-client', () => ({ vi.mock('axios', () => ({ default: { get: axiosHarness.get, + post: axiosHarness.post, isAxiosError: (error: unknown) => ( typeof error === 'object' && error !== null @@ -667,6 +678,901 @@ describe('ApiSessionClient lazy materialization', () => { }) describe('ApiSessionClient incoming user messages', () => { + for (const fault of ['version-race', 'persisted-ack-loss'] as const) { + it.each([false, true])(`recovers a prepared report ${fault} through the real Hub (${fault}, reconstructed=%s)`, async reconstructed => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + axiosHarness.post.mockReset() + const directory = mkdtempSync(join(tmpdir(), 'api-rewind-preparation-')) + const database = join(directory, 'hub.db') + const hubModule = (path: string) => JSON.stringify(new URL(`../../../hub/src/${path}`, import.meta.url).href) + const runHub = (body: string) => { + const source = `import { Store } from ${hubModule('store/index.ts')}; + import { Database } from 'bun:sqlite'; + import { SyncEngine } from ${hubModule('sync/syncEngine.ts')}; + import { RpcRegistry } from ${hubModule('socket/rpcRegistry.ts')}; + const store = new Store(${JSON.stringify(database)}); + const db = new Database(${JSON.stringify(database)}); + const engine = new SyncEngine(store, {}, new RpcRegistry(), { broadcast() {} }); + const invalidations = []; + engine.subscribe(event => { if (event.type === 'messages-invalidated') invalidations.push(event); }); + const state = id => { + const session = store.sessions.getSession(id); + return { session, history: { rows: store.messages.getAllMessages(id), + checkpoint: session.metadata.opencodeHistoryCheckpoint, indexes: session.metadata.conversationHistoryIndexes, + epoch: store.messages.getMessageEpoch(id), + read: db.query('SELECT content_revision, read_revision, read_state_version, manual_unread FROM sessions WHERE id = ?').get(id), + fts: db.query('SELECT rowid, * FROM message_content_search ORDER BY rowid').all(), + lookup: db.query('SELECT * FROM message_content_search_lookup ORDER BY search_rowid').all(), + short: db.query('SELECT * FROM message_content_search_short ORDER BY gram, search_rowid').all() }, invalidations }; + }; + try { ${body} } finally { engine.stop(); db.close(); store.close(); }` + const result = spawnSync('bun', ['--eval', source], { encoding: 'utf8', timeout: 15_000 }) + expect(result.status, result.stderr).toBe(0) + return JSON.parse(result.stdout.trim().split('\n').at(-1)!) + } + const initial = runHub(` + const session = engine.getOrCreateSession('preparation-recovery', { path: '/tmp', host: 'test', flavor: 'opencode', + opencodeSessionId: 'native', opencodeWorkerId: 'worker', opencodeWorkerProcess: { workerId: 'worker', pid: ${process.pid}, startMarker: ${JSON.stringify(getProcessStartMarker(process.pid))} }, conversationHistoryIndexes: { local1: 0, local2: 1 }, + opencodeHistoryCheckpoint: { sessionId: 'native', messageIds: ['u1', 'a1', 'u2', 'a2'], + userMessageIds: ['u1', 'u2'], localMessageIds: [] }, + capabilities: { conversationHistory: { rewindToMessage: true } } }, null, 'default'); + engine.handleSessionAlive({ sid: session.id, time: Date.now(), mode: 'remote' }); + for (const [role, localId, text] of [['user','local1','retainedprefix'], ['agent',null,'retainedprefix answer'], + ['user','local2','removedsuffix'], ['agent',null,'removedsuffix answer']]) { + store.messages.addMessage(session.id, { role, content: role === 'user' ? { type:'text', text } + : { type:'codex', data: { type:'message', id:text, message:text } } }, localId ?? undefined); + if (localId) store.messages.markMessagesInvoked(session.id, [localId], Date.now()); + } + let operation; + engine.rpcGateway.rewindConversation = async (_id, request) => { + operation = request.opencodeRewind; + return { success:false, outcome:'unknown', error:'dispatch deferred to controller' }; + }; + await engine.rewindConversation(session.id, 'default', 'local2'); + console.log(JSON.stringify({ operation, state: state(session.id) }));`) + const id = initial.state.session.id as string + const inspect = () => runHub(`console.log(JSON.stringify(state(${JSON.stringify(id)})));`) + let inject = true + const persistedReports: Array<{ phase: string; result: any }> = [] + axiosHarness.get.mockImplementation(async (url: string) => url.endsWith('/messages') ? { data: { messages: [] } } + : { data: { session: inspect().session } }) + axiosHarness.post.mockImplementation(async (_url: string, input: { report: OpenCodeRewindReport; expectedVersion: number }) => { + const preparedFault = inject && input.report.phase === 'prepared' + if (preparedFault) inject = false + const result = runHub(` + const input = ${JSON.stringify(input)}; + if (${preparedFault && fault === 'version-race'}) { + const current = store.sessions.getSession(${JSON.stringify(id)}); + const changed = store.sessions.updateSessionMetadata(current.id, + { ...current.metadata, name:'concurrent metadata update' }, current.metadataVersion, 'default'); + if (changed.result !== 'success') throw new Error('metadata race setup failed'); + } + try { + const operation = engine.reportOpenCodeRewind(${JSON.stringify(id)}, 'default', input.report, input.expectedVersion); + console.log(JSON.stringify({ operation, state:state(${JSON.stringify(id)}) })); + } catch (error) { console.log(JSON.stringify({ error:String(error.message), state:state(${JSON.stringify(id)}) })); }`) + persistedReports.push({ phase: input.report.phase, result }) + if (result.error) throw new Error(result.error) + if (preparedFault && fault === 'persisted-ack-loss') throw new Error('prepared ACK lost after persistence') + return { data: { operation: result.operation } } + }) + const client = new ApiSessionClient('token', createSession({ id, metadata: initial.state.session.metadata, + metadataVersion: initial.state.session.metadataVersion })) + const nativeRows = [{ id:'u1', type:'user' }, { id:'a1', type:'assistant' }, { id:'u2', type:'user' }, { id:'a2', type:'assistant' }] + const nativeRequest = vi.fn(async (url: string, init?: RequestInit) => { + if (init?.method === 'POST') throw new Error('unexpected native mutation before preparation') + if (url.includes('/message?')) return Response.json({ data:nativeRows, cursor:{} }) + if (url.endsWith('/active')) return Response.json({ data:{} }) + if (url.endsWith('/inbox')) return Response.json({ data:[] }) + return Response.json({ data:{ id:'native' } }) + }) + const gate = new OpenCodeRuntimeGate() + const options = { directory, hapiSessionId:id, workerId:'worker', gate, baseUrl:'http://synthetic-native', + nativeSessionId:'native', headers:{}, request:nativeRequest, report:(report:OpenCodeRewindReport) => client.reportOpenCodeRewind(report), + getAuthoritativeOperation: async () => { if (!await client.refreshMetadata()) throw new Error('refresh failed'); return client.getMetadata()?.opencodeRewind }, + flush:async () => true, isIdle:() => true, + sourceCheckpoint:() => initial.state.session.metadata.opencodeHistoryCheckpoint, + sourceIndexes:() => ({ local1:0, local2:1 }), requestsFromPreviousWorkerCannotRun:() => false } + const rewind = new OpenCodeRewind(options) + try { + expect(await rewind.execute(initial.operation)).toMatchObject({ success:false, outcome:'unknown' }) + const failed = inspect() + const intent = rewind.readIntent()! + const backup = readFileSync(intent.backupPath, 'utf8') + expect(gate.isBlocked()).toBe(true) + expect(intent.pendingRequest).toBe(false) + const recoveryGate = reconstructed ? new OpenCodeRuntimeGate() : gate + const recovery = reconstructed ? new OpenCodeRewind({ ...options, gate:recoveryGate, + workerId:'replacement', previousWorkerCannotRun:() => true }) : rewind + const result = await recovery.recover(failed.session.metadata.opencodeRewind) + const after = inspect() + expect(result).toMatchObject({ success:false, outcome:'rejected', error:'Native source is unchanged' }) + expect(failed.session.metadata.opencodeRewind.phase).toBe(fault === 'version-race' ? 'reserved' : 'unknown') + expect(persistedReports[0]?.result.error).toBe(fault === 'version-race' ? 'OpenCode rewind metadata version changed' : undefined) + expect(after.session.metadata.opencodeRewind.phase).toBe('rejected') + expect(after.history).toEqual(initial.state.history) + expect(failed.history).toEqual(initial.state.history) + expect(after.invalidations).toEqual([]) + expect(nativeRequest.mock.calls.filter(([, init]) => init?.method === 'POST')).toEqual([]) + expect(recovery.readIntent()?.phase).toBe('finalized') + expect(readFileSync(intent.backupPath, 'utf8')).toBe(backup) + expect(recoveryGate.isBlocked()).toBe(false) + const release = recoveryGate.enterRuntime() + release() + } finally { client.close() } + }, 15_000) + } + + it('catches up a new row below the boundary seq after invocation-ordered Hub rewind', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const hubModule = (path: string) => JSON.stringify(new URL(`../../../hub/src/${path}`, import.meta.url).href) + const source = `import { Store } from ${hubModule('store/index.ts')}; + import { SyncEngine } from ${hubModule('sync/syncEngine.ts')}; + import { RpcRegistry } from ${hubModule('socket/rpcRegistry.ts')}; + const store = new Store(':memory:'); + const engine = new SyncEngine(store, {}, new RpcRegistry(), { broadcast() {} }); + const checkpoint = { sessionId: 'native', messageIds: ['u1', 'u2', 'u3'], + userMessageIds: ['u1', 'u2', 'u3'], localMessageIds: [] }; + const session = engine.getOrCreateSession('ordered-catchup', { path: '/tmp', host: 'test', flavor: 'opencode', + opencodeSessionId: 'native', opencodeWorkerId: 'worker', opencodeWorkerProcess: { workerId: 'worker', pid: 4321, startMarker: 'worker-generation' }, opencodeHistoryCheckpoint: checkpoint, + conversationHistoryIndexes: { one: 0, two: 1, three: 2 }, + capabilities: { conversationHistory: { rewindToMessage: true } } }, null, 'default'); + engine.handleSessionAlive({ sid: session.id, time: Date.now(), mode: 'remote' }); + const at = Date.now() - 10000; + const user = text => ({ role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'webapp' } }); + const first = store.messages.addMessage(session.id, user('retained'), 'one', undefined, at); + store.messages.markMessagesInvoked(session.id, ['one'], at); + store.messages.addMessage(session.id, user('later scheduled'), 'three', at + 3000, at + 1000); + const boundary = store.messages.addMessage(session.id, user('boundary scheduled'), 'two', at + 2000, at + 1500); + store.messages.markMessagesInvoked(session.id, ['two'], at + 2000); + store.messages.markMessagesInvoked(session.id, ['three'], at + 3000); + const oldTail = store.messages.addMessage(session.id, { role: 'agent', content: { type: 'text', text: 'old tail' } }, + undefined, undefined, at + 4000); + engine.rpcGateway.rewindConversation = async (_id, { opencodeRewind: operation }) => { + const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) }; + engine.reportOpenCodeRewind(session.id, 'default', { operation, phase: 'prepared', ...hashes }, store.sessions.getSession(session.id).metadataVersion); + engine.reportOpenCodeRewind(session.id, 'default', { operation, phase: 'applied', ...hashes, + checkpoint: { ...checkpoint, messageIds: ['u1'], userMessageIds: ['u1'] }, indexes: { one: 0 } }, store.sessions.getSession(session.id).metadataVersion); + return { success: true }; + }; + const result = await engine.rewindConversation(session.id, 'default', 'two'); + const retained = store.messages.getAllMessages(session.id); + const pending = store.messages.addMessage(session.id, user('new disconnected input'), 'new-input'); + const current = store.sessions.getSession(session.id); + const messages = engine.getDeliverableMessagesAfter(session.id, { afterSeq: 0, limit: 200, now: Date.now() }); + console.log(JSON.stringify({ result, first, boundary, oldTail, retained, pending, metadata: current.metadata, + metadataVersion: current.metadataVersion, messages })); + engine.stop(); store.close();` + const result = spawnSync('bun', ['--eval', source], { encoding: 'utf8', timeout: 15_000 }) + expect(result.status, result.stderr).toBe(0) + const hub = JSON.parse(result.stdout.trim().split('\n').at(-1)!) + expect(hub.result).toEqual({ type: 'success' }) + expect(hub.retained.map((row: { id: string }) => row.id)).toEqual([hub.first.id]) + expect(hub.pending.seq).toBeLessThan(hub.boundary.seq) + expect(hub.metadata.opencodeRewind.cutoffSeq).toBe(hub.boundary.seq) + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => + url.endsWith('/messages') ? { data: { messages: hub.messages.filter((row: { seq: number }) => row.seq > config.params!.afterSeq) } } + : { data: { session: { metadataVersion: hub.metadataVersion, metadata: hub.metadata } } }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + triggerIncomingUserMessage(socket, { id: hub.oldTail.id, seq: hub.oldTail.seq, text: 'old tail', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), expect.anything())) + await vi.waitFor(() => expect((client as unknown as { backfillInFlight: Promise | null }).backfillInFlight).toBeNull()) + expect(received.mock.calls.map(([, id]) => id)).toEqual(['new-input']) + } finally { client.close() } + }) + + it('does not reissue an evicted invoked postcommit row from durable Hub recovery backfill', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const database = join(mkdtempSync(join(tmpdir(), 'api-rewind-replay-')), 'hub.db') + const hubModule = (path: string) => JSON.stringify(new URL(`../../../hub/src/${path}`, import.meta.url).href) + const runHub = (body: string) => { + const source = `import { Store } from ${hubModule('store/index.ts')}; + import { Database } from 'bun:sqlite'; + import { registerSessionHandlers } from ${hubModule('socket/handlers/cli/sessionHandlers.ts')}; + import { SyncEngine } from ${hubModule('sync/syncEngine.ts')}; + import { RpcRegistry } from ${hubModule('socket/rpcRegistry.ts')}; + const database = ${JSON.stringify(database)}; ${body}` + const result = spawnSync('bun', ['--eval', source], { encoding: 'utf8', timeout: 15_000 }) + expect(result.status, result.stderr).toBe(0) + return JSON.parse(result.stdout.trim().split('\n').at(-1)!) + } + const initial = runHub(` + const store = new Store(database); + const session = store.sessions.getOrCreateSession('rewind-replay', + { path: '/tmp', host: 'test', flavor: 'opencode' }, null, 'default'); + for (let n = 0; n < 9; n++) store.messages.addMessage(session.id, + { role: 'agent', content: { type: 'text', text: 'old-' + n } }); + const oldTail = store.messages.getAllMessages(session.id).at(-1); + store.messages.truncateOpenCodeRewind(session.id, 3, store.messages.getAllMessages(session.id).find(row => row.seq === 3).id); + const user = text => ({ role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'webapp' } }); + const invoked = store.messages.addMessage(session.id, user('invoked-X'), 'invoked-X'); + const missed = store.messages.addMessage(session.id, user('missed-Y'), 'missed-Y'); + const live = Array.from({ length: 300 }, (_, n) => store.messages.addMessage(session.id, + { role: 'agent', content: { type: 'text', text: 'later-' + n } })); + store.close(); + console.log(JSON.stringify({ sessionId: session.id, oldTail, invoked, missed, live })); + `) + const response = deferred<{ messages: typeof initial.live }>() + const committed = { path: '/tmp', host: 'test', flavor: 'opencode' as const, opencodeRewind: { + operationId: 'eviction-recovery', nativeSessionId: 'native', workerId: 'worker', requestedLocalId: 'removed', + nativeMessageId: 'native-removed', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 9, + reservationVersion: 2, sourceTranscriptHash: 'a'.repeat(64), phase: 'committed' as const + } } + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => { + if (!url.endsWith('/messages')) return { data: { session: { metadataVersion: 2, metadata: committed } } } + const result = await response.promise + return { data: { messages: result.messages.filter((m: { seq: number }) => m.seq > config.params!.afterSeq).slice(0, 200) } } + }) + const client = new ApiSessionClient('token', createSession({ id: initial.sessionId, metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + const queue = new MessageQueue2(() => 'plain') + queue.onBatchConsumed = ids => client.emitMessagesConsumed(ids) + client.onUserMessage((message, localId) => queue.push(message.content.text, {}, localId)) + const issued: string[] = [] + await Promise.resolve() + socket.trigger('update', { body: { t: 'new-message', message: initial.oldTail } }) + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 2, value: committed } } }) + socket.trigger('update', { body: { t: 'new-message', message: initial.invoked } }) + try { + expect(initial.live.length).toBeGreaterThan(256) + const first = await queue.waitForMessagesAndGetAsString() + expect(first?.items.map(item => item.localId)).toEqual(['invoked-X']) + issued.push(...first!.items.map(item => item.localId!)) + const ack = socket.emitted.find(event => event.event === 'messages-consumed')?.args[0] + expect(ack).toMatchObject({ sid: initial.sessionId, localIds: ['invoked-X'] }) + const persisted = runHub(` + const store = new Store(database); + const session = store.sessions.getSession(${JSON.stringify(initial.sessionId)}); + const handlers = new Map(); + const socket = { on(event, handler) { handlers.set(event, handler); return this; }, + to() { return { emit() {} }; } }; + registerSessionHandlers(socket, { store, + resolveSessionAccess: () => ({ ok: true, value: session }), emitAccessError() {} }); + handlers.get('messages-consumed')(${JSON.stringify(ack)}); + store.close(); + const reopened = new Store(database); + const probeDb = new Database(database); + const probe = probeDb.query('SELECT invoked_at, delivery_state FROM messages WHERE session_id = ? AND local_id = ?') + .get(session.id, 'invoked-X'); + probeDb.close(); + const engine = new SyncEngine(reopened, {}, new RpcRegistry(), { broadcast() {} }); + const messages = []; + let cursor = 0; + while (true) { + const page = engine.getDeliverableMessagesAfter(session.id, { afterSeq: cursor, limit: 200, now: Date.now() }); + messages.push(...page); + if (page.length < 200) break; + cursor = page.at(-1).seq; + } + engine.stop(); reopened.close(); + console.log(JSON.stringify({ probe, messages })); + `) + expect(persisted.probe).toMatchObject({ delivery_state: 'queued', invoked_at: expect.any(Number) }) + expect(persisted.messages.find((m: { localId: string }) => m.localId === 'invoked-X')) + .toMatchObject({ invokedAt: persisted.probe.invoked_at }) + expect(persisted.messages.find((m: { localId: string }) => m.localId === 'missed-Y')) + .toMatchObject({ invokedAt: null }) + // Durable invocation/ACK precedes the later live burst that evicts X. + for (const message of initial.live) socket.trigger('update', { body: { t: 'new-message', message } }) + expect((client as unknown as { incomingFilter: { seenIds: Set } }) + .incomingFilter.seenIds.has(initial.invoked.id)).toBe(false) + response.resolve(persisted) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 0, limit: 200 } }))) + await vi.waitFor(() => expect((client as unknown as { backfillInFlight: Promise | null }) + .backfillInFlight).toBeNull()) + expect(queue.size()).toBeGreaterThan(0) + const catchup = await queue.waitForMessagesAndGetAsString() + issued.push(...catchup!.items.map(item => item.localId!)) + expect(issued.filter(id => id === 'invoked-X')).toHaveLength(1) + expect(issued.filter(id => id === 'missed-Y')).toHaveLength(1) + expect(catchup?.items.map(item => item.localId)).toEqual(['missed-Y']) + } finally { response.resolve({ messages: [] }); client.close() } + }) + + describe('HAPI7-CURSOR-R2 invocation contract', () => { + const committed = { path: '/tmp', host: 'test', flavor: 'opencode' as const, opencodeRewind: { + operationId: 'invocation-contract', nativeSessionId: 'native', workerId: 'worker', requestedLocalId: 'removed', + nativeMessageId: 'native-removed', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 9, + reservationVersion: 2, sourceTranscriptHash: 'a'.repeat(64), phase: 'committed' as const + } } + const user = (id: string, seq: number, invokedAt?: number | null) => ({ + id, seq, createdAt: seq, localId: id, ...(invokedAt === undefined ? {} : { invokedAt }), + content: { role: 'user', content: { type: 'text', text: id }, meta: { sentFrom: 'webapp' } } + }) + + it.each([false, true])('uses invocation proof only during rewind recovery (%s)', async recovery => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const metadata = recovery ? committed : { path: '/tmp', host: 'test', flavor: 'claude' as const } + const agent = { id: 'agent-output', seq: 6, createdAt: 6, localId: null, invokedAt: 123, + content: { role: 'agent', content: { type: 'text', text: 'history event' } } } + const messages = [user('invoked-zero', 3, 0), user('uninvoked', 4, null), user('legacy', 5), agent] + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => + url.endsWith('/messages') + ? { data: { messages: messages.filter(m => m.seq > config.params!.afterSeq) } } + : { data: { session: { metadataVersion: 2, metadata } } }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: metadata.flavor } })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + const output = vi.fn() + client.onUserMessage(received) + client.on('message', output) + await Promise.resolve() + triggerIncomingUserMessage(socket, { id: 'initial', seq: 2, text: 'local history', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(output).toHaveBeenCalledWith(agent.content)) + expect(received.mock.calls.map(([, id]) => id)).toEqual(recovery + ? ['uninvoked', 'legacy'] : ['invoked-zero', 'uninvoked', 'legacy']) + } finally { client.close() } + }) + + it('advances past an invoked-only recovery page without enqueueing or repeating it', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const messages = [user('already-invoked', 3, 1)] + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => + url.endsWith('/messages') + ? { data: { messages: messages.filter(m => m.seq > config.params!.afterSeq) } } + : { data: { session: { metadataVersion: 2, metadata: committed } } }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + await Promise.resolve() + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old local tail', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 0, limit: 200 } }))) + await vi.waitFor(() => expect((client as unknown as { backfillInFlight: Promise | null }) + .backfillInFlight).toBeNull()) + expect(received).not.toHaveBeenCalled() + axiosHarness.get.mockClear() + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 3, limit: 200 } }))) + expect(received).not.toHaveBeenCalled() + } finally { client.close() } + }) + }) + + describe('HAPI7-CURSOR-R1 unscanned recovery floor', () => { + const metadata = (operationId = 'floor-a', cutoffSeq = 3) => ({ + path: '/tmp', host: 'test', flavor: 'opencode' as const, + opencodeRewind: { + operationId, nativeSessionId: 'native', workerId: 'worker', requestedLocalId: 'removed', + nativeMessageId: 'native-removed', cutoffSeq, sourceEpoch: 0, sourceMaxSeq: 9, + reservationVersion: 2, sourceTranscriptHash: 'a'.repeat(64), phase: 'committed' as const + } + }) + const prompt = (id: string, seq: number) => ({ id, seq, createdAt: seq, localId: id, + content: { role: 'user', content: { type: 'text', text: id }, meta: { sentFrom: 'webapp' } } }) + const settled = async (client: ApiSessionClient) => { + await vi.waitFor(() => expect((client as unknown as { backfillInFlight: Promise | null }) + .backfillInFlight).toBeNull()) + } + + it.each(['old message request', 'reconnect metadata'] as const)( + 'keeps queued3 below live4 while awaiting %s', async held => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const old = deferred<{ data: { messages: unknown[] } }>() + const meta = deferred<{ data: { session: { metadataVersion: number; metadata: ReturnType } } }>() + const rows = [prompt('queued3', 3), prompt('live4', 4)] + let metaReads = 0 + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => { + if (!url.endsWith('/messages')) { + if (++metaReads === 1 && held === 'reconnect metadata') return await meta.promise + return { data: { session: { metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } } } } + } + if (config.params!.afterSeq === 9) return await old.promise + return { data: { messages: rows.filter(m => m.seq > config.params!.afterSeq) } } + }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + await Promise.resolve() // Finish initial-connect continuation before disconnecting. + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old tail', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + if (held === 'old message request') { + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 9, limit: 200 } }))) + } else { + await vi.waitFor(() => expect(metaReads).toBe(1)) + expect(axiosHarness.get.mock.calls.filter(([url]) => String(url).endsWith('/messages'))).toHaveLength(0) + } + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 2, value: metadata() } } }) + socket.trigger('update', { body: { t: 'new-message', message: rows[1] } }) + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 3, value: metadata() } } }) + old.resolve({ data: { messages: [prompt('removed-old-suffix', 10)] } }) + meta.resolve({ data: { session: { metadataVersion: 2, metadata: metadata() } } }) + await vi.waitFor(() => expect(received).toHaveBeenCalledWith(expect.anything(), 'queued3')) + expect(received).toHaveBeenCalledTimes(2) + expect(received.mock.calls.some(([, id]) => id === 'removed-old-suffix')).toBe(false) + socket.trigger('update', { body: { t: 'new-message', message: rows[0] } }) + socket.trigger('update', { body: { t: 'new-message', message: rows[1] } }) + expect(received).toHaveBeenCalledTimes(2) + await settled(client) + } finally { + old.resolve({ data: { messages: [] } }) + meta.resolve({ data: { session: { metadataVersion: 3, metadata: metadata() } } }) + client.close() + } + } + ) + + it('starts repair on live committed metadata without an old query or another reconnect', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const rows = [prompt('queued3', 3), prompt('live4', 4)] + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => + url.endsWith('/messages') + ? { data: { messages: rows.filter(m => m.seq > config.params!.afterSeq) } } + : { data: { session: { metadataVersion: 3, metadata: metadata() } } }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + await Promise.resolve() // No leftover initial-connect backfill in this live-only case. + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old tail', sentFrom: 'cli' }) + try { + expect(axiosHarness.get).not.toHaveBeenCalled() + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 2, value: metadata() } } }) + socket.trigger('update', { body: { t: 'new-message', message: rows[1] } }) + await vi.waitFor(() => expect(received).toHaveBeenCalledWith(expect.anything(), 'queued3')) + await settled(client) + expect(received).toHaveBeenCalledTimes(2) + expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 0, limit: 200 } })) + const reads = axiosHarness.get.mock.calls.length + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 3, value: metadata() } } }) + socket.trigger('update', { body: { t: 'new-message', message: rows[0] } }) + expect(received).toHaveBeenCalledTimes(2) + expect(axiosHarness.get.mock.calls.length).toBe(reads) + } finally { client.close() } + }) + + it('starts the newer recovery epoch after a superseded old request rejects', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const held = deferred<{ data: { messages: unknown[] } }>() + const rows = [prompt('queued3', 3), prompt('live4', 4)] + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => { + if (!url.endsWith('/messages')) return { data: { session: { metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } } } } + if (config.params!.afterSeq === 9) return await held.promise + return { data: { messages: rows.filter(m => m.seq > config.params!.afterSeq) } } + }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + await Promise.resolve() + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old tail', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 9, limit: 200 } }))) + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 2, value: metadata() } } }) + socket.trigger('update', { body: { t: 'new-message', message: rows[1] } }) + held.reject(new Error('superseded request failed')) + await vi.waitFor(() => expect(received).toHaveBeenCalledWith(expect.anything(), 'queued3')) + await settled(client) + expect(received).toHaveBeenCalledTimes(2) + expect(axiosHarness.get.mock.calls.filter(([url]) => String(url).endsWith('/messages')) + .map(([, config]) => config.params.afterSeq)).toEqual([9, 0]) + } finally { held.resolve({ data: { messages: [] } }); client.close() } + }) + + it.each(['failed', 'interrupted'] as const)( + 'does not raise an earlier floor when a newer rewind follows a %s scan', async outcome => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + let current = metadata() + let version = 2 + let reads = 0 + const first = deferred<{ data: { messages: unknown[] } }>() + const rows: ReturnType[] = [] + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => { + if (!url.endsWith('/messages')) return { data: { session: { metadataVersion: version, metadata: current } } } + if (++reads === 1) return await first.promise + return { data: { messages: rows.filter(m => m.seq > config.params!.afterSeq) } } + }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + await Promise.resolve() + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old tail', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(reads).toBe(1)) + // The first response snapshot predates these queued rows. + rows.push(prompt('queued3', 3), prompt('live4', 4)) + socket.trigger('update', { body: { t: 'new-message', message: rows[1] } }) + if (outcome === 'interrupted') { + socket.connected = false + socket.trigger('disconnect', 'transport close') + first.resolve({ data: { messages: [] } }) + } else { + first.reject(new Error('transient backfill failure')) + } + await settled(client) + socket.connected = false + socket.trigger('disconnect', 'transport close') + current = metadata('floor-b', 5) + version = 4 + expect(await client.refreshMetadata()).toBe(true) + version = 5 + expect(await client.refreshMetadata()).toBe(true) + axiosHarness.get.mockClear() + socket.triggerConnect() + await vi.waitFor(() => expect(received).toHaveBeenCalledWith(expect.anything(), 'queued3')) + await settled(client) + expect(received).toHaveBeenCalledTimes(2) + expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 0, limit: 200 } })) + axiosHarness.get.mockClear() + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 4, limit: 200 } }))) + expect(received).toHaveBeenCalledTimes(2) + } finally { first.resolve({ data: { messages: [] } }); client.close() } + } + ) + + it('keeps the earlier floor when a newer reserved rewind suppresses a response', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const held = deferred<{ data: { messages: unknown[] } }>() + const rows = [prompt('queued3', 3), prompt('live4', 4)] + let reads = 0 + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => { + if (!url.endsWith('/messages')) return { data: { session: { metadataVersion: 2, metadata: metadata() } } } + if (++reads === 1) return await held.promise + return { data: { messages: rows.filter(m => m.seq > config.params!.afterSeq) } } + }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + await Promise.resolve() + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old tail', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(reads).toBe(1)) + socket.trigger('update', { body: { t: 'new-message', message: rows[1] } }) + const next = metadata('floor-b', 5) + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 3, value: { + ...next, opencodeRewind: { ...next.opencodeRewind, phase: 'reserved' } + } } } }) + // Hub's durable pending-operation gate may return no deliverable + // rows. That is not evidence that the old prefix was drained. + held.resolve({ data: { messages: [] } }) + await settled(client) + expect(received).toHaveBeenCalledTimes(1) + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 4, value: next } } }) + await vi.waitFor(() => expect(received).toHaveBeenCalledWith(expect.anything(), 'queued3')) + await settled(client) + expect(received).toHaveBeenCalledTimes(2) + expect(axiosHarness.get.mock.calls.filter(([url]) => String(url).endsWith('/messages')) + .map(([, config]) => config.params.afterSeq)).toEqual([0, 0]) + } finally { held.resolve({ data: { messages: [] } }); client.close() } + }) + }) + + it.each([false, true])('delivers a queued lower-seq prompt exactly once on the same client after disconnected commit/consumption (recovery=%s)', async recoverCommitted => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + axiosHarness.post.mockReset() + const operation: OpenCodeRewindOperation = { + operationId: 'same-client-delivery', nativeSessionId: 'native', workerId: 'worker', + workerPid: process.pid, workerStartMarker: getProcessStartMarker(process.pid)!, + requestedLocalId: 'two', nativeMessageId: 'u2', cutoffSeq: 3, sourceEpoch: 0, + sourceMaxSeq: 9, reservationVersion: 2, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' + } + let authoritative = operation + let version = 2 + const metadata = () => ({ path: '/tmp', host: 'test', flavor: 'opencode' as const, + opencodeSessionId: 'native', opencodeRewind: authoritative }) + const queued: Array<{ id: string; seq: number; createdAt: number; localId: string; content: unknown }> = [] + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => { + if (url.endsWith('/messages')) return { data: { messages: queued.filter(m => m.seq > config.params!.afterSeq) } } + return { data: { session: { metadataVersion: version, metadata: metadata() } } } + }) + axiosHarness.post.mockImplementation(async (_url: string, { report }: { report: OpenCodeRewindReport }) => { + if (authoritative.phase !== 'committed') { + authoritative = { ...report.operation, phase: report.phase === 'applied' ? 'committed' : report.phase } + version += 1 + } + return { data: { operation: authoritative } } + }) + const client = new ApiSessionClient('token', createSession({ metadata: metadata(), metadataVersion: version })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old transcript', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + let rows = [{ id: 'u1', type: 'user' }, { id: 'a1', type: 'assistant' }, + { id: 'u2', type: 'user' }, { id: 'a2', type: 'assistant' }] + let staged: string | undefined + const nativeRequest = vi.fn(async (url: string, init?: RequestInit) => { + if (url.endsWith('/revert/stage')) { + staged = JSON.parse(init!.body as string).messageID + return Response.json({}) + } + if (url.endsWith('/revert/commit')) { + rows = rows.slice(0, 2) + staged = undefined + return new Response(null, { status: 204 }) + } + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }) + if (url.endsWith('/active')) return Response.json({ data: {} }) + if (url.endsWith('/inbox')) return Response.json({ data: [] }) + return Response.json({ data: { id: 'native', ...(staged ? { revert: { messageID: staged } } : {}) } }) + }) + let failConsumption = recoverCommitted + const consumeCommitted = vi.fn(async () => { + expect(socket.connected).toBe(false) + expect(authoritative.phase).toBe('committed') + // A runtime-consumption metadata update can carry the same committed + // receipt at a newer version, including recovery and duplicate use. + version += 1 + expect(await client.refreshMetadata()).toBe(true) + if (failConsumption) { + failConsumption = false + throw new Error('interrupted committed runtime consumption') + } + }) + const gate = new OpenCodeRuntimeGate() + const rewind = new OpenCodeRewind({ + directory: mkdtempSync(join(tmpdir(), 'api-rewind-delivery-')), hapiSessionId: client.sessionId, + workerId: 'worker', gate, baseUrl: 'http://synthetic-native', nativeSessionId: 'native', headers: {}, + request: nativeRequest, report: report => client.reportOpenCodeRewind(report), + getAuthoritativeOperation: async () => { if (!await client.refreshMetadata()) throw new Error('refresh failed'); return client.getMetadata()?.opencodeRewind }, + flush: async () => true, isIdle: () => true, + sourceCheckpoint: () => ({ sessionId: 'native', messageIds: ['u1', 'a1', 'u2', 'a2'], + userMessageIds: ['u1', 'u2'], localMessageIds: [] }), + sourceIndexes: () => ({ one: 0, two: 1 }), requestsFromPreviousWorkerCannotRun: () => true, + consumeCommitted + }) + try { + expect((await rewind.execute(operation)).success).toBe(!recoverCommitted) + expect(authoritative.phase).toBe('committed') + if (recoverCommitted) { + nativeRequest.mockClear() + expect((await rewind.recover(authoritative)).success).toBe(true) + expect(nativeRequest).not.toHaveBeenCalled() + } + expect(rewind.readIntent()?.phase).toBe('finalized') + expect(gate.isBlocked()).toBe(false) + expect(received).not.toHaveBeenCalled() + // The input is accepted only AFTER disconnected commit/consumption. + const prompt = { id: 'new-prompt', seq: 3, createdAt: 3, localId: 'new-input', + content: { role: 'user', content: { type: 'text', text: 'queued after commit' }, meta: { sentFrom: 'webapp' } } } + queued.push(prompt) + socket.triggerConnect() + await vi.waitFor(() => expect(received).toHaveBeenCalledWith( + expect.objectContaining({ content: { type: 'text', text: 'queued after commit' } }), 'new-input')) + expect(received).toHaveBeenCalledTimes(1) + triggerIncomingUserMessage(socket, { id: 'later', seq: 6, text: 'postcommit progress', sentFrom: 'webapp' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + // Committed recovery after progress stays terminal: the finalized + // journal is released without re-consumption (the runner's entry + // reconciliation owns history refresh), so delivery continues + // without resetting to the old cutoff. + expect((await rewind.recover(authoritative)).success).toBe(true) + axiosHarness.get.mockClear() + socket.triggerConnect() + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 6, limit: 200 } }))) + socket.trigger('update', { body: { t: 'new-message', message: prompt } }) + triggerIncomingUserMessage(socket, { id: 'retained-scheduled', seq: 1, text: 'mature scheduled', sentFrom: 'webapp' }) + triggerIncomingUserMessage(socket, { id: 'retained-scheduled', seq: 1, text: 'mature scheduled', sentFrom: 'webapp' }) + expect(received).toHaveBeenCalledTimes(3) + // Consumption ran during execute plus (recovery=true) the applied- + // journal recovery; post-progress recovery is terminal and does + // not re-consume. + expect(consumeCommitted).toHaveBeenCalledTimes(recoverCommitted ? 2 : 1) + } finally { client.close() } + }) + + it.each(['live update', 'reconnect refresh', 'metadata acknowledgement'] as const)( + 'backfills an immediate prompt below the old cursor after committed rewind (%s)', async commitDelivery => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const metadata = { path: '/tmp', host: 'test', flavor: 'opencode' as const } + const committed = { ...metadata, opencodeRewind: { + operationId: 'rewind-delivery', nativeSessionId: 'native', workerId: 'worker', + requestedLocalId: 'removed-turn', nativeMessageId: 'native-removed', + cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 9, reservationVersion: 2, + sourceTranscriptHash: 'a'.repeat(64), phase: 'committed' as const + } } + let version = 2 + const prompt = { id: 'post-rewind-prompt', seq: 3, createdAt: 3, localId: 'new-prompt', + content: { role: 'user', content: { type: 'text', text: 'queued during disconnect' }, + meta: { sentFrom: 'webapp' } } } + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => { + if (url.endsWith('/messages')) { + return { data: { messages: config.params!.afterSeq < prompt.seq ? [prompt] : [] } } + } + return { data: { session: { metadataVersion: version, metadata: committed } } } + }) + const client = new ApiSessionClient('token', createSession({ metadata, metadataVersion: 1 })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old local tail', sentFrom: 'cli' }) + if (commitDelivery === 'live update') { + socket.trigger('update', { body: { t: 'update-session', metadata: { version, value: committed } } }) + } else if (commitDelivery === 'metadata acknowledgement') { + socket.emitWithAckImpl = async event => event === 'update-metadata' + ? { result: 'success', version, metadata: committed } : {} + client.updateMetadata(meta => ({ ...meta, hostPid: 42 })) + expect(await client.flushMetadata()).toBe(true) + } + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(received).toHaveBeenCalledWith( + expect.objectContaining({ content: { type: 'text', text: 'queued during disconnect' } }), 'new-prompt')) + expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 0, limit: 200 } })) + // The same committed tombstone in later metadata must not + // repeatedly rewind the cursor or erase ID deduplication. + version = 3 + socket.trigger('update', { body: { t: 'update-session', metadata: { version, value: committed } } }) + socket.trigger('update', { body: { t: 'new-message', message: prompt } }) + expect(received).toHaveBeenCalledTimes(1) + triggerIncomingUserMessage(socket, { id: 'later', seq: 6, text: 'later prompt', sentFrom: 'webapp' }) + axiosHarness.get.mockClear() + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 6, limit: 200 } }))) + expect(received).toHaveBeenCalledTimes(2) + } finally { client.close() } + } + ) + + it.each(['reserved', 'prepared', 'unknown', 'rejected'] as const)( + 'does not rewind the delivery cursor for a noncommitted operation (%s)', async phase => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const metadata = { path: '/tmp', host: 'test', flavor: 'opencode' as const, opencodeRewind: { + operationId: 'not-committed', nativeSessionId: 'native', workerId: 'worker', + requestedLocalId: 'removed', nativeMessageId: 'native-removed', cutoffSeq: 3, + sourceEpoch: 0, sourceMaxSeq: 9, reservationVersion: 2, + sourceTranscriptHash: 'a'.repeat(64), phase + } } + axiosHarness.get.mockImplementation(async (url: string) => url.endsWith('/messages') + ? { data: { messages: [] } } : { data: { session: { metadataVersion: 2, metadata } } }) + const client = new ApiSessionClient('token', createSession({ metadataVersion: 1, + metadata: { path: '/tmp', host: 'test', flavor: 'opencode' } })) + const socket = socketHarness.sockets[0] + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old tail', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 9, limit: 200 } }))) + } finally { client.close() } + } + ) + + it.each([1, 201])('restarts an in-flight old-cursor backfill without losing postcommit progress (%s queued)', async queuedCount => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockReset() + const metadata = { path: '/tmp', host: 'test', flavor: 'opencode' as const } + const pending = deferred<{ data: { messages: unknown[] } }>() + const prompts = Array.from({ length: queuedCount }, (_, index) => ({ + id: `new-after-rewind-${index}`, seq: index + 3, createdAt: index + 3, localId: `new-prompt-${index}`, + content: { role: 'user', content: { type: 'text', text: `new retained history ${index}` }, meta: { sentFrom: 'webapp' } } + })) + axiosHarness.get.mockImplementation(async (url: string, config: { params?: { afterSeq: number } }) => { + if (!url.endsWith('/messages')) return { data: { session: { metadataVersion: 1, metadata } } } + if (config.params!.afterSeq === 9) return await pending.promise + return { data: { messages: prompts.filter(m => m.seq > config.params!.afterSeq).slice(0, 200) } } + }) + const client = new ApiSessionClient('token', createSession({ metadata, metadataVersion: 1 })) + const socket = socketHarness.sockets[0] + const received = vi.fn() + client.onUserMessage(received) + triggerIncomingUserMessage(socket, { id: 'old-tail', seq: 9, text: 'old tail', sentFrom: 'cli' }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + try { + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: 9, limit: 200 } }))) + // A second reconnect must join the old request, not start another + // high-cursor backfill while that response is still outstanding. + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + await vi.waitFor(() => expect(axiosHarness.get.mock.calls.filter(([url]) => !String(url).endsWith('/messages'))).toHaveLength(2)) + expect(axiosHarness.get.mock.calls.filter(([url]) => String(url).endsWith('/messages'))).toHaveLength(1) + const committed = { + ...metadata, opencodeRewind: { + operationId: 'rewind-in-flight', nativeSessionId: 'native', workerId: 'worker', + requestedLocalId: 'removed', nativeMessageId: 'native-removed', cutoffSeq: 3, + sourceEpoch: 0, sourceMaxSeq: 9, reservationVersion: 2, + sourceTranscriptHash: 'a'.repeat(64), phase: 'committed' as const + } + } + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 2, value: committed } } }) + const progressSeq = queuedCount + 20 + triggerIncomingUserMessage(socket, { id: 'postcommit-progress', seq: progressSeq, + text: 'live postcommit progress', sentFrom: 'webapp' }) + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 3, value: committed } } }) + pending.resolve({ data: { messages: [{ ...prompts[0], id: 'deleted-old-response', seq: 10, + localId: 'removed-prompt', content: { ...prompts[0].content, + content: { type: 'text', text: 'deleted stale response' } } }] } }) + await vi.waitFor(() => expect(received).toHaveBeenCalledTimes(queuedCount + 1)) + expect(received).toHaveBeenCalledWith(expect.objectContaining({ + content: { type: 'text', text: 'new retained history 0' } }), 'new-prompt-0') + expect(received.mock.calls.some(([, id]) => id === 'removed-prompt')).toBe(false) + // ID duplicates stay rejected, and the next reconnect starts at the + // live progress cursor rather than the retained cutoff or old9. + socket.trigger('update', { body: { t: 'new-message', message: prompts[0] } }) + expect(received).toHaveBeenCalledTimes(queuedCount + 1) + axiosHarness.get.mockClear() + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalledWith(expect.stringContaining('/messages'), + expect.objectContaining({ params: { afterSeq: progressSeq, limit: 200 } }))) + } finally { pending.resolve({ data: { messages: [] } }); client.close() } + }) + it.each([true, false])('replays explicitly marked native queue input only for shared sessions (%s)', shared => { socketHarness.sockets.length = 0 const client = new ApiSessionClient('token', createSession({ @@ -950,6 +1856,21 @@ describe('IncomingMessageFilter (HAPI Bot R3 finding #1)', () => { expect(filter.cursorSeq()).toBe(11) }) + it('rewinds only the sequence cursor and preserves seen IDs, including an empty retained prefix', () => { + const filter = new IncomingMessageFilter() + filter.accept({ id: 'old-tail', seq: 9 }) + filter.rewindCursor(2) + expect(filter.cursorSeq()).toBe(2) + expect(filter.accept({ id: 'old-tail', seq: 9 })).toBe(false) + expect(filter.accept({ id: 'new-prompt', seq: 3 })).toBe(true) + filter.rewindCursor(8) + expect(filter.cursorSeq()).toBe(3) + filter.rewindCursor(0) + expect(filter.cursorSeq()).toBe(0) + expect(filter.accept({ id: 'first-new-turn', seq: 1 })).toBe(true) + expect(filter.accept({ id: 'new-prompt', seq: 3 })).toBe(false) + }) + it('bounds the seen-id set to the configured capacity (LRU eviction)', () => { const filter = new IncomingMessageFilter(3) filter.accept({ id: 'a', seq: 1 }) @@ -987,6 +1908,84 @@ describe('IncomingMessageFilter (HAPI Bot R3 finding #1)', () => { }) }) +describe('strict OpenCode rewind metadata and socket entry', () => { + type StrictReader = { readRewindMetadata(): Promise<{ metadata: NonNullable; version: number } | null> }; + it('returns the parsed equal-version REST snapshot itself without rewriting the equal-version cache', async () => { + const cached = { path: '/cached', host: 'test', name: 'cached' }; + const authoritative = { path: '/fresh', host: 'test', name: 'fresh' }; + const client = new ApiSessionClient('test-token', createSession({ metadataVersion: 10, metadata: cached })); + try { + axiosHarness.get.mockResolvedValue({ data: { session: { metadataVersion: 10, metadata: authoritative } } }); + expect(await (client as unknown as StrictReader).readRewindMetadata()).toEqual({ metadata: authoritative, version: 10 }); + expect(client.getMetadata()).toMatchObject(cached); + } finally { client.close(); } + }); + + it('rejects null, malformed, stale and failed strict metadata snapshots', async () => { + const client = new ApiSessionClient('test-token', createSession({ metadataVersion: 10, metadata: { path: '/cached', host: 'test' } })); + try { + for (const session of [{ metadataVersion: 11, metadata: null }, { metadataVersion: 11, metadata: { titleLocked: true } }, + { metadataVersion: 9, metadata: { path: '/stale', host: 'test' } }]) { + axiosHarness.get.mockResolvedValue({ data: { session } }); + expect(await (client as unknown as StrictReader).readRewindMetadata()).toBeNull(); + } + axiosHarness.get.mockRejectedValue(new Error('offline')); + expect(await (client as unknown as StrictReader).readRewindMetadata()).toBeNull(); + } finally { client.close(); } + }); + + it('rejects a snapshot superseded by a socket version while REST is in flight', async () => { + const client = new ApiSessionClient('test-token', createSession({ metadataVersion: 10, metadata: { path: '/old', host: 'test' } })); + const socket = socketHarness.sockets.at(-1)!; const held = deferred(); + try { + axiosHarness.get.mockReturnValue(held.promise); + const reading = (client as unknown as StrictReader).readRewindMetadata(); + socket.trigger('update', { body: { t: 'update-session', metadata: { version: 12, value: { path: '/new', host: 'test' } } } }); + held.resolve({ data: { session: { metadataVersion: 11, metadata: { path: '/stale', host: 'test' } } } }); + expect(await reading).toBeNull(); + expect(client.getMetadata()).toMatchObject({ path: '/new' }); + } finally { client.close(); } + }); + + it('does not invent authoritative absence or materialize a lazy pending session', async () => { + const materialize = vi.fn(async () => createSession()); + const client = new ApiSessionClient('test-token', createSession(), { materialize }); + try { + axiosHarness.get.mockClear(); + expect(await client.readRewindMetadata()).toBeNull(); + expect(axiosHarness.get).not.toHaveBeenCalled(); + expect(materialize).not.toHaveBeenCalled(); + } finally { client.close(); } + }); + + it('emits a synchronous opt-in reconnect start before REST and queued acknowledgement', async () => { + const client = new ApiSessionClient('test-token', createSession({ metadataVersion: 1, metadata: { path: '/fixture', host: 'test' } })); + const socket = socketHarness.sockets.at(-1)!; const held = deferred(); const gate = new OpenCodeRuntimeGate(); + await new Promise(resolve => setImmediate(resolve)); + const queue = new MessageQueue2<{ permissionMode: 'default' }>(() => 'mode'); const acknowledged = vi.fn(); + queue.beforeDequeue = () => { gate.enterRuntime(); }; queue.onBatchConsumed = acknowledged; + let fence: symbol | undefined; const order: string[] = []; + const rpcConnect = vi.spyOn(client.rpcHandlerManager, 'onSocketConnect').mockImplementation(() => { order.push('rpc'); }); + client.on('connection-start', () => { order.push('start'); fence = (gate as unknown as { acquireEntryFence(): symbol }).acquireEntryFence(); }); + client.on('connected', () => { order.push('connected'); }); + try { + axiosHarness.get.mockImplementation(() => { order.push('REST'); return held.promise; }); + queue.push('queued input', { permissionMode: 'default' }, 'queued'); socket.triggerConnect(); + expect(order[0]).toBe('start'); expect(gate.isBlocked()).toBe(true); + expect(order.indexOf('rpc')).toBeGreaterThan(order.indexOf('start')); + expect(order.indexOf('REST')).toBeGreaterThan(order.indexOf('rpc')); + await expect(queue.waitForMessagesAndGetAsString()).rejects.toThrow('reconciliation'); + expect(acknowledged).not.toHaveBeenCalled(); expect(queue.size()).toBe(1); + expect(order).not.toContain('connected'); + } finally { + held.resolve({ data: { session: { metadataVersion: 1, metadata: { path: '/fixture', host: 'test' } } } }); + rpcConnect.mockRestore(); + if (fence) (gate as unknown as { releaseEntryFence(token: symbol): void }).releaseEntryFence(fence); + queue.close(); client.close(); + } + }); +}); + describe('explicit title action metadata refresh', () => { it('observes user lock changes without rolling back a newer socket metadata version', async () => { const client = new ApiSessionClient('test-token', createSession({ diff --git a/cli/src/api/apiSession.ts b/cli/src/api/apiSession.ts index fbb1a205..43fd4a8a 100644 --- a/cli/src/api/apiSession.ts +++ b/cli/src/api/apiSession.ts @@ -129,6 +129,13 @@ export class IncomingMessageFilter { return this.lastSeenSeq } + /** Keep ID deduplication, but stop skipping sequence numbers reused after rewind. */ + rewindCursor(lastRetainedSeq: number): void { + if (this.lastSeenSeq !== null) { + this.lastSeenSeq = Math.min(this.lastSeenSeq, lastRetainedSeq) + } + } + /** Returns true if this message should be processed; false to drop as a duplicate. */ accept(message: { id?: string | null; seq?: number | null }): boolean { const id = typeof message.id === 'string' && message.id.length > 0 ? message.id : null @@ -255,6 +262,10 @@ export class ApiSessionClient extends EventEmitter { private cancelQueuedMessageCallback: ((localId: string) => QueueCancelResult | Promise) | null = null private retryQueuedMessageCallback: ((localId: string) => boolean | Promise) | null = null private readonly incomingFilter = new IncomingMessageFilter() + private reconciledRewindOperationId: string | undefined + private incomingCursorEpoch = 0 + private pendingRewindBackfill: { operationId: string; epoch: number; afterSeq: number } | null = null + private rewindBackfillScheduled = false private backfillInFlight: Promise | null = null private needsBackfill = false private hasConnectedOnce = false @@ -297,6 +308,7 @@ export class ApiSessionClient extends EventEmitter { this.token = token this.sessionId = session.id this.metadata = session.metadata + this.reconcileCommittedRewindCursor(this.metadata) this.metadataVersion = session.metadataVersion this.agentState = session.agentState this.agentStateVersion = session.agentStateVersion @@ -340,6 +352,7 @@ export class ApiSessionClient extends EventEmitter { this.socket.on('connect', () => { logger.debug('Socket connected successfully') + this.emit('connection-start') this.awaitingMaterializedConnection = false this.rpcHandlerManager.onSocketConnect(this.socket) const isReconnect = this.hasConnectedOnce @@ -354,6 +367,7 @@ export class ApiSessionClient extends EventEmitter { : Promise.resolve() void afterMeta.finally(() => { void this.backfillIfNeeded() + if (this.state === 'active' && this.allowReconnect) this.emit('connected') }) this.hasConnectedOnce = true this.reconnectHandler?.() @@ -551,6 +565,11 @@ export class ApiSessionClient extends EventEmitter { return this.state === 'pending' || this.state === 'materializing' } + /** Whether hub reads are served live: a null read then is a transient miss, not a waiting socket. */ + isActive(): boolean { + return this.state === 'active' + } + private isClosed(): boolean { return this.state === 'closed' } @@ -605,6 +624,7 @@ export class ApiSessionClient extends EventEmitter { || !hasSameJsonValue(materialized.agentState, latestAgentState) this.metadata = materialized.metadata + this.reconcileCommittedRewindCursor(this.metadata) this.metadataVersion = materialized.metadataVersion this.agentState = materialized.agentState this.agentStateVersion = materialized.agentStateVersion @@ -842,13 +862,57 @@ export class ApiSessionClient extends EventEmitter { } try { await this.backfillMessages() - this.needsBackfill = false + this.needsBackfill = this.pendingRewindBackfill !== null } catch (error) { logger.debug('[API] Backfill failed', error) this.needsBackfill = true } } + private reconcileCommittedRewindCursor(metadata: Metadata | null): void { + const operation = metadata?.opencodeRewind + if (operation?.phase !== 'committed') { + this.scheduleRewindBackfill() + return + } + // A same-process reconnect must see prompts queued while disconnected, + // even if Hub truncation reused a sequence below the old cursor. Repeated + // metadata for the committed tombstone must not rewind later deliveries. + if (operation.operationId !== this.reconciledRewindOperationId) { + this.reconciledRewindOperationId = operation.operationId + // Invocation order can remove rows below the boundary's insertion + // seq too. New inputs may reuse those slots, so rescan from zero. + this.incomingFilter.rewindCursor(0) + // A newer rewind cannot retire an earlier, still-unscanned prefix. + const previousFloor = this.pendingRewindBackfill?.afterSeq + const cursor = this.incomingFilter.cursorSeq() + const afterSeq = previousFloor === undefined ? cursor : Math.min(previousFloor, cursor ?? previousFloor) + this.incomingCursorEpoch += 1 + this.pendingRewindBackfill = afterSeq === null ? null : { + operationId: operation.operationId, epoch: this.incomingCursorEpoch, afterSeq + } + } + this.scheduleRewindBackfill() + } + + private scheduleRewindBackfill(): void { + if (!this.pendingRewindBackfill || this.state !== 'active' || this.rewindBackfillPaused() + || this.rewindBackfillScheduled) return + this.needsBackfill = true + this.rewindBackfillScheduled = true + queueMicrotask(() => { + this.rewindBackfillScheduled = false + if (this.pendingRewindBackfill && this.state === 'active' && !this.rewindBackfillPaused()) { + void this.backfillIfNeeded() + } + }) + } + + private rewindBackfillPaused(): boolean { + const phase = this.metadata?.opencodeRewind?.phase + return !this.socket?.connected || phase === 'reserved' || phase === 'prepared' || phase === 'unknown' + } + /** * Apply a remote metadata snapshot (Socket.IO update-session or reconnect * REST reconcile). Advances metadataVersion and emits hub-archived when @@ -865,6 +929,7 @@ export class ApiSessionClient extends EventEmitter { const wasHubArchived = this.metadata?.lifecycleState === 'archived' && this.metadata?.archivedBy === 'hub' this.metadata = parsed.data + this.reconcileCommittedRewindCursor(this.metadata) this.metadataVersion = version // #1910: hub may archive via metadata when KillSession cannot reach // this CLI. Stop reconnect immortality and let runners exit instead @@ -886,6 +951,17 @@ export class ApiSessionClient extends EventEmitter { } /** Refresh Hub-owned metadata before an explicit tool action or after reconnect. */ + async reportOpenCodeRewind(report: import('@hapi/protocol/apiTypes').OpenCodeRewindReport): Promise { + const before = await this.readRewindMetadata() + if (!before) throw new Error('Cannot reconcile Hub rewind reservation') + const response = await axios.post(`${configuration.apiUrl}/cli/sessions/${encodeURIComponent(this.sessionId)}/opencode-rewind`, + { report, expectedVersion: before.version }, { headers: buildHubRequestHeaders({ Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json' }), timeout: 15_000 }) + const { OpenCodeRewindSchema } = await import('@hapi/protocol/schemas') + const operation = OpenCodeRewindSchema.parse(response.data?.operation) + if (!await this.readRewindMetadata()) throw new Error('Cannot confirm authoritative rewind state') + return operation + } + async refreshMetadata(): Promise { try { const response = await axios.get( @@ -904,6 +980,7 @@ export class ApiSessionClient extends EventEmitter { if (session.metadataVersion >= this.metadataVersion) { this.applyRemoteMetadata(session.metadataVersion, session.metadata) } + this.scheduleRewindBackfill() return true } catch (error) { logger.debug('[API] Session metadata reconcile failed', error) @@ -911,22 +988,47 @@ export class ApiSessionClient extends EventEmitter { } } + /** Read the exact validated REST snapshot for rewind admission decisions. */ + async readRewindMetadata(): Promise<{ metadata: Metadata; version: number } | null> { + if (this.state !== 'active') return null + try { + const response = await axios.get(`${configuration.apiUrl}/cli/sessions/${encodeURIComponent(this.sessionId)}`, { + headers: buildHubRequestHeaders({ Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json' }), + timeout: 15_000 + }) + const session = response.data?.session + if (this.state !== 'active' || !session || !Number.isSafeInteger(session.metadataVersion) || session.metadataVersion < this.metadataVersion + || session.metadata === null) return null + const parsed = MetadataSchema.safeParse(session.metadata) + if (!parsed.success) return null + if (session.metadataVersion > this.metadataVersion) this.applyRemoteMetadata(session.metadataVersion, parsed.data) + return { metadata: parsed.data, version: session.metadataVersion } + } catch (error) { + logger.debug('[API] Strict rewind metadata reconcile failed', error) + return null + } + } + private async backfillMessages(): Promise { if (this.backfillInFlight) { await this.backfillInFlight return } - const startSeq = this.incomingFilter.cursorSeq() + const startSeq = this.pendingRewindBackfill?.afterSeq ?? this.incomingFilter.cursorSeq() if (startSeq === null) { logger.debug('[API] Skipping backfill because no last-seen message sequence is available') return } const limit = 200 + let attemptedEpoch = this.incomingCursorEpoch const run = async () => { let cursor = startSeq + let cursorEpoch = this.incomingCursorEpoch while (true) { + if (this.pendingRewindBackfill && this.rewindBackfillPaused()) return + attemptedEpoch = cursorEpoch const response = await axios.get( `${configuration.apiUrl}/cli/sessions/${encodeURIComponent(this.sessionId)}/messages`, { @@ -939,6 +1041,13 @@ export class ApiSessionClient extends EventEmitter { } ) + if (this.pendingRewindBackfill && this.rewindBackfillPaused()) return + if (cursorEpoch !== this.incomingCursorEpoch) { + cursor = this.pendingRewindBackfill?.afterSeq ?? this.incomingFilter.cursorSeq() ?? 0 + cursorEpoch = this.incomingCursorEpoch + continue + } + const parsed = CliMessagesResponseSchema.safeParse(response.data) if (!parsed.success) { throw apiValidationError('Invalid /cli/sessions/:id/messages response', response) @@ -956,17 +1065,40 @@ export class ApiSessionClient extends EventEmitter { maxSeq = message.seq } } + if (this.pendingRewindBackfill && message.invokedAt != null + && UserMessageSchema.safeParse(message.content).success) { + // Hub's queued delivery state also includes durable + // invocation ACKs. A backward rewind scan can outlive + // the bounded ID LRU; never enqueue that input again. + this.incomingFilter.accept({ id: message.id, seq: message.seq }) + continue + } this.handleIncomingMessage(message) } + if (this.pendingRewindBackfill && this.rewindBackfillPaused()) return + if (cursorEpoch !== this.incomingCursorEpoch) { + cursor = this.pendingRewindBackfill?.afterSeq ?? this.incomingFilter.cursorSeq() ?? 0 + cursorEpoch = this.incomingCursorEpoch + continue + } + + // Revisited IDs stay deduplicated, but their scanned positions + // still count as progress after a rewind reset the cursor. + if (this.pendingRewindBackfill) this.incomingFilter.accept({ seq: maxSeq }) const observedSeq = this.incomingFilter.cursorSeq() ?? maxSeq - const nextCursor = Math.max(maxSeq, observedSeq) + // Do not let a live high-seq delivery skip unread pages in the + // post-rewind prefix. The filter still retains that progress. + const nextCursor = this.pendingRewindBackfill !== null + ? maxSeq + : Math.max(maxSeq, observedSeq) if (nextCursor <= cursor) { logger.debug('[API] Backfill stopped due to non-advancing cursor', { cursor, maxSeq, observedSeq }) + if (this.pendingRewindBackfill) throw new Error('Rewind backfill did not advance') break } @@ -975,10 +1107,18 @@ export class ApiSessionClient extends EventEmitter { break } } + if (this.pendingRewindBackfill?.epoch === cursorEpoch && !this.rewindBackfillPaused()) { + this.pendingRewindBackfill = null + } } this.backfillInFlight = run().finally(() => { this.backfillInFlight = null + // A failed old request must not consume the wake for a newer + // committed epoch. Retry that new epoch once, not the failed one. + if (this.pendingRewindBackfill && this.pendingRewindBackfill.epoch !== attemptedEpoch) { + this.scheduleRewindBackfill() + } }) await this.backfillInFlight @@ -1359,6 +1499,7 @@ export class ApiSessionClient extends EventEmitter { const wasHubArchived = this.metadata?.lifecycleState === 'archived' && this.metadata?.archivedBy === 'hub' this.metadata = value + this.reconcileCommittedRewindCursor(this.metadata) if ( !wasHubArchived && value?.lifecycleState === 'archived' diff --git a/cli/src/claude/registerKillSessionHandler.test.ts b/cli/src/claude/registerKillSessionHandler.test.ts index 3edba234..f09dfe1e 100644 --- a/cli/src/claude/registerKillSessionHandler.test.ts +++ b/cli/src/claude/registerKillSessionHandler.test.ts @@ -1,6 +1,14 @@ import { describe, expect, it, vi } from 'vitest' -import { RPC_METHODS } from '@hapi/protocol/rpcMethods' +import { getSessionStopPreparationMethod, RPC_METHODS } from '@hapi/protocol/rpcMethods' import { registerKillSessionHandler } from './registerKillSessionHandler' +import { monotonicTimeMs } from '@/utils/time' + +vi.mock('@/utils/time', async (original) => ({ + ...await original(), monotonicTimeMs: () => Date.now() +})) +vi.mock('@/utils/process', async (original) => ({ + ...await original(), getProcessStartMarker: () => 'generation' +})) // tiann/hapi#914: the KillSession RPC is the authoritative "user-terminated" // signal because the hub only sends it when the operator clicks Archive in @@ -48,6 +56,62 @@ describe('registerKillSessionHandler (tiann/hapi#914)', () => { expect(lifecycle.cleanupAndExit).toHaveBeenCalled() }) + it('keeps the process alive after prepare-only ACK so the runner can collect and terminate its tree', async () => { + const registry = makeRegistry() + const beforeKill = vi.fn(async () => {}) + const cleanupAndExit = vi.fn(async () => {}) + registerKillSessionHandler(registry as never, { beforeKill, cleanupAndExit }) + const result = await registry.handlers.get(RPC_METHODS.KillSession)?.({ prepareOnly: true, + preparationLease: { id: 'fixture', expiresAt: monotonicTimeMs() + 30000 } }) as { success: boolean } + expect(result.success).toBe(true) + expect(beforeKill).toHaveBeenCalledOnce() + expect(cleanupAndExit).not.toHaveBeenCalled() + }) + + it('registers an immutable machine/PID preparation alias with generation validation', async () => { + const registry = makeRegistry() + const beforeKill = vi.fn(async () => true) + const cleanupAndExit = vi.fn(async () => {}) + const lifecycle = { machineId: 'machine/one', beforeKill, cleanupAndExit } + registerKillSessionHandler(registry as never, lifecycle) + lifecycle.machineId = 'changed-metadata-machine' + const handler = registry.handlers.get(getSessionStopPreparationMethod('machine/one', process.pid))! + expect(handler).toBeDefined() + const request = { prepareOnly: true, expectedMachineId: 'machine/one', expectedPid: process.pid, + expectedProcessStartMarker: 'generation', preparationLease: { id: 'fixture', expiresAt: monotonicTimeMs() + 30000 } } + const response = await handler(request) as { success: boolean; machineId: string; pid: number } + expect(response).toMatchObject({ success: true, machineId: 'machine/one', pid: process.pid }) + expect(beforeKill).toHaveBeenCalledOnce() + expect(cleanupAndExit).not.toHaveBeenCalled() + await expect(handler({ ...request, expectedProcessStartMarker: 'other-generation' })).rejects.toThrow('generation') + await expect(handler({ ...request, expectedMachineId: 'other-machine' })).rejects.toThrow('exact preparation target') + await expect(handler({ ...request, prepareOnly: false })).rejects.toThrow('exact preparation target') + expect(beforeKill).toHaveBeenCalledOnce() + }) + + it('rejects unconfirmed drains and mismatched process targets before cleanup', async () => { + const registry = makeRegistry() + const cleanupAndExit = vi.fn(async () => {}) + const beforeKill = vi.fn(async () => false) + registerKillSessionHandler(registry as never, { beforeKill, cleanupAndExit }) + const handler = registry.handlers.get(RPC_METHODS.KillSession)! + await expect(handler({ prepareOnly: true, expectedPid: process.pid + 1, expectedProcessStartMarker: 'other' })).rejects.toThrow('generation') + expect(beforeKill).not.toHaveBeenCalled() + await expect(handler({ prepareOnly: true, preparationLease: { id: 'fixture', expiresAt: monotonicTimeMs() + 30000 } })).rejects.toThrow('not confirmed') + expect(cleanupAndExit).not.toHaveBeenCalled() + }) + + it('rejects locally without starting cleanup when the pre-kill drain rejects', async () => { + const registry = makeRegistry() + const cleanupAndExit = vi.fn(async () => {}) + registerKillSessionHandler(registry as never, { + cleanupAndExit, + beforeKill: async () => { throw new Error('drain unavailable') } + }) + await expect(registry.handlers.get(RPC_METHODS.KillSession)?.()).rejects.toThrow('drain unavailable') + expect(cleanupAndExit).not.toHaveBeenCalled() + }) + it('still works with the legacy `(cleanupAndExit: () => Promise)` call shape', async () => { // Back-compat: runAgentSession.ts passes a bare closure as the second // argument instead of a lifecycle object. The handler should not crash diff --git a/cli/src/claude/registerKillSessionHandler.ts b/cli/src/claude/registerKillSessionHandler.ts index 2b58291c..4d1bfa6b 100644 --- a/cli/src/claude/registerKillSessionHandler.ts +++ b/cli/src/claude/registerKillSessionHandler.ts @@ -1,10 +1,16 @@ import { RpcHandlerManager } from "@/api/rpc/RpcHandlerManager"; import { logger } from "@/lib"; -import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; +import { DEFAULT_RPC_TIMEOUT_MS, getSessionStopPreparationMethod, RPC_METHODS, type SessionStopPreparationLease } from '@hapi/protocol/rpcMethods'; import { getProcessStartMarker } from '@/utils/process'; +import { monotonicTimeMs } from '@/utils/time'; interface KillSessionRequest { - // No parameters needed + /** Runner owns process-tree termination after preparation is acknowledged. */ + prepareOnly?: boolean; + expectedPid?: number; + expectedProcessStartMarker?: string; + expectedMachineId?: string; + preparationLease?: SessionStopPreparationLease; } interface KillSessionResponse { @@ -14,6 +20,8 @@ interface KillSessionResponse { pid: number; /** Generation marker for `pid`; required before the runner will tree-kill it. */ processStartMarker?: string; + preparationLease?: SessionStopPreparationLease; + machineId?: string; } /** @@ -27,6 +35,10 @@ interface KillSessionResponse { export interface KillSessionLifecycle { cleanupAndExit: () => Promise; setArchiveReason?: (reason: string) => void; + /** Complete queued publications before the hub starts runner termination. */ + beforeKill?: (lease?: SessionStopPreparationLease) => Promise; + /** Immutable bootstrap identity, independent of later session metadata. */ + machineId?: string; } export function registerKillSessionHandler( @@ -40,6 +52,7 @@ export function registerKillSessionHandler( const lifecycle: KillSessionLifecycle = typeof lifecycleOrCleanup === 'function' ? { cleanupAndExit: lifecycleOrCleanup } : lifecycleOrCleanup; + const machineId = lifecycle.machineId; const exitFromHubArchive = () => { logger.debug('Hub-archived metadata received; exiting CLI'); @@ -47,8 +60,21 @@ export function registerKillSessionHandler( void lifecycle.cleanupAndExit(); }; - rpcHandlerManager.registerHandler(RPC_METHODS.KillSession, async () => { + const killSession = async (request: KillSessionRequest): Promise => { logger.debug('Kill session request received'); + if (request?.expectedMachineId !== undefined && request.expectedMachineId !== machineId) { + throw new Error('Session machine does not match shutdown target'); + } + const processStartMarker = getProcessStartMarker(process.pid) ?? undefined; + if (request?.expectedPid !== undefined && (request.expectedPid !== process.pid + || !request.expectedProcessStartMarker || request.expectedProcessStartMarker !== processStartMarker)) { + throw new Error('Session process generation does not match shutdown target'); + } + const lease = request?.prepareOnly === true ? request.preparationLease : undefined; + if (request?.prepareOnly === true && (!lease?.id || !Number.isFinite(lease.expiresAt) + || lease.expiresAt <= monotonicTimeMs() || lease.expiresAt > monotonicTimeMs() + DEFAULT_RPC_TIMEOUT_MS)) { + throw new Error('Session shutdown preparation lease is invalid or expired'); + } // tiann/hapi#914: stamp the archive reason from the RPC path so the // default in `runnerLifecycle.ts` can be reassigned away from @@ -57,19 +83,37 @@ export function registerKillSessionHandler( // those archives now stay labelled `'Hub restart'` (the new default). lifecycle.setArchiveReason?.('User terminated'); + // The hub follows this ACK with StopSession, whose graceful process + // deadline can be shorter than a healthy publication drain. + if (await lifecycle.beforeKill?.(lease) === false || (lease && lease.expiresAt <= monotonicTimeMs())) { + throw new Error('Session shutdown preparation was not confirmed'); + } + // This will start the cleanup process - void lifecycle.cleanupAndExit(); + if (request?.prepareOnly !== true) void lifecycle.cleanupAndExit(); // Include pid + start marker so archive can ask the runner to verify // this exact process generation exited (#1910) — not a reused PID. - const processStartMarker = getProcessStartMarker(process.pid) ?? undefined; return { success: true, - message: 'Killing hapi CLI process', + message: request?.prepareOnly === true ? 'Session shutdown prepared' : 'Killing hapi CLI process', pid: process.pid, ...(processStartMarker ? { processStartMarker } : {}), + ...(lease ? { preparationLease: lease } : {}), + ...(machineId ? { machineId } : {}), }; - }); + }; + rpcHandlerManager.registerHandler(RPC_METHODS.KillSession, killSession); + if (machineId && lifecycle.beforeKill) { + rpcHandlerManager.registerHandler( + getSessionStopPreparationMethod(machineId, process.pid), async (request) => { + if (request?.prepareOnly !== true || request.expectedMachineId !== machineId || request.expectedPid !== process.pid) { + throw new Error('Process-scoped shutdown requires the exact preparation target'); + } + return killSession(request); + } + ); + } // #1910: when archive lands as hub metadata (KillSession unreachable), // still exit instead of reconnecting forever. diff --git a/cli/src/opencode/conversationHistory.test.ts b/cli/src/opencode/conversationHistory.test.ts new file mode 100644 index 00000000..4713caa2 --- /dev/null +++ b/cli/src/opencode/conversationHistory.test.ts @@ -0,0 +1,334 @@ +import { describe, expect, it, vi } from 'vitest'; +import { OpencodeConversationHistory } from './conversationHistory'; +import type { FetchLike } from './utils/opencodeCompactBridge'; + +const noSignal = new AbortController().signal; + +describe('OpenCode v2 history transport', () => { + const context = () => ({ + baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_v2', + headers: { authorization: 'Basic fixture' } + }); + + it('probes authenticated docs and forks current using the v2 response envelope', async () => { + const fetchImpl: FetchLike = vi.fn(async (url, init) => { + expect(init?.headers).toMatchObject({ authorization: 'Basic fixture' }); + if (init?.method === 'POST') { + expect(url).toBe('http://127.0.0.1:48273/api/session/ses_v2/fork'); + expect(JSON.parse(init.body as string)).toEqual({}); + return jsonResponse({ data: { id: 'ses_child' } }); + } + if (url.includes('/message?')) return jsonResponse({ data: [], cursor: {} }); + return jsonResponse({ paths: { '/api/session/{sessionID}/fork': { post: {} } } }); + }); + const history = new OpencodeConversationHistory(context, fetchImpl); + await history.probeCapabilities(); + expect(history.getCapabilitiesForMetadata()?.conversationHistory?.forkAtMessage).toBe(true); + await expect(history.fork()).resolves.toEqual({ nativeSessionId: 'ses_child' }); + }); + + it('counts all paginated user messages and resolves an exclusive before boundary on a later page', async () => { + const fetchImpl: FetchLike = vi.fn(async (url, init) => { + expect(init?.headers).toMatchObject({ authorization: 'Basic fixture' }); + if (init?.method === 'POST') { + expect(JSON.parse(init.body as string)).toEqual({ before: 'msg_second' }); + return jsonResponse({ data: { id: 'ses_child' } }); + } + const parsed = new URL(url); + expect(parsed.pathname).toBe('/api/session/ses_v2/message'); + expect(parsed.searchParams.has('type')).toBe(false); + if (parsed.searchParams.has('cursor')) { + expect(parsed.searchParams.get('cursor')).toBe('page-2'); + expect(parsed.searchParams.has('order')).toBe(false); + return jsonResponse({ data: [{ id: 'msg_second', type: 'user', text: 'second' }], cursor: {} }); + } + expect(parsed.searchParams.get('order')).toBe('asc'); + return jsonResponse({ data: [{ id: 'msg_first', type: 'user', text: 'first' }], cursor: { next: 'page-2' } }); + }); + const history = new OpencodeConversationHistory(context, fetchImpl); + await history.reconcileHistory(undefined, { allowUnobservedAppend: true }); + await expect(history.getNativeUserMessageCount()).resolves.toBe(2); + history.rememberPromptIndex('local-second', 1); + await expect(history.fork('local-second')).resolves.toEqual({ nativeSessionId: 'ses_child' }); + }); + + it('fails closed on pagination failure and never posts a guessed boundary', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ data: [], cursor: { next: 'repeated' } })); + const history = new OpencodeConversationHistory(context, fetchImpl); + await expect(history.getNativeUserMessageCount()).resolves.toBeNull(); + history.rememberPromptIndex('local-one', 0); + await expect(history.fork('local-one')).rejects.toThrow('repeated a message cursor'); + expect(fetchImpl.mock.calls.every((call) => (call as unknown[])[1] && ((call as unknown[])[1] as RequestInit).method === 'GET')).toBe(true); + }); +}); + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' } + }); +} + +function createContext(baseUrl: string | null, sessionId: string | null) { + return () => ({ baseUrl, sessionId }); +} + +describe('OpencodeConversationHistory probeCapabilities', () => { + it('marks fork capabilities supported when the openapi doc contains the fork path', async () => { + const fetchImpl: FetchLike = vi.fn(async (url: string) => { + expect(url).toBe('http://127.0.0.1:48273/doc'); + return new Response('session/{id}/fork POST', { status: 200 }); + }); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await history.probeCapabilities(); + + const capabilities = history.getCapabilitiesForMetadata()?.conversationHistory; + expect(capabilities).toEqual({ forkCurrent: true, forkAtMessage: true }); + }); + + it('falls through to /openapi.json when /doc serves a 200 body without the fork path', async () => { + const fetchImpl: FetchLike = vi.fn(async (url: string) => { + if (url.endsWith('/doc')) return new Response('app shell', { status: 200 }); + expect(url).toBe('http://127.0.0.1:48273/openapi.json'); + return jsonResponse({ + paths: { + '/session/{id}/fork': { post: {} } + } + }); + }); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await history.probeCapabilities(); + + expect(history.getCapabilitiesForMetadata()?.conversationHistory?.forkAtMessage).toBe(true); + }); + + it('marks fork unsupported when the docs contain no fork path', async () => { + const fetchImpl: FetchLike = vi.fn(async () => jsonResponse({ paths: { '/session/{id}/message': { get: {} } } })); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await history.probeCapabilities(); + + expect(history.getCapabilitiesForMetadata()?.conversationHistory).toBeUndefined(); + await expect(history.fork()).rejects.toThrow(/not supported/); + }); + + it('gracefully hides all fork capabilities on network failure', async () => { + const fetchImpl: FetchLike = vi.fn(async () => { + throw new Error('ECONNREFUSED'); + }); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await expect(history.probeCapabilities()).resolves.toBeUndefined(); + expect(history.getCapabilitiesForMetadata()?.conversationHistory).toBeUndefined(); + }); + + it('falls back to /openapi.json when /doc returns 404', async () => { + const fetchImpl: FetchLike = vi.fn(async (url: string) => { + if (url.endsWith('/doc')) return new Response('not found', { status: 404 }); + expect(url).toBe('http://127.0.0.1:48273/openapi.json'); + return jsonResponse({ + paths: { + '/session/{sessionID}/fork': { post: {} } + } + }); + }); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await history.probeCapabilities(); + + const capabilities = history.getCapabilitiesForMetadata()?.conversationHistory; + expect(capabilities).toEqual({ forkCurrent: true, forkAtMessage: true }); + }); +}); + +describe('OpencodeConversationHistory.getNativeUserMessageCount', () => { + it('counts user messages from the native session', async () => { + const fetchImpl: FetchLike = vi.fn(async (url: string) => { + expect(url).toBe('http://127.0.0.1:48273/api/session/ses_1/message?limit=200&order=asc'); + return jsonResponse({ data: [ + { id: 'msg_1', type: 'user' }, + { id: 'msg_2', type: 'assistant' }, + { id: 'msg_3', type: 'user' } + ], cursor: {} }); + }); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await history.reconcileHistory(undefined, { allowUnobservedAppend: true }); + await expect(history.getNativeUserMessageCount()).resolves.toBe(2); + }); + + it('returns null on request failure instead of throwing', async () => { + const fetchImpl: FetchLike = vi.fn(async () => new Response('nope', { status: 500 })); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await expect(history.getNativeUserMessageCount()).resolves.toBeNull(); + }); +}); + +describe('OpencodeConversationHistory fork', () => { + it('forks the current session with an empty body and returns the native id', async () => { + const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => { + if (init?.method === 'GET') return jsonResponse({ data: [], cursor: {} }); + expect(url).toBe('http://127.0.0.1:48273/api/session/ses_1/fork'); + expect(init?.method).toBe('POST'); + expect(JSON.parse(init?.body as string)).toEqual({}); + return jsonResponse({ data: { id: 'ses_forked' } }); + }); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + const result = await history.fork(); + + expect(result).toEqual({ nativeSessionId: 'ses_forked' }); + expect(history.getCapabilitiesForMetadata()?.conversationHistory?.forkCurrent).toBe(true); + }); + + it('marks forkCurrent unsupported when the current fork request fails', async () => { + const fetchImpl: FetchLike = vi.fn(async () => new Response('nope', { status: 404 })); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await expect(history.fork()).rejects.toThrow(); + expect(history.getCapabilitiesForMetadata()?.conversationHistory).toBeUndefined(); + }); + + it('selects the right user message by prompt index and forks at that message', async () => { + const messages = [ + { id: 'msg_u0', type: 'user' }, + { id: 'msg_a0', type: 'assistant' }, + { id: 'msg_u1', type: 'user' }, + { id: 'msg_a1', type: 'assistant' }, + { id: 'msg_u2', type: 'user' } + ]; + let forkBody: unknown; + const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => { + if (init?.method === 'GET') { + expect(url).toBe('http://127.0.0.1:48273/api/session/ses_1/message?limit=200&order=asc'); + return jsonResponse({ data: messages, cursor: {} }); + } + forkBody = JSON.parse(init?.body as string); + expect(url).toBe('http://127.0.0.1:48273/api/session/ses_1/fork'); + return jsonResponse({ data: { id: 'ses_forked_at' } }); + }); + + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await history.reconcileHistory(undefined, { allowUnobservedAppend: true }); + history.rememberPromptIndex('local-second', 1); + + const result = await history.fork('local-second'); + + expect(forkBody).toEqual({ before: 'msg_u1' }); + expect(result).toEqual({ nativeSessionId: 'ses_forked_at' }); + const capabilities = history.getCapabilitiesForMetadata()?.conversationHistory; + expect(capabilities?.forkCurrent).toBe(true); + expect(capabilities?.forkAtMessage).toBe(true); + }); + + it('throws for a localId with no remembered prompt index', async () => { + const fetchImpl: FetchLike = vi.fn(); + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + + await expect(history.fork('local-unknown')).rejects.toThrow('No native history point for message local-unknown'); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('throws when historical fork is unsupported', async () => { + const fetchImpl: FetchLike = vi.fn(async () => jsonResponse({ paths: {} })); + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + await history.probeCapabilities(); + history.rememberPromptIndex('local-a', 0); + + await expect(history.fork('local-a')).rejects.toThrow('Historical fork is not supported'); + }); +}); + +describe('OpencodeConversationHistory guards', () => { + it.each([undefined, 'local-second'])('rejects current and historical forks after native identity replacement (%s)', async (localId) => { + const fetchImpl = vi.fn(async (_url: string, _init?: RequestInit) => jsonResponse({ data: [ + { id: 'msg_first', type: 'user' }, + { id: 'msg_new_assistant', type: 'assistant' }, + { id: 'msg_second', type: 'user' } + ], cursor: {} })); + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + history.restorePromptIndexes({ 'local-second': 1 }); + history.restoreCheckpoint({ sessionId: 'ses_1', messageIds: ['msg_first', 'msg_old_assistant', 'msg_second'], + userMessageIds: ['msg_first', 'msg_second'], localMessageIds: [] }); + await expect(history.fork(localId)).rejects.toThrow('diverged'); + expect(history.isDiverged()).toBe(true); + expect(history.getHistoryPoints()).toEqual({}); + expect(fetchImpl.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true); + }); + + it('reconciles expected remote prompt growth including automatic compaction', async () => { + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), + async () => jsonResponse({ data: [ + { id: 'msg_first', type: 'user' }, { id: 'msg_answer', type: 'assistant' }, + { id: 'msg_marker', type: 'user' }, { id: 'msg_continue', type: 'user' } + ], cursor: {} })); + history.restorePromptIndexes({ 'local-first': 0 }); + history.restoreCheckpoint({ sessionId: 'ses_1', messageIds: ['msg_first', 'msg_answer'], userMessageIds: ['msg_first'], localMessageIds: [] }); + await expect(history.reconcileHistory(undefined, { allowUnobservedAppend: true })).resolves.toBe(3); + expect(history.isDiverged()).toBe(false); + expect(history.getHistoryPoints()).toEqual({ 'local-first': true }); + expect(history.getCheckpoint()?.messageIds).toEqual(['msg_first', 'msg_answer', 'msg_marker', 'msg_continue']); + }); + + it('does not trust legacy numeric locators without an identity checkpoint', async () => { + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), + async () => jsonResponse({ data: [{ id: 'msg_unknown', type: 'user' }], cursor: {} })); + history.restorePromptIndexes({ 'local-old': 0 }); + await expect(history.reconcileHistory()).rejects.toThrow('diverged'); + expect(history.isDiverged()).toBe(true); + }); + + it.each([200, 404, 405])('never republishes capabilities from a late %i fork response after teardown', async (status) => { + let complete!: (response: Response) => void; + const fetchImpl: FetchLike = vi.fn(async (_url, init) => init?.method === 'GET' + ? jsonResponse({ data: [], cursor: {} }) : await new Promise((resolve) => { complete = resolve; })); + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + const publish = vi.fn(async () => {}); + history.setPublishCapabilities(publish); + const pending = history.fork(); + await vi.waitFor(() => expect(complete).toBeTypeOf('function')); + await history.disableFork(); + complete(jsonResponse({ data: { id: 'ses_late' } }, status)); + await expect(pending).rejects.toThrow(status === 200 ? 'teardown' : `(${status})`); + expect(history.getCapabilitiesForMetadata()?.conversationHistory).toBeUndefined(); + expect(publish).toHaveBeenCalledTimes(1); + }); + + it('does not issue a historical POST when teardown occurs during message lookup', async () => { + let complete!: (response: Response) => void; + const fetchImpl = vi.fn((_url: string, _init?: RequestInit) => new Promise((resolve) => { complete = resolve; })); + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + history.rememberPromptIndex('local-one', 0); + const pending = history.fork('local-one'); + await history.disableFork(); + complete(jsonResponse({ data: [{ id: 'msg_one', type: 'user' }], cursor: {} })); + await expect(pending).rejects.toThrow('teardown'); + expect(fetchImpl).toHaveBeenCalledTimes(1); + }); + + it('rejects fork while busy', async () => { + const fetchImpl: FetchLike = vi.fn(); + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), fetchImpl); + history.setBusy(true); + + await expect(history.fork()).rejects.toThrow('Session is busy'); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('rejects fork without context', async () => { + const fetchImpl: FetchLike = vi.fn(); + const history = new OpencodeConversationHistory(createContext(null, null), fetchImpl); + + await expect(history.fork()).rejects.toThrow('OpenCode session is not ready'); + }); + + it('restores prompt indexes from durable metadata and exposes them', async () => { + const history = new OpencodeConversationHistory(createContext('http://127.0.0.1:48273', 'ses_1'), vi.fn()); + history.restorePromptIndexes({ 'local-restored': 4 }); + expect(history.getHistoryIndexes()).toEqual({ 'local-restored': 4 }); + expect(history.getHistoryPoints()).toEqual({ 'local-restored': true }); + }); +}); \ No newline at end of file diff --git a/cli/src/opencode/conversationHistory.ts b/cli/src/opencode/conversationHistory.ts new file mode 100644 index 00000000..26569739 --- /dev/null +++ b/cli/src/opencode/conversationHistory.ts @@ -0,0 +1,368 @@ +import { + OPENCODE_CONVERSATION_HISTORY_INITIAL, + markSupported, + markUnsupported, + toConversationHistoryCapabilities, + type ConversationHistoryCapabilityStates +} from '@hapi/protocol/conversationHistory'; +import type { ForkConversationRpcResult } from '@hapi/protocol/apiTypes'; +import type { FetchLike } from './utils/opencodeCompactBridge'; + +type BunFetchInit = RequestInit & { timeout?: false }; + +type HistoryContext = { + baseUrl: string | null; + sessionId: string | null; + headers?: Record; +}; +type HistoryCheckpoint = NonNullable; +type NativeHistorySnapshot = { checkpoint: HistoryCheckpoint; conversationIds: string[]; v2Messages?: Record[] }; + +function isRouteMissing(error: unknown): boolean { + const message = error instanceof Error ? error.message : String(error); + return /\((404|405)\)/.test(message); +} + +function isObjectRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function asString(value: unknown): string | null { + return typeof value === 'string' && value.length > 0 ? value : null; +} + +const FORK_PATH_MARKERS = ['session/{sessionID}/fork', 'session/{id}/fork', 'session/:id/fork']; + +export class OpencodeConversationHistory { + private states: ConversationHistoryCapabilityStates = { ...OPENCODE_CONVERSATION_HISTORY_INITIAL }; + private readonly promptIndexByLocalId = new Map(); + private busy = false; + private rewindReady = false; + private nativeRewindSupported = false; + setRewindReady(ready: boolean): void { + this.rewindReady = ready; + } + + /** A native history major version without the v2 API supports no route: + * capabilities never publish and every fork call refuses locally. */ + declareUnsupported(): void { + this.nativeRewindSupported = false; + for (const key of ['forkCurrent', 'forkAtMessage', 'rewindToMessage'] as const) { + this.states = markUnsupported(this.states, key); + } + } + private disabled = false; + private checkpoint: HistoryCheckpoint | undefined; + private diverged = false; + private publishCapabilities: (() => Promise) | null = null; + + constructor( + private readonly getContext: () => HistoryContext, + fetchImpl?: FetchLike + ) { + this.fetchFn = fetchImpl ?? (async (url: string, init?: RequestInit) => { + const bunInit: BunFetchInit = { ...init, timeout: false } as BunFetchInit; + return await fetch(url, bunInit as RequestInit); + }); + } + + private readonly fetchFn: FetchLike; + + setPublishCapabilities(fn: () => Promise): void { + this.publishCapabilities = fn; + } + + /** Pushes current history points/indexes into session metadata (best-effort). */ + async publish(): Promise { + await this.publishCapabilities?.() + } + + /** Permanently hides fork affordances (e.g. after native/HAPI divergence). */ + async disableFork(): Promise { + this.disabled = true; + this.rewindReady = false; + this.states = markUnsupported(this.states, 'rewindToMessage'); + this.states = markUnsupported(markUnsupported(this.states, 'forkCurrent'), 'forkAtMessage'); + await this.publishCapabilities?.(); + } + + /** Drops all persisted locators (e.g. compaction reindexes native history). */ + clearPromptIndexes(): void { + this.promptIndexByLocalId.clear(); + this.checkpoint = undefined; + } + + setBusy(busy: boolean): void { + this.busy = busy; + } + + rememberPromptIndex(localId: string | undefined, promptIndex: number | null | undefined): void { + if (!localId || promptIndex == null || !Number.isInteger(promptIndex) || promptIndex < 0) return; + this.promptIndexByLocalId.set(localId, promptIndex); + } + + getCapabilitiesForMetadata() { + const conversationHistory = toConversationHistoryCapabilities(this.states); + // Temporary runtime admission/consumption is not a terminal native + // route verdict. Never override markUnsupported's native fence. + if (conversationHistory && (!this.rewindReady || !this.nativeRewindSupported || this.disabled)) delete conversationHistory.rewindToMessage; + if (conversationHistory && Object.keys(conversationHistory).length === 0) return undefined; + return conversationHistory ? { conversationHistory } : undefined; + } + + getHistoryPoints(): Record { + const points: Record = {}; + for (const localId of this.promptIndexByLocalId.keys()) { + points[localId] = true; + } + return points; + } + + getHistoryIndexes(): Record { + const indexes: Record = {}; + for (const [localId, promptIndex] of this.promptIndexByLocalId.entries()) { + indexes[localId] = promptIndex; + } + return indexes; + } + + restorePromptIndexes(indexes: Record | null | undefined): void { + if (!indexes) return; + for (const [localId, promptIndex] of Object.entries(indexes)) { + if (typeof localId !== 'string' || localId.length === 0) continue; + if (!Number.isInteger(promptIndex) || promptIndex < 0) continue; + this.promptIndexByLocalId.set(localId, promptIndex); + } + } + + restoreCheckpoint(checkpoint: HistoryCheckpoint | undefined): void { + this.checkpoint = checkpoint; + } + + getCheckpoint(): HistoryCheckpoint | undefined { + return this.checkpoint; + } + + isDiverged(): boolean { + return this.diverged; + } + + isDisabled(): boolean { + return this.disabled; + } + + async invalidateHistory(): Promise { + this.diverged = true; + this.clearPromptIndexes(); + await this.disableFork(); + } + + private async markDiverged(): Promise { + await this.invalidateHistory(); + throw new Error('OpenCode history diverged from the HAPI transcript'); + } + + async reconcileHistory(signal?: AbortSignal, options: { allowUnobservedAppend?: boolean } = {}): Promise { + if (this.disabled) throw new Error('Fork is not supported after launcher teardown'); + const { baseUrl, sessionId } = this.getContext(); + if (!baseUrl || !sessionId) throw new Error('OpenCode session is not ready'); + const { checkpoint: snapshot, conversationIds, v2Messages } = await this.readSnapshot(baseUrl, sessionId, + AbortSignal.any([AbortSignal.timeout(5_000), ...(signal ? [signal] : [])])); + if (this.disabled) throw new Error('Fork is not supported after launcher teardown'); + const currentIds = new Set(snapshot.messageIds); + const previousIds = new Set(this.checkpoint?.messageIds ?? []); + const observedIds = new Set(this.checkpoint?.localMessageIds ?? []); + if ((!this.checkpoint && this.promptIndexByLocalId.size > 0) + || (this.checkpoint && (this.checkpoint.sessionId !== sessionId + || this.checkpoint.localMessageIds === undefined + || this.checkpoint.localPublicationPending + || this.checkpoint.messageIds.some((id, index) => snapshot.messageIds[index] !== id) + || this.checkpoint.localMessageIds?.some((id) => !currentIds.has(id)) + || [...this.promptIndexByLocalId.values()].some((index) => index >= this.checkpoint!.userMessageIds.length))) + || (!options.allowUnobservedAppend && conversationIds.some((id) => !previousIds.has(id) && !observedIds.has(id)))) { + return await this.markDiverged(); + } + this.checkpoint = snapshot; + return snapshot.userMessageIds.length; + } + + async checkpointForkedSession(sessionId: string): Promise { + const { baseUrl } = this.getContext(); + if (!baseUrl || this.disabled) throw new Error('OpenCode session is not ready'); + const snapshot = await this.readSnapshot(baseUrl, sessionId, AbortSignal.timeout(5_000)); + if (this.disabled) throw new Error('Fork is not supported after launcher teardown'); + return snapshot.checkpoint; + } + + async probeCapabilities(signal?: AbortSignal): Promise { + if (this.disabled) return; + const { baseUrl, sessionId } = this.getContext(); + if (!baseUrl || !sessionId) return; + + try { + // `/openapi.json` serves an HTML app shell with HTTP 200 on some + // versions, so a marker miss must fall through to the next + // candidate rather than concluding "unsupported". + let forkSupported = false; + let rewindSupported = false; + for (const url of [`${baseUrl}/doc`, `${baseUrl}/openapi.json`]) { + let bodyText: string | null = null; + try { + bodyText = await this.fetchDocText(url, signal); + } catch { + // A missing/failing endpoint must not abort the probe — + // fall through to the next candidate. + continue; + } + if (bodyText !== null && FORK_PATH_MARKERS.some((marker) => bodyText.includes(marker))) { + forkSupported = true; + rewindSupported = bodyText.includes('/api/session/{sessionID}/revert/stage') + && bodyText.includes('/api/session/{sessionID}/revert/commit'); + break; + } + } + if (this.disabled) return; + this.nativeRewindSupported = rewindSupported; + this.states = forkSupported + ? markSupported(markSupported(this.states, 'forkCurrent'), 'forkAtMessage') + : markUnsupported(markUnsupported(this.states, 'forkCurrent'), 'forkAtMessage'); + } catch { + if (this.disabled) return; + this.nativeRewindSupported = false; + // Any network failure hides the capability rather than showing a broken affordance. + this.states = markUnsupported(markUnsupported(this.states, 'forkCurrent'), 'forkAtMessage'); + } + this.states = this.nativeRewindSupported ? markSupported(this.states, 'rewindToMessage') : markUnsupported(this.states, 'rewindToMessage'); + + // A torn-down launcher must not overwrite a successor's fresher state. + if (signal?.aborted) return; + await this.publishCapabilities?.(); + } + + private async fetchDocText(url: string, signal?: AbortSignal): Promise { + const response = await this.fetchFn(url, { + method: 'GET', + headers: this.getContext().headers, + signal: AbortSignal.any([AbortSignal.timeout(5_000), ...(signal ? [signal] : [])]) + }); + if (!response.ok) throw new Error(`GET ${url} failed (${response.status})`); + return await response.text(); + } + + async fork(messageLocalId?: string): Promise { + if (this.busy) throw new Error('Session is busy'); + if (this.disabled) throw new Error('Fork is not supported after launcher teardown'); + const { baseUrl, sessionId, headers } = this.getContext(); + if (!baseUrl || !sessionId) throw new Error('OpenCode session is not ready'); + + // A cached numeric position is meaningful only in the native history + // whose identities were observed. Revalidate before any native mutation. + if (messageLocalId && this.states.forkAtMessage === 'unsupported') { + throw new Error('Historical fork is not supported'); + } + if (!messageLocalId && this.states.forkCurrent === 'unsupported') throw new Error('Fork current is not supported'); + if (messageLocalId && !this.promptIndexByLocalId.has(messageLocalId)) { + throw new Error(`No native history point for message ${messageLocalId}`); + } + await this.reconcileHistory(); + + let messageID: string | undefined; + if (messageLocalId) { + if (this.states.forkAtMessage === 'unsupported') { + throw new Error('Historical fork is not supported'); + } + const targetPromptIndex = this.promptIndexByLocalId.get(messageLocalId); + if (targetPromptIndex == null) { + throw new Error(`No native history point for message ${messageLocalId}`); + } + messageID = this.checkpoint?.userMessageIds[targetPromptIndex]; + if (!messageID) throw new Error(`OpenCode has no user message at index ${targetPromptIndex}`); + } else if (this.states.forkCurrent === 'unsupported') { + throw new Error('Fork current is not supported'); + } + + try { + if (this.disabled) throw new Error('Fork is not supported after launcher teardown'); + const response = await this.fetchFn( + `${baseUrl}/api/session/${encodeURIComponent(sessionId)}/fork`, + { + method: 'POST', + headers: { ...headers, 'content-type': 'application/json' }, + body: JSON.stringify(messageID ? { before: messageID } : {}), + signal: AbortSignal.timeout(10_000) + } + ); + if (!response.ok) { + throw new Error(`OpenCode fork request failed (${response.status}): ${(await response.text().catch(() => '')).slice(0, 300)}`); + } + const data: unknown = await response.json().catch(() => null); + const session = isObjectRecord(data) ? data.data : data; + const nativeSessionId = asString(isObjectRecord(session) ? session.id : null); + if (!nativeSessionId) throw new Error('OpenCode fork did not return a session id'); + + if (this.disabled) throw new Error('Fork is not supported after launcher teardown'); + this.states = markSupported(this.states, 'forkCurrent'); + this.states = markSupported(this.states, 'forkAtMessage'); + await this.publishCapabilities?.(); + return { nativeSessionId }; + } catch (error) { + // Only a missing route hides the capability; transient network or + // server errors must not permanently disable an advertised fork. + // Both fork modes share this endpoint, so a 404/405 disables both. + if (!this.disabled && isRouteMissing(error)) { + this.states = markUnsupported( + markUnsupported(this.states, 'forkCurrent'), + 'forkAtMessage' + ); + await this.publishCapabilities?.(); + } + throw error; + } + } + + private async readSnapshot(baseUrl: string, sessionId: string, signal: AbortSignal): Promise { + const messages = await this.fetchV2Messages(baseUrl, sessionId, signal); + return { checkpoint: { sessionId, messageIds: messages.map((message) => message.id as string), + userMessageIds: messages.filter((message) => message.type === 'user').map((message) => message.id as string), localMessageIds: [] }, + conversationIds: messages.filter((message) => message.type === 'user' || message.type === 'assistant').map((message) => message.id as string), + v2Messages: messages }; + } + + /** Number of user messages already in the native session, or null when unknown. */ + async getNativeUserMessageCount(signal?: AbortSignal): Promise { + if (this.disabled) return null; + try { + return await this.reconcileHistory(signal); + } catch { + return null; + } + } + + private async fetchV2Messages(baseUrl: string, sessionId: string, signal: AbortSignal): Promise[]> { + const messages: Record[] = []; + const seen = new Set(); + let cursor: string | null = null; + do { + const query = new URLSearchParams({ limit: '200' }); + if (cursor) query.set('cursor', cursor); + else query.set('order', 'asc'); + const response = await this.fetchFn( + `${baseUrl}/api/session/${encodeURIComponent(sessionId)}/message?${query}`, + { method: 'GET', headers: this.getContext().headers, signal } + ); + if (!response.ok) throw new Error(`OpenCode message lookup failed (${response.status})`); + const data: unknown = await response.json(); + if (!isObjectRecord(data) || !Array.isArray(data.data)) throw new Error('OpenCode message list is not available'); + for (const entry of data.data) { + if (!isObjectRecord(entry) || !asString(entry.type) || !asString(entry.id)) { + throw new Error('OpenCode returned an invalid message'); + } + messages.push(entry); + } + cursor = isObjectRecord(data.cursor) ? asString(data.cursor.next) : null; + if (cursor && seen.has(cursor)) throw new Error('OpenCode repeated a message cursor'); + if (cursor) seen.add(cursor); + } while (cursor); + return messages; + } +} diff --git a/cli/src/opencode/localHistory.test.ts b/cli/src/opencode/localHistory.test.ts new file mode 100644 index 00000000..d209929c --- /dev/null +++ b/cli/src/opencode/localHistory.test.ts @@ -0,0 +1,368 @@ +import { describe, expect, it, vi } from 'vitest'; +import { EventEmitter } from 'node:events'; +import type { Metadata } from '@/api/types'; +import { observeLocalHistory, createLocalHistoryPublisher } from './localHistory'; +import { OpencodeConversationHistory } from './conversationHistory'; +import { monotonicTimeMs } from '@/utils/time'; + +vi.mock('@/utils/time', async (original) => ({ + ...await original(), monotonicTimeMs: () => Date.now() +})); + +const base: Metadata = { path: '/tmp/project', host: 'fixture', + capabilities: { conversationHistory: { forkCurrent: true } }, + opencodeHistoryCheckpoint: { sessionId: 'ses_1', messageIds: ['msg_c'], userMessageIds: ['msg_c'], localMessageIds: [] } }; + +function historyFor(metadata: Metadata, ids: string[]) { + const history = new OpencodeConversationHistory(() => ({ baseUrl: 'http://fixture', sessionId: 'ses_1' }), + async () => new Response(JSON.stringify({ data: ids.map((id) => ({ id, type: 'user' })), cursor: {} }))); + history.restoreCheckpoint(metadata.opencodeHistoryCheckpoint); + return history; +} + +describe('local publication identity observations', () => { + it('refuses unobserved native conversation growth after a publisher crash', async () => { + await expect(historyFor(base, ['msg_c', 'msg_unpublished']).reconcileHistory()).rejects.toThrow('diverged'); + }); + + it('does not trust a local publication that was not committed before the wrapper exited', async () => { + const pending = { ...base, opencodeHistoryCheckpoint: { ...base.opencodeHistoryCheckpoint!, + localMessageIds: ['msg_a'], localPublicationPending: true as const } }; + await expect(historyFor(pending, ['msg_c', 'msg_a']).reconcileHistory()).rejects.toThrow('diverged'); + }); + + it('detects local A -> undo A -> B even though the remote checkpoint prefix C survives', async () => { + const observedA = observeLocalHistory(base, 'ses_1', 'msg_a'); + const observedB = observeLocalHistory(observedA, 'ses_1', 'msg_b'); + expect(observedB.opencodeHistoryCheckpoint?.localMessageIds).toEqual(['msg_a', 'msg_b']); + const history = historyFor(observedB, ['msg_c', 'msg_b']); + await expect(history.reconcileHistory()).rejects.toThrow('diverged'); + expect(history.isDiverged()).toBe(true); + }); + + it('adopts append-only local publications and absorbs their observations into the new snapshot', async () => { + const a = observeLocalHistory(base, 'ses_1', 'msg_a'); + const b = observeLocalHistory(observeLocalHistory(a, 'ses_1', 'msg_a'), 'ses_1', 'msg_b'); + expect(b.opencodeHistoryCheckpoint?.localMessageIds).toEqual(['msg_a', 'msg_b']); + const history = historyFor(b, ['msg_c', 'msg_a', 'msg_b']); + await expect(history.reconcileHistory()).resolves.toBe(3); + expect(history.getCheckpoint()?.localMessageIds).toEqual([]); + expect(history.isDiverged()).toBe(false); + }); + + it('tracks local-only turns even when no remote checkpoint existed yet', async () => { + const a = observeLocalHistory({ path: '/tmp/project', host: 'fixture' }, 'ses_1', 'msg_a'); + const b = observeLocalHistory(a, 'ses_1', 'msg_b'); + await expect(historyFor(b, ['msg_b']).reconcileHistory()).rejects.toThrow('diverged'); + }); + + it.each([null, 'different-session'])('fails closed when the publication cannot be tied to the native session (%s)', (sessionId) => { + const observed = observeLocalHistory(base, sessionId, 'msg_a'); + expect(observed.conversationHistoryDiverged).toBe(true); + expect(observed.capabilities?.conversationHistory).toBeUndefined(); + expect(observed.opencodeHistoryCheckpoint).toBeUndefined(); + }); + + it('fails closed for content without a native message id and never clears persisted divergence', () => { + const unknown = observeLocalHistory(base, 'ses_1', null); + expect(unknown.conversationHistoryDiverged).toBe(true); + expect(observeLocalHistory(unknown, 'ses_1', 'msg_a')).toBe(unknown); + }); + + it('does not silently upgrade an older checkpoint whose local publications were not tracked', async () => { + const { localMessageIds, ...legacy } = base.opencodeHistoryCheckpoint!; + const old: Metadata = { ...base, opencodeHistoryCheckpoint: legacy }; + expect(observeLocalHistory(old, 'ses_1', 'msg_b').conversationHistoryDiverged).toBe(true); + await expect(historyFor(old, ['msg_c', 'msg_b']).reconcileHistory()).rejects.toThrow('diverged'); + }); +}); + +describe('durable local publication journal', () => { + it('does not close admission when a healthy prepare finishes after its caller lease expired', async () => { + vi.useFakeTimers() + let release!: () => void; + let metadata: Metadata = structuredClone(base); + const guard = new Promise((resolve) => { release = resolve; }); + const sent: string[] = []; + const publisher = createLocalHistoryPublisher({ + updateMetadata(handler) { metadata = handler(metadata); }, materialize: async () => true, + flushMetadata: async () => { await guard; return true; }, flush: async () => true + }, vi.fn()); + try { + publisher.publish('ses_1', 'a', () => { sent.push('a'); }); + const preparing = publisher.prepare({ id: 'first', expiresAt: monotonicTimeMs() + 30000 }); + await vi.advanceTimersByTimeAsync(31000); + release(); + expect(await preparing).toBe(false); + publisher.publish('ses_1', 'b', () => { sent.push('b'); }); + await publisher.flush(); + expect(sent).toEqual(['a', 'b']); + } finally { publisher.stop(); vi.useRealTimers(); } + }); + + it('restores publications held after a prepared reply when no caller commits termination', async () => { + vi.useFakeTimers(); + let metadata: Metadata = structuredClone(base); + const sent: string[] = []; + const publisher = createLocalHistoryPublisher({ + updateMetadata(handler) { metadata = handler(metadata); }, materialize: async () => true, + flushMetadata: async () => true, flush: async () => true + }, vi.fn()); + try { + publisher.publish('ses_1', 'a', () => { sent.push('a'); }); + expect(await publisher.prepare({ id: 'first', expiresAt: monotonicTimeMs() + 30000 })).toBe(true); + publisher.publish('ses_1', 'b', () => { sent.push('b'); }); + expect(sent).toEqual(['a']); + expect(await publisher.prepare({ id: 'other', expiresAt: monotonicTimeMs() + 30000 })).toBe(false); + await vi.advanceTimersByTimeAsync(30001); + publisher.publish('ses_1', 'c', () => { sent.push('c'); }); + await publisher.flush(); + expect(sent).toEqual(['a', 'b', 'c']); + expect(metadata.conversationHistoryDiverged).toBe(true); + } finally { publisher.stop(); vi.useRealTimers(); } + }); + + it('retains ownership and retries unsent rows after an unconfirmed cooperative stop', async () => { + let metadata: Metadata = structuredClone(base); + let online = false; + let release!: () => void; + let flushes = 0; + const guard = new Promise((resolve) => { release = resolve; }); + const sent: string[] = []; + const publisher = createLocalHistoryPublisher({ + updateMetadata(handler) { metadata = handler(metadata); }, + materialize: async () => true, + flushMetadata: async () => { if (++flushes === 1) await guard; return online; }, + flush: async () => online + }, vi.fn()); + try { + publisher.publish('ses_1', 'msg_a', () => { sent.push('a'); }); + const preparing = publisher.prepare(); + await vi.waitFor(() => expect(flushes).toBe(1)); + // A local completion can arrive while a reversible preparation is + // waiting for metadata. It must not be deduplicated without send. + publisher.publish('ses_1', 'msg_b', () => { sent.push('b'); }); + release(); + expect(await preparing).toBe(false); + expect(sent).toEqual([]); + online = true; + expect(await publisher.prepare()).toBe(true); + expect(sent).toEqual(['a', 'b']); + expect(metadata.conversationHistoryDiverged).toBe(true); + } finally { publisher.stop(); } + }); + + it('finishes the frozen queue after an in-flight attempt fails but the next metadata flush succeeds', async () => { + let metadata: Metadata = structuredClone(base); + let flushes = 0; + const client = { + updateMetadata(handler: (value: Metadata) => Metadata) { metadata = handler(metadata); }, + materialize: async () => true, + flushMetadata: async () => ++flushes > 1, + flush: async () => true + }; + const sent: string[] = []; + const publisher = createLocalHistoryPublisher(client, vi.fn()); + publisher.publish('ses_1', 'msg_a', () => { sent.push('a'); }); + publisher.publish('ses_1', 'msg_b', () => { sent.push('b'); }); + await expect(publisher.finish()).resolves.toBe(true); + expect(sent).toEqual(['a', 'b']); + expect(metadata.conversationHistoryDiverged).toBe(true); + }); + + it('reports unconfirmed shutdown instead of waiting forever for offline materialization', async () => { + vi.useFakeTimers(); + let metadata: Metadata = structuredClone(base); + const client = { + updateMetadata(handler: (value: Metadata) => Metadata) { metadata = handler(metadata); }, + materialize: async () => new Promise(() => {}), + flushMetadata: async () => false, + flush: async () => false + }; + const sent: string[] = []; + const publisher = createLocalHistoryPublisher(client, vi.fn()); + try { + publisher.publish('ses_1', 'msg_a', () => { sent.push('a'); }); + const finishing = publisher.finish(); + await vi.advanceTimersByTimeAsync(10000); + await expect(finishing).resolves.toBe(false); + expect(sent).toEqual([]); + expect(metadata.conversationHistoryDiverged).toBe(true); + expect(vi.getTimerCount()).toBe(0); + } finally { + publisher.stop(); + vi.useRealTimers(); + } + }); + + it('waits for the identity guard ACK before content and retains it until content is acknowledged', async () => { + let guardAck!: () => void; + let contentAck!: () => void; + const guard = new Promise((resolve) => { guardAck = resolve; }); + const content = new Promise((resolve) => { contentAck = resolve; }); + let metadata: Metadata = structuredClone(base); + const changes: Array<(value: Metadata) => Metadata> = []; + let flushes = 0; + const client = { + updateMetadata(handler: (value: Metadata) => Metadata) { changes.push(handler); }, + materialize: async () => true, + flushMetadata: vi.fn(async () => { + if (++flushes === 1) await guard; + for (const handler of changes.splice(0)) metadata = handler(metadata); + return true; + }), + flush: vi.fn(async () => { await content; return true; }) + }; + const errors = vi.fn(); + const publisher = createLocalHistoryPublisher(client, errors); + const sent: string[] = []; + publisher.publish('ses_1', 'msg_a', () => { + sent.push('a'); + }); + await vi.waitFor(() => expect(changes).toHaveLength(1)); + await new Promise((resolve) => setImmediate(resolve)); + expect(sent).toEqual([]); + expect(client.flushMetadata).toHaveBeenCalledTimes(1); + guardAck(); + await vi.waitFor(() => expect(sent).toEqual(['a'])); + expect(metadata.opencodeHistoryCheckpoint?.localPublicationPending).toBe(true); + await expect(historyFor(metadata, ['msg_c', 'msg_a']).reconcileHistory()).rejects.toThrow('diverged'); + contentAck(); + await publisher.flush(); + expect(errors).not.toHaveBeenCalled(); + expect(metadata.opencodeHistoryCheckpoint?.localPublicationPending).toBeUndefined(); + await expect(historyFor(metadata, ['msg_c', 'msg_a']).reconcileHistory()).resolves.toBe(2); + }); + + it.each(['metadata', 'content'])('recovers queued and future forwarding after reconnect without restoring fork trust (%s timeout)', async (failure) => { + let metadata: Metadata = structuredClone(base); + let connected = failure === 'content'; + let disconnectOnSend = failure === 'content'; + const events = new EventEmitter(); + const changes: Array<(value: Metadata) => Metadata> = []; + const client = { + updateMetadata(handler: (value: Metadata) => Metadata) { changes.push(handler); }, + materialize: async () => true, + flushMetadata: async () => { + if (!connected) return false; + for (const handler of changes.splice(0)) metadata = handler(metadata); + return true; + }, + flush: async () => connected, + on: events.on.bind(events), off: events.off.bind(events) + }; + const errors = vi.fn(); + const publisher = createLocalHistoryPublisher(client, errors); + const sent: string[] = []; + publisher.publish('ses_1', 'msg_a', () => { + sent.push('a'); + if (disconnectOnSend) { connected = false; disconnectOnSend = false; } + }); + publisher.publish('ses_1', 'msg_b', () => { sent.push('b'); }); + try { + await publisher.flush(); + expect(sent).toEqual(failure === 'metadata' ? [] : ['a']); + expect(errors).toHaveBeenCalledTimes(1); + await expect(historyFor(metadata, ['msg_c', 'msg_a']).reconcileHistory()).rejects.toThrow('diverged'); + connected = true; + events.emit('connected'); + await vi.waitFor(() => expect(sent).toEqual(['a', 'b'])); + await publisher.flush(); + expect(metadata.conversationHistoryDiverged).toBe(true); + publisher.publish('ses_1', 'msg_d', () => { sent.push('d'); }); + await publisher.flush(); + expect(sent).toEqual(['a', 'b', 'd']); + expect(metadata.conversationHistoryDiverged).toBe(true); + } finally { + publisher.stop(); + expect(events.listenerCount('connected')).toBe(0); + events.removeAllListeners(); + } + }); + + it('retries an isolated timeout without requiring another publication or connect event', async () => { + vi.useFakeTimers(); + let metadata: Metadata = structuredClone(base); + let online = false; + const client = { + updateMetadata(handler: (value: Metadata) => Metadata) { metadata = handler(metadata); }, + materialize: async () => true, + flushMetadata: async () => online, + flush: async () => online + }; + const sent: string[] = []; + const publisher = createLocalHistoryPublisher(client, vi.fn()); + try { + publisher.publish('ses_1', 'msg_a', () => { sent.push('a'); }); + await publisher.flush(); + expect(sent).toEqual([]); + online = true; + await vi.advanceTimersByTimeAsync(1000); + expect(sent).toEqual(['a']); + expect(metadata.conversationHistoryDiverged).toBe(true); + } finally { + publisher.stop(); + expect(vi.getTimerCount()).toBe(0); + vi.useRealTimers(); + } + }); + + it('does not lose a reconnect that arrives while the old guard attempt is timing out', async () => { + let finish!: (value: boolean) => void; + const oldGuard = new Promise((resolve) => { finish = resolve; }); + const events = new EventEmitter(); + let metadata: Metadata = structuredClone(base); + let calls = 0; + const client = { + updateMetadata(handler: (value: Metadata) => Metadata) { metadata = handler(metadata); }, + materialize: async () => true, + flushMetadata: vi.fn(async () => ++calls === 1 ? await oldGuard : true), + flush: async () => true, + on: events.on.bind(events), off: events.off.bind(events) + }; + const sent: string[] = []; + const publisher = createLocalHistoryPublisher(client, vi.fn()); + try { + publisher.publish('ses_1', 'msg_a', () => { sent.push('a'); }); + await vi.waitFor(() => expect(client.flushMetadata).toHaveBeenCalledTimes(1)); + events.emit('connected'); + finish(false); + await vi.waitFor(() => expect(sent).toEqual(['a'])); + expect(metadata.conversationHistoryDiverged).toBe(true); + } finally { + finish(false); + publisher.stop(); + } + }); + + it('bounds mode handoff while lazy materialization is offline and retains the pending publication', async () => { + vi.useFakeTimers(); + let materialized!: (value: boolean) => void; + const materialization = new Promise((resolve) => { materialized = resolve; }); + let metadata: Metadata = structuredClone(base); + const client = { + updateMetadata(handler: (value: Metadata) => Metadata) { metadata = handler(metadata); }, + materialize: async () => materialization, + flushMetadata: async () => true, + flush: async () => true + }; + const sent: string[] = []; + const publisher = createLocalHistoryPublisher(client, vi.fn()); + try { + publisher.publish('ses_1', 'msg_a', () => { sent.push('a'); }); + const handoff = publisher.flush(); + await vi.advanceTimersByTimeAsync(5000); + await handoff; + expect(sent).toEqual([]); + expect(metadata.conversationHistoryDiverged).toBe(true); + materialized(true); + await publisher.flush(); + expect(sent).toEqual(['a']); + expect(metadata.conversationHistoryDiverged).toBe(true); + } finally { + materialized(true); + publisher.stop(); + vi.useRealTimers(); + } + }); +}); diff --git a/cli/src/opencode/localHistory.ts b/cli/src/opencode/localHistory.ts new file mode 100644 index 00000000..610c720f --- /dev/null +++ b/cli/src/opencode/localHistory.ts @@ -0,0 +1,244 @@ +import type { Metadata } from '@/api/types'; +import type { SessionStopPreparationLease } from '@hapi/protocol/rpcMethods'; +import { monotonicTimeMs } from '@/utils/time'; + +type LocalPublicationClient = { + updateMetadata(handler: (metadata: Metadata) => Metadata): void; + materialize(): Promise; + flushMetadata(): Promise; + flush(): Promise; + on?(event: 'connected', handler: () => void): unknown; + off?(event: 'connected', handler: () => void): unknown; +}; + +// Local hooks/scanners append Hub rows even when native undo later removes +// them. Keep identities of published local messages until remote validation. +export function observeLocalHistory( + metadata: Metadata, + nativeSessionId: string | null, + nativeMessageId: string | null +): Metadata { + if (metadata.conversationHistoryDiverged) return metadata; + const checkpoint = metadata.opencodeHistoryCheckpoint; + if (!nativeSessionId || !nativeMessageId || (checkpoint && (checkpoint.sessionId !== nativeSessionId || checkpoint.localMessageIds === undefined))) { + const capabilities = { ...metadata.capabilities }; + delete capabilities.conversationHistory; + return { ...metadata, capabilities, conversationHistoryDiverged: true, + conversationHistoryPoints: undefined, conversationHistoryIndexes: undefined, opencodeHistoryCheckpoint: undefined }; + } + return { ...metadata, opencodeHistoryCheckpoint: { + ...(checkpoint ?? { sessionId: nativeSessionId, messageIds: [], userMessageIds: [] }), + localMessageIds: [...new Set([...(checkpoint?.localMessageIds ?? []), nativeMessageId])] + } }; +} + +// Journal each local publication before sending content, and leave the guard +// set until the Hub has acknowledged both the content and the final metadata. +export function createLocalHistoryPublisher(client: LocalPublicationClient, onError: (error: unknown) => void) { + const queue: Array<{ sessionId: string | null; messageId: string | null; send: () => void; sent: boolean }> = []; + let running: Promise | null = null; + let uncertain = false; + let divergenceQueued = false; + let reported = false; + let stopped = false; + let closing = false; + let finishing: Promise | null = null; + let preparation: Promise | null = null; + let preparing = false; + let finalizing = false; + let preparationLease: SessionStopPreparationLease | undefined; + let leaseTimer: ReturnType | undefined; + const held: typeof queue = []; + let retryRequested = false; + let timer: ReturnType | undefined; + const clearRetry = () => { if (timer) clearTimeout(timer); timer = undefined; }; + const retry = () => { if (!closing && !preparing) void pump(true); }; + const scheduleRetry = () => { + if (stopped || closing || preparing || timer || queue.length === 0) return; + // Match ApiSessionClient's initial Socket.IO reconnect cadence. + timer = setTimeout(() => { timer = undefined; retry(); }, 1000); + timer.unref(); + }; + const markUncertain = (sessionId: string | null, error: unknown) => { + uncertain = true; + if (!divergenceQueued) { + try { + client.updateMetadata((metadata) => observeLocalHistory(metadata, sessionId, null)); + divergenceQueued = true; + } catch {} + } + if (!reported) { reported = true; try { onError(error); } catch {} } + }; + const materialize = async (): Promise => { + // Match the SDK flush budget, including lazy offline materialization. + let deadline: ReturnType | undefined; + try { + return await Promise.race([client.materialize(), new Promise((resolve) => { + deadline = setTimeout(() => resolve(false), 5_000); + })]); + } finally { if (deadline) clearTimeout(deadline); } + }; + const drain = async () => { + while (!stopped && queue.length > 0) { + const entry = queue[0]!; + try { + const uncertainAtStart = uncertain; + if (!uncertain) { + client.updateMetadata((metadata) => { + const observed = observeLocalHistory(metadata, entry.sessionId, entry.messageId); + return observed.opencodeHistoryCheckpoint ? { ...observed, opencodeHistoryCheckpoint: { + ...observed.opencodeHistoryCheckpoint, localPublicationPending: true + } } : observed; + }); + } else if (!divergenceQueued) { + markUncertain(entry.sessionId, new Error('Local history correspondence is uncertain')); + } + if (uncertain && !divergenceQueued) throw new Error('Local history uncertainty could not be queued'); + if (!await materialize() || !await client.flushMetadata()) { + throw new Error('Local history observation could not be persisted'); + } + if (uncertain && !uncertainAtStart) { + // A mode-handoff drain may have timed out while this guard + // was waiting. Persist divergence before any late content. + if (!divergenceQueued) markUncertain(entry.sessionId, new Error('Local history correspondence is uncertain')); + if (!divergenceQueued) throw new Error('Local history uncertainty could not be queued'); + if (!await client.flushMetadata()) throw new Error('Local history uncertainty was not persisted'); + } + if (stopped) return; + // A prior send with an uncertain ACK may already be in the + // socket buffer or Hub. Do not duplicate it on reconnect. + if (!entry.sent) { entry.send(); entry.sent = true; } + if (!await client.flush()) throw new Error('Local history content was not acknowledged'); + if (stopped) return; + if (!uncertain) { + client.updateMetadata((metadata) => metadata.opencodeHistoryCheckpoint ? { ...metadata, + opencodeHistoryCheckpoint: { ...metadata.opencodeHistoryCheckpoint, localPublicationPending: undefined } + } : metadata); + if (!await client.flushMetadata()) throw new Error('Local history publication could not be committed'); + } + queue.shift(); + reported = false; + } catch (error) { + markUncertain(entry.sessionId, error); + scheduleRetry(); + return; + } + } + }; + function pump(requestRetry = false): Promise { + if (stopped || queue.length === 0) return running ?? Promise.resolve(); + if (running) { retryRequested ||= requestRetry; return running; } + clearRetry(); + running = Promise.resolve().then(drain).finally(() => { + running = null; + if ((retryRequested || (!timer && queue.length > 0)) && !stopped && !closing && !preparing) { + retryRequested = false; + retry(); + } + }); + return running; + } + const clearLeaseTimer = () => { if (leaseTimer) clearTimeout(leaseTimer); leaseTimer = undefined; }; + const stop = () => { stopped = true; clearRetry(); clearLeaseTimer(); held.length = 0; client.off?.('connected', retry); }; + const releaseLease = (id: string) => { + if (preparationLease?.id !== id) return; + preparationLease = undefined; + clearLeaseTimer(); + if (!stopped && !finalizing) { + closing = false; + queue.push(...held.splice(0)); + if (!preparing) { preparation = null; void pump(); } + } + }; + const drainQueue = async (): Promise => { + if (running) await running; + await pump(); + return queue.length === 0; + }; + const prepare = (lease?: SessionStopPreparationLease): Promise => { + if (stopped) return Promise.resolve(queue.length === 0); + if (finalizing || (lease && lease.expiresAt <= monotonicTimeMs())) return Promise.resolve(false); + if (preparation && (preparationLease?.id !== lease?.id || preparationLease?.expiresAt !== lease?.expiresAt)) { + return Promise.resolve(false); + } + if (!preparation) { + preparing = true; + clearRetry(); + preparationLease = lease ? { ...lease } : undefined; + if (lease) { + leaseTimer = setTimeout(() => releaseLease(lease.id), Math.max(0, lease.expiresAt - monotonicTimeMs())); + leaseTimer.unref(); + } + preparation = (async () => { + const drained = await drainQueue(); + const confirmed = drained && !finalizing && (!lease || ( + preparationLease?.id === lease.id && lease.expiresAt > monotonicTimeMs() + )); + preparing = false; + if (confirmed) closing = true; + if (!confirmed) { + // A rejected cooperative stop leaves ownership here. Keep + // ordinary forwarding recoverable for the next attempt. + preparation = null; + if (lease) releaseLease(lease.id); + scheduleRetry(); + } + return confirmed; + })(); + } + return preparation; + }; + client.on?.('connected', retry); + return { + publish(sessionId: string | null, messageId: string | null, send: () => void): void { + if (stopped) return; + if (preparationLease && monotonicTimeMs() >= preparationLease.expiresAt) releaseLease(preparationLease.id); + if (closing) { + if (preparationLease && !finalizing) { + held.push({ sessionId, messageId, send, sent: false }); + markUncertain(sessionId, new Error('Local publication is pending a shutdown preparation lease')); + } + return; + } + queue.push({ sessionId, messageId, send, sent: false }); + void pump(); + }, + async flush(): Promise { + // Use the client's default flush budget for mode handoff; an + // offline lazy materialization must not hold the mode forever. + let deadline: ReturnType | undefined; + try { + await Promise.race([pump(), new Promise((resolve) => { + deadline = setTimeout(() => { + if (!stopped && !closing && queue.length) markUncertain(queue[0]!.sessionId, new Error('Local history drain is still pending')); + resolve(); + }, 5_000); + })]); + } finally { if (deadline) clearTimeout(deadline); } + }, + finish(): Promise { + if (!finishing) { + // Final process teardown commits the admission cutoff. A + // reversible prepare keeps accepting local completions until + // the full queue has actually drained. + closing = true; + finalizing = true; + clearLeaseTimer(); + preparationLease = undefined; + held.length = 0; + finishing = (async () => { + try { + if (preparation) await preparation; + return await drainQueue(); + } + finally { stop(); } + })(); + } + return finishing; + }, + prepare, + stop + }; +} + +export type LocalHistoryPublisher = ReturnType; diff --git a/cli/src/opencode/loop.test.ts b/cli/src/opencode/loop.test.ts index b2bd8a24..2204d27b 100644 --- a/cli/src/opencode/loop.test.ts +++ b/cli/src/opencode/loop.test.ts @@ -59,6 +59,12 @@ function baseOpts(overrides: Record = {}) { } describe('opencodeLoop compact availability wiring', () => { + it.each(['local', 'remote'] as const)('publishes a resumed native id immediately only for %s entry', async startingMode => { + await opencodeLoop(baseOpts({ startingMode, resumeSessionId: 'native-resume' }) as Parameters[0]); + const { session } = harness.runLocalRemoteArgs.at(-1) as { session: { onSessionFound: ReturnType } }; + if (startingMode === 'local') expect(session.onSessionFound).toHaveBeenCalledWith('native-resume'); + else expect(session.onSessionFound).not.toHaveBeenCalled(); + }); // Resetting availability to false used to be loop.ts's job, done here in // runLocal right before every local-mode entry. That left a window // between "a switch/exit was requested" and "runLocal actually ran" diff --git a/cli/src/opencode/loop.ts b/cli/src/opencode/loop.ts index 0946f23b..23a23154 100644 --- a/cli/src/opencode/loop.ts +++ b/cli/src/opencode/loop.ts @@ -8,8 +8,10 @@ import { opencodeRemoteLauncher } from './opencodeRemoteLauncher'; import { ApiClient, ApiSessionClient } from '@/lib'; import type { OpencodeMode, PermissionMode } from './types'; import type { OpencodeHookServer } from './utils/startOpencodeHookServer'; +import type { OpenCodeRuntimeGate } from './rewind'; interface OpencodeLoopOptions { + runtimeGate?: OpenCodeRuntimeGate; path: string; startingMode?: 'local' | 'remote'; startedBy?: 'runner' | 'terminal'; @@ -56,10 +58,11 @@ export async function opencodeLoop(opts: OpencodeLoopOptions): Promise { startedBy, startingMode, permissionMode: opts.permissionMode ?? 'default', - modelReasoningEffort: opts.modelReasoningEffort + modelReasoningEffort: opts.modelReasoningEffort, + runtimeGate: opts.runtimeGate }); - if (opts.resumeSessionId) { + if (opts.resumeSessionId && startingMode === 'local') { session.onSessionFound(opts.resumeSessionId); } diff --git a/cli/src/opencode/opencodeLocalLauncher.test.ts b/cli/src/opencode/opencodeLocalLauncher.test.ts new file mode 100644 index 00000000..285532f0 --- /dev/null +++ b/cli/src/opencode/opencodeLocalLauncher.test.ts @@ -0,0 +1,238 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Metadata } from '@/api/types'; +import type { OpencodeSession } from './session'; +import type { OpencodeHookEvent } from './types'; +import type { OpencodeHookServer } from './utils/startOpencodeHookServer'; +import { OpenCodeRewind, OpenCodeRuntimeGate } from './rewind'; +import { getProcessStartMarker } from '@/utils/process'; +import type { OpenCodeRewindOperation } from '@hapi/protocol/schemas'; +import { mkdtempSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; + +const native = vi.hoisted(() => ({ wait: Promise.resolve(), launched: vi.fn() })); +vi.mock('./opencodeLocal', () => ({ opencodeLocal: async () => { native.launched(); await native.wait; } })); +vi.mock('./utils/hookPlugin', () => ({ ensureOpencodeHookPlugin: vi.fn() })); +vi.mock('./utils/opencodeConfig', () => ({ ensureOpencodeConfig: () => ({ configPath: '/tmp/opencode-fixture.json' }) })); +vi.mock('./utils/config', () => ({ buildOpencodeEnv: () => ({}) })); +vi.mock('./utils/systemPrompt', () => ({ getTitleInstruction: () => 'fixture' })); +vi.mock('@/codex/utils/buildHapiMcpBridge', () => ({ buildHapiMcpBridge: async () => ({ + server: { url: 'http://fixture', stop: vi.fn() }, mcpServers: { hapi: {} } +}) })); +vi.mock('./utils/opencodeStorageScanner', () => ({ createOpencodeStorageScanner: async () => ({ + cleanup: async () => {}, onNewSession: vi.fn() +}) })); + +import { opencodeLocalLauncher } from './opencodeLocalLauncher'; +import { OpencodeConversationHistory } from './conversationHistory'; + +describe('local canonical tool updates through the publication journal', () => { + beforeEach(() => { vi.clearAllMocks(); native.wait = Promise.resolve(); }); + + const operation: OpenCodeRewindOperation = { operationId: 'local-resume-op', nativeSessionId: 'native', workerId: 'worker', + workerPid: process.pid, workerStartMarker: getProcessStartMarker(process.pid)!, + requestedLocalId: 'two', nativeMessageId: 'u2', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 4, + reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + function localSession(metadata: Metadata, runtimeGate = new OpenCodeRuntimeGate()) { + return { path: '/tmp/project', sessionId: 'native', startedBy: 'terminal', startingMode: 'local', runtimeGate, + client: { sessionId: 'hub-local-admission', rpcHandlerManager: { registerHandler: vi.fn() }, + getMetadata: () => metadata, updateMetadata: (update: (value: Metadata) => Metadata) => { metadata = update(metadata); }, + materialize: async () => true, flushMetadata: async () => true, flush: async () => true }, + queue: { size: () => 0, reset: vi.fn(), setOnMessage: vi.fn() }, + addHookEventHandler: vi.fn(), removeHookEventHandler: vi.fn(), onSessionFound: vi.fn(), + sendSessionEvent: vi.fn(), recordLocalLaunchFailure: vi.fn() } as unknown as OpencodeSession; + } + const localOptions = { hookUrl: 'http://fixture/hook', hookServer: { token: 'fixture' } as unknown as OpencodeHookServer }; + + it.each(['reserved', 'prepared', 'unknown', 'committed', 'rejected'] as const)( + 'blocks terminal local native launch before settlement of %s, even with a fresh open JS gate', async (phase) => { + const session = localSession({ path: '/tmp/project', host: 'fixture', opencodeRewind: { ...operation, phase } }); + await expect(opencodeLocalLauncher(session, localOptions)).rejects.toThrow('reconciliation'); + expect(native.launched).not.toHaveBeenCalled(); + }); + + it.each([undefined] as const)('allows local native launch for the safe %s control', async (phase) => { + const session = localSession({ path: '/tmp/project', host: 'fixture', + ...(phase ? { opencodeRewind: { ...operation, phase } } : {}) }); + expect(await opencodeLocalLauncher(session, localOptions)).toBe('exit'); + expect(native.launched).toHaveBeenCalledOnce(); + }); + + it('allows local launch only after this wrapper reconciles the exact rejected tombstone', async () => { + const gate = new OpenCodeRuntimeGate(); + const rejected = { ...operation, phase: 'rejected' as const }; + const metadata: Metadata = { path: '/tmp/project', host: 'fixture', opencodeRewind: rejected }; + const controller = new OpenCodeRewind({ directory: mkdtempSync(join(tmpdir(), 'rewind-local-rejected-')), + hapiSessionId: 'rejected-local', workerId: 'worker', gate, baseUrl: 'http://native', nativeSessionId: 'native', headers: {}, + request: async () => { throw new Error('native must not be queried'); }, + report: async () => { throw new Error('Hub rejection already confirmed'); }, + getAuthoritativeOperation: async () => metadata.opencodeRewind, + flush: async () => true, isIdle: () => true, sourceCheckpoint: () => undefined, + sourceIndexes: () => ({}), requestsFromPreviousWorkerCannotRun: () => false }); + expect(await controller.recover(rejected)).toMatchObject({ outcome: 'rejected' }); + expect(await opencodeLocalLauncher(localSession(metadata, gate), localOptions)).toBe('exit'); + expect(native.launched).toHaveBeenCalledOnce(); + metadata.opencodeRewind = { ...rejected, operationId: 'different-rejection' }; + await expect(opencodeLocalLauncher(localSession(metadata, gate), localOptions)).rejects.toThrow('reconciliation'); + expect(native.launched).toHaveBeenCalledOnce(); + }); + + it('allows local ownership only after this wrapper finalized and consumed that committed operation', async () => { + const gate = new OpenCodeRuntimeGate(); + let current = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'u2', type: 'user', text: 'two' }]; + let staged: string | undefined; + const metadata: Metadata = { path: '/tmp/project', host: 'fixture', opencodeRewind: operation }; + const controller = new OpenCodeRewind({ directory: mkdtempSync(join(tmpdir(), 'rewind-local-admission-')), + hapiSessionId: 'local-finalized', workerId: 'worker', gate, baseUrl: 'http://native', nativeSessionId: 'native', headers: {}, + request: async (url) => { + if (url.endsWith('/revert/stage')) { staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { current = current.slice(0, 1); staged = undefined; return new Response(null, { status: 204 }); } + if (url.includes('/message?')) return Response.json({ data: current, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + return Response.json({ data: { id: 'native', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }, report: async report => { + const value = { ...operation, phase: report.phase === 'applied' ? 'committed' as const : report.phase }; + metadata.opencodeRewind = value; return value; + }, getAuthoritativeOperation: async () => metadata.opencodeRewind, flush: async () => true, isIdle: () => true, + sourceCheckpoint: () => ({ sessionId: 'native', messageIds: ['u1', 'u2'], userMessageIds: ['u1', 'u2'], localMessageIds: [] }), + sourceIndexes: () => ({ one: 0, two: 1 }), requestsFromPreviousWorkerCannotRun: () => false, + consumeCommitted: async () => {} }); + expect(await controller.execute(operation)).toMatchObject({ success: true }); + expect(await opencodeLocalLauncher(localSession(metadata, gate), localOptions)).toBe('exit'); + expect(native.launched).toHaveBeenCalledOnce(); + metadata.opencodeRewind = { ...operation, operationId: 'different-committed-op', phase: 'committed' }; + await expect(opencodeLocalLauncher(localSession(metadata, gate), localOptions)).rejects.toThrow('reconciliation'); + expect(native.launched).toHaveBeenCalledOnce(); + }); + + + it.each(['user', 'assistant', 'summary', 'failure'] as const)( + 'journals projected native %s output before forwarding it', async (kind) => { + let releaseNative!: () => void; + let releaseGuard!: () => void; + native.wait = new Promise((resolve) => { releaseNative = resolve; }); + const guard = new Promise((resolve) => { releaseGuard = resolve; }); + let handler: ((event: OpencodeHookEvent) => void) | undefined; + let metadata: Metadata = { path: '/tmp/project', host: 'fixture', opencodeHistoryCheckpoint: { + sessionId: 'native', messageIds: [], userMessageIds: [], localMessageIds: [] + } }; + const messages: unknown[] = []; + const send = (message: unknown) => { + expect(metadata.opencodeHistoryCheckpoint?.localPublicationPending).toBe(true); + messages.push(message); + }; + const flushMetadata = vi.fn(async () => { await guard; return true; }); + const session = { + path: '/tmp/project', sessionId: 'native', startedBy: 'terminal', startingMode: 'local', + runtimeGate: new OpenCodeRuntimeGate(), + client: { sessionId: 'hub-fixture', rpcHandlerManager: { registerHandler: vi.fn() }, + getMetadata: () => metadata, + updateMetadata(update: (current: Metadata) => Metadata) { metadata = update(metadata); }, + materialize: async () => true, flushMetadata, flush: async () => true, sendAgentMessage: send }, + queue: { size: () => 0, reset: vi.fn(), setOnMessage: vi.fn() }, + addHookEventHandler(callback: typeof handler) { handler = callback; }, + removeHookEventHandler: vi.fn(), onSessionFound: vi.fn(), + sendUserMessage: send, sendAgentMessage: send, + sendSessionEvent: vi.fn(), recordLocalLaunchFailure: vi.fn() + }; + const result = opencodeLocalLauncher(session as unknown as OpencodeSession, { + hookUrl: 'http://fixture/hook', hookServer: { token: 'fixture' } as unknown as OpencodeHookServer + }); + try { + await vi.waitFor(() => expect(native.launched).toHaveBeenCalledOnce()); + const event = (type: string, payload: unknown) => handler!({ event: type, sessionId: 'native', payload } as OpencodeHookEvent); + if (kind === 'user' || kind === 'assistant') { + event('message.updated', { info: { sessionID: 'native', id: 'native-message', role: kind } }); + event('message.part.updated', { part: { sessionID: 'native', id: 'text-part', messageID: 'native-message', + type: 'text', text: 'Native text', time: { end: 1 } } }); + } else { + event('message.updated', { info: { sessionID: 'native', id: 'native-message', type: 'compaction', + reason: 'auto', status: kind === 'summary' ? 'completed' : 'failed', summary: 'Native summary' } }); + event('transcript.scan.completed', {}); + } + await vi.waitFor(() => expect(flushMetadata).toHaveBeenCalled()); + expect(messages).toEqual([]); + releaseGuard(); releaseNative(); + expect(await result).toBe('exit'); + expect(messages).toHaveLength(1); + if (kind === 'summary') expect(messages[0]).toMatchObject({ type: 'compact-summary', summary: 'Native summary' }); + if (kind === 'failure') expect(messages[0]).toMatchObject({ type: 'error' }); + expect(metadata.opencodeHistoryCheckpoint?.localMessageIds).toEqual(['native-message']); + expect(metadata.opencodeHistoryCheckpoint?.localPublicationPending).toBeUndefined(); + } finally { + releaseGuard(); releaseNative(); + await result; + } + } + ); + + it.each(['message.part.updated', 'tool.execute'] as const)( + 'retains partial-to-full tool input and its result behind the metadata ACK (%s)', async (transport) => { + let releaseNative!: () => void; + let releaseGuard!: () => void; + native.wait = new Promise((resolve) => { releaseNative = resolve; }); + const guard = new Promise((resolve) => { releaseGuard = resolve; }); + let handler: ((event: OpencodeHookEvent) => void) | undefined; + let metadata: Metadata = { path: '/tmp/project', host: 'fixture', opencodeHistoryCheckpoint: { + sessionId: 'native', messageIds: [], userMessageIds: [], localMessageIds: [] + } }; + const messages: Array> = []; + const flushMetadata = vi.fn(async () => { await guard; return true; }); + const session = { + path: '/tmp/project', sessionId: 'native', startedBy: 'terminal', startingMode: 'local', + runtimeGate: new OpenCodeRuntimeGate(), + client: { + sessionId: 'hub-fixture', + getMetadata: () => metadata, + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata(update: (current: Metadata) => Metadata) { metadata = update(metadata); }, + materialize: async () => true, flushMetadata, flush: async () => true + }, + queue: { size: () => 0, reset: vi.fn(), setOnMessage: vi.fn() }, + addHookEventHandler(callback: typeof handler) { handler = callback; }, + removeHookEventHandler: vi.fn(), onSessionFound: vi.fn(), + sendAgentMessage(message: Record) { + expect(metadata.opencodeHistoryCheckpoint?.localPublicationPending).toBe(true); + messages.push(message); + }, + sendSessionEvent: vi.fn(), recordLocalLaunchFailure: vi.fn() + }; + const result = opencodeLocalLauncher(session as unknown as OpencodeSession, { + hookUrl: 'http://fixture/hook', hookServer: { token: 'fixture' } as unknown as OpencodeHookServer + }); + try { + await vi.waitFor(() => expect(native.launched).toHaveBeenCalledOnce()); + const emit = (input: Record, completed = false) => { + const event = transport === 'message.part.updated' ? { + event: 'message.part.updated', sessionId: 'native', payload: { part: { + id: 'part-1', messageID: 'msg-1', type: 'tool', tool: 'write', callID: 'call-1', + state: { status: completed ? 'completed' : 'running', input, ...(completed ? { output: 'wrote' } : {}) } + } } + } : { + event: completed ? 'tool.execute.after' : 'tool.execute.before', sessionId: 'native', + payload: { messageID: 'msg-1', tool: { name: 'write', id: 'call-1', input }, ...(completed ? { output: 'wrote' } : {}) } + }; + handler!(event as OpencodeHookEvent); + }; + emit({ filePath: '/tmp/a.txt', content: '' }); + await vi.waitFor(() => expect(flushMetadata).toHaveBeenCalled()); + emit({ filePath: '/tmp/a.txt', content: 'final\n' }, true); + expect(messages).toEqual([]); + releaseGuard(); + releaseNative(); + expect(await result).toBe('exit'); + expect(messages).toHaveLength(3); + expect(messages.map((message) => message.type)).toEqual(['tool-call', 'tool-call', 'tool-call-result']); + expect(messages[0]).toMatchObject({ name: 'Write', callId: 'call-1', input: { content: '' } }); + expect(messages[1]).toMatchObject({ name: 'Write', callId: 'call-1', input: { content: 'final\n' } }); + expect(metadata.conversationHistoryDiverged).not.toBe(true); + expect(metadata.opencodeHistoryCheckpoint?.localMessageIds).toEqual(['msg-1']); + expect(metadata.opencodeHistoryCheckpoint?.localPublicationPending).toBeUndefined(); + } finally { + releaseGuard(); releaseNative(); + await result; + } + } + ); +}); diff --git a/cli/src/opencode/opencodeLocalLauncher.ts b/cli/src/opencode/opencodeLocalLauncher.ts index 6d967d71..a7c9c52e 100644 --- a/cli/src/opencode/opencodeLocalLauncher.ts +++ b/cli/src/opencode/opencodeLocalLauncher.ts @@ -19,6 +19,7 @@ import { configuration } from '@/configuration'; import type { PermissionCompletion } from '@/modules/common/permission/BasePermissionHandler'; import { hashObject } from '@/utils/deterministicJson'; import { BaseLocalLauncher } from '@/modules/common/launcher/BaseLocalLauncher'; +import { createLocalHistoryPublisher } from './localHistory'; type OpencodeLocalLauncherOptions = { hookServer: OpencodeHookServer; @@ -52,14 +53,6 @@ function parseMaybeJson(value: unknown): unknown { return value; } -function getNumber(value: unknown): number | null { - if (typeof value === 'number' && Number.isFinite(value)) { - return value; - } - return null; -} - - function buildToolSignature(name: string, input: unknown): string { return `${name}:${hashObject(input ?? null)}`; } @@ -175,6 +168,17 @@ function resolveOpencodeConfigDir(session: OpencodeSession): string { export async function opencodeLocalLauncher( session: OpencodeSession, opts: OpencodeLocalLauncherOptions +): Promise<'switch' | 'exit'> { + // Terminal resume reaches this path without starting a remote controller. + // Reject before config/plugin/scanner work or any native writer/stdio spawn. + const release = session.runtimeGate.enterLocalRuntime(session.client.getMetadata()?.opencodeRewind); + try { return await launchLocal(session, opts); } + finally { release(); } +} + +async function launchLocal( + session: OpencodeSession, + opts: OpencodeLocalLauncherOptions ): Promise<'switch' | 'exit'> { const hookUrl = opts.hookUrl; @@ -238,12 +242,15 @@ export async function opencodeLocalLauncher( if (!projector) { projector = new OpencodeCompactionProjector({ sessionId, - onSummary: (id, summary) => session.client.sendAgentMessage({ type: 'compact-summary', summary }, opencodeCompactionEventId(sessionId, id)), - onFailure: id => session.client.sendAgentMessage({ type: 'error', message: 'OpenCode compaction failed or was interrupted.' }, `${opencodeCompactionEventId(sessionId, id)}:failed`), + onControlMessage: messageId => historyPublisher.publish(sessionId, messageId, () => {}), + onSummary: (id, summary) => historyPublisher.publish(sessionId, id, () => + session.client.sendAgentMessage({ type: 'compact-summary', summary }, opencodeCompactionEventId(sessionId, id))), + onFailure: id => historyPublisher.publish(sessionId, id, () => + session.client.sendAgentMessage({ type: 'error', message: 'OpenCode compaction failed or was interrupted.' }, `${opencodeCompactionEventId(sessionId, id)}:failed`)), onText: (part) => { if (!part.complete || part.type !== 'text' || sentTextParts.has(part.id)) return; - if (part.role === 'user') session.sendUserMessage(part.text); - else session.sendAgentMessage({ type: 'message', message: part.text }); + if (part.role === 'user') sendLocalUserMessage(part.text, part.messageId); + else sendLocalAgentMessage({ type: 'message', message: part.text }, part.messageId); sentTextParts.add(part.id); } }); @@ -259,6 +266,14 @@ export async function opencodeLocalLauncher( // it so the web Edit/Write view receives the complete arguments. const emittedToolInputs = new Map(); const toolExecutionQueues = new Map(); + const historyPublisher = session.localHistoryPublisher ??= createLocalHistoryPublisher(session.client, + (error) => logger.warn('[opencode-local] History publication paused after synchronization failure', error)); + const sendLocalUserMessage = (text: string, messageId: string | null) => { + historyPublisher.publish(session.sessionId, messageId, () => session.sendUserMessage(text)); + }; + const sendLocalAgentMessage = (message: Parameters[0], messageId: string | null) => { + historyPublisher.publish(session.sessionId, messageId, () => session.sendAgentMessage(message)); + }; const handleHookEvent = (event: OpencodeHookEvent) => { const payload = event.payload; @@ -304,6 +319,9 @@ export async function opencodeLocalLauncher( return; } const partType = getString(part.type); + const messageId = getString(part.messageID) + || getString(part.messageId) + || (payloadRecord ? getString(payloadRecord.messageID) || getString(payloadRecord.messageId) : null); if (sessionId) projectorFor(sessionId).part(part); if (partType === 'text' || partType === 'compaction' || partType === 'reasoning') return; @@ -323,13 +341,13 @@ export async function opencodeLocalLauncher( if (shouldEmit) { emittedToolInputs.set(toolCall.callId, toolCall.input); sentToolCalls.add(toolCall.callId); - session.sendAgentMessage({ + sendLocalAgentMessage({ type: 'tool-call', name: toolCall.name, callId: toolCall.callId, input: toolCall.input, ...(toolCall.title ? { nativeTitle: toolCall.title } : {}) - }); + }, messageId); } } @@ -339,21 +357,21 @@ export async function opencodeLocalLauncher( // whatever input is on this completed part before the result. if (!sentToolCalls.has(toolResult.callId) && toolCall) { sentToolCalls.add(toolResult.callId); - session.sendAgentMessage({ + sendLocalAgentMessage({ type: 'tool-call', name: toolCall.name, callId: toolCall.callId, input: toolCall.input, ...(toolCall.title ? { nativeTitle: toolCall.title } : {}) - }); + }, messageId); } sentToolResults.add(toolResult.callId); emittedToolInputs.delete(toolResult.callId); - session.sendAgentMessage({ + sendLocalAgentMessage({ type: 'tool-call-result', callId: toolResult.callId, output: toolResult.output - }); + }, messageId); } return; } @@ -364,6 +382,8 @@ export async function opencodeLocalLauncher( } const record = payload as Record; const tool = isObject(record.tool) ? record.tool as Record : record; + const nativeMessageId = getString(record.messageID) || getString(record.messageId) + || getString(tool.messageID) || getString(tool.messageId); let name = getString(tool.name) || getString(record.name); if (!name) { return; @@ -433,13 +453,13 @@ export async function opencodeLocalLauncher( if (shouldEmit) { emittedToolInputs.set(callId, toolInput); sentToolCalls.add(callId); - session.sendAgentMessage({ + sendLocalAgentMessage({ type: 'tool-call', name, callId, input: toolInput, ...(getString(tool.title ?? record.title) ? { nativeTitle: getString(tool.title ?? record.title) } : {}) - }); + }, nativeMessageId); } return; } @@ -456,17 +476,17 @@ export async function opencodeLocalLauncher( if (!sentToolCalls.has(callId) || shouldEmit) { emittedToolInputs.set(callId, toolInput); sentToolCalls.add(callId); - session.sendAgentMessage({ + sendLocalAgentMessage({ type: 'tool-call', name, callId, input: toolInput, ...(getString(tool.title ?? record.title) ? { nativeTitle: getString(tool.title ?? record.title) } : {}) - }); + }, nativeMessageId); } sentToolResults.add(callId); emittedToolInputs.delete(callId); - session.sendAgentMessage({ + sendLocalAgentMessage({ type: 'tool-call-result', callId, output: { @@ -474,7 +494,7 @@ export async function opencodeLocalLauncher( metadata: tool.metadata ?? record.metadata, isError: tool.is_error ?? record.is_error } - }); + }, nativeMessageId); return; } } @@ -611,6 +631,7 @@ export async function opencodeLocalLauncher( if (storageScanner) { await storageScanner.cleanup(); } + await historyPublisher.flush(); if (happyServer) { happyServer.stop(); logger.debug('[opencode-local]: Stopped hapi MCP server'); diff --git a/cli/src/opencode/opencodeRemoteLauncher.test.ts b/cli/src/opencode/opencodeRemoteLauncher.test.ts index 08bc2190..b371732c 100644 --- a/cli/src/opencode/opencodeRemoteLauncher.test.ts +++ b/cli/src/opencode/opencodeRemoteLauncher.test.ts @@ -2,13 +2,26 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { MessageQueue2 } from '@/utils/MessageQueue2'; import { MessageBuffer } from '@/ui/ink/messageBuffer'; import type { OpencodeMode, PermissionMode } from './types'; +import { OpenCodeRewind, OpenCodeRuntimeGate } from './rewind'; +import { configuration } from '@/configuration'; +import { getProcessStartMarker } from '@/utils/process'; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { spawn, spawnSync } from 'node:child_process'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { OpencodeConversationHistory } from './conversationHistory'; +import type { OpenCodeRewindOperation } from '@hapi/protocol/schemas'; +import type { OpenCodeRewindReport } from '@hapi/protocol/apiTypes'; +import { AcpSdkBackend } from '@/agent/backends/acp/AcpSdkBackend'; import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; import { getOpencodeNativeToolInstruction } from './utils/systemPrompt'; import type { PromptContent } from '@/agent/types'; import { ACP_INDETERMINATE_SYMBOL } from '@/agent/backends/acp/AcpStdioTransport'; +import { hashObject } from '@/utils/deterministicJson'; const harness = vi.hoisted(() => ({ + backendOverride: null as AcpSdkBackend | null, transcriptFetchImpl: null as null | (() => Promise), servePid: null as number | null, servePidCalls: [] as number[][], @@ -51,6 +64,9 @@ const harness = vi.hoisted(() => ({ // reproduced via the terminal UI's onExit/onSwitchToLocal callbacks, // not rpcHandlers. newSessionImpl: null as null | (() => Promise), + loadSessionImpl: null as null | (() => Promise), + clientMetadata: undefined as undefined | Record, + metadataUpdates: [] as Array>, disconnectImpl: null as null | (() => Promise), permissionCancelError: null as Error | null, permissionCancelReasons: [] as string[], @@ -114,6 +130,7 @@ vi.mock('./utils/opencodeBackend', () => ({ allocateFreePort: vi.fn(async () => 48273), createOpencodeBackend: vi.fn((opts?: Record) => { harness.createBackendArgs.push(opts ?? {}); + if (harness.backendOverride) return harness.backendOverride; return { initialize: vi.fn(async () => {}), newSession: vi.fn(async () => { @@ -122,7 +139,12 @@ vi.mock('./utils/opencodeBackend', () => ({ } return 'acp-session-1'; }), - loadSession: vi.fn(async () => 'acp-session-1'), + loadSession: vi.fn(async () => { + if (harness.loadSessionImpl) { + return harness.loadSessionImpl(); + } + return 'acp-session-1'; + }), setModel: vi.fn(async (sessionId: string, modelId: string, opts?: { flavor?: string }) => { harness.events.push(`setModel:${modelId}`); harness.setModelArgs.push({ sessionId, modelId, flavor: opts?.flavor }); @@ -432,6 +454,96 @@ vi.mock('@/ui/logger', () => ({ import { opencodeRemoteLauncher, selectAbortStatusMessage } from './opencodeRemoteLauncher'; +afterEach(() => { + harness.backendOverride = null; + harness.clientMetadata = undefined; + harness.metadataUpdates.length = 0; +}); + +function createRewindHubProcess() { + const database = join(mkdtempSync(join(tmpdir(), 'opencode-rewind-hub-r1-')), 'hub.sqlite'); + const hubSource = join(process.cwd(), '..', 'hub', 'src'); + const source = ` + import { Store } from ${JSON.stringify(join(hubSource, 'store', 'index.ts'))}; + import { SyncEngine } from ${JSON.stringify(join(hubSource, 'sync', 'syncEngine.ts'))}; + import { RpcRegistry } from ${JSON.stringify(join(hubSource, 'socket', 'rpcRegistry.ts'))}; + import { createInterface } from 'node:readline'; + const store = new Store(process.env.REWIND_TEST_DB); + const engines = []; const pending = new Map(); let engine; let session; + const send = value => process.stdout.write('@@' + JSON.stringify(value) + '\\n'); + function startEngine() { + engine = new SyncEngine(store, {}, new RpcRegistry(), { broadcast() {} }); engines.push(engine); + if (session) engine.handleSessionAlive({ sid:session.id, time:Date.now(), mode:'remote' }); + } + startEngine(); + const snapshot = () => ({ session:store.sessions.getSession(session.id), rows:store.messages.getAllMessages(session.id) }); + async function command(input) { + if (input.kind === 'init') { + session=engine.getOrCreateSession('r1-session', input.metadata, null, 'default'); + engine.handleSessionAlive({ sid:session.id, time:Date.now(), mode:'remote' }); + for (const [role,localId] of [['user','one'],['agent',null],['user','two'],['agent',null]]) { + store.messages.addMessage(session.id,{role,content:'synthetic'},localId??undefined); + if (localId) store.messages.markMessagesInvoked(session.id,[localId],Date.now()); + } + return snapshot(); + } + if (input.kind === 'snapshot') return snapshot(); + if (input.kind === 'restart') { engine.stop(); startEngine(); return snapshot(); } + if (input.kind === 'reserve') { + let dispatch; const received=new Promise(resolve => { dispatch=resolve; }); + const chosen=engine; + chosen.rpcGateway.rewindConversation=async (_id, request) => { + dispatch(request.opencodeRewind); + return await new Promise(resolve => pending.set(request.opencodeRewind.operationId,resolve)); + }; + void chosen.rewindConversation(session.id,'default',input.localId).catch(error => send({event:'hub-error',error:String(error)})); + return await received; + } + if (input.kind === 'answer') { const resolve=pending.get(input.operationId); if (!resolve) throw new Error('missing RPC'); + pending.delete(input.operationId); resolve({success:false,outcome:'unknown',error:'synthetic busy or lost response'}); return snapshot(); } + if (input.kind === 'report') { + const version=store.sessions.getSession(session.id).metadataVersion; + const operation=engine.reportOpenCodeRewind(session.id,'default',input.report,version); + return {operation,...snapshot()}; + } + if (input.kind === 'close') { + for (const resolve of pending.values()) resolve({success:false}); + for (const item of engines) item.stop(); store.close(); setTimeout(() => process.exit(0),0); return {}; + } + throw new Error('unknown command'); + } + createInterface({input:process.stdin}).on('line', line => { + const input=JSON.parse(line); + Promise.resolve().then(() => command(input)).then(result => send({id:input.id,result}), error => send({id:input.id,error:String(error)})); + }); + `; + const child = spawn('bun', ['--eval', source], { + cwd: process.cwd(), env: { PATH: process.env.PATH, HOME: process.env.HOME, REWIND_TEST_DB: database }, stdio: ['pipe', 'pipe', 'pipe'] + }); + let sequence = 0; let buffered = ''; let stderr = ''; + const waiting = new Map void; reject: (error: Error) => void }>(); + child.stderr.on('data', data => { stderr += String(data); }); + child.stdin.on('error', () => {}); + child.stdout.on('data', data => { + buffered += String(data); + for (;;) { + const newline = buffered.indexOf('\n'); if (newline < 0) break; + const line = buffered.slice(0, newline); buffered = buffered.slice(newline + 1); + if (!line.startsWith('@@')) continue; + const message = JSON.parse(line.slice(2)); + if (message.event === 'hub-error') continue; + const waiter = waiting.get(message.id); if (!waiter) continue; + waiting.delete(message.id); + if (message.error) waiter.reject(new Error(message.error)); else waiter.resolve(message.result); + } + }); + child.on('exit', code => { for (const waiter of waiting.values()) waiter.reject(new Error(`Hub fixture exited ${code}: ${stderr}`)); waiting.clear(); }); + const call = (kind: string, data: Record = {}): Promise => new Promise((resolve, reject) => { + const id = ++sequence; waiting.set(id, { resolve, reject }); child.stdin.write(JSON.stringify({ id, kind, ...data }) + '\n'); + }); + return { call, close: async () => { await call('close'); } }; +} + function createMode(model?: string): OpencodeMode { return { permissionMode: 'default' as PermissionMode, @@ -504,16 +616,29 @@ function createSessionStub( }); const client = { + sessionId: `entry-fixture-${crypto.randomUUID()}`, + on: vi.fn(), + off: vi.fn(), + flushMetadata: async () => true, + async readRewindMetadata() { + const refresh = (client as unknown as { refreshMetadata?: () => Promise }).refreshMetadata; + if (refresh && !await refresh()) return null; + return { metadata: { ...harness.clientMetadata, opencodeSessionId: harness.clientMetadata?.opencodeSessionId ?? session.sessionId ?? 'acp-session-1' }, version: 1 }; + }, + getMetadata() { + return harness.clientMetadata; + }, + updateMetadata(handler: (metadata: Record) => Record) { + const next = handler(harness.clientMetadata ?? {}); + harness.clientMetadata = { ...harness.clientMetadata, ...next }; + harness.metadataUpdates.push(next); + }, rpcHandlerManager: { registerHandler(method: string, handler: (params: unknown) => unknown) { rpcHandlers.set(method, handler); } }, sendAgentMessage(message: unknown) { sentAgentMessages.push(message); }, - getMetadata() { - return null; - }, - updateMetadata(_handler: (metadata: unknown) => unknown) {}, sendClaudeSessionMessage(message: unknown) { claudeSessionMessages.push(message); }, @@ -632,6 +757,9 @@ afterEach(async () => { harness.sessionModelsMetadata = undefined; harness.cancelPromptImpl = null; harness.newSessionImpl = null; + harness.loadSessionImpl = null; + harness.clientMetadata = undefined; + harness.metadataUpdates.length = 0; harness.disconnectImpl = null; harness.permissionCancelError = null; harness.permissionCancelReasons = []; @@ -678,6 +806,1832 @@ afterEach(async () => { describe('opencodeRemoteLauncher inline model switch', () => { + + it('holds the fork busy guard across an in-flight batch', async () => { + let resolvePrompt: (() => void) | null = null; + harness.promptImpl = () => new Promise((resolve) => { + resolvePrompt = resolve; + }); + const { session, rpcHandlers } = createSessionStub([ + { message: 'in-flight prompt', mode: createMode() } + ]); + + const launcherPromise = opencodeRemoteLauncher(session as never); + while (!harness.events.includes('prompt:start')) { + await new Promise((resolve) => setImmediate(resolve)); + } + + const forkHandler = rpcHandlers.get('fork-conversation'); + expect(forkHandler).toBeDefined(); + await expect(forkHandler!({})).rejects.toThrow('Session is busy'); + + // The guard releases once the batch settles; the subsequent rejection + // comes from the fork path itself (teardown keeps busy set and marks + // the capability withdrawn, so either fence may fire first). + resolvePrompt!(); + await launcherPromise; + await expect(forkHandler!({})).rejects.toThrow(/Session is busy|not supported/); + const backendModule = await import('./utils/opencodeBackend'); + (backendModule.createOpencodeBackend as unknown as ReturnType).mockClear(); + }); + + it.each(['idle', 'active'] as const)('recovers a real Hub reservation whose RPC was dropped before this wrapper saw it (%s)', async runtime => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const hub = createRewindHubProcess(); const gate = new OpenCodeRuntimeGate(); + const rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }, { id: 'a2', type: 'assistant', text: 'answer two' }]; + const initial = await hub.call('init', { metadata: { path: '/tmp/hapi-opencode-test', host: 'fixture', flavor: 'opencode', + opencodeSessionId: 'acp-session-1', opencodeWorkerId: gate.workerId, + opencodeWorkerProcess: { workerId: gate.workerId, pid: process.pid, startMarker: getProcessStartMarker(process.pid)! }, + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), userMessageIds: ['u1', 'u2'], localMessageIds: [] }, + conversationHistoryIndexes: { one: 0, two: 1 }, capabilities: { conversationHistory: { rewindToMessage: true } } } }); + harness.clientMetadata = initial.session.metadata; + let mutations = 0; let reports = 0; let connected: (() => void) | undefined; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.endsWith('/revert/stage') || url.endsWith('/revert/commit')) { mutations++; return Response.json({}); } + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1' } }); + }); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + Object.assign(session.client, { sessionId: initial.session.id, flushMetadata: async () => true, flush: async () => true, + refreshMetadata: async () => { const snapshot = await hub.call('snapshot'); harness.clientMetadata = snapshot.session.metadata; return true; }, + on: vi.fn((event: string, handler: () => void) => { if (event === 'connected') connected = handler; }), off: vi.fn(), + reportOpenCodeRewind: async (report: OpenCodeRewindReport): Promise => { + reports++; const result = await hub.call('report', { report }); harness.clientMetadata = result.session.metadata; return result.operation; + } }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let releaseActive: (() => void) | undefined; + try { + await vi.waitFor(() => expect(rpcHandlers.get('rewind-conversation')).toBeTypeOf('function')); + // The initial entry fence opens only after the first reconciliation + // settles, which can trail the handler registration. + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + if (runtime === 'active') releaseActive = gate.enterRuntime(); + const operation: OpenCodeRewindOperation = await hub.call('reserve', { localId: 'two' }); + await hub.call('answer', { operationId: operation.operationId }); + expect((await hub.call('snapshot')).session.metadata.opencodeRewind).toMatchObject({ operationId: operation.operationId, phase: 'reserved' }); + expect(connected).toBeTypeOf('function'); connected!(); + expect.soft(gate.isBlocked()).toBe(true); + if (releaseActive) { + await new Promise(resolve => setImmediate(resolve)); + expect(reports).toBe(0); expect(mutations).toBe(0); + releaseActive(); + } + await vi.waitFor(async () => expect((await hub.call('snapshot')).session.metadata.opencodeRewind) + .toMatchObject({ operationId: operation.operationId, phase: 'rejected' })); + expect(reports).toBe(1); expect(mutations).toBe(0); + // Hub records the rejection before the entry reconciliation finishes + // its final verification and releases the fence. + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + } finally { releaseActive?.(); gate.release(); session.queue.close(); await launcher; fetchSpy.mockRestore(); await hub.close(); } + }); + + it('admits one queued input after initial metadata failure recovers to a verified no-operation state', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }]; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), userMessageIds: ['u1'], localMessageIds: [] }, + conversationHistoryIndexes: { one: 0 } }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1' } }); + }); + const gate = new OpenCodeRuntimeGate(); const { session } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let connected: (() => void) | undefined; let refreshes = 0; + Object.assign(session.client, { sessionId: `no-op-reconnect-${Date.now()}`, flushMetadata: async () => true, flush: async () => true, + refreshMetadata: async () => ++refreshes > 1, + on: vi.fn((event: string, handler: () => void) => { if (event === 'connected') connected = handler; }), off: vi.fn(), + reportOpenCodeRewind: async () => { throw new Error('no rewind report expected'); } }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(connected).toBeTypeOf('function')); + await vi.waitFor(() => expect(refreshes).toBeGreaterThan(0)); + expect(gate.isBlocked()).toBe(true); + session.queue.push('ordinary input', createMode(), 'ordinary'); + expect(harness.promptCount).toBe(0); connected!(); + await vi.waitFor(() => expect(harness.promptCount).toBe(1)); + expect(gate.isBlocked()).toBe(false); + await new Promise(resolve => setImmediate(resolve)); + expect(harness.promptCount).toBe(1); + } finally { gate.release(); session.queue.close(); await launcher; fetchSpy.mockRestore(); } + }); + + it('registers the rewind handler and keeps forks enabled when reconnect recovery succeeds after a failed startup flush', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }]; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), userMessageIds: ['u1'], localMessageIds: [] }, + conversationHistoryIndexes: { one: 0 } }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1' } }); + }); + const gate = new OpenCodeRuntimeGate(); const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let connected: (() => void) | undefined; let refreshes = 0; let flushes = 0; let reconnected = false; + Object.assign(session.client, { sessionId: `rewind-register-reconnect-${Date.now()}`, flush: async () => true, + flushMetadata: async () => { flushes++; return reconnected; }, + refreshMetadata: async () => ++refreshes > 1, + on: vi.fn((event: string, handler: () => void) => { if (event === 'connected') connected = handler; }), off: vi.fn(), + reportOpenCodeRewind: async () => { throw new Error('no rewind report expected'); } }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(connected).toBeTypeOf('function')); + await vi.waitFor(() => expect(flushes).toBeGreaterThan(0)); + // The startup flush failed while the entry fence is still held, so + // forks must not be disabled yet and the handler stays unregistered. + expect(gate.isBlocked()).toBe(true); + expect(rpcHandlers.has('rewind-conversation')).toBe(false); + reconnected = true; connected!(); + await vi.waitFor(() => expect(rpcHandlers.get('rewind-conversation')).toBeTypeOf('function')); + expect(gate.isBlocked()).toBe(false); + } finally { gate.release(); session.queue.close(); await launcher; fetchSpy.mockRestore(); } + }); + + it.each(['unavailable', 'native-mismatch', 'corrupt-journal', 'unfinished-journal'] as const)( + 'keeps reconnect admission fenced and does not spin for %s', async problem => { + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + let dequeuedRelease: (() => void) | undefined; const acknowledged: string[] = []; + session.queue.beforeDequeue = () => { dequeuedRelease = gate.enterRuntime(); }; + session.queue.onBatchConsumed = ids => acknowledged.push(...ids); + Object.assign(session, { takeDequeuedRuntimeRelease: () => { const release = dequeuedRelease; dequeuedRelease = undefined; return release; } }); + let start: (() => void) | undefined; let connected: (() => void) | undefined; + let fault = false; let reads = 0; + const directory = join(configuration.happyHomeDir, 'opencode-rewind', hashObject(session.client.sessionId)); + const operation = { nativeSessionId: 'acp-session-1' }; + const writeJournal = (phase: 'prepared' | 'finalized') => { + mkdirSync(directory, { recursive: true }); + const backupPath = join(directory, 'entry-test-backup.json'); + writeFileSync(backupPath, JSON.stringify({ info: { id: 'acp-session-1' }, messages: [] })); + writeFileSync(join(directory, 'intent.json'), JSON.stringify({ operation, phase, backupPath, + source: [], prefix: [], sourceHash: hashObject([]), prefixHash: hashObject([]), + ownerWorkerId: 'fixture', pendingRequest: false })); + }; + Object.assign(session.client, { + on: vi.fn((event: string, handler: () => void) => { + if (event === 'connection-start') start = handler; + if (event === 'connected') connected = handler; + }), + readRewindMetadata: async () => { + reads++; + if (fault && problem === 'unavailable') return null; + return { metadata: { ...harness.clientMetadata, + opencodeSessionId: fault && problem === 'native-mismatch' ? 'wrong-native' : 'acp-session-1' }, version: 1 }; + } + }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + if (problem === 'corrupt-journal') { + mkdirSync(directory, { recursive: true }); writeFileSync(join(directory, 'intent.json'), '{'); + } + if (problem === 'unfinished-journal') writeJournal('prepared'); + fault = true; start!(); + expect(gate.isBlocked()).toBe(true); + if (problem === 'unavailable') { + await rpcHandlers.get('abort')!({}); + expect(harness.cancelPrompt).not.toHaveBeenCalled(); + } + session.queue.push('held input', createMode(), 'held'); + const beforeReads = reads; + connected!(); + await vi.waitFor(() => expect(reads).toBeGreaterThan(beforeReads)); + const stoppedAt = reads; + await new Promise(resolve => setTimeout(resolve, 30)); + expect(reads).toBe(stoppedAt); + expect(gate.isBlocked()).toBe(true); + expect(harness.promptCount).toBe(0); + expect(acknowledged).toEqual([]); + fault = false; + if (problem === 'corrupt-journal' || problem === 'unfinished-journal') writeJournal('finalized'); + connected!(); + await vi.waitFor(() => expect(harness.promptCount).toBe(1)); + expect(acknowledged).toEqual(['held']); + } finally { session.queue.close(); await launcher; } + }); + + it('retries a transient entry failure while connected and admits exactly one queued prompt', async () => { + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + let dequeuedRelease: (() => void) | undefined; const acknowledged: string[] = []; + session.queue.beforeDequeue = () => { dequeuedRelease = gate.enterRuntime(); }; + session.queue.onBatchConsumed = ids => acknowledged.push(...ids); + Object.assign(session, { takeDequeuedRuntimeRelease: () => { const release = dequeuedRelease; dequeuedRelease = undefined; return release; } }); + let start: (() => void) | undefined; let connected: (() => void) | undefined; + let reads = 0; let failNextRead = false; + Object.assign(session.client, { + on: vi.fn((event: string, handler: () => void) => { + if (event === 'connection-start') start = handler; + if (event === 'connected') connected = handler; + }), + readRewindMetadata: async () => { + reads++; + if (failNextRead) { failNextRead = false; return null; } + return { metadata: { ...harness.clientMetadata }, version: 1 }; + } + }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + start!(); + expect(gate.isBlocked()).toBe(true); + session.queue.push('queued input', createMode(), 'queued'); + const beforeReads = reads; + failNextRead = true; + connected!(); + await vi.waitFor(() => expect(reads).toBeGreaterThan(beforeReads)); + // The only connected event of this test already fired: the transient + // failure must recover through the scheduled retry, not a reconnect. + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false), { timeout: 5000 }); + await vi.waitFor(() => expect(harness.promptCount).toBe(1)); + expect(acknowledged).toEqual(['queued']); + await new Promise(resolve => setImmediate(resolve)); + expect(harness.promptCount).toBe(1); + } finally { session.queue.close(); await launcher; } + }); + + it('retries admission when the initial metadata read fails on an already-connected socket', async () => { + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + let dequeuedRelease: (() => void) | undefined; const acknowledged: string[] = []; + session.queue.beforeDequeue = () => { dequeuedRelease = gate.enterRuntime(); }; + session.queue.onBatchConsumed = ids => acknowledged.push(...ids); + Object.assign(session, { takeDequeuedRuntimeRelease: () => { const release = dequeuedRelease; dequeuedRelease = undefined; return release; } }); + let reads = 0; + Object.assign(session.client, { + // The socket is already live: no later 'connected' event will fire. + isActive: () => true, + readRewindMetadata: async () => { + reads++; + if (reads === 1) return null; + return { metadata: { ...harness.clientMetadata }, version: 1 }; + } + }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true)); + expect(reads).toBe(1); + expect(gate.isBlocked()).toBe(true); + session.queue.push('queued input', createMode(), 'queued'); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false), { timeout: 5000 }); + await vi.waitFor(() => expect(harness.promptCount).toBe(1)); + expect(acknowledged).toEqual(['queued']); + await new Promise(resolve => setImmediate(resolve)); + expect(harness.promptCount).toBe(1); + } finally { session.queue.close(); await launcher; } + }); + + it('does not wait for an unrelated active turn when reconnect proves a genuine no-op', async () => { + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let start: (() => void) | undefined; let connected: (() => void) | undefined; + Object.assign(session.client, { on: vi.fn((event: string, handler: () => void) => { + if (event === 'connection-start') start = handler; + if (event === 'connected') connected = handler; + }) }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let finish: (() => void) | undefined; + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + finish = gate.enterRuntime(); start!(); + expect(() => gate.enterRuntime()).toThrow('pending reconciliation'); + await rpcHandlers.get('abort')!({}); + expect(harness.cancelPrompt).toHaveBeenCalledOnce(); + connected!(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + expect(gate.isRuntimeActive()).toBe(true); + } finally { finish?.(); session.queue.close(); await launcher; } + }); + + it('keeps the checkpoint of a prompt that completes while reconnect verification is delayed', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const rows: Array<{ id: string; type: string; text: string }> = [ + { id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }]; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), userMessageIds: ['u1'], localMessageIds: [] }, + conversationHistoryIndexes: { one: 0 }, capabilities: { conversationHistory: { rewindToMessage: true } } }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1' } }); + }); + const gate = new OpenCodeRuntimeGate(); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let dequeuedRelease: (() => void) | undefined; + session.queue.beforeDequeue = () => { dequeuedRelease = gate.enterRuntime(); }; + Object.assign(session, { takeDequeuedRuntimeRelease: () => { const release = dequeuedRelease; dequeuedRelease = undefined; return release; } }); + let start: (() => void) | undefined; let connected: (() => void) | undefined; + let promptRelease!: () => void; let reads = -1; let heldReadEntered = false; let releaseHeldRead!: () => void; + const promptHeld = new Promise(resolve => { promptRelease = resolve; }); + const heldRead = new Promise(resolve => { releaseHeldRead = resolve; }); + harness.promptImpl = () => promptHeld; + const readMetadata = session.client.readRewindMetadata.bind(session.client); + Object.assign(session.client, { + on: vi.fn((event: string, handler: () => void) => { + if (event === 'connection-start') start = handler; + if (event === 'connected') connected = handler; + }), + // The second read of an entry pass is the confirmation snapshot: + // hold it so the admitted prompt can finish while the fence is up. + readRewindMetadata: async () => { + if (reads >= 0 && ++reads === 2) { heldReadEntered = true; await heldRead; } + return readMetadata(); + } + }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + session.queue.push('two', createMode(), 'two'); + await vi.waitFor(() => expect(harness.promptCount).toBe(1)); + expect(gate.isRuntimeActive()).toBe(true); + reads = 0; start!(); connected!(); + await vi.waitFor(() => expect(heldReadEntered).toBe(true)); + // The admitted prompt completes while reconnect still holds the fence. + rows.push({ id: 'u2', type: 'user', text: 'two' }, { id: 'a2', type: 'assistant', text: 'answer two' }); + promptRelease(); + await vi.waitFor(() => expect(gate.isRuntimeActive()).toBe(false)); + expect(gate.isBlocked()).toBe(true); + releaseHeldRead(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + await new Promise(resolve => setTimeout(resolve, 50)); + const metadata = harness.clientMetadata as Record; + expect(metadata.conversationHistoryDiverged).toBeUndefined(); + expect(metadata.opencodeHistoryCheckpoint?.userMessageIds).toEqual(['u1', 'u2']); + expect(metadata.conversationHistoryIndexes).toEqual({ one: 0, two: 1 }); + expect(metadata.capabilities?.conversationHistory).toBeDefined(); + } finally { + promptRelease(); releaseHeldRead(); harness.promptImpl = null; + gate.release(); session.queue.close(); await launcher; fetchSpy.mockRestore(); + } + }); + + it('preserves the saved checkpoint when the entry confirmation read fails before the first restore', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const rows: Array<{ id: string; type: string; text: string }> = [ + { id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }]; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), userMessageIds: ['u1'], localMessageIds: [] }, + conversationHistoryIndexes: { one: 0 }, capabilities: { conversationHistory: { forkCurrent: true, forkAtMessage: true } } }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1' } }); + }); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + const gate = new OpenCodeRuntimeGate(); + let reads = 0; + const readMetadata = session.client.readRewindMetadata.bind(session.client); + Object.assign(session.client, { + on: vi.fn((event: string, handler: () => void) => { void event; void handler; }), + readRewindMetadata: async () => { + reads++; + // The initial entry's confirmation read fails once: the in-memory + // checkpoint has not been restored yet when the failure publishes. + if (reads === 3) throw new Error('metadata read failed'); + return readMetadata(); + } + }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true), { timeout: 8000 }); + // The retried entry pass settled (its snapshot and confirmation reads ran). + await vi.waitFor(() => expect(reads).toBeGreaterThanOrEqual(5), { timeout: 8000 }); + // The next prompt must verify the restored persisted history against + // the native transcript instead of marking it as unobserved growth. + let promptRelease!: () => void; + const promptHeld = new Promise(resolve => { promptRelease = resolve; }); + harness.promptImpl = () => promptHeld; + session.queue.push('two', createMode(), 'two'); + await vi.waitFor(() => expect(harness.promptCount).toBe(1), { timeout: 8000 }); + rows.push({ id: 'u2', type: 'user', text: 'two' }, { id: 'a2', type: 'assistant', text: 'answer two' }); + promptRelease(); + const metadata = () => harness.clientMetadata as Record; + await vi.waitFor(() => { + expect(metadata().opencodeHistoryCheckpoint?.userMessageIds).toEqual(['u1', 'u2']); + expect(metadata().conversationHistoryIndexes).toEqual({ one: 0, two: 1 }); + }, { timeout: 8000 }); + expect(metadata().conversationHistoryDiverged).toBeUndefined(); + expect(metadata().capabilities?.conversationHistory?.forkCurrent).toBe(true); + } finally { + harness.promptImpl = null; + session.queue.close(); await launcher; fetchSpy.mockRestore(); + } + }, 15000); + + it('holds real Hub pending recovery until an entry-time Stop and reset settle', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const hub = createRewindHubProcess(); const gate = new OpenCodeRuntimeGate(); + const rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }, { id: 'a2', type: 'assistant', text: 'answer two' }]; + const initial = await hub.call('init', { metadata: { path: '/tmp/hapi-opencode-test', host: 'fixture', flavor: 'opencode', + opencodeSessionId: 'acp-session-1', opencodeWorkerId: gate.workerId, + opencodeWorkerProcess: { workerId: gate.workerId, pid: process.pid, startMarker: getProcessStartMarker(process.pid)! }, + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), userMessageIds: ['u1', 'u2'], localMessageIds: [] }, + conversationHistoryIndexes: { one: 0, two: 1 }, capabilities: { conversationHistory: { rewindToMessage: true } } } }); + harness.clientMetadata = initial.session.metadata; + let cancelEntered = false; let releaseCancel!: () => void; + const heldCancel = new Promise(resolve => { releaseCancel = resolve; }); + harness.cancelPromptImpl = async () => { cancelEntered = true; await heldCancel; }; + let reportStarted = false; let releaseReport!: () => void; let reports = 0; let mutations = 0; + const heldReport = new Promise(resolve => { releaseReport = resolve; }); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.endsWith('/revert/stage') || url.endsWith('/revert/commit')) { mutations++; return Response.json({}); } + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1' } }); + }); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let start: (() => void) | undefined; let connected: (() => void) | undefined; + let dequeuedRelease: (() => void) | undefined; const acknowledged: string[] = []; + session.queue.beforeDequeue = () => { dequeuedRelease = gate.enterRuntime(); }; + session.queue.onBatchConsumed = ids => acknowledged.push(...ids); + Object.assign(session, { takeDequeuedRuntimeRelease: () => { const result = dequeuedRelease; dequeuedRelease = undefined; return result; } }); + Object.assign(session.client, { sessionId: initial.session.id, flushMetadata: async () => true, flush: async () => true, + refreshMetadata: async () => { harness.clientMetadata = (await hub.call('snapshot')).session.metadata; return true; }, + on: vi.fn((event: string, handler: () => void) => { if (event === 'connection-start') start = handler; if (event === 'connected') connected = handler; }), off: vi.fn(), + reportOpenCodeRewind: async (report: OpenCodeRewindReport): Promise => { + reports++; reportStarted = true; await heldReport; + const result = await hub.call('report', { report }); harness.clientMetadata = result.session.metadata; return result.operation; + } }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let releaseOriginal: (() => void) | undefined; let stop: Promise | undefined; + try { + await vi.waitFor(() => expect(rpcHandlers.has('rewind-conversation')).toBe(true)); + releaseOriginal = gate.enterRuntime(); start!(); + stop = Promise.resolve(rpcHandlers.get('abort')!({})); + await vi.waitFor(() => expect(cancelEntered).toBe(true)); + const operation: OpenCodeRewindOperation = await hub.call('reserve', { localId: 'two' }); + await hub.call('answer', { operationId: operation.operationId }); + connected!(); releaseOriginal(); releaseOriginal = undefined; + await new Promise(resolve => setTimeout(resolve, 60)); + expect(reportStarted).toBe(false); expect(reports).toBe(0); expect(mutations).toBe(0); + expect(gate.isBlocked()).toBe(true); expect(() => gate.enterRuntime()).toThrow('reconciliation'); + expect((await hub.call('snapshot')).session.metadata.opencodeRewind.phase).toBe('reserved'); + releaseCancel(); await stop; + await vi.waitFor(() => expect(reportStarted).toBe(true)); + session.queue.push('after stop', createMode(), 'after-stop'); + await new Promise(resolve => setImmediate(resolve)); + expect(acknowledged).toEqual([]); expect(harness.promptCount).toBe(0); expect(gate.isBlocked()).toBe(true); + releaseReport(); + await vi.waitFor(() => expect(harness.promptCount).toBe(1)); + expect(acknowledged).toEqual(['after-stop']); expect(reports).toBe(1); expect(mutations).toBe(0); + expect((await hub.call('snapshot')).session.metadata.opencodeRewind.phase).toBe('rejected'); + } finally { + releaseOriginal?.(); releaseCancel(); releaseReport(); await stop?.catch(() => {}); + gate.release(); session.queue.close(); await launcher; fetchSpy.mockRestore(); await hub.close(); harness.cancelPromptImpl = null; + } + }); + + it('keeps a verified no-op fenced until a held Stop resets, then admits one input', async () => { + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let start: (() => void) | undefined; let connected: (() => void) | undefined; + let cancelEntered = false; let cancellationSettled = false; let releaseCancel!: () => void; + let confirmationHeld = false; let releaseConfirmation!: () => void; + const heldCancel = new Promise(resolve => { releaseCancel = resolve; }); + const heldConfirmation = new Promise(resolve => { releaseConfirmation = resolve; }); + harness.cancelPromptImpl = async () => { cancelEntered = true; await heldCancel; cancellationSettled = true; }; + let dequeuedRelease: (() => void) | undefined; const acknowledged: string[] = []; + session.queue.beforeDequeue = () => { dequeuedRelease = gate.enterRuntime(); }; + session.queue.onBatchConsumed = ids => acknowledged.push(...ids); + Object.assign(session, { takeDequeuedRuntimeRelease: () => { const result = dequeuedRelease; dequeuedRelease = undefined; return result; } }); + Object.assign(session.client, { + on: vi.fn((event: string, handler: () => void) => { if (event === 'connection-start') start = handler; if (event === 'connected') connected = handler; }), + readRewindMetadata: async () => { + if (cancellationSettled) { confirmationHeld = true; await heldConfirmation; } + return { metadata: { ...harness.clientMetadata }, version: 1 }; + } + }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let original: (() => void) | undefined; let stopping: Promise | undefined; + try { + await vi.waitFor(() => expect(rpcHandlers.has('abort')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + original = gate.enterRuntime(); start!(); stopping = Promise.resolve(rpcHandlers.get('abort')!({})); + await vi.waitFor(() => expect(cancelEntered).toBe(true)); + original(); original = undefined; connected!(); + session.queue.push('before reset', createMode(), 'discarded-before-reset'); + await new Promise(resolve => setTimeout(resolve, 60)); + expect(gate.isBlocked()).toBe(true); expect(() => gate.enterRuntime()).toThrow('reconciliation'); + expect(harness.promptCount).toBe(0); expect(acknowledged).toEqual([]); expect(session.queue.size()).toBe(1); + releaseCancel(); await stopping; + expect(session.queue.size()).toBe(0); + await vi.waitFor(() => expect(confirmationHeld).toBe(true)); + session.queue.push('after reset', createMode(), 'after-reset'); + await new Promise(resolve => setImmediate(resolve)); + expect(acknowledged).toEqual([]); expect(harness.promptCount).toBe(0); expect(gate.isBlocked()).toBe(true); + releaseConfirmation(); await vi.waitFor(() => expect(harness.promptCount).toBe(1)); + expect(acknowledged).toEqual(['after-reset']); + } finally { + original?.(); releaseCancel(); releaseConfirmation(); await stopping?.catch(() => {}); + session.queue.close(); await launcher; harness.cancelPromptImpl = null; + } + }); + + it.each(['v1', 'v2'] as const)('counts an entry-time %s Stop through deferred cancellation', async version => { + harness.detectedVersion = version; + if (version === 'v2') { harness.discoveredPort = 41234; harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; } + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: [], cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + return Response.json({ data: { id: 'acp-session-1' }, paths: {} }); + }); + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let start: (() => void) | undefined; let connected: (() => void) | undefined; + Object.assign(session.client, { on: vi.fn((event: string, handler: () => void) => { + if (event === 'connection-start') start = handler; if (event === 'connected') connected = handler; + }) }); + let entered = false; let resume!: () => void; + const held = new Promise(resolve => { resume = resolve; }); + harness.cancelPromptImpl = async () => { entered = true; await held; }; + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let original: (() => void) | undefined; let stopping: Promise | undefined; + try { + await vi.waitFor(() => expect(rpcHandlers.has('abort')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + original = gate.enterRuntime(); start!(); + stopping = Promise.resolve(rpcHandlers.get('abort')!({})); + await vi.waitFor(() => expect(entered).toBe(true)); + original(); original = undefined; + let idle = false; const waiting = gate.waitUntilIdle().then(() => { idle = true; }); + await new Promise(resolve => setImmediate(resolve)); expect(idle).toBe(false); + resume(); await stopping; await waiting; expect(idle).toBe(true); + } finally { + original?.(); resume(); await stopping?.catch(() => {}); connected?.(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + session.queue.close(); await launcher; harness.cancelPromptImpl = null; fetchSpy.mockRestore(); + } + }); + + it.each(['v1', 'v2'] as const)('does not issue a native cancel for an idle entry-time %s Stop', async version => { + harness.detectedVersion = version; + if (version === 'v2') { harness.discoveredPort = 41234; harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; } + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: [], cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + return Response.json({ data: { id: 'acp-session-1' }, paths: {} }); + }); + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let start: (() => void) | undefined; let connected: (() => void) | undefined; + Object.assign(session.client, { on: vi.fn((event: string, handler: () => void) => { + if (event === 'connection-start') start = handler; if (event === 'connected') connected = handler; + }) }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('abort')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + start!(); await rpcHandlers.get('abort')!({}); + expect(harness.cancelPrompt).not.toHaveBeenCalled(); + await gate.waitUntilIdle(); expect(gate.isBlocked()).toBe(true); + } finally { + connected?.(); await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + session.queue.close(); await launcher; fetchSpy.mockRestore(); + } + }); + + it.each(['v1', 'v2'] as const)('retains %s Stop ownership through rejection without changing reset semantics', async version => { + harness.detectedVersion = version; + if (version === 'v2') { harness.discoveredPort = 41234; harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; } + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: [], cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + return Response.json({ data: { id: 'acp-session-1' }, paths: {} }); + }); + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let start: (() => void) | undefined; let connected: (() => void) | undefined; + Object.assign(session.client, { on: vi.fn((event: string, handler: () => void) => { + if (event === 'connection-start') start = handler; if (event === 'connected') connected = handler; + }) }); + let entered = false; let rejectCancel!: () => void; + const held = new Promise((_resolve, reject) => { rejectCancel = () => reject(new Error('cancel failed')); }); + harness.cancelPromptImpl = async () => { entered = true; await held; }; + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + const reset = vi.spyOn(session.queue, 'reset'); let original: (() => void) | undefined; let stopping: Promise | undefined; + try { + await vi.waitFor(() => expect(rpcHandlers.has('abort')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + harness.cleanupEvents.length = 0; + original = gate.enterRuntime(); start!(); + stopping = Promise.resolve(rpcHandlers.get('abort')!({})); + const rejection = expect(stopping).rejects.toThrow('cancel failed'); + await vi.waitFor(() => expect(entered).toBe(true)); original(); original = undefined; + let idle = false; const waiting = gate.waitUntilIdle().then(() => { idle = true; }); + await new Promise(resolve => setImmediate(resolve)); expect(idle).toBe(false); + rejectCancel(); await rejection; await waiting; + expect(idle).toBe(true); expect(reset).not.toHaveBeenCalled(); + expect(harness.cleanupEvents).not.toContain('cleanup:permission'); + } finally { + original?.(); rejectCancel(); await stopping?.catch(() => {}); connected?.(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + session.queue.close(); await launcher; harness.cancelPromptImpl = null; fetchSpy.mockRestore(); + } + }); + + it.each(['v1', 'v2'] as const)('keeps overlapping %s Stops and switch counted until cleanup', async version => { + harness.detectedVersion = version; + if (version === 'v2') { harness.discoveredPort = 41234; harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; } + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: [], cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + return Response.json({ data: { id: 'acp-session-1' }, paths: {} }); + }); + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let start: (() => void) | undefined; + Object.assign(session.client, { on: vi.fn((event: string, handler: () => void) => { if (event === 'connection-start') start = handler; }) }); + let cancelCalls = 0; let resume!: () => void; + const held = new Promise(resolve => { resume = resolve; }); + harness.cancelPromptImpl = async () => { cancelCalls++; await held; }; + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let original: (() => void) | undefined; let first: Promise | undefined; let second: Promise | undefined; let switching: Promise | undefined; + try { + await vi.waitFor(() => expect(rpcHandlers.has('switch')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + original = gate.enterRuntime(); start!(); + first = Promise.resolve(rpcHandlers.get('abort')!({})); second = Promise.resolve(rpcHandlers.get('abort')!({})); + await vi.waitFor(() => expect(cancelCalls).toBe(version === 'v1' ? 2 : 1)); + original(); original = undefined; + let idle = false; const waiting = gate.waitUntilIdle().then(() => { idle = true; }); + switching = Promise.resolve(rpcHandlers.get('switch')!({})); + await new Promise(resolve => setImmediate(resolve)); + expect(idle).toBe(false); expect(gate.isBlocked()).toBe(true); + expect(() => gate.enterRuntime()).toThrow('reconciliation'); + resume(); await Promise.all([first, second, switching]); await waiting; + expect(idle).toBe(true); expect(await launcher).toBe('switch'); + expect(() => gate.enterLocalRuntime(undefined)).toThrow('reconciliation'); + } finally { + original?.(); resume(); await Promise.allSettled([first, second, switching].filter(Boolean) as Promise[]); + const inherited = gate.takeInitialEntryFence(); if (inherited) gate.releaseEntryFence(inherited); + session.queue.close(); await launcher; harness.cancelPromptImpl = null; fetchSpy.mockRestore(); + } + }); + + it('defers the native identity publication until initial authority is available', async () => { + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + const found = vi.spyOn(session, 'onSessionFound'); + let connected: (() => void) | undefined; let healthy = false; let reads = 0; + Object.assign(session.client, { + on: vi.fn((event: string, handler: () => void) => { if (event === 'connected') connected = handler; }), + readRewindMetadata: async () => { reads++; return healthy ? { metadata: { ...harness.clientMetadata }, version: 1 } : null; } + }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true)); + expect(reads).toBe(1); expect(found).not.toHaveBeenCalled(); expect(gate.isBlocked()).toBe(true); + healthy = true; connected!(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + expect(found).toHaveBeenCalledOnce(); expect(found).toHaveBeenCalledWith('acp-session-1'); + } finally { session.queue.close(); await launcher; } + }); + + it('hands an unresolved entry fence across shutdown to a later remote owner', async () => { + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const first = createSessionStub([], { keepOpen: true }); first.session.sessionId = 'acp-session-1'; + Object.assign(first.session.client, { readRewindMetadata: async () => null }); + const old = opencodeRemoteLauncher({ ...first.session, runtimeGate: gate } as never); + await vi.waitFor(() => expect(first.rpcHandlers.has('switch')).toBe(true)); + expect(gate.isBlocked()).toBe(true); + await first.rpcHandlers.get('switch')!({}); + expect(await old).toBe('switch'); + expect(() => gate.enterLocalRuntime(undefined)).toThrow('pending reconciliation'); + const next = createSessionStub([], { keepOpen: true }); next.session.sessionId = 'acp-session-1'; + const fresh = opencodeRemoteLauncher({ ...next.session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + next.session.queue.push('after handoff', createMode(), 'handoff'); + await vi.waitFor(() => expect(harness.promptCount).toBe(1)); + } finally { next.session.queue.close(); await fresh; } + }); + + it('does not let a disposed launcher release a successor fence after a deferred REST read', async () => { + const gate = new OpenCodeRuntimeGate(); + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const first = createSessionStub([], { keepOpen: true }); first.session.sessionId = 'acp-session-1'; + let connected: (() => void) | undefined; let hold = false; let resume!: () => void; let entered = false; + Object.assign(first.session.client, { + on: vi.fn((event: string, handler: () => void) => { if (event === 'connected') connected = handler; }), + readRewindMetadata: async () => { + if (hold) { entered = true; await new Promise(resolve => { resume = resolve; }); } + return { metadata: { ...harness.clientMetadata }, version: 1 }; + } + }); + const old = opencodeRemoteLauncher({ ...first.session, runtimeGate: gate } as never); + await vi.waitFor(() => expect(first.rpcHandlers.has('switch')).toBe(true)); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + hold = true; connected!(); + await vi.waitFor(() => expect(entered).toBe(true)); + await first.rpcHandlers.get('switch')!({}); + expect(await old).toBe('switch'); + const next = createSessionStub([], { keepOpen: true }); next.session.sessionId = 'acp-session-1'; + const fresh = opencodeRemoteLauncher({ ...next.session, runtimeGate: gate } as never); + let successor: symbol | undefined; + try { + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + successor = gate.acquireEntryFence(); + resume(); await new Promise(resolve => setImmediate(resolve)); + expect(gate.isBlocked()).toBe(true); + gate.releaseEntryFence(successor); successor = undefined; + } finally { resume?.(); if (successor) gate.releaseEntryFence(successor); next.session.queue.close(); await fresh; } + }); + + it('keeps a live other-worker reservation fenced without retrying until a new event', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: [], cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + return Response.json({ data: { id: 'acp-session-1' }, paths: {} }); + }); + const gate = new OpenCodeRuntimeGate(); const marker = getProcessStartMarker(process.pid)!; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeSessionId: 'acp-session-1' }; + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let start: (() => void) | undefined; let connected: (() => void) | undefined; let reports = 0; let reads = 0; + Object.assign(session.client, { flush: async () => true, + on: vi.fn((event: string, handler: () => void) => { + if (event === 'connection-start') start = handler; + if (event === 'connected') connected = handler; + }), + readRewindMetadata: async () => { reads++; return { metadata: { ...harness.clientMetadata }, version: 1 }; }, + reportOpenCodeRewind: async (report: OpenCodeRewindReport) => { + reports++; const rejected = { ...report.operation, phase: 'rejected' as const }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: rejected }; return rejected; + } }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('rewind-conversation')).toBe(true)); + const operation: OpenCodeRewindOperation = { operationId: 'live-foreign', nativeSessionId: 'acp-session-1', nativeMessageId: 'u1', + workerId: 'other-worker', workerPid: process.pid, workerStartMarker: marker, requestedLocalId: 'one', cutoffSeq: 1, + sourceEpoch: 0, sourceMaxSeq: 1, reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + harness.clientMetadata!.opencodeRewind = operation; + start!(); const previousReads = reads; connected!(); + await vi.waitFor(() => expect(reads).toBeGreaterThan(previousReads)); + await new Promise(resolve => setTimeout(resolve, 30)); + const stoppedAt = reads; + await new Promise(resolve => setTimeout(resolve, 30)); + expect(reads).toBe(stoppedAt); expect(reports).toBe(0); expect(gate.isBlocked()).toBe(true); + expect(() => gate.enterRuntime()).toThrow('pending reconciliation'); + harness.clientMetadata!.opencodeRewind = { ...operation, operationId: 'same-worker-next', workerId: gate.workerId }; + connected!(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + expect(reports).toBe(1); + } finally { session.queue.close(); await launcher; fetchSpy.mockRestore(); } + }); + + it.each([false, true])('drains a reconnect received while preparation is unresolved after execution settles (retry=%s)', async retry => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }]; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), + userMessageIds: ['u1', 'u2'], localMessageIds: [] }, conversationHistoryIndexes: { one: 0, two: 1 } }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1' } }); + }); + const gate = new OpenCodeRuntimeGate(); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + let connected: (() => void) | undefined; + let failPreparation!: () => void; + const preparation = new Promise((_resolve, reject) => { + failPreparation = () => reject(new Error('prepared ACK lost')); + }); + const reports: string[] = []; + let rejectRecovery = retry; + Object.assign(session.client, { sessionId: `reconnect-latched-${Date.now()}`, flushMetadata: async () => true, + flush: async () => true, refreshMetadata: async () => true, + on: vi.fn((event: string, listener: () => void) => { if (event === 'connected') connected = listener; }), off: vi.fn(), + reportOpenCodeRewind: async (report: OpenCodeRewindReport): Promise => { + reports.push(report.phase); + if (report.phase === 'prepared') return await preparation; + if (report.phase === 'rejected' && rejectRecovery) { rejectRecovery = false; throw new Error('synthetic recovery failure'); } + const result = { ...report.operation, phase: report.phase === 'applied' ? 'committed' as const : report.phase }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: result }; + return result; + } }); + const pending = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(harness.clientMetadata?.capabilities).toMatchObject({ conversationHistory: { rewindToMessage: true } })); + const operation: OpenCodeRewindOperation = { operationId: 'latched', nativeSessionId: 'acp-session-1', + nativeMessageId: 'u2', workerId: harness.clientMetadata!.opencodeWorkerId as string, + workerPid: (harness.clientMetadata!.opencodeWorkerProcess as { pid: number } | undefined)?.pid ?? process.pid, + workerStartMarker: (harness.clientMetadata!.opencodeWorkerProcess as { startMarker: string } | undefined)?.startMarker ?? getProcessStartMarker(process.pid)!, + requestedLocalId: 'two', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 3, + reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + harness.clientMetadata!.opencodeRewind = operation; + const executing = rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: operation }) as Promise; + await vi.waitFor(() => expect(reports).toContain('prepared')); + expect(connected).toBeTypeOf('function'); connected!(); connected!(); + expect(gate.isBlocked()).toBe(true); + failPreparation(); await executing; + if (retry) { + await vi.waitFor(() => expect(reports.filter(phase => phase === 'rejected')).toHaveLength(1)); + await new Promise(resolve => setImmediate(resolve)); + expect(reports.filter(phase => phase === 'rejected')).toHaveLength(1); + expect(gate.isBlocked()).toBe(true); connected!(); + } + await vi.waitFor(() => expect(harness.clientMetadata?.opencodeRewind).toMatchObject({ operationId: 'latched', phase: 'rejected' })); + expect(reports.filter(phase => phase === 'rejected')).toHaveLength(retry ? 2 : 1); + expect(gate.isBlocked()).toBe(false); + } finally { gate.release(); session.queue.close(); await pending; fetchSpy.mockRestore(); } + }); + + it.each(['execute', 'recover', 'applied-ack-loss', 'unknown-success'] as const)('keeps a reconstructed Hub reservation gated during committed %s consumption', async mode => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const hub = createRewindHubProcess(); const gate = new OpenCodeRuntimeGate(); + const marker = getProcessStartMarker(process.pid)!; + const checkpoint = { sessionId: 'acp-session-1', messageIds: ['u1', 'a1', 'u2', 'a2'], + userMessageIds: ['u1', 'u2'], localMessageIds: [] }; + const initial = await hub.call('init', { metadata: { path: '/tmp/hapi-opencode-test', host: 'fixture', flavor: 'opencode', + opencodeSessionId: 'acp-session-1', opencodeWorkerId: gate.workerId, + opencodeWorkerProcess: { workerId: gate.workerId, pid: process.pid, startMarker: marker }, + opencodeHistoryCheckpoint: checkpoint, conversationHistoryIndexes: { one: 0, two: 1 }, + capabilities: { conversationHistory: { rewindToMessage: true } } } }); + harness.clientMetadata = initial.session.metadata; + let rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }, { id: 'a2', type: 'assistant', text: 'answer two' }]; + let staged: string | undefined; let stages = 0; let commits = 0; let loadCount = 0; + let releaseConsumption!: () => void; let consumptionHeld = false; let consumptionReleased = false; let refreshAfterRelease = 0; + const holding = new Promise(resolve => { releaseConsumption = resolve; }); + harness.loadSessionImpl = async () => { + loadCount++; + if ((mode === 'recover' || mode === 'unknown-success') && loadCount === 2) throw new Error('synthetic first consumption failure'); + if ((mode === 'execute' && loadCount === 2) || (mode === 'recover' && loadCount === 3)) { consumptionHeld = true; await holding; } + return 'acp-session-1'; + }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.endsWith('/revert/stage')) { stages++; staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { commits++; rows = rows.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let connected: (() => void) | undefined; let nextId = ''; let nextPending = false; let earlyRelease = false; + let rejectionStarted = false; let rejectionCount = 0; let releaseRejection!: () => void; + const rejectionHold = new Promise(resolve => { releaseRejection = resolve; }); + const originalRelease = gate.release.bind(gate); + vi.spyOn(gate, 'release').mockImplementation(id => { if (nextPending) earlyRelease = true; originalRelease(id); }); + Object.assign(session.client, { sessionId: initial.session.id, flushMetadata: async () => true, flush: async () => true, + refreshMetadata: async () => { const value = await hub.call('snapshot'); harness.clientMetadata = value.session.metadata; + if (consumptionReleased) refreshAfterRelease++; return true; }, + on: vi.fn((event: string, listener: () => void) => { if (event === 'connected') connected = listener; }), off: vi.fn(), + reportOpenCodeRewind: async (report: OpenCodeRewindReport): Promise => { + if (report.operation.operationId === nextId && report.phase === 'rejected') { + rejectionCount++; rejectionStarted = true; await rejectionHold; + } + const result = await hub.call('report', { report }); + harness.clientMetadata = result.session.metadata; + if (mode === 'applied-ack-loss' && report.phase === 'applied') { consumptionHeld = true; await holding; throw new Error('synthetic applied ACK loss'); } + if (mode === 'unknown-success' && report.phase === 'unknown') { consumptionHeld = true; await holding; } + if (report.operation.operationId === nextId && result.operation.phase === 'rejected') nextPending = false; + return result.operation; + } }); + const launcher = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let firstExecution: Promise | undefined; + try { + await vi.waitFor(() => expect(rpcHandlers.get('rewind-conversation')).toBeTypeOf('function')); + const first: OpenCodeRewindOperation = await hub.call('reserve', { localId: 'two' }); + firstExecution = Promise.resolve(rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: first })); + if (mode === 'recover') { + expect(await firstExecution).toMatchObject({ outcome: 'unknown' }); + await hub.call('answer', { operationId: first.operationId }); + expect(connected).toBeTypeOf('function'); connected!(); + } + await vi.waitFor(() => expect(consumptionHeld).toBe(true)); + expect((await hub.call('snapshot')).session.metadata.opencodeRewind.phase).toBe('committed'); + expect(gate.isBlocked()).toBe(true); + await hub.call('restart'); + const newer: OpenCodeRewindOperation = await hub.call('reserve', { localId: 'one' }); + nextId = newer.operationId; nextPending = true; + await expect(Promise.resolve(rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'one', opencodeRewind: newer }))).rejects.toThrow('busy'); + await hub.call('answer', { operationId: newer.operationId }); + expect((await hub.call('snapshot')).session.metadata.opencodeRewind).toMatchObject({ operationId: nextId, phase: 'reserved' }); + consumptionReleased = true; releaseConsumption(); + if (mode !== 'recover') await firstExecution!.catch(() => {}); + if (mode === 'applied-ack-loss' || mode === 'unknown-success') { + await vi.waitFor(() => expect(refreshAfterRelease).toBeGreaterThanOrEqual(3)); + expect(earlyRelease).toBe(false); expect(gate.isBlocked()).toBe(true); + expect(() => gate.enterRuntime()).toThrow('pending reconciliation'); + expect(rejectionCount).toBe(0); + const path = join(configuration.happyHomeDir, 'opencode-rewind', + (await import('@/utils/deterministicJson')).hashObject(initial.session.id), 'intent.json'); + expect(JSON.parse(readFileSync(path, 'utf8'))).toMatchObject({ operation: { operationId: first.operationId }, + phase: mode === 'unknown-success' ? 'unknown' : 'applied' }); + const final = await hub.call('snapshot'); + expect(final.session.metadata.opencodeRewind).toMatchObject({ operationId: nextId, phase: 'reserved' }); + } else { + await vi.waitFor(() => { expect(earlyRelease).toBe(false); expect(rejectionStarted).toBe(true); }); + expect(gate.isBlocked()).toBe(true); + expect(() => gate.enterRuntime()).toThrow('pending reconciliation'); + expect(rejectionCount).toBe(1); + releaseRejection(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + const final = await hub.call('snapshot'); + expect(final.session.metadata.opencodeRewind).toMatchObject({ operationId: nextId, phase: 'rejected' }); + expect(final.rows.filter((row: { localId?: string }) => row.localId === 'one')).toHaveLength(1); + expect(rejectionCount).toBe(1); + } + expect(stages).toBe(1); expect(commits).toBe(1); + } finally { + releaseConsumption(); releaseRejection(); await firstExecution?.catch(() => {}); + harness.loadSessionImpl = null; gate.release(); session.queue.close(); await launcher; fetchSpy.mockRestore(); + await hub.close(); + } + }); + + it.each([false, true])('automatically recovers a newer reservation after a stale queued rewind (retry=%s)', async retry => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + let rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }]; + let staged: string | undefined; let resumeFlush!: () => void; + let holdFlush = true; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), + userMessageIds: ['u1', 'u2'], localMessageIds: [] }, conversationHistoryIndexes: { one: 0, two: 1 } }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.endsWith('/revert/stage')) { staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { rows = rows.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }); + const gate = new OpenCodeRuntimeGate(); const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; const reports: Array<{ id: string; phase: string }> = []; + let connected: (() => void) | undefined; let failOnce = retry; + Object.assign(session.client, { sessionId: `superseded-rewind-${Date.now()}`, flushMetadata: async () => true, + flush: async () => { if (holdFlush) { holdFlush = false; return await new Promise(resolve => { resumeFlush = () => resolve(true); }); } return true; }, + refreshMetadata: async () => true, on: vi.fn((event: string, listener: () => void) => { if (event === 'connected') connected = listener; }), off: vi.fn(), + reportOpenCodeRewind: async (report: OpenCodeRewindReport): Promise => { + reports.push({ id: report.operation.operationId, phase: report.phase }); + if (report.operation.operationId === 'newer-two' && report.phase === 'rejected' && failOnce) { failOnce = false; throw new Error('synthetic rejection failure'); } + const result = { ...report.operation, phase: report.phase === 'applied' ? 'committed' as const : report.phase }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: result, + ...(report.phase === 'applied' ? { opencodeHistoryCheckpoint: report.checkpoint, conversationHistoryIndexes: report.indexes } : {}) }; + return result; + } }); + const pending = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(harness.clientMetadata?.capabilities).toMatchObject({ conversationHistory: { rewindToMessage: true } })); + const proof = harness.clientMetadata!.opencodeWorkerProcess as { pid: number; startMarker: string } | undefined; + const first: OpenCodeRewindOperation = { operationId: 'stale-one', nativeSessionId: 'acp-session-1', nativeMessageId: 'u2', + workerId: gate.workerId, workerPid: proof?.pid ?? process.pid, workerStartMarker: proof?.startMarker ?? getProcessStartMarker(process.pid)!, requestedLocalId: 'two', + cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 3, reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + harness.clientMetadata!.opencodeRewind = first; + const old = rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: first }) as Promise; + await vi.waitFor(() => expect(resumeFlush).toBeTypeOf('function')); + const newer = { ...first, operationId: 'newer-two', reservationVersion: 2 }; + harness.clientMetadata!.opencodeRewind = newer; resumeFlush(); + await expect(old).rejects.toThrow(); + if (retry) { + await vi.waitFor(() => expect(reports.filter(item => item.id === 'newer-two' && item.phase === 'rejected')).toHaveLength(1)); + await new Promise(resolve => setImmediate(resolve)); + expect(reports.filter(item => item.id === 'newer-two' && item.phase === 'rejected')).toHaveLength(1); + expect(gate.isBlocked()).toBe(true); connected!(); + } + await vi.waitFor(() => expect(harness.clientMetadata?.opencodeRewind).toMatchObject({ operationId: 'newer-two', phase: 'rejected' })); + expect(reports.filter(item => item.id === 'stale-one')).toEqual([]); + expect(reports.filter(item => item.id === 'newer-two' && item.phase === 'rejected')).toHaveLength(retry ? 2 : 1); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + const next = { ...first, operationId: 'next-three', reservationVersion: 3 }; + harness.clientMetadata!.opencodeRewind = next; + await vi.waitFor(async () => { + expect(await rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: next })).toMatchObject({ success: true }); + }); + harness.promptImpl = async () => { rows.push({ id: 'u3', type: 'user', text: 'after' }); }; + session.queue.push('after rewind', createMode(), 'after'); + await vi.waitFor(() => expect(harness.promptCount).toBeGreaterThan(0)); + } finally { resumeFlush?.(); gate.release(); session.queue.close(); await pending; fetchSpy.mockRestore(); } + }); + + it('consumes a newer prepared operation that commits before the automatic recovery refresh', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + let rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }]; + let staged: string | undefined; let stageCount = 0; let commitCount = 0; let loads = 0; + let resumeOld!: () => void; let releasePrepared!: () => void; let sawPrepared!: () => void; + let releaseDrain!: () => void; let drainStarted!: () => void; + const prepared = new Promise(resolve => { sawPrepared = resolve; }); + const holdPrepared = new Promise(resolve => { releasePrepared = resolve; }); + const drainWaiting = new Promise(resolve => { drainStarted = resolve; }); + const holdDrain = new Promise(resolve => { releaseDrain = resolve; }); + let observedPrepared = false; let drainHeld = false; + const gate = new OpenCodeRuntimeGate(); const sessionId = `superseded-committed-${Date.now()}`; + const checkpoint = { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), userMessageIds: ['u1', 'u2'], localMessageIds: [] }; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeHistoryCheckpoint: checkpoint, + conversationHistoryIndexes: { one: 0, two: 1 } }; + harness.loadSessionImpl = async () => { loads++; return 'acp-session-1'; }; + const nativeRequest = async (input: string | URL | Request) => { + const url = String(input); + if (url.endsWith('/revert/stage')) { stageCount++; staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { commitCount++; rows = rows.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(nativeRequest); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + let holdFlush = true; const reports: string[] = []; + const report = async (value: OpenCodeRewindReport): Promise => { + reports.push(`${value.operation.operationId}:${value.phase}`); + const result = { ...value.operation, phase: value.phase === 'applied' ? 'committed' as const : value.phase }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: result, + ...(value.phase === 'applied' ? { opencodeHistoryCheckpoint: value.checkpoint, conversationHistoryIndexes: value.indexes } : {}) }; + if (value.operation.operationId === 'newer-committed' && value.phase === 'prepared') { sawPrepared(); await holdPrepared; } + return result; + }; + Object.assign(session.client, { sessionId, flushMetadata: async () => true, + flush: async () => { if (holdFlush) { holdFlush = false; return await new Promise(resolve => { resumeOld = () => resolve(true); }); } return true; }, + refreshMetadata: async () => { + const current = harness.clientMetadata?.opencodeRewind as OpenCodeRewindOperation | undefined; + if (current?.operationId === 'newer-committed' && current.phase === 'prepared') { + if (!observedPrepared) observedPrepared = true; + else if (!drainHeld) { drainHeld = true; drainStarted(); await holdDrain; } + } + return true; + }, on: vi.fn(), off: vi.fn(), reportOpenCodeRewind: report }); + const pending = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let newerExecution: Promise | undefined; + try { + await vi.waitFor(() => expect(harness.clientMetadata?.capabilities).toMatchObject({ conversationHistory: { rewindToMessage: true } })); + const proof = harness.clientMetadata!.opencodeWorkerProcess as { pid: number; startMarker: string } | undefined; + const old: OpenCodeRewindOperation = { operationId: 'stale-one', nativeSessionId: 'acp-session-1', nativeMessageId: 'u2', + workerId: gate.workerId, workerPid: proof?.pid ?? process.pid, workerStartMarker: proof?.startMarker ?? getProcessStartMarker(process.pid)!, + requestedLocalId: 'two', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 3, reservationVersion: 1, + sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + harness.clientMetadata!.opencodeRewind = old; + const oldExecution = rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: old }) as Promise; + await vi.waitFor(() => expect(resumeOld).toBeTypeOf('function')); + const newer = { ...old, operationId: 'newer-committed', workerId: 'other-worker', reservationVersion: 2 }; + harness.clientMetadata!.opencodeRewind = newer; + const second = new OpenCodeRewind({ directory: join(configuration.happyHomeDir, 'opencode-rewind'), hapiSessionId: sessionId, + workerId: 'other-worker', gate: new OpenCodeRuntimeGate(), baseUrl: 'http://synthetic-native', nativeSessionId: 'acp-session-1', headers: {}, + request: nativeRequest, report, getAuthoritativeOperation: async () => harness.clientMetadata?.opencodeRewind as OpenCodeRewindOperation, + flush: async () => true, isIdle: () => true, sourceCheckpoint: () => checkpoint, + sourceIndexes: () => ({ one: 0, two: 1 }), requestsFromPreviousWorkerCannotRun: () => false }); + newerExecution = second.execute(newer); await prepared; + resumeOld(); await expect(oldExecution).rejects.toThrow(); + await vi.waitFor(() => expect(drainHeld).toBe(true)); await drainWaiting; + releasePrepared(); expect(await newerExecution).toMatchObject({ success: true }); + const journal = second.readIntent()!; + const exited = spawnSync(process.execPath, ['-e', 'process.exit(0)']); + expect(exited.status).toBe(0); + // Model a later recovery owner that has exited; the operation and + // backup remain those of the real second controller above. + const path = join(configuration.happyHomeDir, 'opencode-rewind', + (await import('@/utils/deterministicJson')).hashObject(sessionId), 'intent.json'); + writeFileSync(path, JSON.stringify({ ...journal, ownerWorkerId: 'retired-recovery-worker', + ownerProcess: { pid: exited.pid, startMarker: 'synthetic-retired-generation' } })); + expect(stageCount).toBe(1); expect(commitCount).toBe(1); + releaseDrain(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + // A finalized committed journal is terminal on recovery: + // consumption is not re-run, so only the startup resume loads. + expect(loads).toBe(1); + expect(stageCount).toBe(1); expect(commitCount).toBe(1); + expect(reports.filter(value => value === 'newer-committed:applied')).toHaveLength(1); + expect(reports.some(value => value.startsWith('stale-one:'))).toBe(false); + } finally { + resumeOld?.(); releasePrepared?.(); releaseDrain?.(); await newerExecution; + harness.loadSessionImpl = null; gate.release(); session.queue.close(); await pending; fetchSpy.mockRestore(); + } + }); + + it('disables forks instead of failing consumption when a committed recovery reconciles diverged history', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + let rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }]; + let staged: string | undefined; let divergeNow = false; + let resumeOld!: () => void; let releasePrepared!: () => void; let sawPrepared!: () => void; + let releaseDrain!: () => void; let drainStarted!: () => void; + const prepared = new Promise(resolve => { sawPrepared = resolve; }); + const holdPrepared = new Promise(resolve => { releasePrepared = resolve; }); + const drainWaiting = new Promise(resolve => { drainStarted = resolve; }); + const holdDrain = new Promise(resolve => { releaseDrain = resolve; }); + let observedPrepared = false; let drainHeld = false; + const gate = new OpenCodeRuntimeGate(); const sessionId = `diverged-consumption-${Date.now()}`; + const checkpoint = { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), userMessageIds: ['u1', 'u2'], localMessageIds: [] }; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', opencodeHistoryCheckpoint: checkpoint, + conversationHistoryIndexes: { one: 0, two: 1 } }; + harness.loadSessionImpl = async () => 'acp-session-1'; + const nativeRequest = async (input: string | URL | Request) => { + const url = String(input); + if (url.endsWith('/revert/stage')) { staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { rows = rows.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (url.includes('/message?')) return Response.json({ data: divergeNow ? [{ id: 'msg_replacement', type: 'user' }] : rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(nativeRequest); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + const reports: string[] = []; + let holdFlush = true; + const report = async (value: OpenCodeRewindReport): Promise => { + reports.push(`${value.operation.operationId}:${value.phase}`); + const result = { ...value.operation, phase: value.phase === 'applied' ? 'committed' as const : value.phase }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: result, + ...(value.phase === 'applied' ? { opencodeHistoryCheckpoint: value.checkpoint, conversationHistoryIndexes: value.indexes } : {}) }; + if (value.operation.operationId === 'newer-committed' && value.phase === 'prepared') { sawPrepared(); await holdPrepared; } + return result; + }; + Object.assign(session.client, { sessionId, flushMetadata: async () => true, + flush: async () => { if (holdFlush) { holdFlush = false; return await new Promise(resolve => { resumeOld = () => resolve(true); }); } return true; }, + refreshMetadata: async () => { + const current = harness.clientMetadata?.opencodeRewind as OpenCodeRewindOperation | undefined; + if (current?.operationId === 'newer-committed' && current.phase === 'prepared') { + if (!observedPrepared) observedPrepared = true; + else if (!drainHeld) { drainHeld = true; drainStarted(); await holdDrain; } + } + return true; + }, on: vi.fn(), off: vi.fn(), reportOpenCodeRewind: report }); + const pending = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + let newerExecution: Promise | undefined; + try { + await vi.waitFor(() => expect(harness.clientMetadata?.capabilities).toMatchObject({ conversationHistory: { rewindToMessage: true } })); + const proof = harness.clientMetadata!.opencodeWorkerProcess as { pid: number; startMarker: string } | undefined; + const old: OpenCodeRewindOperation = { operationId: 'stale-one', nativeSessionId: 'acp-session-1', nativeMessageId: 'u2', + workerId: gate.workerId, workerPid: proof?.pid ?? process.pid, workerStartMarker: proof?.startMarker ?? getProcessStartMarker(process.pid)!, + requestedLocalId: 'two', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 3, reservationVersion: 1, + sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + harness.clientMetadata!.opencodeRewind = old; + const oldExecution = rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: old }) as Promise; + await vi.waitFor(() => expect(resumeOld).toBeTypeOf('function')); + const newer = { ...old, operationId: 'newer-committed', workerId: 'other-worker', reservationVersion: 2 }; + harness.clientMetadata!.opencodeRewind = newer; + // The second controller dies between the applied report and its own + // consumption: its consumeCommitted never resolves, so the journal + // stays in the 'applied' phase for the launcher's recovery to finish. + const second = new OpenCodeRewind({ directory: join(configuration.happyHomeDir, 'opencode-rewind'), hapiSessionId: sessionId, + workerId: 'other-worker', gate: new OpenCodeRuntimeGate(), baseUrl: 'http://synthetic-native', nativeSessionId: 'acp-session-1', headers: {}, + request: nativeRequest, report, getAuthoritativeOperation: async () => harness.clientMetadata?.opencodeRewind as OpenCodeRewindOperation, + flush: async () => true, isIdle: () => true, sourceCheckpoint: () => checkpoint, + sourceIndexes: () => ({ one: 0, two: 1 }), requestsFromPreviousWorkerCannotRun: () => false, + consumeCommitted: () => new Promise(() => {}) }); + newerExecution = second.execute(newer); await prepared; + resumeOld(); await expect(oldExecution).rejects.toThrow(); + await vi.waitFor(() => expect(drainHeld).toBe(true)); await drainWaiting; + releasePrepared(); + await vi.waitFor(() => expect(second.readIntent()?.phase).toBe('applied')); + const exited = spawnSync(process.execPath, ['-e', 'process.exit(0)']); + expect(exited.status).toBe(0); + const journalPath = join(configuration.happyHomeDir, 'opencode-rewind', hashObject(sessionId), 'intent.json'); + writeFileSync(journalPath, JSON.stringify({ ...second.readIntent()!, ownerWorkerId: 'retired-recovery-worker', + ownerProcess: { pid: exited.pid, startMarker: 'synthetic-retired-generation' } })); + // The recovering launcher must reconcile a native history that no + // longer has the committed prefix: consumption catches the + // divergence into disableFork instead of failing into 'unknown'. + divergeNow = true; + releaseDrain(); + await vi.waitFor(() => expect(gate.isBlocked()).toBe(false)); + expect(JSON.parse(readFileSync(journalPath, 'utf8')).phase).toBe('finalized'); + expect(harness.clientMetadata?.opencodeRewind).toMatchObject({ operationId: 'newer-committed', phase: 'committed' }); + } finally { + resumeOld?.(); releasePrepared?.(); releaseDrain?.(); + harness.loadSessionImpl = null; gate.release(); session.queue.close(); await pending; fetchSpy.mockRestore(); + } + }); + + it('finalizes a rejected ACK-loss journal on launcher restart before the next successful rewind', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + let rows = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }]; + let staged: string | undefined; + const gate = new OpenCodeRuntimeGate(); + const sessionId = `rejected-startup-${Date.now()}`; + const first: OpenCodeRewindOperation = { operationId: 'old-rejected', nativeSessionId: 'acp-session-1', + nativeMessageId: 'u2', workerId: gate.workerId, workerPid: process.pid, + workerStartMarker: getProcessStartMarker(process.pid)!, requestedLocalId: 'two', cutoffSeq: 3, + sourceEpoch: 0, sourceMaxSeq: 3, reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + let authoritative: OpenCodeRewindOperation = first; + let dropPreparation = true; let dropRejection = true; + const checkpoint = { sessionId: 'acp-session-1', messageIds: rows.map(row => row.id), + userMessageIds: ['u1', 'u2'], localMessageIds: [] }; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeHistoryCheckpoint: checkpoint, conversationHistoryIndexes: { one: 0, two: 1 }, opencodeRewind: first }; + const nativeRequest = async (input: string | URL | Request) => { + const url = String(input); + if (url.endsWith('/revert/stage')) { staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { rows = rows.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (url.includes('/message?')) return Response.json({ data: rows, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }; + const report = async (value: OpenCodeRewindReport): Promise => { + if (value.phase === 'prepared' && dropPreparation) { dropPreparation = false; throw new Error('prepare ACK lost'); } + if (value.phase === 'rejected' && dropRejection) { + dropRejection = false; authoritative = { ...value.operation, phase: 'rejected' }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: authoritative }; + throw new Error('rejection ACK lost'); + } + if (authoritative.phase !== 'rejected' || value.operation.operationId !== authoritative.operationId) { + authoritative = { ...value.operation, phase: value.phase === 'applied' ? 'committed' : value.phase }; + } + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: authoritative, + ...(value.phase === 'applied' ? { opencodeHistoryCheckpoint: value.checkpoint, conversationHistoryIndexes: value.indexes } : {}) }; + return authoritative; + }; + const prior = new OpenCodeRewind({ directory: join(configuration.happyHomeDir, 'opencode-rewind'), hapiSessionId: sessionId, + workerId: gate.workerId, gate, baseUrl: 'http://synthetic-native', nativeSessionId: 'acp-session-1', headers: {}, + request: nativeRequest, report, getAuthoritativeOperation: async () => authoritative, + flush: async () => true, isIdle: () => true, sourceCheckpoint: () => checkpoint, + sourceIndexes: () => ({ one: 0, two: 1 }), requestsFromPreviousWorkerCannotRun: () => false }); + expect(await prior.execute(first)).toMatchObject({ outcome: 'unknown' }); + expect(await prior.recover(authoritative)).toMatchObject({ outcome: 'unknown' }); + expect(authoritative.phase).toBe('rejected'); + const original = prior.readIntent()!; const backup = readFileSync(original.backupPath, 'utf8'); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(nativeRequest); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); session.sessionId = 'acp-session-1'; + Object.assign(session.client, { sessionId, flushMetadata: async () => true, flush: async () => true, + refreshMetadata: async () => true, on: vi.fn(), off: vi.fn(), reportOpenCodeRewind: report }); + const pending = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => expect(harness.clientMetadata?.capabilities).toMatchObject({ conversationHistory: { rewindToMessage: true } })); + expect(prior.readIntent()?.phase).toBe('finalized'); + expect(readFileSync(original.backupPath, 'utf8')).toBe(backup); + const next = { ...first, operationId: 'next-after-rejection', reservationVersion: 2 }; + authoritative = next; harness.clientMetadata!.opencodeRewind = next; + expect(await rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: next })).toMatchObject({ success: true }); + expect(rows.map(row => row.id)).toEqual(['u1', 'a1']); + } finally { gate.release(); session.queue.close(); await pending; fetchSpy.mockRestore(); } + }); + + it('consumes a successful rewind after same-wrapper remote/local/remote and drains a new input', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + let current = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'answer' }, + { id: 'u2', type: 'user', text: 'two' }]; + let staged: string | undefined; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: current.map(row => row.id), + userMessageIds: ['u1', 'u2'], localMessageIds: [] }, conversationHistoryIndexes: { one: 0, two: 1 } }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + const url = String(input); + if (url.endsWith('/revert/stage')) { staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { current = current.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (url.includes('/message?')) return Response.json({ data: current, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }); + const gate = new OpenCodeRuntimeGate(); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + const instance = { ...session, runtimeGate: gate }; + Object.assign(session.client, { sessionId: `same-wrapper-${Date.now()}`, flushMetadata: async () => true, + flush: async () => true, refreshMetadata: async () => true, on: vi.fn(), off: vi.fn(), + reportOpenCodeRewind: async (report: OpenCodeRewindReport): Promise => { + const operation = { ...report.operation, phase: report.phase === 'applied' ? 'committed' as const : report.phase }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: operation, + ...(report.phase === 'applied' ? { opencodeHistoryCheckpoint: report.checkpoint, conversationHistoryIndexes: report.indexes } : {}) }; + return operation; + } }); + let pending = opencodeRemoteLauncher(instance as never); + try { + await vi.waitFor(() => expect(harness.clientMetadata?.capabilities).toMatchObject({ conversationHistory: { rewindToMessage: true } })); + const workerId = harness.clientMetadata!.opencodeWorkerId as string; + const operation: OpenCodeRewindOperation = { operationId: 'same-wrapper-operation', nativeSessionId: 'acp-session-1', + nativeMessageId: 'u2', workerId, workerPid: (harness.clientMetadata!.opencodeWorkerProcess as { pid: number } | undefined)?.pid ?? process.pid, + workerStartMarker: (harness.clientMetadata!.opencodeWorkerProcess as { startMarker: string } | undefined)?.startMarker ?? getProcessStartMarker(process.pid)!, requestedLocalId: 'two', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 3, + reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + harness.clientMetadata!.opencodeRewind = operation; + expect(await rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: operation })).toMatchObject({ success: true }); + await rpcHandlers.get('switch')!({ to: 'local' }); + expect(await pending).toBe('switch'); + expect(gate.isBlocked()).toBe(false); + // A witnessed local turn is retained, rather than compared with + // the obsolete prefix from before this committed operation. + current.push({ id: 'local-turn', type: 'user', text: 'local input' }); + const checkpoint = harness.clientMetadata!.opencodeHistoryCheckpoint as { localMessageIds: string[] }; + checkpoint.localMessageIds.push('local-turn'); + harness.promptImpl = async () => { current.push({ id: 'new-remote-turn', type: 'user', text: 'new remote input' }); }; + session.queue.push('new remote input', createMode(), 'after'); + pending = opencodeRemoteLauncher(instance as never); + await vi.waitFor(() => expect(harness.clientMetadata!.conversationHistoryIndexes).toMatchObject({ after: 2 }), { timeout: 1000 }); + expect(harness.promptCount).toBe(1); + expect(gate.isBlocked()).toBe(false); + expect(harness.clientMetadata!.opencodeWorkerId).toBe(workerId); + expect(harness.clientMetadata!.opencodeHistoryCheckpoint).toMatchObject({ userMessageIds: ['u1', 'local-turn', 'new-remote-turn'] }); + } finally { + gate.release(); session.queue.close(); await pending; fetchSpy.mockRestore(); + } + }); + + it.each(['during-load', 'after-load-response', 'queued-after-restore', 'load-failure', 'identity-mismatch'] as const)('suppresses real ACP history replay after a completed prompt and rewind (%s)', async (timing) => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const statics = AcpSdkBackend as unknown as Record; + const retryOptions = (AcpSdkBackend as unknown as { INIT_RETRY_OPTIONS: { maxAttempts: number } }).INIT_RETRY_OPTIONS; + const originalMaxAttempts = retryOptions.maxAttempts; + if (timing === 'load-failure') retryOptions.maxAttempts = 1; + const originalTimings = Object.fromEntries([ + 'UPDATE_QUIET_PERIOD_MS', 'UPDATE_DRAIN_TIMEOUT_MS', 'PRE_PROMPT_UPDATE_QUIET_PERIOD_MS', + 'PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS', 'LATE_FLUSH_INTERVAL_MS', + 'LATE_FLUSH_QUIET_PERIOD_MS', 'LATE_FLUSH_WINDOW_MS' + ].map(key => [key, statics[key]])); + Object.assign(statics, { UPDATE_QUIET_PERIOD_MS: 5, UPDATE_DRAIN_TIMEOUT_MS: 100, + PRE_PROMPT_UPDATE_QUIET_PERIOD_MS: 30, PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS: 300, + LATE_FLUSH_INTERVAL_MS: 5, LATE_FLUSH_QUIET_PERIOD_MS: 5, LATE_FLUSH_WINDOW_MS: 30 }); + const backend = new AcpSdkBackend({ command: 'opencode', flavor: 'opencode', textChunkMode: 'delta' }); + harness.backendOverride = backend; + vi.spyOn(backend, 'initialize').mockResolvedValue(); + const internal = backend as unknown as { + transport: unknown; + handleNotification(method: string, params: unknown): void; + sessionUpdateQueue: Promise; + messageHandler: unknown; + }; + let current = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'a1', type: 'assistant', text: 'retained answer' }]; + let staged: string | undefined; + let loadCount = 0; + let promptCount = 0; + let resolveReplay!: () => void; + const replayDelivered = new Promise(resolve => { resolveReplay = resolve; }); + let replayTimer: ReturnType | undefined; + let releaseNotificationQueue: (() => void) | undefined; + const replaySuppressed: boolean[] = []; + const emit = (update: unknown) => internal.handleNotification('session/update', { sessionId: 'acp-session-1', update }); + const emitText = (text: string) => emit({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } }); + const replay = () => { + replaySuppressed.push(internal.messageHandler === null); + emitText('replayed retained answer'); + emit({ sessionUpdate: 'tool_call', toolCallId: 'replayed-tool', title: 'replayed retained tool', + kind: 'read', status: 'completed', rawInput: { path: 'replayed-file' } }); + emitText('replayed buffered tail'); + resolveReplay(); + }; + internal.transport = { + getProcessPid: () => process.pid, + close: async () => {}, + sendNotification: () => {}, + sendRequest: async (method: string) => { + if (method === 'session/load') { + if (++loadCount > 1) { + if (timing === 'queued-after-restore') { + const blocked = new Promise(resolve => { releaseNotificationQueue = resolve; }); + internal.sessionUpdateQueue = internal.sessionUpdateQueue.then(() => blocked); + } + if (timing === 'during-load') replay(); + else if (timing === 'after-load-response') replayTimer = setTimeout(replay, 15); + else replay(); + if (timing === 'load-failure') throw new Error('fixture reload failure'); + if (timing === 'identity-mismatch') return { sessionId: 'unexpected-native-session' }; + } + return { sessionId: 'acp-session-1' }; + } + if (method === 'session/list') return { sessions: [] }; + if (method === 'session/prompt') { + const first = ++promptCount === 1; + current.push({ id: first ? 'u2' : 'u3', type: 'user', text: first ? 'two' : 'after rewind' }); + current.push({ id: first ? 'a2' : 'a3', type: 'assistant', text: first ? 'completed-before-rewind' : 'fresh-after-rewind' }); + emitText(first ? 'completed-before-rewind' : 'fresh-after-rewind'); + return { stopReason: 'end_turn' }; + } + throw new Error(`Unexpected ACP request: ${method}`); + } + }; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: ['u1', 'a1'], + userMessageIds: ['u1'], localMessageIds: [] }, conversationHistoryIndexes: { one: 0 } }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input); + if (url.endsWith('/revert/stage')) { staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { current = current.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (url.includes('/message?')) return Response.json({ data: current, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }); + const gate = new OpenCodeRuntimeGate(); + const { session, rpcHandlers, agentMessages } = createSessionStub([{ message: 'two', mode: createMode(), localId: 'two' }], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + Object.assign(session.client, { sessionId: `reload-replay-${timing}-${Date.now()}`, flushMetadata: async () => true, + flush: async () => true, refreshMetadata: async () => true, on: vi.fn(), off: vi.fn(), + reportOpenCodeRewind: async (report: OpenCodeRewindReport): Promise => { + const previous = harness.clientMetadata?.opencodeRewind as OpenCodeRewindOperation | undefined; + const operation = previous?.phase === 'committed' ? previous + : { ...report.operation, phase: report.phase === 'applied' ? 'committed' as const : report.phase }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: operation, + ...(report.phase === 'applied' ? { opencodeHistoryCheckpoint: report.checkpoint, conversationHistoryIndexes: report.indexes } : {}) }; + // The Hub already committed deletion before runtime consumption reloads ACP. + if (report.phase === 'applied') agentMessages.length = 0; + return operation; + } }); + const pending = opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + try { + await vi.waitFor(() => { + expect(harness.clientMetadata?.conversationHistoryIndexes).toMatchObject({ two: 1 }); + expect(session.thinking).toBe(false); + }); + expect(JSON.stringify(agentMessages)).toContain('completed-before-rewind'); + expect(internal.messageHandler).not.toBeNull(); + const previousHandler = internal.messageHandler; + expect(backend.isPromptRequestInFlight()).toBe(false); + const operation: OpenCodeRewindOperation = { operationId: `reload-replay-${timing}`, + nativeSessionId: 'acp-session-1', nativeMessageId: 'u2', workerId: harness.clientMetadata!.opencodeWorkerId as string, + workerPid: (harness.clientMetadata!.opencodeWorkerProcess as { pid: number } | undefined)?.pid ?? process.pid, + workerStartMarker: (harness.clientMetadata!.opencodeWorkerProcess as { startMarker: string } | undefined)?.startMarker ?? getProcessStartMarker(process.pid)!, requestedLocalId: 'two', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 4, + reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + harness.clientMetadata!.opencodeRewind = operation; + const result = await rpcHandlers.get('rewind-conversation')!({ messageLocalId: 'two', opencodeRewind: operation }); + await replayDelivered; + if (releaseNotificationQueue) { + expect(internal.messageHandler).toBe(previousHandler); + releaseNotificationQueue(); + } + await internal.sessionUpdateQueue; + const afterReload = JSON.stringify(agentMessages); + if (timing === 'load-failure' || timing === 'identity-mismatch') { + expect(result).toMatchObject({ success: false, outcome: 'unknown', + error: timing === 'load-failure' ? 'fixture reload failure' : 'Rewind native reload changed identity' }); + expect(gate.isBlocked()).toBe(true); + expect(internal.messageHandler).toBe(previousHandler); + expect(promptCount).toBe(1); + expect(loadCount).toBe(2); + expect(harness.clientMetadata?.opencodeRewind).toMatchObject({ phase: 'committed' }); + expect(harness.clientMetadata?.opencodeHistoryCheckpoint).toMatchObject({ messageIds: ['u1', 'a1'] }); + expect(afterReload).not.toContain('replayed'); + return; + } + expect(result).toMatchObject({ success: true }); + session.queue.push('after rewind', createMode(), 'after'); + await vi.waitFor(() => { + expect(harness.clientMetadata?.conversationHistoryIndexes).toMatchObject({ after: 1 }); + expect(session.thinking).toBe(false); + }); + expect(promptCount).toBe(2); + expect(loadCount).toBe(2); + expect.soft(afterReload).not.toContain('replayed'); + expect.soft(JSON.stringify(agentMessages)).not.toContain('replayed'); + expect(JSON.stringify(agentMessages)).toContain('fresh-after-rewind'); + expect(replaySuppressed).toEqual([true]); + expect(gate.isBlocked()).toBe(false); + } finally { + if (replayTimer) clearTimeout(replayTimer); + releaseNotificationQueue?.(); + session.queue.close(); + gate.release(); + try { await pending; } finally { + fetchSpy.mockRestore(); + Object.assign(statics, originalTimings); + retryOptions.maxAttempts = originalMaxAttempts; + } + } + }); + + it.each([false, true])('persists divergence after local undo (local-only turn=%s)', async (localOnly) => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + harness.clientMetadata = { + path: '/tmp/hapi-opencode-test', host: 'fixture', + conversationHistoryPoints: { 'local-original': true }, + conversationHistoryIndexes: { 'local-original': 0 }, + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: ['msg_original'], userMessageIds: ['msg_original'], + localMessageIds: localOnly ? ['msg_local_a', 'msg_local_b'] : [] } + }; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => new Response(JSON.stringify( + init?.method === 'POST' ? { data: { id: 'ses_wrong_child' } } + : String(input).includes('/message?') ? { data: localOnly + ? [{ id: 'msg_original', type: 'user' }, { id: 'msg_local_b', type: 'user' }] + : [{ id: 'msg_replacement', type: 'user' }], cursor: {} } + : { paths: { '/api/session/{sessionID}/fork': { post: {} } } } + ))); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + const pending = opencodeRemoteLauncher(session as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true)); + await expect(rpcHandlers.get('fork-conversation')!(localOnly ? {} : { messageLocalId: 'local-original' })) + .rejects.toThrow(/diverg|not supported/i); + expect(harness.clientMetadata?.conversationHistoryDiverged).toBe(true); + expect(harness.clientMetadata?.conversationHistoryIndexes).toBeUndefined(); + expect(fetchSpy.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false); + } finally { + session.queue.close(); + await pending; + fetchSpy.mockRestore(); + } + }); + + it.each(['history-get', 'v2-discovery', 'metadata-flush', 'existing-fork-child'])('keeps ordinary ACP resume usable when optional verification fails (%s)', async (failure) => { + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: ['msg_original'], userMessageIds: ['msg_original'], localMessageIds: [] } }; + if (failure === 'existing-fork-child') harness.clientMetadata.forkedFrom = 'parent-hapi-session'; + if (failure === 'v2-discovery') { + harness.detectedVersion = 'v2'; + harness.discoveredPort = null; + harness.discoveredPassword = null; + } + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response('unavailable', { status: 503 })); + try { + const { session, agentMessages } = createSessionStub([{ message: 'keep chatting', mode: createMode() }]); + session.sessionId = 'acp-session-1'; + if (failure === 'metadata-flush') Object.assign(session.client, { flushMetadata: vi.fn(async () => false) }); + await opencodeRemoteLauncher(session as never); + expect(harness.promptCount).toBe(1); + expect(agentMessages).not.toEqual(expect.arrayContaining([expect.objectContaining({ type: 'error' })])); + expect(harness.clientMetadata?.capabilities).not.toHaveProperty('conversationHistory'); + } finally { + fetchSpy.mockRestore(); + } + }); + + it.each(['history-get', 'v2-discovery'])('retains strict validation for new fork children (%s)', async (failure) => { + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', forkedFrom: 'parent-hapi-session', opencodeForkPending: true, + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: ['msg_original'], userMessageIds: ['msg_original'], localMessageIds: [] } }; + if (failure === 'v2-discovery') harness.detectedVersion = 'v2'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response('unavailable', { status: 503 })); + try { + const { session } = createSessionStub([{ message: 'must not start', mode: createMode() }]); + session.sessionId = 'acp-session-1'; + const ready = vi.fn(); + Object.assign(session.client, { emitSessionReady: ready }); + await expect(opencodeRemoteLauncher(session as never)).rejects.toThrow(); + expect(harness.promptCount).toBe(0); + expect(ready).not.toHaveBeenCalled(); + } finally { + fetchSpy.mockRestore(); + } + }); + + it('refuses strict fork-child entry until previous checkpoint writes are durable', async () => { + harness.clientMetadata = { forkedFrom: 'parent-hapi-session', opencodeForkPending: true }; + const { session, rpcHandlers } = createSessionStub([]); + session.sessionId = 'acp-session-1'; + Object.assign(session.client, { flushMetadata: vi.fn(async () => false) }); + await expect(opencodeRemoteLauncher(session as never)).rejects.toThrow('durable before remote entry'); + expect(rpcHandlers.has('fork-conversation')).toBe(false); + expect(harness.promptCount).toBe(0); + }); + + it('keeps a post-compaction identity baseline across local undo and remote current fork', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + let ids = ['msg_user']; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: ids.slice(), userMessageIds: ['msg_user'], localMessageIds: [] } }; + harness.sessionModelsMetadata = { currentModelId: 'ollama/x', availableModels: [] }; + compactHarness.triggerV2Impl = async () => { + ids = ['msg_user', 'msg_compaction_summary']; + return { kind: 'admitted' as const, compactionId: 'msg_compaction_summary' }; + }; + compactHarness.pollImpl = async () => ({ status: 'success', text: 'compaction summary' }); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => new Response(JSON.stringify( + init?.method === 'POST' ? { data: { id: 'ses_wrong_child' } } + : String(input).includes('/message?') ? { data: ids.map((id, i) => ({ id, type: i === 0 ? 'user' : 'assistant' })), cursor: {} } + : { paths: { '/api/session/{sessionID}/fork': { post: {} } } } + ))); + try { + const first = createSessionStub([{ message: '', mode: createCompactMode('ollama/x') }]); + first.session.sessionId = 'acp-session-1'; + await opencodeRemoteLauncher(first.session as never); + expect(harness.clientMetadata?.opencodeHistoryCheckpoint).toMatchObject({ messageIds: ['msg_user', 'msg_compaction_summary'] }); + ids = ['msg_user', 'msg_replacement_summary']; + const second = createSessionStub([], { keepOpen: true }); + second.session.sessionId = 'acp-session-1'; + const pending = opencodeRemoteLauncher(second.session as never); + try { + await vi.waitFor(() => expect(second.rpcHandlers.has('fork-conversation')).toBe(true)); + await expect(second.rpcHandlers.get('fork-conversation')!({})).rejects.toThrow(/diverg|not supported/i); + expect(harness.clientMetadata?.conversationHistoryDiverged).toBe(true); + expect(fetchSpy.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false); + } finally { + second.session.queue.close(); + await pending; + } + } finally { + fetchSpy.mockRestore(); + } + }); + + it('waits for checkpoint persistence before completing a prompt batch', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + let persist!: () => void; + const persistence = new Promise((resolve) => { persist = resolve; }); + const { session } = createSessionStub([{ message: 'hello', localId: 'local-hello', mode: createMode() }]); + let waitingForPersistence = false; + Object.assign(session.client, { flushMetadata: vi.fn(async () => { + if (harness.clientMetadata?.opencodeHistoryCheckpoint && harness.promptCount > 0) { + waitingForPersistence = true; + await persistence; + } + return true; + }) }); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => new Response(JSON.stringify( + String(input).includes('/message?') + ? { data: harness.promptCount ? [{ id: 'msg_hello', type: 'user' }] : [], cursor: {} } + : { paths: { '/api/session/{sessionID}/fork': { post: {} } } } + ))); + let finished = false; + const pending = opencodeRemoteLauncher(session as never).then(() => { finished = true; }); + try { + await vi.waitFor(() => expect(waitingForPersistence).toBe(true)); + await new Promise((resolve) => setImmediate(resolve)); + expect(finished).toBe(false); + } finally { + persist(); + await pending; + fetchSpy.mockRestore(); + } + }); + + it('forks the actual next prompt after automatic compaction adds internal user messages', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const messages: Array<{ id: string; type: string; text?: string }> = []; + let forkBody: unknown; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const url = String(input); + if (init?.method === 'POST') { + forkBody = JSON.parse(init.body as string); + return new Response(JSON.stringify({ data: { id: 'ses_compacted_fork' } })); + } + if (url.includes('/ses_compacted_fork/message')) { + return new Response(JSON.stringify({ data: messages.filter((entry) => entry.type === 'user').slice(0, 3) + .map((entry) => ({ ...entry, id: 'forked_' + entry.id })), cursor: {} })); + } + return new Response(JSON.stringify(url.includes('/message?') + ? { data: messages, cursor: {} } + : { paths: { '/api/session/{sessionID}/fork': { post: {} } } })); + }); + harness.promptImpl = async () => { + if (harness.promptCount === 1) { + messages.push( + { id: 'msg_first', type: 'user' }, + { id: 'msg_reply', type: 'assistant' }, + { id: 'msg_compaction', type: 'user', text: 'Continue if you have next steps' }, + { id: 'msg_summary', type: 'assistant' }, + { id: 'msg_continue', type: 'user', text: 'Continue if you have next steps' } + ); + } else { + messages.push({ id: 'msg_second', type: 'user', text: 'second' }); + } + }; + const { session, rpcHandlers } = createSessionStub([ + { message: 'first', localId: 'local-first', mode: createMode() }, + { message: 'second', localId: 'local-second', mode: createMode() } + ], { keepOpen: true }); + const launcherPromise = opencodeRemoteLauncher(session as never); + try { + await vi.waitFor(() => expect(harness.clientMetadata?.conversationHistoryPoints).toMatchObject({ 'local-second': true })); + await new Promise((resolve) => setImmediate(resolve)); + await expect(rpcHandlers.get('fork-conversation')!({ messageLocalId: 'local-second' })) + .resolves.toEqual({ nativeSessionId: 'ses_compacted_fork', opencodeHistoryCheckpoint: { + sessionId: 'ses_compacted_fork', messageIds: ['forked_msg_first', 'forked_msg_compaction', 'forked_msg_continue'], + userMessageIds: ['forked_msg_first', 'forked_msg_compaction', 'forked_msg_continue'], localMessageIds: [] + } }); + expect(forkBody).toEqual({ before: 'msg_second' }); + expect(harness.clientMetadata?.conversationHistoryIndexes).toMatchObject({ 'local-first': 0, 'local-second': 3 }); + } finally { + session.queue.close(); + await launcherPromise; + fetchSpy.mockRestore(); + } + }); + + it('records no fork point when native history is unavailable', async () => { + const { OpencodeConversationHistory } = await import('./conversationHistory'); + const countSpy = vi.spyOn(OpencodeConversationHistory.prototype, 'getNativeUserMessageCount') + .mockResolvedValue(null); + const rememberSpy = vi.spyOn(OpencodeConversationHistory.prototype, 'rememberPromptIndex'); + const { session } = createSessionStub([ + { message: 'hello', mode: createMode() } + ]); + + try { + await opencodeRemoteLauncher(session as never); + expect(countSpy).toHaveBeenCalled(); + expect(rememberSpy).not.toHaveBeenCalled(); + } finally { + countSpy.mockRestore(); + rememberSpy.mockRestore(); + } + }); + + it('retries the native count for the next batch instead of reusing an unavailable position', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + const { OpencodeConversationHistory } = await import('./conversationHistory'); + const countSpy = vi.spyOn(OpencodeConversationHistory.prototype, 'getNativeUserMessageCount') + .mockResolvedValueOnce(null).mockResolvedValueOnce(3); + const rememberSpy = vi.spyOn(OpencodeConversationHistory.prototype, 'rememberPromptIndex'); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => new Response(JSON.stringify( + String(input).includes('/message?') + ? { data: Array.from({ length: harness.promptCount === 0 ? 0 : harness.promptCount === 1 ? 1 : 4 }, (_, i) => ({ id: `msg_${i}`, type: 'user' })), cursor: {} } + : { paths: { '/api/session/{sessionID}/fork': { post: {} } } } + ))); + try { + const { session } = createSessionStub([ + { message: 'unavailable', localId: 'local-unavailable', mode: createMode() }, + { message: 'recovered', localId: 'local-recovered', mode: createMode() } + ]); + await opencodeRemoteLauncher(session as never); + expect(countSpy).toHaveBeenCalledTimes(2); + expect(rememberSpy).toHaveBeenCalledExactlyOnceWith('local-recovered', 3); + } finally { + countSpy.mockRestore(); + rememberSpy.mockRestore(); + fetchSpy.mockRestore(); + } + }); + it('reaches /clear only after the earlier prompt settles, without starting another OpenCode turn', async () => { let resolvePrompt: (() => void) | null = null; harness.promptImpl = () => new Promise((resolve) => { @@ -728,6 +2682,82 @@ describe('opencodeRemoteLauncher inline model switch', () => { (backendModule.createOpencodeBackend as unknown as ReturnType).mockClear(); }); + it('never starts a blank native session when a fork child fails to load its native session', async () => { + harness.clientMetadata = { forkedFrom: 'parent-session' }; + harness.loadSessionImpl = async () => { + throw new Error('load failed'); + }; + const { session } = createSessionStub([ + { message: 'hello', mode: createMode(), localId: 'local-1' } + ]); + (session as { sessionId: string | null }).sessionId = 'ses_child'; + + await expect(opencodeRemoteLauncher(session as never)).rejects.toThrow('load failed'); + const backendModule = await import('./utils/opencodeBackend'); + const backend = (backendModule.createOpencodeBackend as unknown as ReturnType).mock.results[0]?.value; + expect(backend.newSession).not.toHaveBeenCalled(); + (backendModule.createOpencodeBackend as unknown as ReturnType).mockClear(); + }); + + it('falls back to a new native session when a plain resume fails', async () => { + harness.loadSessionImpl = async () => { + throw new Error('load failed'); + }; + const { session } = createSessionStub([ + { message: 'hello', mode: createMode() } + ]); + (session as { sessionId: string | null }).sessionId = 'ses_plain'; + + const result = await opencodeRemoteLauncher(session as never); + expect(result).toBe('exit'); + const backendModule = await import('./utils/opencodeBackend'); + const backend = (backendModule.createOpencodeBackend as unknown as ReturnType).mock.results[0]?.value; + expect(backend.newSession).toHaveBeenCalled(); + (backendModule.createOpencodeBackend as unknown as ReturnType).mockClear(); + }); + + it('marks history diverged and drops stale locators after a resume falls back to a fresh native session', async () => { + harness.clientMetadata = { + capabilities: { conversationHistory: { forkCurrent: true, forkAtMessage: true } }, + conversationHistoryPoints: { local1: true }, + conversationHistoryIndexes: { local1: 0 } + }; + harness.loadSessionImpl = async () => { + throw new Error('load failed'); + }; + const { session } = createSessionStub([ + { message: 'hello', mode: createMode() } + ]); + (session as { sessionId: string | null }).sessionId = 'ses_plain'; + + await opencodeRemoteLauncher(session as never); + + const divergedUpdate = harness.metadataUpdates.find((update) => update.conversationHistoryDiverged === true); + expect(divergedUpdate).toBeDefined(); + expect(divergedUpdate!.conversationHistoryPoints).toBeUndefined(); + expect(divergedUpdate!.conversationHistoryIndexes).toBeUndefined(); + expect((divergedUpdate!.capabilities as Record).conversationHistory).toBeUndefined(); + }); + + it('keeps history disabled on a later launch when divergence was persisted', async () => { + harness.clientMetadata = { conversationHistoryDiverged: true }; + const probeSpy = vi.spyOn( + (await import('./conversationHistory')).OpencodeConversationHistory.prototype, + 'probeCapabilities' + ); + const { session } = createSessionStub([ + { message: 'hello', mode: createMode() } + ]); + (session as { sessionId: string | null }).sessionId = 'ses_diverged'; + + try { + await opencodeRemoteLauncher(session as never); + expect(probeSpy).not.toHaveBeenCalled(); + } finally { + probeSpy.mockRestore(); + } + }); + it.each(['permission', 'server'] as const)('aborts clear when %s cleanup fails', async (stage) => { if (stage === 'permission') harness.permissionCancelError = new Error('permission cleanup failed'); else harness.serverStopError = new Error('server cleanup failed'); @@ -1407,6 +3437,78 @@ describe('opencodeRemoteLauncher inline model switch', () => { expect(sentAgentMessages).toContainEqual({ type: 'compact-summary', summary: '## Objective\n- Did the thing' }); }); + it('fork child startup does not republish the inherited automatic compaction its copied transcript already carries', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + // Hub fork state: the child's transcript was hydrated from the parent + // (its auto-compaction card is already stored there under the parent + // session's localId) and the child resumed its own forked native + // session. The baseline transcript refresh below replays that same + // completed compaction; republishing it would mint a child-session + // localId the hub cannot dedupe against the copied card, appending a + // duplicate historical summary at the child's tail. + harness.clientMetadata = { + path: '/tmp/hapi-opencode-test', host: 'fixture', + forkedFrom: 'parent-hapi-session', + opencodeForkPending: true, + conversationHistoryPoints: { 'local-first': true }, + conversationHistoryIndexes: { 'local-first': 0 }, + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: ['msg_marker', 'msg_summary'], userMessageIds: ['msg_marker'], localMessageIds: [] } + }; + harness.transcriptFetchImpl = async () => Response.json([ + { info: { id: 'msg_marker', sessionID: 'acp-session-1', role: 'user' }, + parts: [{ id: 'part_marker', messageID: 'msg_marker', sessionID: 'acp-session-1', type: 'compaction', auto: true }] }, + { info: { id: 'msg_summary', sessionID: 'acp-session-1', role: 'assistant', summary: true, parentID: 'msg_marker', finish: 'stop' }, + parts: [{ id: 'part_summary', messageID: 'msg_summary', sessionID: 'acp-session-1', type: 'text', text: 'inherited summary', time: { end: 1 } }] } + ]); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => new Response(JSON.stringify( + String(input).includes('/message?') + ? { data: [{ id: 'msg_marker', type: 'user' }, { id: 'msg_summary', type: 'assistant' }], cursor: {} } + : { paths: { '/api/session/{sessionID}/fork': { post: {} } } } + ))); + const { session, sentAgentMessages } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + const sentLocalIds: unknown[] = []; + const clientSend = session.client.sendAgentMessage.bind(session.client); + Object.assign(session.client, { + sendAgentMessage: (message: unknown, localId?: string) => { + sentLocalIds.push(localId); + clientSend(message); + } + }); + + const launcherPromise = opencodeRemoteLauncher(session as never); + try { + // The baseline read is awaited before the event stream subscribes, + // so the inherited compaction's replay has already been decided. + await vi.waitFor(() => expect(harness.eventStreamOptions.length).toBe(1)); + + // A compaction completing in the child after startup is a genuine + // new event and must still publish under the child's localId. + const onEvent = harness.eventStreamOptions[0]!.onEvent!; + onEvent('message.updated', { info: { id: 'msg_new', sessionID: 'acp-session-1', role: 'user' } }); + onEvent('message.part.updated', { part: { id: 'part_new_marker', messageID: 'msg_new', sessionID: 'acp-session-1', type: 'compaction', auto: true } }); + onEvent('message.updated', { info: { id: 'msg_new_summary', sessionID: 'acp-session-1', role: 'assistant', summary: true, parentID: 'msg_new' } }); + onEvent('message.part.updated', { part: { id: 'part_new_text', messageID: 'msg_new_summary', sessionID: 'acp-session-1', type: 'text', text: 'child summary', time: { end: 2 } } }); + onEvent('message.updated', { info: { id: 'msg_new_summary', sessionID: 'acp-session-1', role: 'assistant', summary: true, parentID: 'msg_new', finish: 'stop' } }); + await vi.waitFor(() => expect(sentAgentMessages).toContainEqual({ type: 'compact-summary', summary: 'child summary' })); + + // Exactly one compaction summary card ends up in the child: the + // copied one. The inherited replay must not add a second. + expect(sentAgentMessages.filter((m: unknown) => (m as { type?: string; summary?: string }).type === 'compact-summary' + && (m as { summary?: string }).summary === 'inherited summary')).toHaveLength(0); + expect(sentLocalIds).toContain('opencode:acp-session-1:compaction:msg_new'); + expect(sentLocalIds).not.toContain('opencode:acp-session-1:compaction:msg_marker'); + } finally { + session.queue.close(); + await Promise.race([ + launcherPromise, + new Promise((_, reject) => setTimeout(() => reject(new Error('launcher did not exit in time')), 5000)) + ]); + fetchSpy.mockRestore(); + } + }); + it('does not report completion when HTTP success resolves to the observed empty terminal summary failure', async () => { compactHarness.compactionResult = { status: 'failed', @@ -1962,6 +4064,20 @@ describe('opencodeRemoteLauncher inline model switch', () => { expect(lookupAfterEager!).toBeLessThan(harness.events.indexOf('prompt:start')); }); + it('holds synchronous admission across the eager native model request', async () => { + const gate = new OpenCodeRuntimeGate(); + harness.sessionModelsMetadata = { currentModelId: 'default', availableModels: [] }; + const { session } = createSessionStub([]); + session.model = 'requested'; + let rejected = false; + harness.setModelImpl = async () => { + try { gate.reserve(); } catch { rejected = true; } + if (!rejected) gate.release(); + }; + await opencodeRemoteLauncher({ ...session, runtimeGate: gate } as never); + expect(rejected).toBe(true); + }); + it('ignores an eager startup model failure and lets the first batch retry inline', async () => { let eagerFailed = false; harness.setModelImpl = async () => { @@ -3005,8 +5121,7 @@ describe('selectAbortStatusMessage', () => { } const { session, rpcHandlers } = createSessionStub([{ message: 'aborted before prompt', mode: createMode() }], { keepOpen: true }) const launchPromise = opencodeRemoteLauncher(session as never) - await new Promise((resolve) => setImmediate(resolve)) - expect(roundSummaryHarness.snapshotCalls).toHaveLength(1) + await vi.waitFor(() => expect(roundSummaryHarness.snapshotCalls).toHaveLength(1)) const abortHandler = rpcHandlers.get(RPC_METHODS.Abort) as (() => Promise) | undefined expect(abortHandler).toBeDefined() @@ -3022,6 +5137,43 @@ describe('selectAbortStatusMessage', () => { expect(text).toContain('actual second prompt') }) + it('keeps native instructions for the first actual prompt after Stop aborts the history read', async () => { + roundSummaryHarness.snapshotImpl = async () => ({ messageIds: [] }) + harness.promptCount = 0 + harness.promptContents = [] + const { OpencodeConversationHistory } = await import('./conversationHistory') + let countCalls = 0 + let releaseFirstCount: ((value: number | null) => void) | null = null + const countSpy = vi.spyOn(OpencodeConversationHistory.prototype, 'getNativeUserMessageCount') + .mockImplementation(() => { + countCalls += 1 + return countCalls === 1 + ? new Promise((resolve) => { releaseFirstCount = resolve }) + : Promise.resolve(null) + }) + try { + const { session, rpcHandlers } = createSessionStub([{ message: 'aborted during history read', mode: createMode() }], { keepOpen: true }) + const launchPromise = opencodeRemoteLauncher(session as never) + await vi.waitFor(() => expect(countCalls).toBe(1)) + + const abortHandler = rpcHandlers.get(RPC_METHODS.Abort) as (() => Promise) | undefined + expect(abortHandler).toBeDefined() + await abortHandler!() + session.queue.push('actual second prompt', createMode()) + releaseFirstCount!(null) + await vi.waitFor(() => expect(harness.promptCount).toBe(1)) + session.queue.close() + await launchPromise + + expect(harness.promptCount).toBe(1) + const text = (harness.promptContents[0] as Array<{ type: string; text?: string }>)[0]?.text + expect(text).toContain(getOpencodeNativeToolInstruction()) + expect(text).toContain('actual second prompt') + } finally { + countSpy.mockRestore() + } + }) + it('does not start a backend prompt when Switch arrives during the blocking pre-prompt snapshot', async () => { roundSummaryHarness.snapshotCalls = [] harness.promptCount = 0 @@ -3029,8 +5181,7 @@ describe('selectAbortStatusMessage', () => { roundSummaryHarness.snapshotImpl = () => new Promise((resolve) => { releaseSnapshot = resolve }) const { session, rpcHandlers, sessionEvents } = createSessionStub([{ message: 'snapshot switch', mode: createMode() }]) const launchPromise = opencodeRemoteLauncher(session as never) - await new Promise((resolve) => setImmediate(resolve)) - expect(roundSummaryHarness.snapshotCalls).toHaveLength(1) + await vi.waitFor(() => expect(roundSummaryHarness.snapshotCalls).toHaveLength(1)) const switchHandler = rpcHandlers.get(RPC_METHODS.Switch) as (() => Promise) | undefined expect(switchHandler).toBeDefined() @@ -3050,8 +5201,7 @@ describe('selectAbortStatusMessage', () => { roundSummaryHarness.snapshotImpl = () => new Promise((resolve) => { releaseSnapshot = resolve }) const { session, rpcHandlers, sessionEvents } = createSessionStub([{ message: 'snapshot abort', mode: createMode() }]) const launchPromise = opencodeRemoteLauncher(session as never) - await new Promise((resolve) => setImmediate(resolve)) - expect(roundSummaryHarness.snapshotCalls).toHaveLength(1) + await vi.waitFor(() => expect(roundSummaryHarness.snapshotCalls).toHaveLength(1)) const abortHandler = rpcHandlers.get('abort') as (() => Promise) | undefined expect(abortHandler).toBeDefined() @@ -3126,6 +5276,8 @@ describe('opencodeRemoteLauncher mid-turn steer', () => { firstMode?: OpencodeMode; holdPrompt?: boolean; launcherOptions?: Parameters[1]; + runtimeGate?: OpenCodeRuntimeGate; + prepareSession?: (stub: SteerSession) => void; } = {}): Promise<{ stub: SteerSession; handlers: Map unknown>; @@ -3146,6 +5298,8 @@ describe('opencodeRemoteLauncher mid-turn steer', () => { [{ message: opts.firstMessage ?? 'first', mode, localId: 'first' }], { keepOpen: true } ); + if (opts.runtimeGate) Object.assign(stub.session, { runtimeGate: opts.runtimeGate }); + opts.prepareSession?.(stub); const runPromise = opencodeRemoteLauncher(stub.session as never, opts.launcherOptions); await vi.waitFor(() => expect(harness.promptCount).toBe(1)); // Later prompts fall back to the default auto-resolving prompt, so a @@ -3189,6 +5343,123 @@ describe('opencodeRemoteLauncher mid-turn steer', () => { return { steering, releaseState }; } + it('composition: refuses steering under a managed rewind gate before queue reservation', async () => { + const gate = new OpenCodeRuntimeGate(); + const { stub, releasePrompt, runPromise } = await startTurn({ runtimeGate: gate }); + try { + gate.block(); + stub.session.queue.push('correction', createMode(), 'steer'); + await expect(steerHandlerOf(stub)({ localId: 'steer' })).resolves.toMatchObject({ steered: false }); + expect(stub.session.queue.peekByLocalId('steer')?.message).toBe('correction'); + expect(harness.steerStateCalls).toEqual([]); + expect(harness.softSteerCalls).toEqual([]); + } finally { + gate.release(); + await stopTurn(stub, releasePrompt, runPromise); + } + }); + + it('composition: drains accepted steer ownership before publishing the foreground checkpoint', async () => { + let releaseSteer!: () => void; + harness.deferSoftSteer = new Promise(resolve => { releaseSteer = resolve; }); + const reconcile = vi.spyOn(OpencodeConversationHistory.prototype, 'reconcileHistory'); + const { stub, releasePrompt, runPromise } = await startTurn(); + try { + stub.session.queue.push('correction', createMode(), 'steer'); + await steerHandlerOf(stub)({ localId: 'steer' }); + const readsBeforeCompletion = reconcile.mock.calls.length; + releasePrompt(); + await vi.waitFor(() => expect(harness.events).toContain('prompt:end')); + await new Promise(resolve => setImmediate(resolve)); + expect(reconcile.mock.calls.length).toBe(readsBeforeCompletion); + expect(stub.session.thinking).toBe(true); + releaseSteer(); + await vi.waitFor(() => expect(stub.session.thinking).toBe(false)); + expect(reconcile.mock.calls.length).toBeGreaterThan(readsBeforeCompletion); + } finally { + releaseSteer(); + await stopTurn(stub, releasePrompt, runPromise); + reconcile.mockRestore(); + } + }); + + it.each(['lost-admission', 'cancelled-writer'] as const)('composition: refuses rewind with an unresolved native steer (%s)', async scenario => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; harness.servePid = process.pid; + let current = [{ id: 'u1', type: 'user', text: 'one' }, { id: 'u2', type: 'user', text: 'two' }]; + let staged: string | undefined; + let nativeInputId = ''; + let postCount = 0; + let stageCount = 0; + const metadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: ['u1', 'u2'], + userMessageIds: ['u1', 'u2'], localMessageIds: [] }, conversationHistoryIndexes: { one: 0, two: 1 } }; + harness.clientMetadata = metadata; + const nativeFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const url = String(input); + if (url.endsWith('/revert/stage')) { stageCount++; staged = 'u2'; return Response.json({}); } + if (url.endsWith('/revert/commit')) { current = current.slice(0, 1); staged = undefined; return new Response(null, { status: 204 }); } + if (url.endsWith('/prompt') && init?.method === 'POST') { + postCount++; nativeInputId = JSON.parse(String(init.body)).id; + // Transport loss is not evidence that the native write cannot run later. + throw new Error('lost admission response'); + } + if (url.includes('/message?')) return Response.json({ data: current, cursor: {} }); + if (url.endsWith('/active')) return Response.json({ data: {} }); + if (url.endsWith('/inbox')) return Response.json({ data: [] }); + if (url.includes('/message/msg_')) return new Response(null, { status: 404 }); + if (url.endsWith('/doc') || url.endsWith('/openapi.json')) return Response.json({ paths: { + '/api/session/{sessionID}/fork': {}, '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} } }); + return Response.json({ data: { id: 'acp-session-1', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }); + const gate = new OpenCodeRuntimeGate(); + let reportCount = 0; + const { stub, releasePrompt, runPromise } = await startTurn({ runtimeGate: gate, prepareSession: stub => { + stub.session.sessionId = 'acp-session-1'; + Object.assign(stub.session.client, { sessionId: `steer-rewind-${scenario}-${Date.now()}`, + flushMetadata: async () => true, flush: async () => true, refreshMetadata: async () => true, on: vi.fn(), off: vi.fn(), + reportOpenCodeRewind: async (report: OpenCodeRewindReport): Promise => { + reportCount++; + const operation = { ...report.operation, phase: report.phase === 'applied' ? 'committed' as const : report.phase }; + harness.clientMetadata = { ...harness.clientMetadata, opencodeRewind: operation, + ...(report.phase === 'applied' ? { opencodeHistoryCheckpoint: report.checkpoint, conversationHistoryIndexes: report.indexes } : {}) }; + return operation; + } }); + } }); + try { + const workerId = harness.clientMetadata!.opencodeWorkerId as string; + current.push({ id: 'u3', type: 'user', text: 'first' }); + stub.session.queue.push('correction', createMode(), 'steer'); + await expect(steerHandlerOf(stub)({ localId: 'steer' })).resolves.toMatchObject({ steered: false }); + expect(postCount).toBe(1); + expect(nativeInputId).toMatch(/^msg_/); + if (scenario === 'cancelled-writer') { + // Explicit HAPI resolution does not fence a lost native POST. + expect(stub.session.queue.cancelByLocalId('steer')).toBe(true); + await (stub.rpcHandlers.get('abort') as () => Promise)(); + } + releasePrompt(); + await vi.waitFor(() => expect(stub.session.thinking).toBe(false)); + const operation: OpenCodeRewindOperation = { operationId: 'unresolved-native-steer', nativeSessionId: 'acp-session-1', + nativeMessageId: 'u2', workerId, workerPid: (harness.clientMetadata!.opencodeWorkerProcess as { pid: number } | undefined)?.pid ?? process.pid, + workerStartMarker: (harness.clientMetadata!.opencodeWorkerProcess as { startMarker: string } | undefined)?.startMarker ?? getProcessStartMarker(process.pid)!, requestedLocalId: 'two', cutoffSeq: 2, sourceEpoch: 0, sourceMaxSeq: 3, + reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase: 'reserved' }; + harness.clientMetadata!.opencodeRewind = operation; + const result = await (stub.rpcHandlers.get('rewind-conversation') as (p: unknown) => Promise)({ + messageLocalId: 'two', opencodeRewind: operation + }).catch(error => ({ success: false, error: String(error) })); + expect(result).toMatchObject({ success: false, error: expect.stringMatching(/busy|idle/) }); + expect(stageCount).toBe(0); + expect(reportCount).toBe(1); // Definite local refusal is reported without native mutation. + expect(current.map(row => row.id)).toEqual(['u1', 'u2', 'u3']); + expect(stub.emitMessagesConsumedCalls).toEqual([]); + } finally { + gate.release(); + await stopTurn(stub, releasePrompt, runPromise); + nativeFetch.mockRestore(); + } + }); + it.each([true, false])('advertises v2 steering only with REST discovery=%s', async (discovered) => { harness.detectedVersion = 'v2'; harness.discoveredPort = discovered ? 48274 : null; @@ -5424,6 +7695,74 @@ describe('opencodeRemoteLauncher v2 flavor wiring', () => { expect(harness.v2PasswordCalls).toEqual([{ pid: 4242 }]); }); + it('v2: preserves the exact historical target through resume', async () => { + const projected = [ + { id: 'marker', type: 'compaction', status: 'completed', reason: 'manual', summary: 'retained summary' }, + { id: 'target', type: 'user', text: 'last prompt' } + ]; + harness.clientMetadata = { path: '/tmp/hapi-opencode-test', host: 'fixture', + opencodeSessionId: 'acp-session-1', + opencodeHistoryCheckpoint: { sessionId: 'acp-session-1', messageIds: ['marker', 'target'], + userMessageIds: ['target'], localMessageIds: [] }, + conversationHistoryIndexes: { 'local-target': 0 } }; + harness.detectedVersion = 'v2'; + harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; + harness.servePid = process.pid; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const url = String(input); + return Response.json(init?.method === 'POST' ? { data: { id: 'child' } } + : url.includes('/child/message?') ? { data: [projected[0]], cursor: {} } + : url.includes('/message?') ? { data: projected, cursor: {} } + : { paths: { '/api/session/{sessionID}/fork': { post: {} } } }); + }); + const { session, rpcHandlers } = createSessionStub([], { keepOpen: true }); + session.sessionId = 'acp-session-1'; + Object.assign(session.client, { sessionId: 'acp-hapi-session' }); + const pending = opencodeRemoteLauncher(session as never); + try { + await vi.waitFor(() => expect(rpcHandlers.has('fork-conversation')).toBe(true)); + expect(harness.clientMetadata?.conversationHistoryIndexes).toEqual({ 'local-target': 0 }); + expect(harness.clientMetadata?.opencodeHistoryCheckpoint).toMatchObject({ + sessionId: 'acp-session-1', messageIds: ['marker', 'target'], userMessageIds: ['target'] + }); + expect(harness.clientMetadata?.conversationHistoryDiverged).not.toBe(true); + await expect(rpcHandlers.get('fork-conversation')!({ messageLocalId: 'local-target' })).resolves.toMatchObject({ + nativeSessionId: 'child', opencodeHistoryCheckpoint: { sessionId: 'child', messageIds: ['marker'], userMessageIds: [] } + }); + const post = fetchSpy.mock.calls.find(([, init]) => init?.method === 'POST'); + expect(JSON.parse(post![1]!.body as string)).toEqual({ before: 'target' }); + } finally { + session.queue.close(); + await pending; + fetchSpy.mockRestore(); + } + }); + + it('v2: connects history probes and message counts to the discovered authenticated server', async () => { + harness.detectedVersion = 'v2'; + harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + const url = String(input); + return new Response(JSON.stringify(url.includes('/message?') + ? { data: [], cursor: {} } + : { paths: { '/api/session/{sessionID}/fork': { post: {} } } })); + }); + try { + const { session } = createSessionStub([{ message: 'hello', mode: createMode() }]); + await opencodeRemoteLauncher(session as never); + const messageCall = fetchSpy.mock.calls.find(([url]) => String(url).includes('/message?')); + expect(messageCall).toBeDefined(); + expect(String(messageCall![0])).toContain('http://127.0.0.1:41234/api/session/'); + expect(messageCall![1]?.headers).toMatchObject({ + authorization: 'Basic ' + Buffer.from('opencode:fixture-password').toString('base64') + }); + } finally { + fetchSpy.mockRestore(); + } + }); + it('v2: scopes port discovery to the serve process so an unrelated descendant listener cannot win', async () => { // GPT finding: the tree can own other listeners (e.g. a configured // MCP server with a lower port). Discovery must scan the serve diff --git a/cli/src/opencode/opencodeRemoteLauncher.ts b/cli/src/opencode/opencodeRemoteLauncher.ts index b4e683a6..4a4bbfd4 100644 --- a/cli/src/opencode/opencodeRemoteLauncher.ts +++ b/cli/src/opencode/opencodeRemoteLauncher.ts @@ -52,6 +52,12 @@ import { OpencodePermissionHandler } from './utils/permissionHandler'; import { presentQuestionToolCall } from './utils/opencodeQuestion'; import { getOpencodeNativeToolInstruction, PLAN_MODE_INSTRUCTION } from './utils/systemPrompt'; import { resolveThoughtLevelEffort } from './thoughtLevelEffort'; +import { OpencodeConversationHistory } from './conversationHistory'; +import { OpenCodeRewind, OpenCodeRewindSupersededError, OpenCodeRuntimeBlockedError, OpenCodeRuntimeGate, readOpenCodeRewindIntent, sameOperation } from './rewind'; +import { OpenCodeRewindSchema } from '@hapi/protocol/schemas'; +import { configuration } from '@/configuration'; +import { join } from 'node:path'; +import { getProcessStartMarker } from '@/utils/process'; import { fetchOpencodeUserMessages } from './utils/opencodeInputReceipt'; type OpencodeRemoteLauncherOptions = { @@ -189,19 +195,10 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { // replacement while the source backend may still be live. private clearRequested = false; private abortController = new AbortController(); - // Set by the dequeue loop as soon as a batch is identified as a - // `operation:'compact'` one — deliberately *before* that batch's inline - // model/effort switch runs, not only once runCompactOperation()'s - // triggerOpencodeCompact() REST call actually starts (a hostile-review - // sweep found that creating it any later left a window during that - // switch — a real async ACP round-trip — where an abort had nothing to - // act on yet). Null whenever no compact batch is in flight. Unlike - // `abortController` above (which governs the dequeue loop's - // wait-for-next-message signal), `handleAbort()` needs this to actually - // interrupt the compact's HTTP call(s) — without it, Stop/switch-to-local - // has no way to unblock a dequeued /compact whose REST call is - // deliberately unbounded (see triggerOpencodeCompact's doc comment) and - // the launcher stays wedged until it eventually settles on its own. + // Created before the compact batch's async model/effort switch so aborts + // during that switch reach the same controller as the later HTTP calls. + // Null when no compact batch is in flight. Unlike abortController, which + // interrupts queue waiting, this controller interrupts compact HTTP work. private compactAbortController: AbortController | null = null; private roundSummaryAbortController: AbortController | null = null; /** Distinguishes an active prompt from read-only post-prompt work for Stop semantics. */ @@ -230,6 +227,16 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { private eventStream: OpencodeEventSubscription | null = null; private nativeTranscript: OpencodeNativeTranscript | null = null; private stallErrorReportedForPrompt = false; + private nativeHistoryUnverified = false; + /** Cancels the detached capability probe when remote mode is left. */ + private readonly historyProbeAbortController = new AbortController(); + private readonly conversationHistory = new OpencodeConversationHistory(() => ({ + baseUrl: this.v2RestInfo?.baseUrl ?? this.baseUrl, + headers: this.v2RestInfo ? { + authorization: 'Basic ' + Buffer.from(`opencode:${this.v2RestInfo.password}`).toString('base64') + } : undefined, + sessionId: this.activeAcpSessionId + })); /** True while a normal (non-compact/clear) prompt turn is in flight — the only steerable state. */ private promptInFlight = false; /** Mode hash of the prompt turn currently in flight; steers must match it. */ @@ -278,6 +285,25 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { private majorVersion: OpencodeFlavorVersion | null = null; /** v2-only REST access discovered after spawn; null unless both port and OPENCODE_PASSWORD were found. */ private v2RestInfo: { baseUrl: string; password: string } | null = null; + private readonly workerId: string; + private readonly runtimeGate: OpenCodeRuntimeGate; + private nativeProcess: { pid: number; startMarker: string } | undefined; + private rewind: OpenCodeRewind | null = null; + private rewindInFlight = false; + private rewindReconnect: (() => void) | null = null; + private rewindConnectionStart: (() => void) | null = null; + private entryFence: symbol | undefined; + private entryEpoch = 0; + /** The in-memory checkpoint is newer than Hub's: a publication was withheld by the entry fence. */ + private historyPublicationDeferred = false; + private detachEntryHandoff: (() => void) | undefined; + private drainReconnect: (() => void) | undefined; + private rewindReconnectPending = false; + private entryRetryTimer: NodeJS.Timeout | undefined; + private entryRetryAttempt = 0; + private rewindStopped = false; + private readonly rewindEntryAbortController = new AbortController(); + private rewindSupersededId: string | undefined; private v2Steers = new Map(); private v2AbortInProgress: Promise | null = null; private v2ResetInProgress: Promise | null = null; @@ -288,6 +314,87 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { ) { super(process.env.DEBUG ? session.logPath : undefined); this.session = session; + this.runtimeGate = session.runtimeGate ?? new OpenCodeRuntimeGate(); + this.workerId = this.runtimeGate.workerId; + this.entryFence = this.runtimeGate.takeInitialEntryFence() ?? this.runtimeGate.acquireEntryFence(); + this.detachEntryHandoff = this.runtimeGate.onEntryHandoff(() => { + if (this.rewindStopped) return; + this.entryFence = this.runtimeGate.adoptInitialEntryFence(this.entryFence); + this.entryEpoch++; + this.rewindReconnectPending = true; + this.entryRetryAttempt = 0; + this.drainReconnect?.(); + }); + this.rewindConnectionStart = () => { + if (this.rewindStopped) return; + this.entryEpoch++; + this.entryFence ??= this.runtimeGate.acquireEntryFence(); + }; + this.rewindReconnect = () => { + if (this.rewindStopped) return; + this.rewindConnectionStart?.(); + this.rewindReconnectPending = true; + this.entryRetryAttempt = 0; + this.drainReconnect?.(); + }; + session.client.on('connection-start', this.rewindConnectionStart); + session.client.on('connected', this.rewindReconnect); + } + + private noteSupersededRewind(error: unknown): void { + if (!this.rewindStopped && error instanceof OpenCodeRewindSupersededError + && error.operationId !== this.rewindSupersededId) { + this.entryFence ??= this.runtimeGate.acquireEntryFence(); + this.rewindSupersededId = error.operationId; + this.rewindReconnectPending = true; + } + } + + /** A dropped GET, a stale snapshot or a withheld flush can all clear on + * their own while the socket stays connected, so admission stays fenced + * but the entry is retried with backoff. Journal/identity mismatches and + * superseded operations are decisions, not outages: only a fresh + * connection event re-drives those. */ + private entryFailureRetriable(error: unknown): boolean { + if (this.rewindStopped || this.rewindEntryAbortController.signal.aborted) return false; + if (error instanceof OpenCodeRewindSupersededError) return false; + const permanent = ['OpenCode entry journal native identity mismatch', 'OpenCode entry native identity mismatch', + 'OpenCode entry has an unresolved journal', 'OpenCode rewind requires remote reconciliation', + 'OpenCode entry is not reconciled', 'OpenCode entry journal remains unresolved']; + return !(error instanceof Error && permanent.includes(error.message)); + } + + private clearEntryRetryTimer(): void { + if (!this.entryRetryTimer) return; + clearTimeout(this.entryRetryTimer); + this.entryRetryTimer = undefined; + } + + private scheduleEntryRetry(): void { + this.clearEntryRetryTimer(); + const delay = Math.min(500 * 2 ** this.entryRetryAttempt, 15_000); + this.entryRetryAttempt++; + const timer = setTimeout(() => { + this.entryRetryTimer = undefined; + if (this.rewindStopped || this.rewindInFlight || this.rewindReconnectPending) return; + this.rewindReconnectPending = true; + this.drainReconnect?.(); + }, delay); + // A pending retry must never hold the process open during teardown. + timer.unref?.(); + this.entryRetryTimer = timer; + } + + private detachRewindEntry(): void { + this.detachEntryHandoff?.(); + this.detachEntryHandoff = undefined; + this.clearEntryRetryTimer(); + if (this.rewindConnectionStart) this.session.client.off('connection-start', this.rewindConnectionStart); + if (this.rewindReconnect) this.session.client.off('connected', this.rewindReconnect); + this.rewindConnectionStart = null; + this.rewindReconnect = null; + if (this.entryFence) this.runtimeGate.handoffEntryFence(this.entryFence); + this.entryFence = undefined; } public async launch(): Promise { @@ -322,6 +429,12 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { // session; any detection failure falls back to the v1 path. this.majorVersion = await detectOpencodeFlavorVersion(); const isV2 = this.majorVersion === 'v2'; + if (!isV2) { + // v1 keeps upstream's non-history behavior; the fork/rewind + // machinery must never advertise or mutate history there. + this.conversationHistory.declareUnsupported(); + } + const workerStartMarker = getProcessStartMarker(process.pid); // v1: pre-select a loopback port for the ACP subprocess's internal // HTTP API and pass it explicitly via --port/--hostname. opencode @@ -359,7 +472,39 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { await backend.initialize(); + // Read the REST value itself before using cached metadata to select a + // native resume or publish a session binding. A failed read remains + // an owned entry fence until a later connection event retries it. + const initialSnapshot = await session.client.readRewindMetadata(); + + // Forks can trust restored metadata only after the previous launcher's + // writes reached the hub. Ordinary ACP resumes can run without forks. + let historyMetadataDurable = true; + if (typeof session.client.flushMetadata === 'function' + && !(typeof session.client.isPending === 'function' && session.client.isPending())) { + try { + historyMetadataDurable = await session.client.flushMetadata(); + } catch { + historyMetadataDurable = false; + } + } + const resumeSessionId = session.sessionId; + // A fork child's transcript already lives on the hub; silently + // falling back to a blank native session would show inherited + // messages the model cannot actually see (same fence as grok). + const currentMetadata = initialSnapshot?.metadata ?? session.client.getMetadata(); + const strictForkResume = !initialSnapshot || currentMetadata?.forkedFrom != null || currentMetadata?.opencodeRewind != null; + // Fork provenance persists; strict history availability is needed only + // until the hub commits the child's first validated readiness. + const strictHistoryVerification = currentMetadata?.opencodeForkPending === true; + if (strictHistoryVerification && !historyMetadataDurable) { + throw new Error('OpenCode history metadata did not become durable before remote entry'); + } + // A resume that fell back to a blank native session invalidates every + // persisted history locator: old local ids would resolve to unrelated + // native turns. History stays disabled for such sessions. + let startedFreshAfterResumeFailure = false; const mcpServerList = toAcpMcpServers(mcpServers); let acpSessionId: string; if (resumeSessionId) { @@ -370,7 +515,11 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { mcpServers: mcpServerList }); } catch (error) { + if (strictForkResume) { + throw error; + } logger.warn('[opencode-remote] resume failed, starting new session', error); + startedFreshAfterResumeFailure = true; session.sendSessionEvent({ type: 'message', message: 'OpenCode resume failed; starting a new session.' @@ -386,7 +535,25 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { mcpServers: mcpServerList }); } - session.onSessionFound(acpSessionId); + + // Fire the validated session-ready fence only now (after the actual + // load/new below): loop.ts seeds onSessionFound with the resume id + // before ACP initialize, so the hub's exact-binding wait must not + // succeed until this point (same fence as Pi). + if (strictForkResume && resumeSessionId && acpSessionId !== resumeSessionId) { + // OpenCode replaced the forked native id — binding readiness to a + // different session would report a successful fork for context + // the child never loaded. + throw new Error('OpenCode fork loaded a different native session'); + } + let nativeBindingPublished = false; + if (initialSnapshot && !initialSnapshot.metadata.opencodeRewind + && (!initialSnapshot.metadata.opencodeSessionId || initialSnapshot.metadata.opencodeSessionId === acpSessionId)) { + session.onSessionFound(acpSessionId); + nativeBindingPublished = true; + } else { + session.sessionId = acpSessionId; + } this.activeAcpSessionId = acpSessionId; // v2: the internal HTTP API port is bound randomly after spawn and @@ -408,6 +575,8 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { const servePid = acpPid !== null ? await findOpencodeServePid({ rootPids: [acpPid, ...descendants] }) : null; + const marker = servePid !== null ? getProcessStartMarker(servePid) : null; + if (servePid !== null && marker) this.nativeProcess = { pid: servePid, startMarker: marker }; const ownerPids = servePid !== null ? [servePid] : acpPid !== null @@ -452,6 +621,10 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { this.nativeTranscript = new OpencodeNativeTranscript({ baseUrl: restBaseUrl, sessionId: acpSessionId, directory: session.path, mode: this.majorVersion ?? 'v1', headers: nativeHeaders, + // A fork child's native history holds the source's compactions and + // the hub's transcript copy already carries their cards; outcomes + // this runtime never observed live would be republished duplicates. + suppressInheritedCompactions: currentMetadata?.forkedFrom != null, onSummary: (id, summary, trigger) => { // Only the verified manual bridge owns remote manual outcomes, // including cancellation. Hub history restores published cards. @@ -501,6 +674,392 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { }); } + this.conversationHistory.setPublishCapabilities(async () => { + const conversationHistory = this.conversationHistory.getCapabilitiesForMetadata()?.conversationHistory; + try { + session.client.updateMetadata((metadata) => { + const capabilities = { ...metadata?.capabilities }; + delete capabilities.conversationHistory; + if (metadata.opencodeRewind && !this.runtimeGate.hasReconciled(metadata.opencodeRewind.operationId)) { + return { ...metadata, capabilities }; + } + if (conversationHistory) { + capabilities.conversationHistory = conversationHistory; + } + const diverged = Boolean(metadata.conversationHistoryDiverged || this.conversationHistory.isDiverged()); + if (diverged || this.runtimeGate.isBlocked()) delete capabilities.conversationHistory; + const publishSnapshot = !this.conversationHistory.isDisabled() && !this.runtimeGate.isBlocked(); + // An uninitialized in-memory checkpoint (the entry read + // failed before the first restore) must not publish an + // empty state over the saved one; the startup retry + // restores and verifies the persisted history instead. + const uninitializedCheckpoint = this.conversationHistory.getCheckpoint() === undefined + && metadata.opencodeHistoryCheckpoint != null; + const publishHistory = publishSnapshot && !uninitializedCheckpoint; + this.historyPublicationDeferred = !diverged && !this.conversationHistory.isDisabled() && !publishSnapshot + && JSON.stringify(this.conversationHistory.getCheckpoint()) !== JSON.stringify(metadata.opencodeHistoryCheckpoint); + return { + ...metadata, + path: metadata?.path ?? session.path, + host: metadata?.host ?? 'unknown', + capabilities, + conversationHistoryPoints: diverged ? undefined : publishHistory ? this.conversationHistory.getHistoryPoints() : metadata.conversationHistoryPoints, + conversationHistoryIndexes: diverged ? undefined : publishHistory ? this.conversationHistory.getHistoryIndexes() : metadata.conversationHistoryIndexes, + opencodeHistoryCheckpoint: diverged ? undefined : publishHistory ? this.conversationHistory.getCheckpoint() : metadata.opencodeHistoryCheckpoint, + conversationHistoryDiverged: metadata?.conversationHistoryDiverged || diverged || undefined + }; + }); + if (typeof session.client.flushMetadata === 'function' + && !(typeof session.client.isPending === 'function' && session.client.isPending()) + && !await session.client.flushMetadata()) { + throw new Error('OpenCode history checkpoint could not be persisted'); + } + } catch (error) { + logger.warn('[opencode-remote] History metadata persistence failed', error); + throw error; + } + }); + // A persisted divergence flag must survive later launches too — the + // hub rejects history actions for diverged sessions, so republished + // capabilities would only surface controls that cannot succeed. + let historyDiverged = startedFreshAfterResumeFailure + || currentMetadata?.conversationHistoryDiverged === true; + let lastRewindSnapshot: Awaited> = null; + if (historyDiverged) { + // Drop stale locators and hide history affordances: the native + // session no longer corresponds to the persisted HAPI transcript. + // The CLI refuses forks too (defense in depth alongside the hub's + // conversationHistoryDiverged gate). + void this.conversationHistory.disableFork().catch(() => {}); + try { + session.client.updateMetadata((metadata) => { + if (metadata.opencodeRewind && !this.runtimeGate.hasReconciled(metadata.opencodeRewind.operationId)) return metadata; + const capabilities = { ...metadata?.capabilities }; + delete capabilities.conversationHistory; + return { + ...metadata, + capabilities, + conversationHistoryPoints: undefined, + conversationHistoryIndexes: undefined, + opencodeHistoryCheckpoint: undefined, + conversationHistoryDiverged: true + }; + }); + } catch { + // best-effort; transient hub disconnects must not crash the loop + } + } else { + if (isV2 && this.v2RestInfo && typeof session.client.reportOpenCodeRewind === 'function') { + this.rewind = new OpenCodeRewind({ directory: join(configuration.happyHomeDir, 'opencode-rewind'), + hapiSessionId: session.client.sessionId, workerId: this.workerId, gate: this.runtimeGate, + nativeSessionId: acpSessionId, baseUrl: this.v2RestInfo.baseUrl, + headers: { authorization: 'Basic ' + Buffer.from(`opencode:${this.v2RestInfo.password}`).toString('base64') }, + nativeProcess: this.nativeProcess, + consumeCommitted: async () => { + const snapshot = await session.client.readRewindMetadata(); + if (!snapshot || this.rewindStopped) throw new Error('Cannot refresh OpenCode rewind metadata'); + const metadata = snapshot.metadata; + this.conversationHistory.clearPromptIndexes(); + this.conversationHistory.restoreCheckpoint(metadata?.opencodeHistoryCheckpoint); + this.conversationHistory.restorePromptIndexes(metadata?.conversationHistoryIndexes); + const loaded = await backend.suppressUpdatesDuring(() => backend.loadSession({ + sessionId: acpSessionId, cwd: session.path, mcpServers: mcpServerList + })); + if (this.rewindStopped) throw new Error('OpenCode rewind launcher is stopping'); + if (loaded !== acpSessionId) throw new Error('Rewind native reload changed identity'); + try { + await this.conversationHistory.reconcileHistory(); + } catch (error) { + // Hub truncation has already committed: a diverged + // read must disable forks, not fail consumption and + // overwrite the finalized journal with 'unknown'. + await this.conversationHistory.disableFork(); + logger.warn('[opencode-rewind] Consumption reconciliation diverged; forks disabled', error); + } + if (this.rewindStopped) throw new Error('OpenCode rewind launcher is stopping'); + this.instructionsSent = (this.conversationHistory.getCheckpoint()?.userMessageIds.length ?? 0) > 0; + if (!workerStartMarker) throw new Error('OpenCode worker generation is unavailable'); + session.client.updateMetadata(meta => meta.opencodeRewind?.operationId !== snapshot.metadata.opencodeRewind?.operationId + ? meta : ({ ...meta, opencodeWorkerId: this.workerId, + opencodeWorkerProcess: { workerId: this.workerId, pid: process.pid, startMarker: workerStartMarker } })); + if (!await session.client.flushMetadata()) throw new Error('Rewind runtime consumption is not durable'); + }, + report: report => session.client.reportOpenCodeRewind(report), + getAuthoritativeOperation: async () => { + const snapshot = await session.client.readRewindMetadata(); + if (!snapshot) throw new Error('Cannot refresh OpenCode rewind metadata'); + lastRewindSnapshot = snapshot; + return snapshot.metadata.opencodeRewind; + }, + flush: async () => { + await this.conversationHistory.reconcileHistory(); + return await session.client.flush() && await session.client.flushMetadata(); + }, + isIdle: () => !session.thinking && session.queue.size() === 0 && !backend.isPromptRequestInFlight?.() + && !this.hasUnresolvedNativeInput(), + sourceCheckpoint: () => this.conversationHistory.getCheckpoint(), + sourceIndexes: () => this.conversationHistory.getHistoryIndexes(), + previousWorkerCannotRun: previous => { + const marker = getProcessStartMarker(previous.pid); + if (marker !== null) return marker !== previous.startMarker; + try { process.kill(previous.pid, 0); return false; } + catch (error) { return (error as NodeJS.ErrnoException).code === 'ESRCH'; } + }, + requestsFromPreviousWorkerCannotRun: () => { + const previous = this.rewind?.readIntent()?.nativeProcess; + if (!previous) return false; + const marker = getProcessStartMarker(previous.pid); + if (marker !== null) return marker !== previous.startMarker; + try { process.kill(previous.pid, 0); return false; } + catch (error) { return (error as NodeJS.ErrnoException).code === 'ESRCH'; } + } + }); + + } + } + // Entry ownership is independent of the rewind blocker. Every release + // requires a fresh REST snapshot and a validated local journal. + const reconcileEntry = async () => { + const token = this.entryFence; + const epoch = this.entryEpoch; + if (!token || this.rewindStopped) return; + const ownsEntry = () => !this.rewindStopped && token === this.entryFence && epoch === this.entryEpoch; + const snapshot = await session.client.readRewindMetadata(); + if (!ownsEntry()) return; + if (!snapshot) throw new Error('OpenCode entry metadata unavailable'); + const operation = snapshot.metadata.opencodeRewind; + const readIntent = () => readOpenCodeRewindIntent(join(configuration.happyHomeDir, 'opencode-rewind'), session.client.sessionId); + let intent = readIntent(); + if (intent && intent.operation.nativeSessionId !== acpSessionId) throw new Error('OpenCode entry journal native identity mismatch'); + if (snapshot.metadata.opencodeSessionId && snapshot.metadata.opencodeSessionId !== acpSessionId) { + if (!startedFreshAfterResumeFailure || operation || intent) throw new Error('OpenCode entry native identity mismatch'); + // Withdraw the old worker's reservation capability durably + // before replacing a failed resume's native binding. If an + // operation won the race, leave its metadata untouched. + session.client.updateMetadata(meta => { + if (meta.opencodeRewind) return meta; + const capabilities = { ...meta.capabilities }; + delete capabilities.conversationHistory; + return { ...meta, capabilities, opencodeWorkerId: undefined, opencodeWorkerProcess: undefined }; + }); + if (!await session.client.flushMetadata()) throw new Error('OpenCode stale readiness withdrawal failed'); + const withdrawn = await session.client.readRewindMetadata(); + if (!ownsEntry()) return; + if (!withdrawn || withdrawn.metadata.opencodeRewind + || withdrawn.metadata.capabilities?.conversationHistory?.rewindToMessage) { + throw new Error('OpenCode stale readiness withdrawal unconfirmed'); + } + } + if (operation) { + if (!this.rewind) throw new Error('OpenCode rewind requires remote reconciliation'); + do { + await this.runtimeGate.waitUntilIdle(this.rewindEntryAbortController.signal); + if (!ownsEntry()) return; + } while (this.runtimeGate.isRuntimeActive()); + if (!this.runtimeGate.hasReconciled(operation.operationId) || !['rejected', 'committed'].includes(operation.phase)) { + this.runtimeGate.block(); + await this.rewind.recover(operation); + } + } else if (intent && intent.phase !== 'finalized') { + throw new Error('OpenCode entry has an unresolved journal'); + } + const confirmed = await session.client.readRewindMetadata(); + if (!ownsEntry()) return; + if (!confirmed) throw new Error('OpenCode entry confirmation unavailable'); + const latest = confirmed.metadata.opencodeRewind; + if (latest && (!operation || latest.operationId !== operation.operationId)) { + throw new OpenCodeRewindSupersededError(latest.operationId); + } + if ((confirmed.metadata.opencodeSessionId && confirmed.metadata.opencodeSessionId !== acpSessionId + && !(startedFreshAfterResumeFailure && !latest && !intent)) + || (latest && confirmed.metadata.opencodeSessionId !== acpSessionId) + || (latest && (!['committed', 'rejected'].includes(latest.phase) || !this.runtimeGate.hasReconciled(latest.operationId)))) { + throw new Error('OpenCode entry is not reconciled'); + } + intent = readIntent(); + if (intent && (intent.phase !== 'finalized' || intent.operation.nativeSessionId !== acpSessionId)) { + throw new Error('OpenCode entry journal remains unresolved'); + } + if (!nativeBindingPublished) { + session.onSessionFound(acpSessionId); + if (!await session.client.flushMetadata()) throw new Error('OpenCode native binding is not durable'); + nativeBindingPublished = true; + // A durable write just reached the hub: the startup flush miss + // is superseded, so fork support no longer rests on it. + historyMetadataDurable = true; + } + if (!ownsEntry()) return; + if (confirmed.metadata.conversationHistoryDiverged && !historyDiverged) { + historyDiverged = true; + await this.conversationHistory.disableFork(); + } + // A prompt admitted before the fence may have completed after the + // snapshots above were read. Its verified checkpoint is newer than + // Hub's and is published once the fence opens; restoring the stale + // snapshot would make that growth look unobserved. An uninitialized + // checkpoint is not an advance: the retry must still restore and + // verify the persisted history. + if (!historyDiverged && !this.runtimeGate.isRuntimeActive() + && (!this.historyPublicationDeferred || this.conversationHistory.getCheckpoint() === undefined)) { + this.conversationHistory.clearPromptIndexes(); + this.conversationHistory.restoreCheckpoint(confirmed.metadata.opencodeHistoryCheckpoint); + this.conversationHistory.restorePromptIndexes(confirmed.metadata.conversationHistoryIndexes); + if (restBaseUrl && historyMetadataDurable) { + try { await this.conversationHistory.reconcileHistory(); } + catch (error) { + await this.conversationHistory.disableFork(); + if (strictHistoryVerification) throw error; + } + } else if (strictHistoryVerification) { + throw new Error('OpenCode fork history is unavailable'); + } + } + let final: Awaited>; + do { + // A no-op may overlap an unrelated ordinary turn, but Stop's + // later queue reset must settle before admission can reopen. + await this.runtimeGate.waitUntilCancellationsIdle(this.rewindEntryAbortController.signal); + if (!ownsEntry()) return; + final = await session.client.readRewindMetadata(); + if (!ownsEntry()) return; + } while (this.runtimeGate.hasCancellationActivity()); + if (final?.metadata.conversationHistoryDiverged) historyDiverged = true; + if (!final || final.metadata.opencodeSessionId !== acpSessionId + || JSON.stringify(final.metadata.opencodeRewind) !== JSON.stringify(latest) + || (!historyDiverged && (JSON.stringify(final.metadata.opencodeHistoryCheckpoint) !== JSON.stringify(confirmed.metadata.opencodeHistoryCheckpoint) + || JSON.stringify(final.metadata.conversationHistoryIndexes) !== JSON.stringify(confirmed.metadata.conversationHistoryIndexes)))) { + if (final?.metadata.opencodeRewind && final.metadata.opencodeRewind.operationId !== latest?.operationId) { + throw new OpenCodeRewindSupersededError(final.metadata.opencodeRewind.operationId); + } + throw new Error('OpenCode entry changed during verification'); + } + if (ownsEntry()) { + this.entryFence = undefined; + this.runtimeGate.releaseEntryFence(token); + } + }; + this.drainReconnect = () => { + if (this.rewindStopped || this.rewindInFlight || !this.rewindReconnectPending) return; + // A fresh drain supersedes whatever backoff a failed attempt scheduled. + this.clearEntryRetryTimer(); + this.rewindReconnectPending = false; + this.rewindInFlight = true; + void reconcileEntry().then(async () => { + if (this.rewindStopped) return; + this.entryRetryAttempt = 0; + this.conversationHistory.setRewindReady(!this.runtimeGate.isBlocked()); + if (!this.runtimeGate.isBlocked() && this.rewind && this.nativeProcess && workerStartMarker) { + session.client.updateMetadata(metadata => metadata.opencodeRewind && !this.runtimeGate.hasReconciled(metadata.opencodeRewind.operationId) + ? metadata : ({ ...metadata, opencodeWorkerId: this.workerId, + opencodeWorkerProcess: { workerId: this.workerId, pid: process.pid, startMarker: workerStartMarker } })); + // Re-verify metadata durability on the recovery path: the + // one-shot startup read must not decide fork support forever. + if (await session.client.flushMetadata()) historyMetadataDurable = true; + } + if (this.rewindStopped) return; + await this.conversationHistory.publish(); + await registerRewindHandler(); + }).catch(error => { + this.noteSupersededRewind(error); + if (this.entryFailureRetriable(error)) this.scheduleEntryRetry(); + logger.warn('[opencode-rewind] Reconnect recovery remains blocked', error); + }).finally(() => { this.rewindInFlight = false; this.drainReconnect?.(); }); + }; + let rewindHandlerRegistered = false; + const registerRewindHandler = async () => { + if (rewindHandlerRegistered || this.rewindStopped) return; + if (!this.rewind || !this.nativeProcess || !workerStartMarker || this.conversationHistory.isDisabled()) return; + if (!this.runtimeGate.isBlocked()) session.client.updateMetadata(metadata => metadata.opencodeRewind && !this.runtimeGate.hasReconciled(metadata.opencodeRewind.operationId) + ? metadata : ({ ...metadata, opencodeWorkerId: this.workerId, + opencodeWorkerProcess: { workerId: this.workerId, pid: process.pid, startMarker: workerStartMarker } })); + if (!await session.client.flushMetadata()) return; + session.client.rpcHandlerManager.registerHandler(RPC_METHODS.RewindConversation, async (payload: unknown) => { + const input = payload as { messageLocalId?: string; opencodeRewind?: unknown }; + const operation = OpenCodeRewindSchema.parse(input?.opencodeRewind); + if (input.messageLocalId !== operation.requestedLocalId) throw new Error('Rewind boundary mismatch'); + if (this.rewindInFlight) throw new Error('OpenCode rewind is busy'); + this.rewindInFlight = true; + try { + const result = await this.rewind!.execute(operation); + if (result.success) { + // The controller's post-consumption authority read + // returned this exact parsed snapshot immediately + // before its verified terminal release. + const snapshot = lastRewindSnapshot; + const current = snapshot?.metadata.opencodeRewind; + if (!snapshot || !current || !sameOperation(current, operation) || current.phase !== 'committed') { + this.runtimeGate.block(); + throw new Error('Committed OpenCode rewind metadata is unavailable'); + } + this.conversationHistory.clearPromptIndexes(); + this.conversationHistory.restoreCheckpoint(snapshot.metadata.opencodeHistoryCheckpoint); + this.conversationHistory.restorePromptIndexes(snapshot.metadata.conversationHistoryIndexes); + } + this.conversationHistory.setRewindReady(!this.runtimeGate.isBlocked()); + await this.conversationHistory.publish(); + return result; + } catch (error) { + this.noteSupersededRewind(error); + throw error; + } finally { this.rewindInFlight = false; this.drainReconnect?.(); } + }); + rewindHandlerRegistered = true; + this.conversationHistory.setRewindReady(!this.runtimeGate.isBlocked()); + this.drainReconnect?.(); + }; + this.rewindInFlight = true; + try { + // A failed optional publication is not proof of absence. The strict + // snapshot below still decides whether admission is safe. + await session.client.flushMetadata().catch(() => false); + if (initialSnapshot) await reconcileEntry(); + // A null startup read on a live socket is a transient miss (the GET + // swallowed a timeout/503 or saw a stale version), not a waiting + // socket: retry it through the same serialized backoff. A socket + // still connecting keeps the existing connected-event path. + else if (!this.rewindStopped && typeof session.client.isActive === 'function' && session.client.isActive()) this.scheduleEntryRetry(); + } catch (error) { + this.noteSupersededRewind(error); + if (this.entryFailureRetriable(error)) this.scheduleEntryRetry(); + logger.warn('[opencode-rewind] Initial entry remains blocked', error); + if (strictHistoryVerification) throw error; + } finally { + this.rewindInFlight = false; + this.drainReconnect(); + } + if (!historyDiverged) { + if (!historyMetadataDurable) { + // An entry fence held by a pending retry is not a verdict: the + // recovery path re-verifies durability before forks are lost. + if (!this.entryFence) await this.conversationHistory.disableFork().catch((error) => logger.warn('[opencode-remote] Forks disabled while metadata is unavailable', error)); + } else { + try { + await this.conversationHistory.publish(); + } catch (error) { + await this.conversationHistory.disableFork().catch((writeError) => logger.warn('[opencode-remote] Forks disabled while history is unavailable', writeError)); + if (strictHistoryVerification) throw error; + } + } + } + session.client.rpcHandlerManager.registerHandler(RPC_METHODS.ForkConversation, async (payload: unknown) => { + const release = this.runtimeGate.enterRuntime(); + try { + const messageLocalId = payload !== null && typeof payload === 'object' && !Array.isArray(payload) + && typeof (payload as Record).messageLocalId === 'string' + ? (payload as Record).messageLocalId as string + : undefined; + const result = await this.conversationHistory.fork(messageLocalId); + return { ...result, opencodeHistoryCheckpoint: await this.conversationHistory.checkpointForkedSession(result.nativeSessionId) }; + } finally { release(); } + }); + await registerRewindHandler(); + if (isV2 && !historyDiverged) { + void this.conversationHistory.probeCapabilities(this.historyProbeAbortController.signal).catch(() => {}); + } + if ((resumeSessionId || strictForkResume) && typeof session.client.emitSessionReady === 'function') { + session.client.emitSessionReady(); + } + // Seed currentBackendModel from the ACP session metadata so the first // batch — whose model the hub mirrors from the just-discovered session — // does not trigger a redundant setModel on the very first turn. @@ -521,11 +1080,13 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { const requestedStartupModel = this.session.getModel?.(); if ( !this.shouldExit + && !this.runtimeGate.isBlocked() && typeof requestedStartupModel === 'string' && requestedStartupModel.length > 0 && requestedStartupModel !== this.defaultBackendModel && typeof backend.setModel === 'function' ) { + const release = this.runtimeGate.enterRuntime(); try { await backend.setModel(acpSessionId, requestedStartupModel, { flavor: 'opencode' }); this.currentBackendModel = requestedStartupModel; @@ -536,7 +1097,7 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { this.defaultBackendEffort = this.currentBackendEffort; } catch (error) { logger.warn('[opencode-remote] Eager startup model application failed; first batch will retry inline', error); - } + } finally { release(); } } // Let the caller (runOpencode.ts) know native /compact can actually @@ -544,25 +1105,9 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { // dequeue loop below (not an externally-invoked trigger) is what // executes it, in its actual FIFO queue position. // - // A 9th PR-review round found a race here: a terminal - // switch-to-local/exit can land *during* the newSession/loadSession - // await above (setupTerminal() wires up onExit/onSwitchToLocal - // before runMainLoop() even starts, so this is reachable well - // before setupAbortHandlers() below registers the RPC - // 'abort'/'switch' handlers). RemoteLauncherBase.requestExit() - // already fired onLeavingRemote() (availability(false)) and set - // `this.shouldExit = true` synchronously for that switch/exit, - // before awaiting its handler — but this line used to run - // regardless once initialization finished, resurrecting - // availability(true) even though the session is already on its way - // out. runOpencode.ts's compactSupported/compactTeardownInProgress - // gate treats compactSupported flipping true as reason enough to - // ignore compactTeardownInProgress entirely (see that gate's doc - // comment), so this stray true could let a /compact arriving right - // after slip into the queue mid-teardown. Checking `shouldExit` - // here — the same flag requestExit() already set — keeps - // availability from ever un-flipping once a switch/exit is - // underway. + // Terminal switch/exit handlers are active during newSession/loadSession. + // requestExit() synchronously withdraws availability and sets shouldExit; + // finishing initialization must not advertise compact again mid-teardown. if (!this.shouldExit && (this.v2RestInfo !== null || this.baseUrl !== null)) { this.options.onCompactAvailabilityChange?.(true); } @@ -638,7 +1183,17 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { while (!this.shouldExit) { const waitSignal = this.abortController.signal; - const batch = await session.queue.waitForMessagesAndGetAsString(waitSignal); + await this.runtimeGate.waitUntilOpen(waitSignal); + if (waitSignal.aborted) continue; + let batch; + try { + batch = await session.queue.waitForMessagesAndGetAsString(waitSignal); + } catch (error) { + // beforeDequeue acquired no ownership and removed/ACKed no row. + // A socket entry can fence the gate while this await is parked. + if (error instanceof OpenCodeRuntimeBlockedError) continue; + throw error; + } if (!batch) { if (waitSignal.aborted && !this.shouldExit) { continue; @@ -646,421 +1201,425 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { break; } - // /clear is deliberately a queue operation rather than a direct - // slash side effect: every prompt and /compact ahead of it has - // completed before this point. In particular, do not route this - // through handleAbort(true): that method exists to interrupt an - // in-flight compact, while clear can only run after one finishes. - if (batch.mode.operation === 'clear') { - await this.options.onClearRequested?.(); - this.clearRequested = true; - await this.requestExit('exit', async () => {}) - break; - } + // Hold the fork busy guard across the whole dequeued batch — + // collectBatch() already acked the rows, so the hub can briefly see an + // empty queue + thinking=false while model/effort setup or native + // mutations are still in flight (same fence as grok). + this.conversationHistory.setBusy(true); + const releaseRuntime = session.takeDequeuedRuntimeRelease?.() ?? this.runtimeGate.enterRuntime(); + try { - // Created here — before the model/effort switch below — rather - // than inside runCompactOperation(), so it already exists for - // handleAbort() to act on during that switch. backend.setModel()/ - // setConfigOption() are real async ACP round-trips that yield to - // the event loop; a hostile-review whole-feature sweep found - // that an abort landing in that window used to hit a still-null - // compactAbortController (a no-op) and then get silently - // forgotten once runCompactOperation() created a *fresh* - // controller afterward — the compact's unbounded REST call would - // then run to completion with no way to interrupt it, despite - // the user having already pressed Stop/switch/exit. + this.settleBackendSoftSteers(backend, null, 'dequeue'); - // No foreground turn is live here (the previous one settled and its - // drain completed), so this is the one safe place to force-settle a - // soft request a cancellation left counted: the inter-turn - // model/effort switch below awaits response-complete and would - // otherwise block on it forever. - this.settleBackendSoftSteers(backend, null, 'dequeue'); + // /clear is deliberately a queue operation rather than a direct + // slash side effect: every prompt and /compact ahead of it has + // completed before this point. In particular, do not route this + // through handleAbort(true): that method exists to interrupt an + // in-flight compact, while clear can only run after one finishes. + if (batch.mode.operation === 'clear') { + await this.options.onClearRequested?.(); + this.clearRequested = true; + await this.requestExit('exit', async () => {}) + break; + } - const isCompactBatch = batch.mode.operation === 'compact'; - const compactAbortController = isCompactBatch ? new AbortController() : null; - if (compactAbortController) { - this.compactAbortController = compactAbortController; - this.compactOperationPhase = 'idle'; - // Reset here (as early as the controller itself — see its - // sibling field's doc comment for why that timing matters) - // rather than inside runCompactOperation(), so a plain Stop - // landing during the model/effort switch below already has - // something to suppress. - this.compactResultSuppressed = false; - } + // Install the controller before async model/effort changes so + // handleAbort() can cancel this batch even before HTTP work starts. + const isCompactBatch = batch.mode.operation === 'compact'; + const compactAbortController = isCompactBatch ? new AbortController() : null; + if (compactAbortController) { + this.compactAbortController = compactAbortController; + this.compactOperationPhase = 'idle'; + // Reset here (as early as the controller itself — see its + // sibling field's doc comment for why that timing matters) + // rather than inside runCompactOperation(), so a plain Stop + // landing during the model/effort switch below already has + // something to suppress. + this.compactResultSuppressed = false; + } - // Inline model change via ACP RPC (session/set_model — see ACP SDK - // schema `x-method: session/set_model`). Mirrors the Gemini pattern - // from PR #543: if the running OpenCode build does not implement the - // RPC, we learn that from the first method-not-found response and stop - // attempting it for the rest of this session. - // - // `batch.mode.model` semantics: a string is a specific model id; - // `null` means "reset to whatever model the backend launched with" - // (emitted by `/model default`); `undefined` means "no change". - // Preserve Default's null queue intent when display mode resolves - // to a concrete model; only a rollback changes that intent. - let steeringModel = batch.mode.model; - const requestedModel = batch.mode.model === null - ? this.defaultBackendModel - : batch.mode.model; - // The very first batch seeds currentBackendModel — the OpenCode CLI was - // launched with that model via --model and there is nothing to switch yet. - if (requestedModel && this.currentBackendModel === null) { - this.currentBackendModel = requestedModel; - } else if (requestedModel && requestedModel !== this.currentBackendModel) { - if (!backend.setModel || this.setModelSupported === false) { - this.rollbackModel(batch, this.currentBackendModel); - steeringModel = batch.mode.model; - } else { - logger.debug(`[opencode-remote] Switching model inline: ${this.currentBackendModel} -> ${requestedModel}`); - try { - await backend.setModel(acpSessionId, requestedModel, { flavor: 'opencode' }); - this.currentBackendModel = requestedModel; - this.setModelSupported = true; - // set_config_option("model") also switches the backend's - // effort currentValue — refresh both cached efforts so - // a subsequent request equal to the stale value still - // performs the round-trip instead of being skipped, - // and an unset effort falls back to the *new* model's - // default rather than reapplying the old model's. - const refreshedInlineEffort = backend.getThoughtLevelConfigOption?.(acpSessionId); - this.currentBackendEffort = refreshedInlineEffort?.currentValue ?? null; - this.defaultBackendEffort = this.currentBackendEffort; - // Reflect the resolved model back into the batch so - // downstream display logic sees the concrete id rather - // than a `null` placeholder. - batch.mode.model = requestedModel; - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - const methodNotFound = /method not found/i.test(message); - if (methodNotFound && this.setModelSupported === undefined) { - this.setModelSupported = false; - logger.warn('[opencode-remote] OpenCode build does not support session/set_model; inline switching disabled for this session'); - session.sendSessionEvent({ - type: 'message', - message: 'This OpenCode build does not support inline model switching. Restart the session to apply a different model.' - }); - } else { - logger.warn('[opencode-remote] Inline model switch failed', error); - session.sendSessionEvent({ - type: 'message', - message: `Failed to switch model to ${requestedModel}. Continuing with ${this.currentBackendModel ?? '(default)'}.` - }); - } + // Inline model change via ACP RPC (session/set_model — see ACP SDK + // schema `x-method: session/set_model`). Mirrors the Gemini pattern + // from PR #543: if the running OpenCode build does not implement the + // RPC, we learn that from the first method-not-found response and stop + // attempting it for the rest of this session. + // + // `batch.mode.model` semantics: a string is a specific model id; + // `null` means "reset to whatever model the backend launched with" + // (emitted by `/model default`); `undefined` means "no change". + let steeringModel = batch.mode.model; + const requestedModel = batch.mode.model === null + ? this.defaultBackendModel + : batch.mode.model; + // The very first batch seeds currentBackendModel — the OpenCode CLI was + // launched with that model via --model and there is nothing to switch yet. + if (requestedModel && this.currentBackendModel === null) { + this.currentBackendModel = requestedModel; + } else if (requestedModel && requestedModel !== this.currentBackendModel) { + if (!backend.setModel || this.setModelSupported === false) { this.rollbackModel(batch, this.currentBackendModel); steeringModel = batch.mode.model; - } - } - } - - const requestedEffort = batch.mode.modelReasoningEffort ?? this.defaultBackendEffort; - if (requestedEffort && requestedEffort !== this.currentBackendEffort) { - const thoughtLevelOption = backend.getThoughtLevelConfigOption?.(acpSessionId); - if (!backend.setConfigOption || !thoughtLevelOption || this.setEffortSupported === false) { - this.rollbackReasoningEffort(batch, this.currentBackendEffort); - } else { - const resolvedEffort = resolveThoughtLevelEffort( - requestedEffort, - thoughtLevelOption, - this.currentBackendEffort ?? this.defaultBackendEffort - ); - if (!resolvedEffort || resolvedEffort === this.currentBackendEffort) { - if (requestedEffort !== resolvedEffort) { - logger.warn( - `[opencode-remote] Unsupported reasoning effort "${requestedEffort}"; continuing with ${resolvedEffort ?? this.currentBackendEffort ?? '(default)'}` - ); - this.rollbackReasoningEffort(batch, resolvedEffort ?? this.currentBackendEffort); - } } else { - logger.debug(`[opencode-remote] Switching effort inline: ${this.currentBackendEffort ?? '(default)'} -> ${resolvedEffort}`); + logger.debug(`[opencode-remote] Switching model inline: ${this.currentBackendModel} -> ${requestedModel}`); try { - await backend.setConfigOption(acpSessionId, thoughtLevelOption.id, resolvedEffort); - this.currentBackendEffort = resolvedEffort; - this.setEffortSupported = true; - if (requestedEffort !== resolvedEffort) { - this.rollbackReasoningEffort(batch, resolvedEffort); - } + await backend.setModel(acpSessionId, requestedModel, { flavor: 'opencode' }); + this.currentBackendModel = requestedModel; + this.setModelSupported = true; + // set_config_option("model") also switches the backend's + // effort currentValue, so refresh both effort caches. + const refreshedInlineEffort = backend.getThoughtLevelConfigOption?.(acpSessionId); + this.currentBackendEffort = refreshedInlineEffort?.currentValue ?? null; + this.defaultBackendEffort = this.currentBackendEffort; + // Reflect the resolved model back into the batch so + // downstream display logic sees the concrete id rather + // than a `null` placeholder. + batch.mode.model = requestedModel; } catch (error) { const message = error instanceof Error ? error.message : String(error); const methodNotFound = /method not found/i.test(message); - if (methodNotFound && this.setEffortSupported === undefined) { - this.setEffortSupported = false; - logger.warn('[opencode-remote] OpenCode build does not support session/set_config_option; inline effort switching disabled for this session'); + if (methodNotFound && this.setModelSupported === undefined) { + this.setModelSupported = false; + logger.warn('[opencode-remote] OpenCode build does not support session/set_model; inline switching disabled for this session'); session.sendSessionEvent({ type: 'message', - message: 'This OpenCode build does not support inline reasoning effort switching.' + message: 'This OpenCode build does not support inline model switching. Restart the session to apply a different model.' }); } else { - logger.warn('[opencode-remote] Inline effort switch failed', error); + logger.warn('[opencode-remote] Inline model switch failed', error); session.sendSessionEvent({ type: 'message', - message: `Failed to switch reasoning effort to ${resolvedEffort}. Continuing with ${this.currentBackendEffort ?? '(default)'}.` + message: `Failed to switch model to ${requestedModel}. Continuing with ${this.currentBackendModel ?? '(default)'}.` }); } - this.rollbackReasoningEffort(batch, this.currentBackendEffort); + this.rollbackModel(batch, this.currentBackendModel); + steeringModel = batch.mode.model; } } } - } - this.applyDisplayMode(batch.mode.permissionMode); - messageBuffer.addMessage(batch.message, 'user'); - - // /compact reaches here through the exact same dequeue loop as - // any prompt — it was pushed via messageQueue.pushIsolated(...) - // in runOpencode.ts, so it occupies its real FIFO position - // relative to prompts queued before or after it (fixes a prior - // design where /compact ran via an externally-invoked trigger - // and could execute ahead of an already-queued prompt). The - // model/effort switch above already ran for this batch just like - // any other, so compaction runs under whatever model this batch - // resolved to. - if (isCompactBatch && compactAbortController) { - // A compact batch is always a single isolated item (pushed - // via pushIsolated), so its own localId is exactly - // batch.items[0]?.localId. - const compactLocalId = batch.items[0]?.localId; - - // A 7th PR-review round found that a plain Stop landing - // *during the model/effort switch above* — before this - // compact's REST request has ever actually been sent — was - // silently ignored here. Plain Stop's handleAbort(false) only - // sets `compactResultSuppressed = true`; it deliberately - // leaves compactAbortController.signal alone (see that - // field's doc comment — Round 6 needs the real HTTP request - // to keep running so the dequeue loop can wait for genuine - // server-side completion). But that logic assumed a request - // was already in flight to wait for. Here, mid-switch, none - // has been sent yet — so this branch used to call - // runCompactOperation() unconditionally once the switch - // resolved anyway, starting a brand new REST request the - // instant a cancelled compact's turn came up and blocking - // the dequeue loop for however long that takes. - // - // The fix is narrow on purpose: skip starting the operation - // only when a plain Stop landed (compactResultSuppressed) - // AND the controller was never actually aborted. If the - // controller WAS aborted, that means switch/exit's - // handleAbort(true) ran instead — and Round 5's test - // (below) established that runCompactOperation() must still - // be called in that case, threading the pre-aborted signal - // through so the fetch call rejects immediately without any - // network I/O, rather than being skipped here. - // - // An 8th PR-review round found this same reasoning also - // applies to isLocalIdCancelled, which round 7 had - // deliberately left out of this check (see runOpencode.ts's - // preparingLocalIds/cancelledBeforeEnqueue doc comment for - // the full mechanism): the localId-keyed cancel Set it reads - // can *only* ever be populated during the brief network - // round trip between the CLI emitting the /compact item's - // "invoked" ack and the hub recording it — never while a - // compact REST call is actually running. So if - // isLocalIdCancelled(compactLocalId) is already true here, - // that unconditionally means this compact was cancelled - // before its REST request was ever sent, exactly like the - // compactResultSuppressed case above — there's no - // in-flight server-side work to preserve by starting the - // operation anyway. (isLocalIdCancelled is a delete-and- - // return, one-shot callback, so checking it here consumes - // the same entry runCompactOperation()'s own isCancelled() - // would otherwise have consumed — it isn't checked twice.) - const compactCancelledByLocalId = compactLocalId - ? (this.options.isLocalIdCancelled?.(compactLocalId) ?? false) - : false; - const cancelledBeforeStart = - (this.compactResultSuppressed && !compactAbortController.signal.aborted) - || compactCancelledByLocalId; - if (cancelledBeforeStart) { - if (this.compactAbortController === compactAbortController) { - this.compactAbortController = null; - this.compactOperationPhase = 'idle'; + const requestedEffort = batch.mode.modelReasoningEffort ?? this.defaultBackendEffort; + if (requestedEffort && requestedEffort !== this.currentBackendEffort) { + const thoughtLevelOption = backend.getThoughtLevelConfigOption?.(acpSessionId); + if (!backend.setConfigOption || !thoughtLevelOption || this.setEffortSupported === false) { + this.rollbackReasoningEffort(batch, this.currentBackendEffort); + } else { + const resolvedEffort = resolveThoughtLevelEffort( + requestedEffort, + thoughtLevelOption, + this.currentBackendEffort ?? this.defaultBackendEffort + ); + if (!resolvedEffort || resolvedEffort === this.currentBackendEffort) { + if (requestedEffort !== resolvedEffort) { + logger.warn( + `[opencode-remote] Unsupported reasoning effort "${requestedEffort}"; continuing with ${resolvedEffort ?? this.currentBackendEffort ?? '(default)'}` + ); + this.rollbackReasoningEffort(batch, resolvedEffort ?? this.currentBackendEffort); + } + } else { + logger.debug(`[opencode-remote] Switching effort inline: ${this.currentBackendEffort ?? '(default)'} -> ${resolvedEffort}`); + try { + await backend.setConfigOption(acpSessionId, thoughtLevelOption.id, resolvedEffort); + this.currentBackendEffort = resolvedEffort; + this.setEffortSupported = true; + if (requestedEffort !== resolvedEffort) { + this.rollbackReasoningEffort(batch, resolvedEffort); + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + const methodNotFound = /method not found/i.test(message); + if (methodNotFound && this.setEffortSupported === undefined) { + this.setEffortSupported = false; + logger.warn('[opencode-remote] OpenCode build does not support session/set_config_option; inline effort switching disabled for this session'); + session.sendSessionEvent({ + type: 'message', + message: 'This OpenCode build does not support inline reasoning effort switching.' + }); + } else { + logger.warn('[opencode-remote] Inline effort switch failed', error); + session.sendSessionEvent({ + type: 'message', + message: `Failed to switch reasoning effort to ${resolvedEffort}. Continuing with ${this.currentBackendEffort ?? '(default)'}.` + }); + } + this.rollbackReasoningEffort(batch, this.currentBackendEffort); + } + } } - // A 10th PR-review round found this skip path never - // calls session.onThinkingChange(true) (that's the - // whole point of skipping) but also never told the hub - // this queued item is done, leaving the web UI spinner - // stuck: markMessageQueued's 15s "queued thinking" - // grace (hub/src/sync/sessionCache.ts) keeps thinking - // pinned true regardless of keepalives until either the - // grace expires or a messages-consumed ack with - // `clearQueuedThinkingGrace` arrives. Same situation, - // same fix, as the synchronous slash.kind === 'handled' - // path in runOpencode.ts (e.g. /model — see its - // `clearQueuedThinkingGrace` comment there): ack with - // the grace-clearing flag, then push an immediate - // thinking=false keepalive so the spinner clears - // without waiting on the grace. (This is on top of, not - // instead of, the queue's own unflagged - // onBatchConsumed ack — a second ack for an - // already-invoked localId is a no-op on the hub's - // first-write-wins queued-message protocol, and - // clearQueuedThinkingGrace itself is keyed by session, - // not by localId, so it's idempotent too.) - if (compactLocalId) { - session.client.emitMessagesConsumed([compactLocalId], { clearQueuedThinkingGrace: true }); + } + + this.applyDisplayMode(batch.mode.permissionMode); + messageBuffer.addMessage(batch.message, 'user'); + + // /compact reaches here through the exact same dequeue loop as + // any prompt — it was pushed via messageQueue.pushIsolated(...) + // in runOpencode.ts, so it occupies its real FIFO position + // relative to prompts queued before or after it (fixes a prior + // design where /compact ran via an externally-invoked trigger + // and could execute ahead of an already-queued prompt). The + // model/effort switch above already ran for this batch just like + // any other, so compaction runs under whatever model this batch + // resolved to. + if (isCompactBatch && compactAbortController) { + // A compact batch is always a single isolated item (pushed + // via pushIsolated), so its own localId is exactly + // batch.items[0]?.localId. + const compactLocalId = batch.items[0]?.localId; + + // Stop during model/effort setup must not start new HTTP work. + // Switch/exit instead passes its aborted signal through the + // operation so fetch rejects without issuing a request. + // Local-id cancellation is recorded during the invoked ACK, + // before HTTP work starts. Consume its one-shot entry here; + // there is no running server mutation to wait for in that case. + const compactCancelledByLocalId = compactLocalId + ? (this.options.isLocalIdCancelled?.(compactLocalId) ?? false) + : false; + const cancelledBeforeStart = + (this.compactResultSuppressed && !compactAbortController.signal.aborted) + || compactCancelledByLocalId; + if (cancelledBeforeStart) { + if (this.compactAbortController === compactAbortController) { + this.compactAbortController = null; + this.compactOperationPhase = 'idle'; + } + // Clear the hub's queued-thinking grace even though this + // operation never entered thinking=true. The queue's normal + // unflagged consumed ACK does not clear that grace; repeating + // the ACK with the session-level flag is idempotent. + if (compactLocalId) { + session.client.emitMessagesConsumed([compactLocalId], { clearQueuedThinkingGrace: true }); + } + // Plain Stop before summarize already emitted this + // keepalive in handleAbort(); localId cancellation did not. + if (!this.compactResultSuppressed) { + session.onThinkingChange(false); + } + if (session.queue.size() === 0 && !this.shouldExit) { + sendReady(); + } + continue; } - // Plain Stop before summarize already emitted this - // keepalive in handleAbort(); localId cancellation did not. - if (!this.compactResultSuppressed) { + + this.nextRoundSnapshot = null; + session.onThinkingChange(true); + let nativeHistoryMayHaveChanged = false; + try { + await this.runCompactOperation( + acpSessionId, + compactAbortController, + compactLocalId, + () => { + nativeHistoryMayHaveChanged = true; + this.nativeHistoryUnverified = true; + } + ); + if (!nativeHistoryMayHaveChanged) continue; + // Compaction starts a new identity epoch. Discard old + // positions, then persist the new baseline before any + // fork or handoff can trust the compacted history. + this.conversationHistory.clearPromptIndexes(); + try { + await this.conversationHistory.reconcileHistory(undefined, { allowUnobservedAppend: true }); + await this.conversationHistory.publish(); + this.nativeHistoryUnverified = false; + } catch { + if (!this.conversationHistory.isDiverged()) { + await this.conversationHistory.invalidateHistory().catch((error) => logger.warn('[opencode-remote] History divergence persistence deferred', error)); + } + } + } finally { + this.nativeHistoryUnverified = false; session.onThinkingChange(false); + if (session.queue.size() === 0 && !this.shouldExit) { + sendReady(); + } } + continue; + } + + // Inject title instructions on first prompt + let messageText = batch.message; + if (batch.mode.permissionMode === 'plan') { + messageText = `${PLAN_MODE_INSTRUCTION}\n\n${messageText}`; + } + + this.stallErrorReportedForPrompt = false; + const roundSummaryAbortController = new AbortController(); + this.roundSummaryAbortController = roundSummaryAbortController; + this.roundSummaryPhase = 'snapshot'; + const roundApi = this.v2RestInfo + ? { baseUrl: this.v2RestInfo.baseUrl, api: { version: 'v2' as const, password: this.v2RestInfo.password } } + : this.baseUrl ? { baseUrl: this.baseUrl } : null; + const roundSnapshot = this.nextRoundSnapshot ?? (roundApi + ? await captureOpencodeRoundSnapshot({ + ...roundApi, + sessionId: acpSessionId, + signal: roundSummaryAbortController.signal + }).catch((error) => { + logger.debug('[opencode-remote] round snapshot unavailable', error); + return null; + }) + : null); + this.nextRoundSnapshot = null; + if ( + this.roundSummaryAbortController !== roundSummaryAbortController + || roundSummaryAbortController.signal.aborted + || this.shouldExit + ) { + if (this.roundSummaryAbortController === roundSummaryAbortController) { + this.roundSummaryAbortController = null; + this.roundSummaryPhase = 'idle'; + } + session.onThinkingChange(false); if (session.queue.size() === 0 && !this.shouldExit) { sendReady(); } continue; } - this.nextRoundSnapshot = null; + // The one-time flag is consumed only at dispatch below, so a Stop + // during the history read cannot drop the instructions for good. + const attachInstructions = !this.instructionsSent; + if (attachInstructions) { + messageText = `${getOpencodeNativeToolInstruction()}\n\n${messageText}`; + } + + const promptContent: PromptContent[] = [{ + type: 'text', + text: messageText, + }]; + + const promptStartedAt = performance.now(); + let promptDurationMs = 0; + // A pre-dispatch bail-out (aborted wait, unavailable history count) + // must not request a round summary for a prompt that never ran. + let promptDispatched = false; + this.roundSummaryPhase = 'prompt'; session.onThinkingChange(true); + // Only a normal prompt is steerable: /compact and /clear leave this + // false, so a steer arriving during either is rejected rather than + // injected into a turn the agent is not running. + this.promptInFlight = true; + this.permissionHandler?.beginTurn(); + this.activePromptModeHash = session.queue.modeHasher({ ...batch.mode, model: steeringModel }); + this.activePromptText = messageText; + this.steerTurnEpoch += 1; + // Advertise steerability so the web's queued-message Steer button + // is reachable at all; only a normal active prompt may set it. + this.setSteeringActive(true); + const nativeInput = { uncertain: false }; try { - await this.runCompactOperation(acpSessionId, compactAbortController, compactLocalId); + // Native automatic compaction can append both a user-role + // compaction marker and a synthetic continuation. Re-read the + // native count before each prompt instead of assuming that the + // previous HAPI batch added exactly one user message. A failed + // read must omit this point, never reuse a stale position. A + // second snapshot below verifies the completed native history. + const nativeUserCount = await this.conversationHistory.getNativeUserMessageCount(waitSignal); + if (waitSignal.aborted || this.shouldExit) { + continue; + } + if (nativeUserCount === null) { + logger.warn('[opencode-remote] Native history unavailable; skipping fork point'); + } + logger.debug(`[opencode-remote] history point: localId=${batch.items[0]?.localId} index=${nativeUserCount} items=${batch.items.length}`); + // Publish a locator only after completion and verification; + // failed/cancelled requests may leave partial native history. + this.nativeHistoryUnverified = true; + this.nativeInputWriters.add(nativeInput); + promptDispatched = true; + if (attachInstructions) this.instructionsSent = true; + try { + await backend.prompt(acpSessionId, promptContent, (message: AgentMessage) => { + this.handleAgentMessage(message); + }); + } finally { + promptDurationMs = performance.now() - promptStartedAt; + this.roundSummaryPhase = 'settle'; + } + this.completeNativeInput(nativeInput); + // The foreground response does not fence concurrent inbox or + // soft-steer writes. Close admission before awaiting their + // receipts/restores, then snapshot the combined native turn. + this.promptInFlight = false; + this.activePromptModeHash = null; + this.setSteeringActive(false); + await this.drainSteerOperations(); + if (this.hasUnresolvedNativeInput()) throw new Error('OpenCode input outcome is unresolved'); + await this.nativeTranscript?.refresh(); + // A merged batch is one native prompt, so only its first item + // is a native fork boundary (same merge semantics as grok). + try { + await this.conversationHistory.reconcileHistory(undefined, { allowUnobservedAppend: true }); + if (nativeUserCount !== null) { + if (!this.conversationHistory.getCheckpoint()?.userMessageIds[nativeUserCount]) { + throw new Error('OpenCode did not persist the accepted prompt'); + } + this.conversationHistory.rememberPromptIndex(batch.items[0]?.localId, nativeUserCount); + } + await this.conversationHistory.publish(); + this.nativeHistoryUnverified = false; + } catch { + // Never expose newly accepted rows without a verified + // native identity checkpoint for a future handoff. + if (!this.conversationHistory.isDiverged()) { + await this.conversationHistory.invalidateHistory().catch((error) => logger.warn('[opencode-remote] History divergence persistence deferred', error)); + } + } + void backend.refreshSessionInfo(acpSessionId, session.path); + } catch (error) { + if (this.nativeHistoryUnverified && !this.conversationHistory.isDiverged()) { + await this.conversationHistory.invalidateHistory().catch((writeError) => logger.warn('[opencode-remote] History divergence persistence deferred', writeError)); + } + this.invalidateNativeReceiptCorrelation(); + logger.warn('[opencode-remote] prompt failed', error); + this.reportPromptFailure(error); } finally { - session.onThinkingChange(false); - if (session.queue.size() === 0 && !this.shouldExit) { - sendReady(); + this.promptInFlight = false; + this.activePromptModeHash = null; + this.setSteeringActive(false); + await this.drainSteerOperations(); + this.nativeHistoryUnverified = false; + if ( + this.roundSummaryAbortController === roundSummaryAbortController + && !roundSummaryAbortController.signal.aborted + && !this.shouldExit + && promptDispatched + && roundApi + && roundSnapshot + ) { + const result = await settleRoundSummary( + fetchOpencodeRoundSummary({ + ...roundApi, + sessionId: acpSessionId, + promptText: messageText, + snapshot: roundSnapshot, + durationMs: promptDurationMs, + signal: roundSummaryAbortController.signal + }), + roundSummaryAbortController + ); + if (result) { + this.nextRoundSnapshot = result.snapshot; + if (result.summary) this.handleAgentMessage({ type: 'round_summary', summary: result.summary }); + } + } + if (this.roundSummaryAbortController === roundSummaryAbortController) { + this.roundSummaryAbortController = null; + } + try { + session.onThinkingChange(false); + await this.permissionHandler?.cancelAll('Prompt finished'); + if (session.queue.size() === 0 && !this.shouldExit) { + sendReady(); + } + } finally { + this.roundSummaryPhase = 'idle'; } } - continue; - } - - // Inject title instructions on first prompt - let messageText = batch.message; - if (batch.mode.permissionMode === 'plan') { - messageText = `${PLAN_MODE_INSTRUCTION}\n\n${messageText}`; - } - - this.stallErrorReportedForPrompt = false; - const roundSummaryAbortController = new AbortController(); - this.roundSummaryAbortController = roundSummaryAbortController; - this.roundSummaryPhase = 'snapshot'; - const roundApi = this.v2RestInfo - ? { baseUrl: this.v2RestInfo.baseUrl, api: { version: 'v2' as const, password: this.v2RestInfo.password } } - : this.baseUrl ? { baseUrl: this.baseUrl } : null; - const roundSnapshot = this.nextRoundSnapshot ?? (roundApi - ? await captureOpencodeRoundSnapshot({ - ...roundApi, - sessionId: acpSessionId, - signal: roundSummaryAbortController.signal - }).catch((error) => { - logger.debug('[opencode-remote] round snapshot unavailable', error); - return null; - }) - : null); - this.nextRoundSnapshot = null; - if ( - this.roundSummaryAbortController !== roundSummaryAbortController - || roundSummaryAbortController.signal.aborted - || this.shouldExit - ) { - if (this.roundSummaryAbortController === roundSummaryAbortController) { - this.roundSummaryAbortController = null; - this.roundSummaryPhase = 'idle'; - } - session.onThinkingChange(false); - if (session.queue.size() === 0 && !this.shouldExit) { - sendReady(); - } - continue; - } - - if (!this.instructionsSent) { - messageText = `${getOpencodeNativeToolInstruction()} - -${messageText}`; - this.instructionsSent = true; - } - const promptContent: PromptContent[] = [{ - type: 'text', - text: messageText, - }]; - - const promptStartedAt = performance.now(); - let promptDurationMs = 0; - this.roundSummaryPhase = 'prompt'; - session.onThinkingChange(true); - // Only a normal prompt is steerable: /compact and /clear leave this - // false, so a steer arriving during either is rejected rather than - // injected into a turn the agent is not running. - this.promptInFlight = true; - this.permissionHandler?.beginTurn(); - this.activePromptModeHash = session.queue.modeHasher({ ...batch.mode, model: steeringModel }); - this.activePromptText = messageText; - this.steerTurnEpoch += 1; - // Advertise steerability so the web's queued-message Steer button - // is reachable at all; only a normal active prompt may set it. - this.setSteeringActive(true); - const nativeInput = { uncertain: false }; - this.nativeInputWriters.add(nativeInput); - try { - try { - await backend.prompt(acpSessionId, promptContent, (message: AgentMessage) => { - this.handleAgentMessage(message); - }); - } finally { - promptDurationMs = performance.now() - promptStartedAt; - this.roundSummaryPhase = 'settle'; - } - this.completeNativeInput(nativeInput); - await this.nativeTranscript?.refresh(); - void backend.refreshSessionInfo(acpSessionId, session.path); - } catch (error) { - this.invalidateNativeReceiptCorrelation(); - logger.warn('[opencode-remote] prompt failed', error); - this.reportPromptFailure(error); } finally { - // Close the steer gate synchronously, before the first await: - // any steer still parked on its durable-state await must see - // the turn as gone and restore its row instead of injecting - // into a turn that has already returned. - this.promptInFlight = false; - this.activePromptModeHash = null; - // Publish "not steerable" together with the gate, *before* the - // drain: a steer whose completion is still pending would keep - // the web's Steer button visible for the whole drain, and every - // click in that window is a guaranteed rejection. - this.setSteeringActive(false); - // Drain before ready / thinking=false / the next batch, so a - // steer that settled (or is still restoring) cannot cross the - // turn boundary into the next prompt or a /compact. - await this.drainSteerOperations(); - if ( - this.roundSummaryAbortController === roundSummaryAbortController - && !roundSummaryAbortController.signal.aborted - && !this.shouldExit - && roundApi - && roundSnapshot - ) { - const result = await settleRoundSummary( - fetchOpencodeRoundSummary({ - ...roundApi, - sessionId: acpSessionId, - promptText: messageText, - snapshot: roundSnapshot, - durationMs: promptDurationMs, - signal: roundSummaryAbortController.signal - }), - roundSummaryAbortController - ); - if (result) { - this.nextRoundSnapshot = result.snapshot; - if (result.summary) this.handleAgentMessage({ type: 'round_summary', summary: result.summary }); - } - } - if (this.roundSummaryAbortController === roundSummaryAbortController) { - this.roundSummaryAbortController = null; - } - try { - session.onThinkingChange(false); - await this.permissionHandler?.cancelAll('Prompt finished'); - if (session.queue.size() === 0 && !this.shouldExit) { - sendReady(); - } - } finally { - this.roundSummaryPhase = 'idle'; - } + this.conversationHistory.setBusy(false); + releaseRuntime(); } } } @@ -1094,7 +1653,8 @@ ${messageText}`; // draining updates for seconds while the backend still reports // a processing message. A steer accepted in that window would // start a brand-new turn instead of injecting mid-turn. - if (!this.promptInFlight + if (this.runtimeGate.isBlocked() + || !this.promptInFlight || !this.activeAcpSessionId || !backend || this.shouldExit @@ -1195,7 +1755,8 @@ ${messageText}`; : null; // Recheck everything the durable/native-history awaits could // have invalidated before sending to the backend. - if (!this.promptInFlight + if (this.runtimeGate.isBlocked() + || !this.promptInFlight || this.shouldExit || this.steerEpoch !== steerEpoch || this.backend !== backend @@ -1556,6 +2117,14 @@ ${messageText}`; for (const input of this.nativeInputWriters) input.uncertain = true; } + // Queue resolution and transport counters cannot prove a native writer + // is fenced. Unknown v2 admissions and detached ACP writers retain their + // own evidence even after an explicit HAPI row cancellation. + private hasUnresolvedNativeInput(): boolean { + return this.v2Steers.size > 0 || this.nativeInputWriters.size > 0 + || this.pendingSteerOperations.size > 0; + } + private completeNativeInput(input: { uncertain: boolean }): void { this.nativeInputWriters.delete(input); if (!Array.from(this.nativeInputWriters).some(writer => writer.uncertain)) { @@ -1572,7 +2141,8 @@ ${messageText}`; */ private setSteeringActive(active: boolean): void { // v2 uses its experimental durable REST inbox, never concurrent ACP. - const steeringActive = active && (this.majorVersion !== 'v2' || this.v2RestInfo !== null); + const steeringActive = active && !this.runtimeGate.isBlocked() + && (this.majorVersion !== 'v2' || this.v2RestInfo !== null); this.session.client.updateAgentState?.((state) => ({ ...state, steeringActive })); } @@ -1586,6 +2156,7 @@ ${messageText}`; operation: OpencodeSteerOperation; release: () => void; } { + const releaseRuntime = this.runtimeGate.enterRuntime(); let settle!: () => void; const operation: OpencodeSteerOperation = { settled: new Promise((resolve) => { settle = resolve; }), @@ -1605,6 +2176,7 @@ ${messageText}`; released = true; this.pendingSteerOperations.delete(operation); this.pendingSteerAcceptances.delete(operation); + releaseRuntime(); settle(); }; return { operation, release: operation.release }; @@ -1682,14 +2254,27 @@ ${messageText}`; * comment on RemoteLauncherBase for exactly when this fires. */ protected onLeavingRemote(): void { + this.rewindStopped = true; + this.rewindEntryAbortController.abort(); + this.detachRewindEntry(); // Synchronous, before anything here could await: a steer parked on a // durable-state await must not be able to inject into a backend that is // already on its way out. + this.historyProbeAbortController.abort(); this.closeSteerGate(); this.options.onCompactAvailabilityChange?.(false); + // Withdraw history affordances for the teardown window and any + // subsequent local mode: the loopback server is going away, so forks + // can no longer be served (same lifecycle as /compact above). + this.conversationHistory.setBusy(true); + void (this.nativeHistoryUnverified + ? this.conversationHistory.invalidateHistory() + : this.conversationHistory.disableFork()).catch(() => {}); } protected async cleanup(): Promise { + this.rewindStopped = true; + this.detachRewindEntry(); // Before anything that can fail: a steer still parked on a // durable-state await must not be able to send into the backend that is // about to be torn down (or a replacement one). @@ -1914,19 +2499,15 @@ ${messageText}`; * completion, preserving the shared-session FIFO invariant. Switch/exit * aborts every phase because teardown disconnects the session. * - * `compactAbortController` is created by the caller (the dequeue loop), - * not here, and passed in — deliberately, before the loop's model/effort - * switch for this batch runs, not after. A hostile-review whole-feature - * sweep found that creating it in here (i.e. only once this function was - * actually entered) left a window during that switch — a real async ACP - * round-trip — where an abort had nothing to act on yet (`this - * .compactAbortController` was still null) and was silently lost by the - * time this function created a *fresh* controller afterward. + * The dequeue loop creates compactAbortController before async model/effort + * setup and passes it here. Replacing it would lose cancellation received + * during that setup window. */ private async runCompactOperation( acpSessionId: string, compactAbortController: AbortController, - localId?: string + localId?: string, + onMutationIssued?: () => void ): Promise { const session = this.session; session.sendSessionEvent({ type: 'message', message: '📦 Compaction started' }); @@ -2027,6 +2608,7 @@ ${messageText}`; | { ok: false; error: string } | { ok: true; cancelled: false; result: CompactionResult } > => { + onMutationIssued?.(); const admitted = await triggerOpencodeCompactV2({ baseUrl, sessionId: acpSessionId, @@ -2131,6 +2713,7 @@ ${messageText}`; // client abort, so a plain Stop deliberately waits only in this // phase. It has no deadline because real compaction can take minutes. this.compactOperationPhase = 'summarize'; + onMutationIssued?.(); const requestResult = await backend.suppressUpdatesDuring(async () => { try { return await triggerOpencodeCompact({ @@ -2263,12 +2846,10 @@ ${messageText}`; } /** - * `leavingRemote` distinguishes plain Stop (`false`, the default — stays - * in the same remote session) from switch-to-local/exit (`true` — the - * session is being torn down). Compact and a prompt must never touch - * the same OpenCode session concurrently (see - * `compactResultSuppressed`'s field doc comment for the full - * reasoning). Plain Stop aborts only read-only marker/result GETs. It + * leavingRemote distinguishes plain Stop (false, stays in this remote + * session) from switch-to-local/exit (true, tears down the session). + * Compact and a prompt must never mutate the same OpenCode session + * concurrently. Plain Stop aborts only read-only marker/result GETs. It * leaves an in-flight summarize POST running so the dequeue loop waits * for its real server-side completion; only that phase can still mutate * the shared session. Switch/exit aborts every phase because cleanup() @@ -2288,7 +2869,11 @@ ${messageText}`; && !this.v2AbortInProgress ) return; - if (this.majorVersion !== 'v2') return this.performAbort(leavingRemote); + // A connection-entry fence denies new work, but must not suppress Stop + // or teardown of work that was admitted before the fence. + const release = this.runtimeGate.enterCancellation(); + try { + if (this.majorVersion !== 'v2') return await this.performAbort(leavingRemote); if (this.v2AbortInProgress) { // One overlapping Stop/switch owns queue.reset. A later reset // must not erase an input the first cancellation just restored. @@ -2297,7 +2882,7 @@ ${messageText}`; this.compactResultSuppressed = true; this.compactAbortController?.abort(); } - return this.v2AbortInProgress; + return await this.v2AbortInProgress; } let resolve!: () => void; let reject!: (error: unknown) => void; @@ -2306,6 +2891,7 @@ ${messageText}`; void this.performAbort(leavingRemote).then(resolve, reject); try { await abort; } finally { if (this.v2AbortInProgress === abort) this.v2AbortInProgress = null; } + } finally { release(); } } private async performAbort(leavingRemote: boolean): Promise { @@ -2343,7 +2929,8 @@ ${messageText}`; } } const backend = this.backend; - if (backend && this.session.sessionId) { + if (backend && this.session.sessionId + && (!this.runtimeGate.isBlocked() || this.runtimeGate.hasOrdinaryRuntimeActivity())) { try { await backend.cancelPrompt(this.session.sessionId); } finally { @@ -2394,15 +2981,36 @@ ${messageText}`; } private async handleExitFromUi(): Promise { + if (this.runtimeGate.isBlocked() && !this.runtimeGate.isRewindBlocked()) { + await this.requestExit('exit', () => this.handleAbort(true)); + return; + } + const release = this.runtimeGate.enterRuntime(); + try { await this.requestExit('exit', () => this.handleAbort(true)); + } finally { release(); } } private async handleSwitchFromUi(): Promise { + if (this.runtimeGate.isBlocked() && !this.runtimeGate.isRewindBlocked()) { + await this.requestExit('switch', () => this.handleAbort(true)); + return; + } + const release = this.runtimeGate.enterRuntime(); + try { await this.requestExit('switch', () => this.handleAbort(true)); + } finally { release(); } } private async handleSwitchRequest(): Promise { + if (this.runtimeGate.isBlocked() && !this.runtimeGate.isRewindBlocked()) { + await this.requestExit('switch', () => this.handleAbort(true)); + return; + } + const release = this.runtimeGate.enterRuntime(); + try { await this.requestExit('switch', () => this.handleAbort(true)); + } finally { release(); } } } diff --git a/cli/src/opencode/rewind.committedRecovery.test.ts b/cli/src/opencode/rewind.committedRecovery.test.ts new file mode 100644 index 00000000..0b724107 --- /dev/null +++ b/cli/src/opencode/rewind.committedRecovery.test.ts @@ -0,0 +1,97 @@ +// Regression tests: a committed rewind with a missing or finalized +// local journal is terminal — admission is released without re-running +// consumption. +import { describe, expect, it, vi } from 'vitest'; +import { mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { OpenCodeRewind, OpenCodeRuntimeGate } from './rewind'; +import type { OpenCodeRewindOperation } from '@hapi/protocol/schemas'; +import { getProcessStartMarker } from '@/utils/process'; + +const rows = [ + { id: 'u1', type: 'user', content: [{ type: 'text', text: 'one' }] }, + { id: 'a1', type: 'assistant', content: [{ type: 'text', text: 'first answer' }] }, + { id: 'u2', type: 'user', content: [{ type: 'text', text: 'two' }] }, + { id: 'a2', type: 'assistant', content: [{ type: 'text', text: 'second answer' }] } +]; + +const operation: OpenCodeRewindOperation = { operationId: 'operation', nativeSessionId: 'native', workerId: 'worker', + requestedLocalId: 'local2', nativeMessageId: 'u2', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 4, + reservationVersion: 2, sourceTranscriptHash: 'c'.repeat(64), workerPid: process.pid, + workerStartMarker: getProcessStartMarker(process.pid)!, phase: 'committed' as const }; + +async function fixtureWithIntent(directory: string, mintFinalizedJournal: boolean) { + const gate = new OpenCodeRuntimeGate(); + const consumeCommitted = vi.fn(async () => {}); + const rewind = new OpenCodeRewind({ + directory, hapiSessionId: 'hapi', workerId: 'worker', gate, + baseUrl: 'http://native', nativeSessionId: 'native', headers: {}, + request: vi.fn(async () => Response.json({ data: {} })), + report: vi.fn(async (value: { operation: OpenCodeRewindOperation; phase: string }) => value.operation), + getAuthoritativeOperation: async () => operation, + flush: async () => true, isIdle: () => true, + sourceCheckpoint: () => ({ sessionId: 'native', messageIds: rows.map(r => r.id), userMessageIds: ['u1', 'u2'], localMessageIds: [] }), + sourceIndexes: () => ({ local1: 0, local2: 1 }), + requestsFromPreviousWorkerCannotRun: () => false, + consumeCommitted, + nativeProcess: { pid: process.pid, startMarker: getProcessStartMarker(process.pid)! } + }); + if (mintFinalizedJournal) { + // Reuse a real controller run to mint a schema-valid finalized journal: + // execute() drives the full prepare/stage/commit flow against the + // stubbed native server and leaves intent.json + backup on disk. + let current = structuredClone(rows); + let staged: string | undefined; + let authoritative: OpenCodeRewindOperation = { ...operation, phase: 'reserved' as const }; + const seed = new OpenCodeRewind({ + directory, hapiSessionId: 'hapi', workerId: 'worker', gate: new OpenCodeRuntimeGate(), + baseUrl: 'http://native', nativeSessionId: 'native', headers: {}, + request: vi.fn(async (path: string, init?: RequestInit) => { + if (path.endsWith('/revert/stage')) { staged = JSON.parse(init!.body as string).messageID; return Response.json({}); } + if (path.endsWith('/revert/commit')) { current = current.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (path.includes('/message?')) return Response.json({ data: current, cursor: {} }); + if (path.endsWith('/active')) return Response.json({ data: {} }); + if (path.endsWith('/inbox')) return Response.json({ data: [] }); + return Response.json({ data: { id: 'native', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }), + report: vi.fn(async (value: { operation: OpenCodeRewindOperation; phase: string }) => { + authoritative = { ...value.operation, phase: value.phase === 'applied' ? 'committed' : value.phase } as OpenCodeRewindOperation; + return authoritative; + }), + getAuthoritativeOperation: async () => authoritative, + flush: async () => true, isIdle: () => true, + sourceCheckpoint: () => ({ sessionId: 'native', messageIds: rows.map(r => r.id), userMessageIds: ['u1', 'u2'], localMessageIds: [] }), + sourceIndexes: () => ({ local1: 0, local2: 1 }), + requestsFromPreviousWorkerCannotRun: () => false, + consumeCommitted: async () => {}, + nativeProcess: { pid: process.pid, startMarker: getProcessStartMarker(process.pid)! } + }); + expect(await seed.execute({ ...operation, phase: 'reserved' })).toMatchObject({ success: true }); + } + return { rewind, gate, consumeCommitted }; +} + +describe('committed tombstone recovery', () => { + it('treats a committed operation with no local intent as already consumed and releases admission', async () => { + const directory = mkdtempSync(join(tmpdir(), 'opencode-rewind-')); + const { rewind, gate, consumeCommitted } = await fixtureWithIntent(directory, false); + gate.block(); + const result = await rewind.recover(operation); + expect(result).toMatchObject({ success: true }); + expect(consumeCommitted).not.toHaveBeenCalled(); + expect(gate.isBlocked()).toBe(false); + }); + + it('does not re-consume a committed operation whose local intent is already finalized', async () => { + const directory = mkdtempSync(join(tmpdir(), 'opencode-rewind-')); + const { rewind, gate, consumeCommitted } = await fixtureWithIntent(directory, true); + expect(rewind.readIntent()?.phase).toBe('finalized'); + gate.block(); + const result = await rewind.recover(operation); + expect(result).toMatchObject({ success: true }); + expect(consumeCommitted).not.toHaveBeenCalled(); + expect(rewind.readIntent()?.phase).toBe('finalized'); + expect(gate.isBlocked()).toBe(false); + }); +}); \ No newline at end of file diff --git a/cli/src/opencode/rewind.test.ts b/cli/src/opencode/rewind.test.ts new file mode 100644 index 00000000..5cf440ba --- /dev/null +++ b/cli/src/opencode/rewind.test.ts @@ -0,0 +1,847 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { MessageQueue2 } from '@/utils/MessageQueue2'; +import { getProcessStartMarker } from '@/utils/process'; +import { OpencodeSession } from './session'; +import { OpenCodeRewind, OpenCodeRuntimeGate } from './rewind'; +import type { OpenCodeRewindReport } from '@hapi/protocol/apiTypes'; +import type { OpenCodeRewindOperation } from '@hapi/protocol/schemas'; + +// Windows FlushFileBuffers requires GENERIC_WRITE, which a read-only directory +// handle does not carry, so fsyncSync on a directory fd fails there. The guard +// lets tests simulate that EPERM for directory fds while file fds stay real. +const windowsDirectoryFsync = vi.hoisted(() => ({ + guard: undefined as (() => never) | undefined, + markerOverride: undefined as ((pid: number) => string | null) | undefined +})); +vi.mock('node:fs', async importOriginal => { + const actual = await importOriginal(); + const fsyncSync: typeof actual.fsyncSync = fd => { + if (windowsDirectoryFsync.guard && actual.fstatSync(fd).isDirectory()) windowsDirectoryFsync.guard(); + return actual.fsyncSync(fd); + }; + return { ...actual, fsyncSync }; +}); +// The Windows stub must not disturb the worker-generation proof: while active, +// getProcessStartMarker keeps answering with the real Linux marker. +vi.mock('@/utils/process', async importOriginal => { + const actual = await importOriginal(); + const getProcessStartMarker: typeof actual.getProcessStartMarker = pid => + windowsDirectoryFsync.markerOverride ? windowsDirectoryFsync.markerOverride(pid) : actual.getProcessStartMarker(pid); + return { ...actual, getProcessStartMarker }; +}); + +const rows = [ + { id: 'u1', type: 'user', text: 'one' }, + { id: 'a1', type: 'assistant', content: [{ type: 'text', text: 'first answer' }] }, + { id: 'u2', type: 'user', text: 'two' }, + { id: 'a2', type: 'assistant', content: [{ type: 'text', text: 'second answer' }] } +]; +const operation = { operationId: 'operation', nativeSessionId: 'native', workerId: 'worker', requestedLocalId: 'local2', + nativeMessageId: 'u2', cutoffSeq: 3, sourceEpoch: 0, sourceMaxSeq: 4, reservationVersion: 2, sourceTranscriptHash: 'c'.repeat(64), + workerPid: process.pid, workerStartMarker: getProcessStartMarker(process.pid)!, phase: 'reserved' as const }; +const cleanups: Array<() => void> = []; +afterEach(() => { for (const f of cleanups.splice(0)) f(); }); + +/** Pretends the test runs on Windows: platform reports win32 and directory fsync + * fails with EPERM, per the documented FlushFileBuffers access rights. */ +function stubWindowsDirectoryFsync(): () => void { + const marker = getProcessStartMarker(process.pid); + const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32'); + windowsDirectoryFsync.markerOverride = () => marker; + windowsDirectoryFsync.guard = () => { + const error: NodeJS.ErrnoException = new Error('EPERM: FlushFileBuffers requires GENERIC_WRITE on a read-only directory handle'); + error.code = 'EPERM'; + throw error; + }; + return () => { platform.mockRestore(); windowsDirectoryFsync.markerOverride = undefined; windowsDirectoryFsync.guard = undefined; }; +} + +function fixture() { + const directory = mkdtempSync(join(tmpdir(), 'opencode-rewind-')); + let current = structuredClone(rows); + let staged: string | undefined; + const ownership = { nativeGone: false, workerGone: false }; + const gate = new OpenCodeRuntimeGate(); + const reports: OpenCodeRewindReport[] = []; + let authoritative: OpenCodeRewindOperation = operation; + const request = vi.fn(async (path: string, init?: RequestInit) => { + if (path.endsWith('/revert/stage')) { staged = JSON.parse(init!.body as string).messageID; return Response.json({}); } + if (path.endsWith('/revert/commit')) { current = current.slice(0, 2); staged = undefined; return new Response(null, { status: 204 }); } + if (path.includes('/message?')) return Response.json({ data: current, cursor: {} }); + if (path.endsWith('/active')) return Response.json({ data: {} }); + if (path.endsWith('/inbox')) return Response.json({ data: [] }); + return Response.json({ data: { id: 'native', ...(staged ? { revert: { messageID: staged } } : {}) } }); + }); + const report = vi.fn(async (value: OpenCodeRewindReport): Promise => { + reports.push(value); + authoritative = { ...value.operation, phase: value.phase === 'applied' ? 'committed' : value.phase }; + return authoritative; + }); + const consumeCommitted = vi.fn(async () => {}); + const options = { directory, hapiSessionId: 'hapi', workerId: 'worker', gate, + baseUrl: 'http://native', nativeSessionId: 'native', headers: {}, request, + report, getAuthoritativeOperation: async () => authoritative, flush: async () => true, isIdle: () => true, + sourceCheckpoint: () => ({ sessionId: 'native', messageIds: rows.map(r => r.id), userMessageIds: ['u1', 'u2'], localMessageIds: [] }), + sourceIndexes: () => ({ local1: 0, local2: 1 }), requestsFromPreviousWorkerCannotRun: () => ownership.nativeGone, + previousWorkerCannotRun: () => ownership.workerGone, consumeCommitted, + nativeProcess: { pid: 101, startMarker: 'original-native-generation' } }; + const rewind = new OpenCodeRewind(options); + return { rewind, gate, directory, reports, report, request, ownership, consumeCommitted, + restart: (overrides: Partial = {}) => new OpenCodeRewind({ ...options, workerId: 'replacement', ...overrides }), + setAuthoritative: (value: OpenCodeRewindOperation) => { authoritative = value; }, + getAuthoritative: () => authoritative, + setRows: (value: typeof rows) => { current = value; } }; +} + +describe('OpenCode same-native-ID durable rewind', () => { + it('backs up before stage, commits the exact prefix and only releases after authoritative Hub commit', async () => { + const f = fixture(); + const result = await f.rewind.execute(operation); + expect(result.success).toBe(true); + expect(f.reports.map(r => r.phase)).toEqual(['prepared', 'applied']); + expect(f.reports[1]?.checkpoint).toMatchObject({ sessionId: 'native', messageIds: ['u1', 'a1'], userMessageIds: ['u1'] }); + expect(f.reports[1]?.indexes).toEqual({ local1: 0 }); + const journal = f.rewind.readIntent()!; + expect(journal.phase).toBe('finalized'); + expect(JSON.parse(readFileSync(journal.backupPath, 'utf8')).messages).toEqual(rows); + expect(statSync(journal.backupPath).mode & 0o777).toBe(0o600); + expect(statSync(dirname(journal.backupPath)).mode & 0o777).toBe(0o700); + expect(statSync(join(dirname(journal.backupPath), 'intent.json')).mode & 0o777).toBe(0o600); + expect(f.consumeCommitted).toHaveBeenCalledOnce(); + expect(f.gate.isBlocked()).toBe(false); + }); + + it('finalizes the journal on Windows where a directory fsync is unavailable', async () => { + const f = fixture(); + const restore = stubWindowsDirectoryFsync(); + try { + expect(await f.rewind.execute(operation)).toMatchObject({ success: true }); + expect(f.reports.map(r => r.phase)).toEqual(['prepared', 'applied']); + expect(f.rewind.readIntent()?.phase).toBe('finalized'); + expect(f.gate.isBlocked()).toBe(false); + } finally { restore(); } + }); + + it('reports unknown and stays recoverable on Windows where a directory fsync is unavailable', async () => { + const f = fixture(); f.report.mockRejectedValueOnce(new Error('prepared ACK lost')); + const restore = stubWindowsDirectoryFsync(); + try { + expect(await f.rewind.execute(operation)).toMatchObject({ success: false, outcome: 'unknown' }); + expect(f.reports.map(r => r.phase)).toEqual(['unknown']); + expect(f.rewind.readIntent()).toMatchObject({ phase: 'unknown', pendingRequest: false }); + expect(await f.rewind.recover({ ...operation, phase: 'unknown' })).toMatchObject({ success: false, outcome: 'rejected' }); + expect(f.rewind.readIntent()?.phase).toBe('finalized'); + expect(f.gate.isBlocked()).toBe(false); + } finally { restore(); } + }); + + it('keeps independently owned entry fences and rewind blocks isolated', async () => { + const gate = new OpenCodeRuntimeGate() as OpenCodeRuntimeGate & { acquireEntryFence(): symbol; releaseEntryFence(token: symbol): void }; + const first = gate.acquireEntryFence(); const second = gate.acquireEntryFence(); + gate.block(); gate.releaseEntryFence(first); expect(gate.isBlocked()).toBe(true); + gate.release(); expect(gate.isBlocked()).toBe(true); + gate.releaseEntryFence(first); expect(gate.isBlocked()).toBe(true); + gate.releaseEntryFence(second); expect(gate.isBlocked()).toBe(false); + }); + + it('fences new runtime synchronously while waiting for an existing owner to drain', async () => { + const gate = new OpenCodeRuntimeGate() as OpenCodeRuntimeGate & { acquireEntryFence(): symbol; releaseEntryFence(token: symbol): void; waitUntilIdle(): Promise }; + const release = gate.enterRuntime(); const fence = gate.acquireEntryFence(); let idle = false; + const drained = gate.waitUntilIdle().then(() => { idle = true; }); + expect(() => gate.enterRuntime()).toThrow('reconciliation'); + await Promise.resolve(); expect(idle).toBe(false); + release(); await drained; expect(idle).toBe(true); + expect(gate.isBlocked()).toBe(true); gate.releaseEntryFence(fence); expect(gate.isBlocked()).toBe(false); + }); + + it('hands a disposed owner fence to a successor without clearing the successor fence', () => { + const gate = new OpenCodeRuntimeGate(); + const old = gate.acquireEntryFence(); const successor = gate.acquireEntryFence(); + let adopted: symbol | undefined; + const detach = gate.onEntryHandoff(() => { adopted = gate.adoptInitialEntryFence(successor); }); + gate.handoffEntryFence(old); + expect(adopted).toBe(successor); + gate.releaseEntryFence(old); + expect(gate.isBlocked()).toBe(true); + detach(); gate.releaseEntryFence(successor); + expect(gate.isBlocked()).toBe(false); + const orphan = gate.acquireEntryFence(); gate.handoffEntryFence(orphan); + expect(gate.takeInitialEntryFence()).toBe(orphan); + gate.releaseEntryFence(orphan); + }); + + it('counts cancellation owners independently and refuses a real rewind blocker', async () => { + const gate = new OpenCodeRuntimeGate(); + const fence = gate.acquireEntryFence(); + const first = gate.enterCancellation(); const second = gate.enterCancellation(); + expect(gate.isRuntimeActive()).toBe(true); + expect(gate.hasOrdinaryRuntimeActivity()).toBe(false); + expect(() => gate.enterRuntime()).toThrow('reconciliation'); + gate.block(); expect(() => gate.enterCancellation()).toThrow('reconciliation'); + first(); first(); let idle = false; + const waiting = gate.waitUntilIdle().then(() => { idle = true; }); + await Promise.resolve(); expect(idle).toBe(false); + second(); second(); await waiting; expect(idle).toBe(true); + expect(gate.isBlocked()).toBe(true); + gate.release(); gate.releaseEntryFence(fence); expect(gate.isBlocked()).toBe(false); + }); + + it('owns the runtime gate synchronously before its first await', async () => { + const f = fixture(); + const pending = f.rewind.execute(operation); + expect(() => f.gate.enterRuntime()).toThrow(); + await pending; + }); + + it('rejects reconnect recovery while the original operation still owns an awaited preparation', async () => { + const f = fixture(); let resume!: () => void; + f.report.mockImplementationOnce(() => new Promise(resolve => { resume = () => resolve({ ...operation, phase: 'prepared' }); })); + const pending = f.rewind.execute(operation); + await vi.waitFor(() => expect(resume).toBeTypeOf('function')); + try { + await expect(f.rewind.recover(operation)).rejects.toThrow('busy'); + expect(f.gate.isBlocked()).toBe(true); + } finally { resume(); await pending; } + }); + + it('serializes separate controllers sharing a wrapper gate during a suspended preparation', async () => { + const f = fixture(); let resume!: () => void; + f.report.mockImplementationOnce(() => new Promise(resolve => { resume = () => resolve({ ...operation, phase: 'prepared' }); })); + const pending = f.rewind.execute(operation); + await vi.waitFor(() => expect(resume).toBeTypeOf('function')); + try { + await expect(f.restart({ workerId: 'worker' }).recover(operation)).rejects.toThrow('busy'); + expect(f.gate.isBlocked()).toBe(true); + } finally { resume(); await pending; } + }); + + it('does not report an already stale RPC as a rejection of the newer reservation', async () => { + const f = fixture(); + const newer = { ...operation, operationId: 'newer-reservation', reservationVersion: 4 }; + f.setAuthoritative(newer); + const controller = f.restart({ workerId: 'worker', isIdle: () => false }); + await expect(controller.execute(operation)).rejects.toThrow('no longer authoritative'); + expect(f.report).not.toHaveBeenCalled(); + expect(controller.readIntent()).toBeUndefined(); + expect(f.gate.isBlocked()).toBe(true); + expect(await f.rewind.recover(newer)).toMatchObject({ outcome: 'rejected' }); + expect(f.gate.isBlocked()).toBe(false); + }); + + it('keeps admission blocked when authoritative metadata cannot be refreshed', async () => { + const f = fixture(); + const controller = f.restart({ workerId: 'worker', getAuthoritativeOperation: async () => { throw new Error('offline'); } }); + await expect(controller.execute(operation)).rejects.toThrow('offline'); + expect(f.report).not.toHaveBeenCalled(); + expect(f.gate.isBlocked()).toBe(true); + }); + + it.each(['reserved', 'prepared'] as const)('keeps admission blocked for current %s after a queued stale operation', async phase => { + const f = fixture(); let resumeOld!: () => void; + const old = f.restart({ workerId: 'worker', flush: () => new Promise(resolve => { resumeOld = () => resolve(true); }) }); + const oldExecution = old.execute(operation); + await vi.waitFor(() => expect(resumeOld).toBeTypeOf('function')); + const next = { ...operation, operationId: `current-${phase}`, reservationVersion: 3, + workerId: phase === 'prepared' ? 'worker2' : 'worker' }; + f.setAuthoritative(next); + let releasePrepared: (() => void) | undefined; + let preparedEntered: (() => void) | undefined; + let currentExecution: Promise | undefined; + if (phase === 'prepared') { + const ready = new Promise(resolve => { preparedEntered = resolve; }); + const hold = new Promise(resolve => { releasePrepared = resolve; }); + const actualReport = f.report.getMockImplementation()!; + f.report.mockImplementation(async report => { + const result = await actualReport(report); + if (report.phase === 'prepared' && report.operation.operationId === next.operationId) { preparedEntered!(); await hold; } + return result; + }); + currentExecution = f.restart({ workerId: 'worker2', gate: new OpenCodeRuntimeGate() }).execute(next); + await ready; + } + const reportsBefore = f.reports.length; const nativeBefore = f.request.mock.calls.length; + const queue = new MessageQueue2(() => 'mode'); + const session = new OpencodeSession({ api: {} as never, client: { keepAlive: vi.fn(), emitMessagesConsumed: vi.fn() } as never, + path: '/fixture', logPath: '/fixture/log', sessionId: 'native', messageQueue: queue, + onModeChange: () => {}, startedBy: 'runner', startingMode: 'remote', runtimeGate: f.gate }); + cleanups.push(() => session.stopKeepAlive()); + try { + resumeOld(); await expect(oldExecution).rejects.toThrow('no longer authoritative'); + expect(f.reports).toHaveLength(reportsBefore); + expect(f.request.mock.calls).toHaveLength(nativeBefore); + expect(old.readIntent()?.operation.operationId).toBe(phase === 'prepared' ? next.operationId : undefined); + expect(f.gate.isBlocked()).toBe(true); + expect(() => f.gate.enterRuntime()).toThrow('pending reconciliation'); + queue.push('queued input', { permissionMode: 'default' }); + await expect(queue.waitForMessagesAndGetAsString()).rejects.toThrow('pending reconciliation'); + expect(queue.size()).toBe(1); + if (phase === 'prepared') { + releasePrepared!(); expect(await currentExecution).toMatchObject({ success: true }); + f.ownership.workerGone = true; + expect(await f.rewind.recover({ ...next, phase: 'committed' })).toMatchObject({ success: true }); + } else { + expect(await f.rewind.recover(next)).toMatchObject({ outcome: 'rejected' }); + } + expect(f.gate.isBlocked()).toBe(false); + expect((await queue.waitForMessagesAndGetAsString())?.message).toBe('queued input'); + session.takeDequeuedRuntimeRelease()!(); + } finally { releasePrepared?.(); await currentExecution; queue.close(); } + }); + + it('does not reject an absent journal while a different live worker is still before its first write', async () => { + const f = fixture(); let resume!: () => void; + const first = f.restart({ workerId: 'worker', flush: () => new Promise(resolve => { resume = () => resolve(true); }) }); + const running = first.execute(operation); + await vi.waitFor(() => expect(resume).toBeTypeOf('function')); + const replacementGate = new OpenCodeRuntimeGate(); + const replacement = f.restart({ gate: replacementGate }); + try { + expect(first.readIntent()).toBeUndefined(); + await expect(replacement.recover(operation)).rejects.toThrow('Previous HAPI worker'); + expect(replacementGate.isBlocked()).toBe(true); + expect(f.report).not.toHaveBeenCalled(); + } finally { resume(); await running; } + expect(first.readIntent()?.operation.operationId).toBe(operation.operationId); + }); + + it('keeps a malformed or conflicting unfinished journal blocked', async () => { + const f = fixture(); f.report.mockRejectedValueOnce(new Error('prepared ACK lost')); + expect(await f.rewind.execute(operation)).toMatchObject({ outcome: 'unknown' }); + const journal = f.rewind.readIntent()!; + const other = { ...operation, operationId: 'different' }; + f.setAuthoritative(other); + await expect(f.rewind.recover(other)).rejects.toThrow('no matching local intent'); + expect(f.rewind.readIntent()?.operation.operationId).toBe(operation.operationId); + writeFileSync(join(dirname(journal.backupPath), 'intent.json'), '{'); + await expect(f.rewind.recover(other)).rejects.toThrow(); + expect(f.gate.isBlocked()).toBe(true); + }); + + it('rejects an already admitted config/input even with an empty queue', async () => { + const f = fixture(); const release = f.gate.enterRuntime(); + await expect(f.rewind.execute(operation)).rejects.toThrow('busy'); + release(); + expect(f.request).not.toHaveBeenCalled(); + }); + + it('does not execute an already recorded operation or overwrite its original backup', async () => { + const f = fixture(); await f.rewind.execute(operation); + const path = f.rewind.readIntent()!.backupPath; + const backup = readFileSync(path, 'utf8'); f.request.mockClear(); + await expect(f.rewind.execute(operation)).rejects.toThrow('no longer authoritative'); + expect(f.gate.isBlocked()).toBe(false); + expect(f.request).not.toHaveBeenCalled(); + expect(readFileSync(path, 'utf8')).toBe(backup); + }); + + it('rejects an unprepared reservation with no journal and releases only after exact acknowledgement', async () => { + const f = fixture(); + expect(await f.rewind.recover(operation)).toMatchObject({ success: false, outcome: 'rejected' }); + expect(f.reports).toEqual([{ operation, phase: 'rejected' }]); + expect(f.gate.isBlocked()).toBe(false); + expect(f.request).not.toHaveBeenCalled(); + }); + + it('keeps an absent-intent replacement blocked while the reserved owner may still run', async () => { + const f = fixture(); + await expect(f.restart().recover(operation)).rejects.toThrow(); + expect(f.gate.isBlocked()).toBe(true); + expect(f.report).not.toHaveBeenCalled(); + expect(f.request).not.toHaveBeenCalled(); + }); + + it('does not recover a reservation on a different native session', async () => { + const f = fixture(); + const wrongSession = f.restart({ workerId: 'worker', nativeSessionId: 'different-native' }); + await expect(wrongSession.recover(operation)).rejects.toThrow('native session'); + expect(f.gate.isBlocked()).toBe(true); + expect(f.report).not.toHaveBeenCalled(); + expect(f.request).not.toHaveBeenCalled(); + }); + + it('keeps legacy absent-intent reservations without worker proof blocked', async () => { + const f = fixture(); const legacy = { ...operation, workerPid: undefined, workerStartMarker: undefined }; + f.setAuthoritative(legacy); f.ownership.workerGone = true; + await expect(f.restart().recover(legacy)).rejects.toThrow('generation is unavailable'); + expect(f.gate.isBlocked()).toBe(true); + expect(f.report).not.toHaveBeenCalled(); + }); + + it('never finalizes a rejected journal whose native request may still mutate', async () => { + const f = fixture(); const transport = f.request.getMockImplementation()!; + f.request.mockImplementation(async (path, init) => { + if (path.endsWith('/revert/stage')) throw new Error('stage ACK lost'); + return transport(path, init); + }); + expect(await f.rewind.execute(operation)).toMatchObject({ outcome: 'unknown' }); + expect(f.rewind.readIntent()?.pendingRequest).toBe(true); + f.setAuthoritative({ ...operation, phase: 'rejected' }); + await expect(f.rewind.recover({ ...operation, phase: 'rejected' })).rejects.toThrow('cohort'); + expect(f.rewind.readIntent()?.phase).toBe('unknown'); + expect(f.gate.isBlocked()).toBe(true); + }); + + it.each(['committed', 'rejected', 'unknown'] as const)('recovers a matching b6-shaped legacy journal in %s state', async phase => { + const f = fixture(); + if (phase === 'committed') expect(await f.rewind.execute(operation)).toMatchObject({ success: true }); + else { + f.report.mockRejectedValueOnce(new Error('prepare ACK lost')); + expect(await f.rewind.execute(operation)).toMatchObject({ outcome: 'unknown' }); + } + const journal = f.rewind.readIntent()!; + const path = join(dirname(journal.backupPath), 'intent.json'); + const legacyOperation = { ...journal.operation, workerPid: undefined, workerStartMarker: undefined }; + writeFileSync(path, JSON.stringify({ ...journal, operation: legacyOperation })); + f.setAuthoritative({ ...legacyOperation, phase }); f.ownership.workerGone = true; + const replacement = f.restart(); + const result = await replacement.recover({ ...legacyOperation, phase }); + expect(result).toMatchObject(phase === 'committed' ? { success: true } : { outcome: 'rejected' }); + expect(replacement.readIntent()?.phase).toBe('finalized'); + expect(f.gate.isBlocked()).toBe(false); + }); + + it('preserves a finalized legacy journal while admitting a distinct proof-bound rewind', async () => { + const f = fixture(); await f.rewind.execute(operation); + const old = f.rewind.readIntent()!; const backup = readFileSync(old.backupPath, 'utf8'); + const path = join(dirname(old.backupPath), 'intent.json'); + const legacy = { ...old, operation: { ...old.operation, workerPid: undefined, workerStartMarker: undefined } }; + writeFileSync(path, JSON.stringify(legacy)); + f.setRows(rows); + const next = { ...operation, operationId: 'after-legacy-finalized', reservationVersion: 3 }; + f.setAuthoritative(next); + expect(await f.rewind.execute(next)).toMatchObject({ success: true }); + expect(readFileSync(old.backupPath, 'utf8')).toBe(backup); + expect(f.rewind.readIntent()?.operation.operationId).toBe(next.operationId); + }); + + it('blocks a journal whose original owner process differs from the immutable reservation', async () => { + const f = fixture(); f.report.mockRejectedValueOnce(new Error('prepare ACK lost')); + await f.rewind.execute(operation); + const journal = f.rewind.readIntent()!; + const path = join(dirname(journal.backupPath), 'intent.json'); + writeFileSync(path, JSON.stringify({ ...journal, ownerProcess: { pid: operation.workerPid, startMarker: 'wrong-generation' } })); + f.ownership.workerGone = true; f.request.mockClear(); + await expect(f.restart().recover(operation)).rejects.toThrow('Invalid OpenCode rewind intent'); + expect(f.gate.isBlocked()).toBe(true); + expect(f.request).not.toHaveBeenCalled(); + }); + + it('treats a journal with missing pending-request state as corrupt', async () => { + const f = fixture(); f.report.mockRejectedValueOnce(new Error('prepare ACK lost')); + await f.rewind.execute(operation); + const journal = f.rewind.readIntent()!; + const path = join(dirname(journal.backupPath), 'intent.json'); + const incomplete: Record = JSON.parse(readFileSync(path, 'utf8')); + delete incomplete.pendingRequest; writeFileSync(path, JSON.stringify(incomplete)); + f.setAuthoritative({ ...operation, phase: 'rejected' }); + await expect(f.rewind.recover({ ...operation, phase: 'rejected' })).rejects.toThrow('Invalid OpenCode rewind intent'); + expect(f.gate.isBlocked()).toBe(true); + }); + + it('rejects an absent-intent reservation after proving its original worker cannot run', async () => { + const f = fixture(); f.ownership.workerGone = true; + expect(await f.restart().recover(operation)).toMatchObject({ success: false, outcome: 'rejected' }); + expect(f.report).toHaveBeenCalledOnce(); + expect(f.gate.isBlocked()).toBe(false); + expect(f.request).not.toHaveBeenCalled(); + }); + + it.each(['phase', 'identity'] as const)('keeps an absent-intent reservation blocked on mismatched %s acknowledgement', async mismatch => { + const f = fixture(); + f.report.mockResolvedValueOnce(mismatch === 'phase' ? { ...operation, phase: 'prepared' } + : { ...operation, operationId: 'other', phase: 'rejected' }); + await expect(f.rewind.recover(operation)).rejects.toThrow(); + expect(f.gate.isBlocked()).toBe(true); + expect(f.request).not.toHaveBeenCalled(); + }); + + it('finalizes the original rejected journal after acknowledgement loss and executes the next rewind', async () => { + const f = fixture(); + const actualReport = f.report.getMockImplementation()!; + let firstPrepare = true; let firstRejection = true; + f.report.mockImplementation(async report => { + if (report.phase === 'prepared' && firstPrepare) { firstPrepare = false; throw new Error('prepare response lost'); } + if (report.phase === 'rejected' && firstRejection) { + firstRejection = false; + f.setAuthoritative({ ...operation, phase: 'rejected' }); + throw new Error('rejection response lost'); + } + return actualReport(report); + }); + expect(await f.rewind.execute(operation)).toMatchObject({ outcome: 'unknown' }); + expect(await f.rewind.recover({ ...operation, phase: 'unknown' })).toMatchObject({ outcome: 'unknown' }); + // The Hub retains its rejected tombstone when the old unknown report arrives. + f.setAuthoritative({ ...operation, phase: 'rejected' }); + const before = f.rewind.readIntent()!; + const backup = readFileSync(before.backupPath, 'utf8'); + f.request.mockClear(); f.ownership.workerGone = true; + const restarted = f.restart({ workerId: 'worker' }); + expect(await restarted.recover({ ...operation, phase: 'rejected' })).toMatchObject({ outcome: 'rejected' }); + expect(restarted.readIntent()?.phase).toBe('finalized'); + expect(readFileSync(before.backupPath, 'utf8')).toBe(backup); + expect(f.request).not.toHaveBeenCalled(); + const next = { ...operation, operationId: 'next', reservationVersion: 3 }; + f.setAuthoritative(next); + expect(await restarted.execute(next)).toMatchObject({ success: true }); + expect(restarted.readIntent()?.operation.operationId).toBe('next'); + }); + + it('retains original Hub history, backup and peer rows on external input conflict', async () => { + const f = fixture(); + const transport = f.request.getMockImplementation()!; + f.request.mockImplementation(async (path, init) => { + const response = await transport(path, init); + if (path.endsWith('/revert/commit')) f.setRows([...rows.slice(0, 2), { id: 'peer', type: 'user', text: 'peer input' }]); + return response; + }); + const result = await f.rewind.execute(operation); + expect(result).toMatchObject({ success: false, outcome: 'unknown' }); + expect(f.reports.at(-1)?.phase).toBe('unknown'); + expect(f.gate.isBlocked()).toBe(true); + expect(f.request.mock.calls.some(([p, init]) => init?.method === 'DELETE' || p.endsWith('/restore'))).toBe(false); + expect(f.rewind.readIntent()?.backupPath).toBeTruthy(); + }); + + it('accepts a peer-consumed desired prefix only when its own stage request has settled', async () => { + const f = fixture(); const transport = f.request.getMockImplementation()!; + let consumed = false; + f.request.mockImplementation(async (path, init) => { + if (consumed && path.endsWith('/session/native')) return Response.json({ data: { id: 'native' } }); + const response = await transport(path, init); + if (path.endsWith('/revert/stage')) { consumed = true; f.setRows(rows.slice(0, 2)); } + return response; + }); + expect(await f.rewind.execute(operation)).toMatchObject({ success: true }); + expect(f.request.mock.calls.some(([path]) => path.endsWith('/revert/commit'))).toBe(false); + expect(f.gate.isBlocked()).toBe(false); + }); + + it('does not settle an exact prefix while a late generic mutation cohort remains unresolved', async () => { + const f = fixture(); + const transport = f.request.getMockImplementation()!; + f.request.mockImplementation(async (path, init) => { + if (path.endsWith('/revert/commit')) { f.setRows(rows.slice(0, 2)); throw new Error('ACK lost, request cohort unowned'); } + return transport(path, init); + }); + expect(await f.rewind.execute(operation)).toMatchObject({ success: false, outcome: 'unknown' }); + expect(await f.rewind.recover(operation)).toMatchObject({ success: false, outcome: 'unknown' }); + expect(f.request.mock.calls.filter(([p]) => p.endsWith('/revert/commit'))).toHaveLength(1); + expect(f.gate.isBlocked()).toBe(true); + }); + + it('retries an applied report after Hub ACK loss without issuing another native mutation', async () => { + const f = fixture(); const report = f.report.getMockImplementation()!; + f.report.mockImplementationOnce(report).mockImplementationOnce(async () => { throw new Error('Hub ACK lost'); }); + expect(await f.rewind.execute(operation)).toMatchObject({ success: false, outcome: 'unknown' }); + expect(await f.rewind.recover(operation)).toMatchObject({ success: true }); + expect(f.request.mock.calls.filter(([p]) => p.endsWith('/revert/commit'))).toHaveLength(1); + expect(f.gate.isBlocked()).toBe(false); + }); + + it('rejects a prepared-only interruption without clearing or mutating native history', async () => { + const f = fixture(); + f.report.mockRejectedValueOnce(new Error('prepared ACK lost')); + expect(await f.rewind.execute(operation)).toMatchObject({ success: false, outcome: 'unknown' }); + expect(await f.rewind.recover({ ...operation, phase: 'unknown' })).toMatchObject({ success: false, outcome: 'rejected' }); + expect(f.request.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false); + expect(f.gate.isBlocked()).toBe(false); + }); + + it.each(['stage', 'commit'])('recovers %s ACK loss only after both previous worker and native cohort are proven unable to write', async (phase) => { + const f = fixture(); const transport = f.request.getMockImplementation()!; + let fault = true; + f.request.mockImplementation(async (path, init) => { + const response = await transport(path, init); + if (fault && path.endsWith(`/revert/${phase}`)) { fault = false; throw new Error('native ACK lost'); } + return response; + }); + expect(await f.rewind.execute(operation)).toMatchObject({ success: false, outcome: 'unknown' }); + const restarted = f.restart(); + expect(await restarted.recover({ ...operation, phase: 'unknown' })).toMatchObject({ outcome: 'unknown' }); + f.ownership.nativeGone = true; + expect(await restarted.recover({ ...operation, phase: 'unknown' })).toMatchObject({ outcome: 'unknown' }); + f.ownership.nativeGone = false; + f.ownership.workerGone = true; + expect(await restarted.recover({ ...operation, phase: 'unknown' })).toMatchObject({ outcome: 'unknown' }); + f.ownership.nativeGone = true; + expect(await restarted.recover({ ...operation, phase: 'unknown' })).toMatchObject({ success: true }); + expect(f.request.mock.calls.filter(([path]) => path.endsWith('/revert/stage'))).toHaveLength(1); + expect(f.request.mock.calls.filter(([path]) => path.endsWith('/revert/commit'))).toHaveLength(1); + expect(f.gate.isBlocked()).toBe(false); + }); + + it('committed-operation restart does not read or rewind a later native turn', async () => { + const f = fixture(); await f.rewind.execute(operation); + f.setRows([...rows.slice(0, 2), { id: 'later', type: 'user', text: 'new turn' }]); + f.request.mockClear(); + f.ownership.workerGone = true; + expect(await f.restart().recover({ ...operation, phase: 'committed' })).toMatchObject({ success: true }); + expect(f.request).not.toHaveBeenCalled(); + expect(f.gate.isBlocked()).toBe(false); + }); + + it('binds a recovery-issued commit cohort to the replacement native process, not the dead original server', async () => { + const f = fixture(); const transport = f.request.getMockImplementation()!; + f.request.mockImplementation(async (path, init) => { + const response = await transport(path, init); + if (path.endsWith('/revert/stage') || path.endsWith('/revert/commit')) throw new Error('native ACK lost'); + return response; + }); + expect(await f.rewind.execute(operation)).toMatchObject({ outcome: 'unknown' }); + f.ownership.workerGone = true; + const replacement = f.restart({ nativeProcess: { pid: 202, startMarker: 'replacement-native-generation' }, + requestsFromPreviousWorkerCannotRun: () => f.rewind.readIntent()?.nativeProcess?.pid === 101 }); + expect(await replacement.recover(operation)).toMatchObject({ outcome: 'unknown' }); + expect(await replacement.recover(operation)).toMatchObject({ outcome: 'unknown' }); + expect(f.request.mock.calls.filter(([path]) => path.endsWith('/revert/commit'))).toHaveLength(1); + expect(f.rewind.readIntent()?.nativeProcess?.pid).toBe(202); + expect(f.gate.isBlocked()).toBe(true); + }); + + it('does not consume a committed operation while the previous worker may still dispatch', async () => { + const f = fixture(); await f.rewind.execute(operation); + f.consumeCommitted.mockClear(); f.request.mockClear(); + expect(await f.restart().recover({ ...operation, phase: 'committed' })).toMatchObject({ outcome: 'unknown' }); + expect(f.consumeCommitted).not.toHaveBeenCalled(); + expect(f.request).not.toHaveBeenCalled(); + expect(f.gate.isBlocked()).toBe(true); + }); + + it.each(['execute', 'recover'] as const)('keeps newer reservation gated after committed consumption (%s)', async path => { + const f = fixture(); + if (path === 'recover') { + f.consumeCommitted.mockRejectedValueOnce(new Error('first consumption interrupted')); + expect(await f.rewind.execute(operation)).toMatchObject({ outcome: 'unknown' }); + f.setAuthoritative({ ...operation, phase: 'committed' }); + } + let release!: () => void; + f.consumeCommitted.mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + const pending = path === 'execute' ? f.rewind.execute(operation) : f.rewind.recover({ ...operation, phase: 'committed' }); + await vi.waitFor(() => expect(release).toBeTypeOf('function')); + const newer = { ...operation, operationId: 'pending-after-consumption', reservationVersion: 3 }; + f.setAuthoritative(newer); release(); + await expect(pending).rejects.toMatchObject({ operationId: newer.operationId }); + expect(f.gate.isBlocked()).toBe(true); + expect(() => f.gate.enterRuntime()).toThrow('pending reconciliation'); + expect(f.rewind.readIntent()).toMatchObject({ operation: { operationId: operation.operationId }, phase: 'finalized' }); + expect(await f.rewind.recover(newer)).toMatchObject({ outcome: 'rejected' }); + expect(f.gate.isBlocked()).toBe(false); + }); + + it('latches a different reservation after applied-report acknowledgement loss without rewriting the journal', async () => { + const f = fixture(); const report = f.report.getMockImplementation()!; + const newer = { ...operation, operationId: 'after-applied-ack-loss', reservationVersion: 3 }; + f.report.mockImplementation(async value => { + if (value.phase === 'applied') { f.setAuthoritative(newer); throw new Error('applied ACK lost'); } + return report(value); + }); + await expect(f.rewind.execute(operation)).rejects.toMatchObject({ operationId: newer.operationId }); + expect(f.gate.isBlocked()).toBe(true); + expect(f.rewind.readIntent()).toMatchObject({ operation: { operationId: operation.operationId }, phase: 'applied' }); + expect(f.reports.map(item => item.phase)).toEqual(['prepared']); + }); + + it.each(['consumption', 'applied-ack'] as const)('latches O2 appearing during a failed post-commit unknown report (%s)', async failure => { + const f = fixture(); const actualReport = f.report.getMockImplementation()!; + let rejectUnknown!: (error: Error) => void; + f.report.mockImplementation(async value => { + if (value.phase === 'unknown') return await new Promise((_resolve, reject) => { rejectUnknown = reject; }); + const result = await actualReport(value); + if (failure === 'applied-ack' && value.phase === 'applied') throw new Error('applied ACK lost'); + return result; + }); + if (failure === 'consumption') f.consumeCommitted.mockRejectedValueOnce(new Error('consumption failed')); + const pending = f.rewind.execute(operation); + await vi.waitFor(() => expect(rejectUnknown).toBeTypeOf('function')); + const newer = { ...operation, operationId: `during-unknown-${failure}`, reservationVersion: 3 }; + const journal = f.rewind.readIntent()!; const path = join(dirname(journal.backupPath), 'intent.json'); + const newerBytes = JSON.stringify({ ...journal, operation: newer }); + writeFileSync(path, newerBytes); f.setAuthoritative(newer); rejectUnknown(new Error('operation mismatch')); + await expect(pending).rejects.toMatchObject({ operationId: newer.operationId }); + expect(readFileSync(path, 'utf8')).toBe(newerBytes); + expect(f.gate.isBlocked()).toBe(true); + }); + + it.each([false, true])('does not retry a failed post-commit unknown report when authority is unchanged or unavailable (offline=%s)', async offline => { + const f = fixture(); const actualReport = f.report.getMockImplementation()!; let failRefresh = false; let attempts = 0; + f.consumeCommitted.mockRejectedValueOnce(new Error('consumption failed')); + f.report.mockImplementation(async value => { + if (value.phase === 'unknown') { attempts++; failRefresh = offline; throw new Error('report failed'); } + return actualReport(value); + }); + const controller = f.restart({ workerId: 'worker', getAuthoritativeOperation: async () => { + if (failRefresh) throw new Error('metadata offline'); return f.getAuthoritative(); + } }); + expect(await controller.execute(operation)).toMatchObject({ outcome: 'unknown' }); + expect(attempts).toBe(1); + expect(f.gate.isBlocked()).toBe(true); + }); + + it.each(['consumption', 'applied-ack'] as const)('latches O2 appearing during an accepted post-commit unknown report (%s)', async failure => { + const f = fixture(); const actualReport = f.report.getMockImplementation()!; + let acceptUnknown!: () => void; + f.report.mockImplementation(async value => { + if (value.phase === 'unknown') return await new Promise(resolve => { acceptUnknown = () => resolve({ ...operation, phase: 'committed' }); }); + const result = await actualReport(value); + if (failure === 'applied-ack' && value.phase === 'applied') throw new Error('applied ACK lost'); + return result; + }); + if (failure === 'consumption') f.consumeCommitted.mockRejectedValueOnce(new Error('consumption failed')); + const pending = f.rewind.execute(operation); + await vi.waitFor(() => expect(acceptUnknown).toBeTypeOf('function')); + const newer = { ...operation, operationId: `during-accepted-unknown-${failure}`, reservationVersion: 3 }; + const journal = f.rewind.readIntent()!; const path = join(dirname(journal.backupPath), 'intent.json'); + const newerBytes = JSON.stringify({ ...journal, operation: newer }); + writeFileSync(path, newerBytes); f.setAuthoritative(newer); acceptUnknown(); + await expect(pending).rejects.toMatchObject({ operationId: newer.operationId }); + expect(readFileSync(path, 'utf8')).toBe(newerBytes); + expect(f.gate.isBlocked()).toBe(true); + }); + + it.each([false, true])('does not retry an accepted post-commit unknown report when authority is unchanged or unavailable (offline=%s)', async offline => { + const f = fixture(); const actualReport = f.report.getMockImplementation()!; let failRefresh = false; let attempts = 0; + f.consumeCommitted.mockRejectedValueOnce(new Error('consumption failed')); + f.report.mockImplementation(async value => { + if (value.phase === 'unknown') { attempts++; failRefresh = offline; return { ...operation, phase: 'committed' }; } + return actualReport(value); + }); + const controller = f.restart({ workerId: 'worker', getAuthoritativeOperation: async () => { + if (failRefresh) throw new Error('metadata offline'); return f.getAuthoritative(); + } }); + expect(await controller.execute(operation)).toMatchObject({ outcome: 'unknown' }); + expect(attempts).toBe(1); + expect(f.gate.isBlocked()).toBe(true); + }); + + it('guards an unconfirmed applied-report response against a newer reservation', async () => { + const f = fixture(); const report = f.report.getMockImplementation()!; + const newer = { ...operation, operationId: 'after-unconfirmed-applied', reservationVersion: 3 }; + f.report.mockImplementation(async value => { + if (value.phase === 'applied') { f.setAuthoritative(newer); return { ...operation, phase: 'unknown' }; } + return report(value); + }); + await expect(f.rewind.execute(operation)).rejects.toMatchObject({ operationId: newer.operationId }); + expect(f.rewind.readIntent()).toMatchObject({ operation: { operationId: operation.operationId }, phase: 'applied' }); + expect(f.gate.isBlocked()).toBe(true); + expect(f.reports.map(item => item.phase)).toEqual(['prepared']); + }); + + it('retains applied intent if metadata is unavailable after applied-report acknowledgement loss', async () => { + const f = fixture(); let offline = false; + const report = f.report.getMockImplementation()!; + f.report.mockImplementation(async value => { + if (value.phase === 'applied') { offline = true; throw new Error('applied ACK lost'); } + return report(value); + }); + const controller = f.restart({ workerId: 'worker', getAuthoritativeOperation: async () => { + if (offline) throw new Error('offline'); return f.getAuthoritative(); + } }); + await expect(controller.execute(operation)).rejects.toThrow(); + expect(controller.readIntent()?.phase).toBe('applied'); + expect(f.gate.isBlocked()).toBe(true); + expect(f.reports.map(item => item.phase)).toEqual(['prepared']); + }); + + it('does not overwrite a newer journal after applied-report acknowledgement loss', async () => { + const f = fixture(); const report = f.report.getMockImplementation()!; + let rejectApplied!: (error: Error) => void; + f.report.mockImplementation(async value => { + if (value.phase === 'applied') return await new Promise((_resolve, reject) => { rejectApplied = reject; }); + return report(value); + }); + const pending = f.rewind.execute(operation); + await vi.waitFor(() => expect(rejectApplied).toBeTypeOf('function')); + const old = f.rewind.readIntent()!; const newer = { ...operation, operationId: 'newer-after-applied', reservationVersion: 3 }; + const path = join(dirname(old.backupPath), 'intent.json'); const newerBytes = JSON.stringify({ ...old, operation: newer }); + writeFileSync(path, newerBytes); f.setAuthoritative(newer); rejectApplied(new Error('applied ACK lost')); + await expect(pending).rejects.toMatchObject({ operationId: newer.operationId }); + expect(readFileSync(path, 'utf8')).toBe(newerBytes); + expect(f.gate.isBlocked()).toBe(true); + }); + + it('keeps the gate blocked when committed consumption rejects with a falsy value', async () => { + const f = fixture(); f.consumeCommitted.mockImplementationOnce(async () => { throw undefined; }); + expect(await f.rewind.execute(operation)).toMatchObject({ success: false, outcome: 'unknown' }); + expect(f.gate.isBlocked()).toBe(true); + expect(f.rewind.readIntent()?.phase).toBe('unknown'); + }); + + it('preserves the committed journal and gate if authority refresh fails after consumption', async () => { + const f = fixture(); let failRefresh = false; let release!: () => void; + const controller = f.restart({ workerId: 'worker', getAuthoritativeOperation: async () => { + if (failRefresh) throw new Error('offline after consumption'); return f.getAuthoritative(); + } }); + f.consumeCommitted.mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + const pending = controller.execute(operation); + await vi.waitFor(() => expect(release).toBeTypeOf('function')); + const journal = controller.readIntent()!; const path = join(dirname(journal.backupPath), 'intent.json'); + const before = readFileSync(path, 'utf8'); failRefresh = true; release(); + await expect(pending).rejects.toThrow(); + expect(readFileSync(path, 'utf8')).toBe(before); + expect(f.gate.isBlocked()).toBe(true); + expect(f.reports.map(item => item.phase)).toEqual(['prepared', 'applied']); + }); + + it('preserves the old journal when consumption fails after a newer reservation', async () => { + const f = fixture(); let rejectConsumption!: (error: Error) => void; + f.consumeCommitted.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectConsumption = reject; })); + const pending = f.rewind.execute(operation); + await vi.waitFor(() => expect(rejectConsumption).toBeTypeOf('function')); + const journal = f.rewind.readIntent()!; const path = join(dirname(journal.backupPath), 'intent.json'); + const before = readFileSync(path, 'utf8'); + const newer = { ...operation, operationId: 'newer-after-failed-consumption', reservationVersion: 3 }; + f.setAuthoritative(newer); rejectConsumption(new Error('load failed')); + await expect(pending).rejects.toMatchObject({ operationId: newer.operationId }); + expect(readFileSync(path, 'utf8')).toBe(before); + expect(f.gate.isBlocked()).toBe(true); + }); + + it('does not overwrite a newer journal after committed consumption', async () => { + const f = fixture(); let release!: () => void; + f.consumeCommitted.mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + const pending = f.rewind.execute(operation); + await vi.waitFor(() => expect(release).toBeTypeOf('function')); + const old = f.rewind.readIntent()!; + const newer = { ...operation, operationId: 'newer-journal', reservationVersion: 3 }; + const path = join(dirname(old.backupPath), 'intent.json'); + const newerBytes = JSON.stringify({ ...old, operation: newer }); + writeFileSync(path, newerBytes); f.setAuthoritative(newer); release(); + await expect(pending).rejects.toThrow(); + expect(readFileSync(path, 'utf8')).toBe(newerBytes); + expect(f.gate.isBlocked()).toBe(true); + }); + + it('does not release input before postcommit native consumption has completed', async () => { + const f = fixture(); let release!: () => void; + f.consumeCommitted.mockImplementation(() => new Promise(resolve => { release = resolve; })); + const pending = f.rewind.execute(operation); + await vi.waitFor(() => expect(release).toBeTypeOf('function')); + expect(f.gate.isBlocked()).toBe(true); + release(); await pending; + expect(f.gate.isBlocked()).toBe(false); + }); + + it('dequeue admission is synchronous before ACK, including an internal item without a localId', async () => { + const f = fixture(); const queue = new MessageQueue2(() => 'mode'); + const session = new OpencodeSession({ api: {} as never, + client: { keepAlive: vi.fn(), emitMessagesConsumed: vi.fn() } as never, + path: '/fixture', logPath: '/fixture/log', sessionId: 'native', messageQueue: queue, + onModeChange: () => {}, startedBy: 'runner', startingMode: 'remote', runtimeGate: f.gate }); + cleanups.push(() => session.stopKeepAlive()); + queue.push('internal message', { permissionMode: 'default' }); + const batch = queue.waitForMessagesAndGetAsString(); + await expect(f.rewind.execute(operation)).rejects.toThrow('busy'); + expect((await batch)?.message).toBe('internal message'); + expect(f.request).not.toHaveBeenCalled(); session.takeDequeuedRuntimeRelease()!(); + }); + + it('blocks corrupted projected backup recovery rather than advertising recoverability', async () => { + const f = fixture(); await f.rewind.execute(operation); + writeFileSync(f.rewind.readIntent()!.backupPath, '{}'); + await expect(f.restart().recover({ ...operation, phase: 'committed' })).rejects.toThrow(); + expect(f.gate.isBlocked()).toBe(true); + }); +}); diff --git a/cli/src/opencode/rewind.ts b/cli/src/opencode/rewind.ts new file mode 100644 index 00000000..6cfe2da1 --- /dev/null +++ b/cli/src/opencode/rewind.ts @@ -0,0 +1,574 @@ +import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { hashObject } from '@/utils/deterministicJson'; +import { getProcessStartMarker } from '@/utils/process'; +import type { OpenCodeRewindOperation } from '@hapi/protocol/schemas'; +import type { OpenCodeRewindReport } from '@hapi/protocol/apiTypes'; + +type Checkpoint = NonNullable; +type Row = Record & { id: string; type: string }; +type Intent = { + operation: OpenCodeRewindOperation; phase: 'prepared' | 'stage-issued' | 'staged' | 'commit-issued' | 'applied' | 'unknown' | 'finalized'; + backupPath: string; sourceHash: string; prefixHash: string; source: Row[]; prefix: Row[]; + checkpoint: Checkpoint; indexes: Record; pendingRequest: boolean; + nativeProcess?: { pid: number; startMarker: string }; + ownerProcess?: { pid: number; startMarker: string }; + ownerWorkerId: string; + lastError?: string; +}; + +export function readOpenCodeRewindIntent(directory: string, hapiSessionId: string): Intent | undefined { + if (!existsSync(join(directory, hashObject(hapiSessionId), 'intent.json'))) return; + // A malformed journal is a blocking error, never an absent operation. + const intent = JSON.parse(readFileSync(join(directory, hashObject(hapiSessionId), 'intent.json'), 'utf8')) as Intent; + if (!intent.operation || !Array.isArray(intent.source) || !Array.isArray(intent.prefix) + || !['prepared', 'stage-issued', 'staged', 'commit-issued', 'applied', 'unknown', 'finalized'].includes(intent.phase) + || typeof intent.pendingRequest !== 'boolean' || typeof intent.ownerWorkerId !== 'string' || !intent.ownerWorkerId + || typeof intent.backupPath !== 'string' + || (intent.phase !== 'finalized' && intent.operation.workerPid && intent.operation.workerStartMarker + && intent.ownerWorkerId === intent.operation.workerId + && (intent.ownerProcess?.pid !== intent.operation.workerPid + || intent.ownerProcess?.startMarker !== intent.operation.workerStartMarker)) + || hashObject(intent.source) !== intent.sourceHash || hashObject(intent.prefix) !== intent.prefixHash) { + throw new Error('Invalid OpenCode rewind intent'); + } + const backup = JSON.parse(readFileSync(intent.backupPath, 'utf8')); + if (backup.info?.id !== intent.operation.nativeSessionId || hashObject(backup.messages) !== intent.sourceHash) { + throw new Error('OpenCode projected backup is missing or corrupt'); + } + return intent; +} + +export class OpenCodeRuntimeBlockedError extends Error { + constructor() { super('OpenCode rewind is pending reconciliation'); } +} + +/** Shared by OpenCode input/config preparation, dequeue, handoff and history RPCs. */ +export class OpenCodeRuntimeGate { + /** One session/wrapper owner, shared by sequential local/remote launchers. */ + readonly workerId = randomUUID(); + private active = 0; + private cancellations = 0; + private blocked = false; + private readonly entryFences = new Set(); + private initialEntryFence: symbol | undefined; + private entryHandoffListener: (() => void) | undefined; + private readonly idleWaiters: Array<() => void> = []; + private readonly cancellationWaiters: Array<() => void> = []; + private rewindOwner: symbol | undefined; + private reconciledOperationId: string | undefined; + private readonly waiters: Array<() => void> = []; + constructor(initialEntryFence = false) { + if (initialEntryFence) this.initialEntryFence = this.acquireEntryFence(); + } + enterRuntime(): () => void { + if (this.isBlocked()) throw new OpenCodeRuntimeBlockedError(); + return this.enterActivity(false); + } + /** An admitted Stop may cross an entry fence, but never a rewind blocker. */ + enterCancellation(): () => void { + if (this.blocked) throw new OpenCodeRuntimeBlockedError(); + return this.enterActivity(true); + } + private enterActivity(cancellation: boolean): () => void { + this.active++; + if (cancellation) this.cancellations++; + let released = false; + return () => { + if (!released) { + released = true; this.active--; + if (cancellation) { + this.cancellations--; + if (!this.cancellations) for (const resolve of this.cancellationWaiters.splice(0)) resolve(); + } + if (!this.active) for (const resolve of this.idleWaiters.splice(0)) resolve(); + } + }; + } + enterLocalRuntime(operation: OpenCodeRewindOperation | undefined): () => void { + if (operation && (!['committed', 'rejected'].includes(operation.phase) + || this.reconciledOperationId !== operation.operationId)) { + this.block(); + throw new Error('OpenCode rewind requires reconciliation before local launch; resume remotely first'); + } + return this.enterRuntime(); + } + reserve(): void { + if (this.active || this.isBlocked()) throw new Error('OpenCode runtime is busy'); + this.blocked = true; + } + block(): void { this.blocked = true; } + release(reconciledOperationId?: string): void { + if (reconciledOperationId) this.reconciledOperationId = reconciledOperationId; + this.blocked = false; this.notifyOpen(); + } + private notifyOpen(): void { if (!this.isBlocked()) for (const resolve of this.waiters.splice(0)) resolve(); } + waitUntilOpen(signal?: AbortSignal): Promise { + if (!this.isBlocked() || signal?.aborted) return Promise.resolve(); + return new Promise(resolve => { + const done = () => { + signal?.removeEventListener('abort', done); + const index = this.waiters.indexOf(done); + if (index >= 0) this.waiters.splice(index, 1); + resolve(); + }; + this.waiters.push(done); + signal?.addEventListener('abort', done, { once: true }); + }); + } + isBlocked(): boolean { return this.blocked || this.entryFences.size > 0; } + isRewindBlocked(): boolean { return this.blocked; } + isRuntimeActive(): boolean { return this.active > 0; } + hasOrdinaryRuntimeActivity(): boolean { return this.active > this.cancellations; } + hasCancellationActivity(): boolean { return this.cancellations > 0; } + waitUntilIdle(signal?: AbortSignal): Promise { + if (!this.active || signal?.aborted) return Promise.resolve(); + return new Promise(resolve => { + const done = () => { + signal?.removeEventListener('abort', done); + const index = this.idleWaiters.indexOf(done); + if (index >= 0) this.idleWaiters.splice(index, 1); + resolve(); + }; + this.idleWaiters.push(done); + signal?.addEventListener('abort', done, { once: true }); + }); + } + waitUntilCancellationsIdle(signal?: AbortSignal): Promise { + if (!this.cancellations || signal?.aborted) return Promise.resolve(); + return new Promise(resolve => { + const done = () => { + signal?.removeEventListener('abort', done); + const index = this.cancellationWaiters.indexOf(done); + if (index >= 0) this.cancellationWaiters.splice(index, 1); + resolve(); + }; + this.cancellationWaiters.push(done); + signal?.addEventListener('abort', done, { once: true }); + }); + } + acquireEntryFence(): symbol { const token = Symbol('opencode-entry'); this.entryFences.add(token); return token; } + releaseEntryFence(token: symbol): void { this.entryFences.delete(token); this.notifyOpen(); } + takeInitialEntryFence(): symbol | undefined { const token = this.initialEntryFence; this.initialEntryFence = undefined; return token; } + adoptInitialEntryFence(owner?: symbol): symbol | undefined { + const token = this.takeInitialEntryFence(); + if (token && owner && this.entryFences.has(owner)) { + this.entryFences.delete(token); + return owner; + } + return token ?? owner; + } + onEntryHandoff(listener: () => void): () => void { + this.entryHandoffListener = listener; + return () => { if (this.entryHandoffListener === listener) this.entryHandoffListener = undefined; }; + } + handoffEntryFence(token: symbol): void { + if (!this.entryFences.has(token)) return; + if (this.initialEntryFence && this.initialEntryFence !== token) this.entryFences.delete(token); + else this.initialEntryFence = token; + this.entryHandoffListener?.(); + } + hasReconciled(operationId: string): boolean { return this.reconciledOperationId === operationId; } + acquireRewind(): symbol { + if (this.rewindOwner) throw new Error('OpenCode rewind is busy'); + return this.rewindOwner = Symbol('rewind'); + } + releaseRewind(owner: symbol): void { + if (this.rewindOwner === owner) this.rewindOwner = undefined; + } +} + +type Options = { + directory: string; hapiSessionId: string; workerId: string; gate: OpenCodeRuntimeGate; + baseUrl: string; nativeSessionId: string; headers: Record; + request?: (url: string, init?: RequestInit) => Promise; + report: (report: OpenCodeRewindReport) => Promise; + getAuthoritativeOperation: () => Promise; + flush: () => Promise; isIdle: () => boolean; + sourceCheckpoint: () => Checkpoint | undefined; sourceIndexes: () => Record; + requestsFromPreviousWorkerCannotRun: () => boolean; + nativeProcess?: { pid: number; startMarker: string }; + consumeCommitted?: () => Promise; + previousWorkerCannotRun?: (owner: { pid: number; startMarker: string }) => boolean; +}; + +function operationIdentity(op: OpenCodeRewindOperation) { + return { operationId: op.operationId, nativeSessionId: op.nativeSessionId, workerId: op.workerId, + workerPid: op.workerPid, workerStartMarker: op.workerStartMarker, requestedLocalId: op.requestedLocalId, + nativeMessageId: op.nativeMessageId, cutoffSeq: op.cutoffSeq, sourceEpoch: op.sourceEpoch, + sourceMaxSeq: op.sourceMaxSeq, reservationVersion: op.reservationVersion, sourceTranscriptHash: op.sourceTranscriptHash }; +} +export function sameOperation(a: OpenCodeRewindOperation, b: OpenCodeRewindOperation): boolean { + return hashObject(operationIdentity(a)) === hashObject(operationIdentity(b)); +} +export class OpenCodeRewindSupersededError extends Error { + constructor(readonly operationId: string) { + super('OpenCode rewind reservation is no longer authoritative'); + } +} +class OpenCodeRewindPostCommitError extends Error { + constructor(error: unknown) { + super('OpenCode committed rewind could not be reconciled', { cause: error }); + } +} +function staleOperation(observed: OpenCodeRewindOperation, requested: OpenCodeRewindOperation): Error { + return observed.operationId !== requested.operationId + ? new OpenCodeRewindSupersededError(observed.operationId) + : new Error('OpenCode rewind reservation is no longer authoritative'); +} + +function protectedWrite(path: string, value: unknown): void { + const temporary = `${path}.tmp`; + const fd = openSync(temporary, 'w', 0o600); + try { writeFileSync(fd, JSON.stringify(value)); fsyncSync(fd); } finally { closeSync(fd); } + renameSync(temporary, path); +} + +export class OpenCodeRewind { + private readonly path: string; + private readonly directory: string; + constructor(private readonly options: Options) { + this.directory = join(options.directory, hashObject(options.hapiSessionId)); + mkdirSync(this.directory, { recursive: true, mode: 0o700 }); + this.path = join(this.directory, 'intent.json'); + } + readIntent(): Intent | undefined { + return readOpenCodeRewindIntent(this.options.directory, this.options.hapiSessionId); + } + private save(intent: Intent): void { + protectedWrite(this.path, intent); + // Windows FlushFileBuffers requires GENERIC_WRITE, so fsyncing the + // read-only directory handle fails even though the rename persisted. + if (process.platform === 'win32') return; + const fd = openSync(this.directory, 'r'); + try { fsyncSync(fd); } finally { closeSync(fd); } + } + private claimRecovery(intent: Intent): void { + const marker = getProcessStartMarker(process.pid); + intent.ownerWorkerId = this.options.workerId; + intent.ownerProcess = marker ? { pid: process.pid, startMarker: marker } : undefined; + this.save(intent); + } + private async request(path: string, body?: unknown): Promise { + const r = await (this.options.request ?? fetch)(`${this.options.baseUrl}${path}`, { + method: body === undefined ? 'GET' : 'POST', headers: { ...this.options.headers, 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15_000) + }); + if (!r.ok) throw new Error(`OpenCode rewind request failed (${r.status})`); + if (r.status === 204) return undefined; + return await r.json(); + } + private async observe(): Promise<{ rows: Row[]; staged?: string; info: Record; idle: boolean }> { + const session = `/api/session/${encodeURIComponent(this.options.nativeSessionId)}`; + const rows: Row[] = []; const seen = new Set(); let cursor: string | undefined; + do { + const q = new URLSearchParams(cursor ? { limit: '200', cursor } : { limit: '200', order: 'asc' }); + const value = await this.request(`${session}/message?${q}`) as { data?: Row[]; cursor?: { next?: string } }; + if (!Array.isArray(value.data) || value.data.some(r => !r || typeof r.id !== 'string' || typeof r.type !== 'string')) throw new Error('Invalid native projection'); + rows.push(...value.data); cursor = value.cursor?.next; + if (cursor && seen.has(cursor)) throw new Error('Repeated native cursor'); + if (cursor) seen.add(cursor); + } while (cursor); + if (new Set(rows.map(r => r.id)).size !== rows.length) throw new Error('Duplicate native identity'); + const info = (await this.request(session) as { data: Record }).data; + const active = (await this.request('/api/session/active') as { data: Record }).data; + const inbox = (await this.request(`${session}/inbox`) as { data: unknown[] }).data; + if (!info || info.id !== this.options.nativeSessionId || !active || !Array.isArray(inbox)) throw new Error('Incomplete native readback'); + return { rows, info, staged: (info.revert as { messageID?: string } | undefined)?.messageID, + idle: !active[this.options.nativeSessionId] && inbox.length === 0 }; + } + private samePrefix(expected: Row[], actual: Row[]): boolean { + return actual.length >= expected.length && hashObject(actual.slice(0, expected.length)) === hashObject(expected) + && actual.slice(expected.length).every(row => row.type === 'idle' && !expected.some(old => old.id === row.id)); + } + private async unknown(intent: Intent, error: unknown, revalidateAfterReport = false): Promise<{ success: false; outcome: 'unknown'; error: string }> { + this.options.gate.block(); intent.phase = 'unknown'; intent.lastError = error instanceof Error ? error.message : String(error); this.save(intent); + try { await this.options.report({ operation: intent.operation, phase: 'unknown' }); } catch { /* remain blocked */ } + if (revalidateAfterReport) { + let current: OpenCodeRewindOperation | undefined; + try { current = await this.options.getAuthoritativeOperation(); } catch { /* remain blocked */ } + if (current && current.operationId !== intent.operation.operationId) throw staleOperation(current, intent.operation); + } + return { success: false, outcome: 'unknown', error: error instanceof Error ? error.message : String(error) }; + } + private async consumeAndFinalize(intent: Intent) { + let consumptionError: unknown; + let consumptionFailed = false; + try { await this.options.consumeCommitted?.(); } catch (error) { consumptionFailed = true; consumptionError = error; } + try { + const current = await this.options.getAuthoritativeOperation(); + if (!current) throw new Error('OpenCode committed rewind metadata is unavailable'); + const latest = this.readIntent(); + if (!latest || hashObject(latest) !== hashObject(intent)) { + if (!sameOperation(current, intent.operation)) throw staleOperation(current, intent.operation); + throw new Error('OpenCode committed rewind journal ownership changed'); + } + if (!sameOperation(current, intent.operation)) { + if (!consumptionFailed) { latest.phase = 'finalized'; this.save(latest); } + throw staleOperation(current, intent.operation); + } + if (current.phase !== 'committed') throw new Error('OpenCode committed rewind is no longer authoritative'); + if (consumptionFailed) return await this.unknown(latest, consumptionError, true); + latest.phase = 'finalized'; this.save(latest); this.options.gate.release(latest.operation.operationId); + return { success: true as const, truncateFromLocalId: latest.operation.requestedLocalId }; + } catch (error) { + if (error instanceof OpenCodeRewindSupersededError) throw error; + throw new OpenCodeRewindPostCommitError(error); + } + } + private async handleAppliedReportFailure(intent: Intent, error: unknown) { + try { + const current = await this.options.getAuthoritativeOperation(); + if (!current) throw new Error('OpenCode rewind metadata is unavailable after the applied report'); + if (!sameOperation(current, intent.operation)) throw staleOperation(current, intent.operation); + const latest = this.readIntent(); + if (!latest || hashObject(latest) !== hashObject(intent)) throw new Error('OpenCode rewind journal ownership changed'); + return await this.unknown(latest, error, true); + } catch (failure) { + if (failure instanceof OpenCodeRewindSupersededError) throw failure; + throw new OpenCodeRewindPostCommitError(failure); + } + } + private async settle(intent: Intent) { + if (intent.pendingRequest && !this.options.requestsFromPreviousWorkerCannotRun()) { + return await this.unknown(intent, new Error('Native request cohort may still mutate later')); + } + const read = await this.observe(); + if (!read.idle || read.staged || !this.samePrefix(intent.prefix, read.rows)) { + return await this.unknown(intent, new Error('Native rewind conflicts with the retained prefix or new input')); + } + intent.pendingRequest = false; intent.phase = 'applied'; this.save(intent); + let committed: OpenCodeRewindOperation; + try { + committed = await this.options.report({ operation: intent.operation, phase: 'applied', + sourceHash: intent.sourceHash, prefixHash: intent.prefixHash, checkpoint: intent.checkpoint, indexes: intent.indexes }); + } catch (error) { return await this.handleAppliedReportFailure(intent, error); } + if (!sameOperation(committed, intent.operation) || committed.phase !== 'committed') { + return await this.handleAppliedReportFailure(intent, new Error('Hub rewind commit is unconfirmed')); + } + return await this.consumeAndFinalize(intent); + } + async execute(operation: OpenCodeRewindOperation) { + // Ownership is acquired synchronously, before flush/read/journal awaits. + const owner = this.options.gate.acquireRewind(); + let intent: Intent | undefined; + let reserved = false; + let stale = false; + let restoreReconciled = false; + let authorityUncertain = false; + try { + this.options.gate.reserve(); reserved = true; + authorityUncertain = true; + const admission = await this.options.getAuthoritativeOperation(); + if (!admission) throw new Error('OpenCode rewind reservation is unavailable'); + authorityUncertain = false; + if (!sameOperation(admission, operation) || admission.phase !== 'reserved' + || operation.nativeSessionId !== this.options.nativeSessionId || operation.workerId !== this.options.workerId + || operation.workerPid !== process.pid || !operation.workerStartMarker + || getProcessStartMarker(process.pid) !== operation.workerStartMarker) { + stale = true; + restoreReconciled = sameOperation(admission, operation) + && (admission.phase === 'committed' || admission.phase === 'rejected') + && this.options.gate.hasReconciled(operation.operationId); + throw staleOperation(admission, operation); + } + if (!this.options.isIdle()) throw new Error('Native rewind worker is not idle'); + const prior = this.readIntent(); + if (prior?.phase !== undefined && prior.phase !== 'finalized') throw new Error('An earlier rewind intent is unresolved'); + // An operation ID owns its original projection permanently, even + // after a newer operation replaces the current journal. + if (prior?.operation.operationId === operation.operationId + || existsSync(join(this.directory, `${hashObject(operation.operationId)}.projection.json`))) { + throw new Error('OpenCode rewind operation is already recorded'); + } + if (!await this.options.flush()) throw new Error('Source metadata/output is not durable'); + authorityUncertain = true; + const afterFlush = await this.options.getAuthoritativeOperation(); + if (!afterFlush) throw new Error('OpenCode rewind reservation is unavailable'); + authorityUncertain = false; + if (!sameOperation(afterFlush, operation) || afterFlush.phase !== 'reserved') { + stale = true; + restoreReconciled = sameOperation(afterFlush, operation) + && (afterFlush.phase === 'committed' || afterFlush.phase === 'rejected') + && this.options.gate.hasReconciled(operation.operationId); + throw staleOperation(afterFlush, operation); + } + const cp = this.options.sourceCheckpoint(); + const read = await this.observe(); + if (!cp || cp.localPublicationPending || cp.localMessageIds === undefined || cp.sessionId !== operation.nativeSessionId + || !read.idle || read.staged || hashObject(cp.messageIds) !== hashObject(read.rows.map(r => r.id))) throw new Error('Native source is not the verified checkpoint'); + const boundary = read.rows.findIndex(r => r.id === operation.nativeMessageId && r.type === 'user'); + const indexes = this.options.sourceIndexes(); + if (boundary < 0 || cp.userMessageIds[indexes[operation.requestedLocalId]!] !== operation.nativeMessageId) throw new Error('Unproven native rewind boundary'); + const prefix = read.rows.slice(0, boundary); + const users = prefix.filter(r => r.type === 'user').map(r => r.id); + const retained: Record = {}; + for (const [local, index] of Object.entries(indexes)) { + const next = users.indexOf(cp.userMessageIds[index]!); + if (next >= 0) retained[local] = next; + } + authorityUncertain = true; + const current = await this.options.getAuthoritativeOperation(); + if (!current) throw new Error('OpenCode rewind reservation is unavailable'); + authorityUncertain = false; + if (!sameOperation(current, operation) || current.phase !== 'reserved') { + stale = true; + restoreReconciled = sameOperation(current, operation) + && (current.phase === 'committed' || current.phase === 'rejected') + && this.options.gate.hasReconciled(operation.operationId); + throw staleOperation(current, operation); + } + const backupPath = join(this.directory, `${hashObject(operation.operationId)}.projection.json`); + protectedWrite(backupPath, { info: read.info, messages: read.rows }); + if (hashObject(JSON.parse(readFileSync(backupPath, 'utf8')).messages) !== hashObject(read.rows)) throw new Error('Backup verification failed'); + intent = { operation, phase: 'prepared', source: read.rows, prefix, sourceHash: hashObject(read.rows), prefixHash: hashObject(prefix), + backupPath, checkpoint: { sessionId: operation.nativeSessionId, messageIds: prefix.map(r => r.id), userMessageIds: users, localMessageIds: [] }, + indexes: retained, pendingRequest: false, nativeProcess: this.options.nativeProcess, ownerWorkerId: this.options.workerId, + ownerProcess: { pid: operation.workerPid!, startMarker: operation.workerStartMarker! } }; + this.save(intent); + const prepared = await this.options.report({ operation, phase: 'prepared', sourceHash: intent.sourceHash, prefixHash: intent.prefixHash }); + if (prepared.phase !== 'prepared' || !sameOperation(prepared, operation)) throw new Error('Hub preparation unconfirmed'); + // Confirm the source after the durable Hub/backup barriers. + const finalSource = await this.observe(); + if (!finalSource.idle || finalSource.staged || hashObject(finalSource.rows) !== intent.sourceHash) return await this.unknown(intent, 'Native source changed during preparation'); + const session = `/api/session/${encodeURIComponent(operation.nativeSessionId)}`; + intent.phase = 'stage-issued'; intent.pendingRequest = true; this.save(intent); + await this.request(`${session}/revert/stage`, { messageID: operation.nativeMessageId, files: false }); + intent.pendingRequest = false; intent.phase = 'staged'; this.save(intent); + const staged = await this.observe(); + if (!staged.idle) return await this.unknown(intent, 'New native input while staging'); + if (!staged.staged && this.samePrefix(intent.prefix, staged.rows)) return await this.settle(intent); + if (staged.staged !== operation.nativeMessageId || hashObject(staged.rows) !== intent.sourceHash) return await this.unknown(intent, 'Native stage ownership changed'); + intent.phase = 'commit-issued'; intent.pendingRequest = true; this.save(intent); + await this.request(`${session}/revert/commit`, {}); + intent.pendingRequest = false; this.save(intent); + return await this.settle(intent); + } catch (error) { + if (!reserved) { + if (!this.options.gate.isBlocked()) { + const current = await this.options.getAuthoritativeOperation(); + if (current && sameOperation(current, operation) && current.phase === 'reserved' + && operation.workerId === this.options.workerId && operation.nativeSessionId === this.options.nativeSessionId + && operation.workerPid === process.pid && operation.workerStartMarker + && getProcessStartMarker(process.pid) === operation.workerStartMarker) { + await this.options.report({ operation, phase: 'rejected' }); + } + } + throw error; + } + if (stale) { if (restoreReconciled) this.options.gate.release(); throw error; } + if (authorityUncertain) throw error; + if (error instanceof OpenCodeRewindSupersededError || error instanceof OpenCodeRewindPostCommitError) throw error; + if (intent) return await this.unknown(intent, error); + // No native write has been issued in this branch. An unresolved + // earlier journal must nevertheless keep the runtime blocked. + const prior = this.readIntent(); + if (prior && prior.phase !== 'finalized') { + if (!sameOperation(prior.operation, operation)) throw error; + return await this.unknown(prior, error); + } + const rejected = await this.options.report({ operation, phase: 'rejected' }); + const current = await this.options.getAuthoritativeOperation(); + if (!sameOperation(rejected, operation) || rejected.phase !== 'rejected' + || !current || !sameOperation(current, operation) || current.phase !== 'rejected') throw new Error('Hub rejection is unconfirmed'); + this.options.gate.release(operation.operationId); + return { success: false as const, outcome: 'rejected' as const, error: String(error) }; + } finally { this.options.gate.releaseRewind(owner); } + } + async recover(operation: OpenCodeRewindOperation) { + const owner = this.options.gate.acquireRewind(); + try { return await this.recoverReserved(operation); } + finally { this.options.gate.releaseRewind(owner); } + } + private async recoverReserved(operation: OpenCodeRewindOperation) { + if (!this.options.gate.isBlocked()) this.options.gate.reserve(); + const current = await this.options.getAuthoritativeOperation(); + if (!current) throw new Error('OpenCode rewind reservation is unavailable'); + if (!sameOperation(current, operation)) { + throw staleOperation(current, operation); + } + operation = current; + if (operation.nativeSessionId !== this.options.nativeSessionId) throw new Error('OpenCode rewind native session mismatch'); + const intent = this.readIntent(); + if (!intent || (intent.phase === 'finalized' && !sameOperation(intent.operation, operation))) { + if (operation.phase === 'committed') { + // Hub commit is terminal and the original journal is gone, so + // consumption can neither be replayed nor verified locally. + // Treat the rewind as already consumed and release admission + // instead of bricking every future entry on a missing tombstone. + this.options.gate.release(operation.operationId); + return { success: true as const, truncateFromLocalId: operation.requestedLocalId }; + } + if (operation.phase !== 'reserved' && operation.phase !== 'rejected') throw new Error('Durable rewind reservation has no matching local intent'); + if (!operation.workerPid || !operation.workerStartMarker) throw new Error('Rewind worker generation is unavailable'); + const sameWorker = operation.workerId === this.options.workerId && operation.workerPid === process.pid + && getProcessStartMarker(process.pid) === operation.workerStartMarker; + if (!sameWorker && !this.options.previousWorkerCannotRun?.({ pid: operation.workerPid, startMarker: operation.workerStartMarker })) { + throw new Error('Previous HAPI worker generation may still dispatch'); + } + const rejected = operation.phase === 'reserved' ? await this.options.report({ operation, phase: 'rejected' }) : operation; + const current = await this.options.getAuthoritativeOperation(); + if (!sameOperation(rejected, operation) || rejected.phase !== 'rejected' + || !current || !sameOperation(current, operation) || current.phase !== 'rejected') throw new Error('Hub rejection is unconfirmed'); + this.options.gate.release(operation.operationId); + return { success: false as const, outcome: 'rejected' as const, error: 'Unprepared reservation was rejected' }; + } + if (!sameOperation(intent.operation, operation)) { + throw new Error('Durable rewind reservation has no matching local intent'); + } + if (intent.ownerWorkerId !== this.options.workerId && (!intent.ownerProcess || !this.options.previousWorkerCannotRun?.(intent.ownerProcess))) { + return { success: false as const, outcome: 'unknown' as const, error: 'Previous HAPI worker generation may still dispatch' }; + } + if (intent.phase === 'finalized' && operation.phase === 'committed') { + // The rewind was already applied and finalized locally; re-running + // consumption would truncate a history that has moved on. Release + // admission and report the terminal state instead. + this.options.gate.release(operation.operationId); + return { success: true as const, truncateFromLocalId: intent.operation.requestedLocalId }; + } + if (operation.phase === 'rejected') { + if (intent.pendingRequest) throw new Error('Native request cohort may still mutate later'); + const current = await this.options.getAuthoritativeOperation(); + if (!current || !sameOperation(current, operation) || current.phase !== 'rejected') throw new Error('Hub rejection is unconfirmed'); + this.claimRecovery(intent); + intent.phase = 'finalized'; this.save(intent); this.options.gate.release(operation.operationId); + return { success: false as const, outcome: 'rejected' as const, error: 'Hub rejected rewind' }; + } + // A committed Hub operation is authoritative even after a later user + // turn. Never compare that turn with the old prefix or truncate again. + if (operation.phase === 'committed') { + this.claimRecovery(intent); + return await this.consumeAndFinalize(intent); + } + try { + if (intent.pendingRequest && !this.options.requestsFromPreviousWorkerCannotRun()) return await this.unknown(intent, 'Native request cohort may still mutate later'); + intent.pendingRequest = false; + this.claimRecovery(intent); + const read = await this.observe(); + if (!read.idle) return await this.unknown(intent, 'Native input is still active'); + if (hashObject(read.rows) === intent.sourceHash) { + if (!read.staged) { + const rejected = await this.options.report({ operation: intent.operation, phase: 'rejected', unchanged: true, + sourceHash: intent.sourceHash, prefixHash: intent.prefixHash }); + const current = await this.options.getAuthoritativeOperation(); + if (rejected.phase !== 'rejected' || !sameOperation(rejected, operation) + || !current || current.phase !== 'rejected' || !sameOperation(current, operation)) throw new Error('Source-unchanged rejection not confirmed'); + intent.phase = 'finalized'; this.save(intent); this.options.gate.release(operation.operationId); + return { success: false as const, outcome: 'rejected' as const, error: 'Native source is unchanged' }; + } + if (read.staged !== operation.nativeMessageId) return await this.unknown(intent, 'Another native stage owns this session'); + // A recovery can itself lose an ACK. Its new request belongs + // to this server generation, not the already-dead old cohort. + intent.nativeProcess = this.options.nativeProcess; + intent.phase = 'commit-issued'; intent.pendingRequest = true; this.save(intent); + await this.request(`/api/session/${encodeURIComponent(operation.nativeSessionId)}/revert/commit`, {}); + intent.pendingRequest = false; this.save(intent); + } + return await this.settle(intent); + } catch (error) { + if (error instanceof OpenCodeRewindSupersededError || error instanceof OpenCodeRewindPostCommitError) throw error; + return await this.unknown(intent, error); + } + } +} diff --git a/cli/src/opencode/rewindCapability.test.ts b/cli/src/opencode/rewindCapability.test.ts new file mode 100644 index 00000000..2b2fc305 --- /dev/null +++ b/cli/src/opencode/rewindCapability.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { OpencodeConversationHistory } from './conversationHistory'; + +describe('OpenCode rewind capability is runtime and native-contract bound', () => { + it.each([false, true])('requires both native revert routes as well as durable handler consumption (routes=%s)', async (routes) => { + const history = new OpencodeConversationHistory(() => ({ baseUrl: 'http://native', sessionId: 'native', mode: 'v2' }), + async () => Response.json({ paths: { '/api/session/{sessionID}/fork': {}, ...(routes ? { + '/api/session/{sessionID}/revert/stage': {}, '/api/session/{sessionID}/revert/commit': {} + } : {}) } })); + await history.probeCapabilities(); + expect(history.getCapabilitiesForMetadata()?.conversationHistory?.rewindToMessage).not.toBe(true); + history.setRewindReady(true); + expect(history.getCapabilitiesForMetadata()?.conversationHistory?.rewindToMessage === true).toBe(routes); + await history.disableFork(); + history.setRewindReady(true); + expect(history.getCapabilitiesForMetadata()?.conversationHistory?.rewindToMessage).not.toBe(true); + }); +}); diff --git a/cli/src/opencode/runOpencode.test.ts b/cli/src/opencode/runOpencode.test.ts index 76aa5a8a..0b7f9113 100644 --- a/cli/src/opencode/runOpencode.test.ts +++ b/cli/src/opencode/runOpencode.test.ts @@ -2,6 +2,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { buildCliArgs } from '@/runner/run'; import { parseRemoteAgentCommandOptions } from '@/commands/agentCommandOptions'; import { OPENCODE_PERMISSION_MODES } from '@hapi/protocol/modes'; +import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; +import { createLocalHistoryPublisher, type LocalHistoryPublisher } from './localHistory'; +import type { Metadata } from '@/api/types'; import type { MessageQueue2 } from '@/utils/MessageQueue2'; import type { OpencodeMode } from './types'; @@ -14,6 +17,7 @@ const mockOpencodeSession = vi.hoisted(() => ({ stopKeepAlive: vi.fn(), kill: vi.fn(async () => {}), onThinkingChange: vi.fn(), + localHistoryPublisher: null as LocalHistoryPublisher | null, // Mirrors AgentSessionBase's own `mode` field ('local' | 'remote', // flipped synchronously by onModeChange before either launcher // starts/finishes) — settable per test to simulate a session that @@ -30,6 +34,8 @@ const harness = vi.hoisted(() => ({ bootstrapExistingArgs: [] as Array>, opencodeLoopArgs: [] as Array>, opencodeLoopError: null as Error | null, + lifecycleOptions: undefined as Record | undefined, + killLifecycle: undefined as Record | undefined, triggerClear: false, triggerCleanupFailure: false, clearOpenCodeSession: vi.fn(async () => 'fresh-session'), @@ -39,6 +45,7 @@ const harness = vi.hoisted(() => ({ listSlashCommands: vi.fn(async (..._args: unknown[]) => [] as Array), session: { sessionId: 'source-session', + getMetadata: vi.fn(() => null as Metadata | null), onUserMessage: vi.fn(), onCancelQueuedMessage: vi.fn(), sendAgentMessage: vi.fn(), @@ -59,14 +66,16 @@ vi.mock('@/agent/sessionFactory', () => ({ harness.bootstrapArgs.push(options); return { api: { clearOpenCodeSession: harness.clearOpenCodeSession, reserveOpenCodeClearSession: harness.reserveOpenCodeClearSession, confirmOpenCodeClearCleanup: harness.confirmOpenCodeClearCleanup, abortOpenCodeClearSession: harness.abortOpenCodeClearSession }, - session: harness.session + session: harness.session, + machineId: 'machine-1' }; }), bootstrapExistingSession: vi.fn(async (options: Record) => { harness.bootstrapExistingArgs.push(options); return { api: { clearOpenCodeSession: harness.clearOpenCodeSession, reserveOpenCodeClearSession: harness.reserveOpenCodeClearSession, confirmOpenCodeClearCleanup: harness.confirmOpenCodeClearCleanup, abortOpenCodeClearSession: harness.abortOpenCodeClearSession }, - session: harness.session + session: harness.session, + machineId: 'machine-1' }; }) })); @@ -74,6 +83,13 @@ vi.mock('@/agent/sessionFactory', () => ({ vi.mock('./loop', () => ({ opencodeLoop: vi.fn(async (options: Record) => { harness.opencodeLoopArgs.push(options); + // This mock represents a remote launcher that has reconciled an + // operation-free session; pending-operation cases stay fenced. + const gate = options.runtimeGate as import('./rewind').OpenCodeRuntimeGate; + if (!harness.session.getMetadata()?.opencodeRewind) { + const token = gate.takeInitialEntryFence(); + if (token) gate.releaseEntryFence(token); + } if (harness.opencodeLoopError) { throw harness.opencodeLoopError; } @@ -96,7 +112,7 @@ vi.mock('./loop', () => ({ })); vi.mock('@/claude/registerKillSessionHandler', () => ({ - registerKillSessionHandler: vi.fn() + registerKillSessionHandler: vi.fn((_manager: unknown, lifecycle: Record) => { harness.killLifecycle = lifecycle; }) })); const lifecycleMock = vi.hoisted(() => ({ @@ -113,7 +129,7 @@ const lifecycleMock = vi.hoisted(() => ({ vi.mock('@/agent/runnerLifecycle', () => ({ createModeChangeHandler: vi.fn(() => vi.fn()), - createRunnerLifecycle: vi.fn(() => lifecycleMock), + createRunnerLifecycle: vi.fn((options: Record) => { harness.lifecycleOptions = options; return lifecycleMock; }), setControlledByUser: vi.fn() })); @@ -126,7 +142,8 @@ vi.mock('./utils/startOpencodeHookServer', () => ({ vi.mock('@/ui/logger', () => ({ logger: { - debug: vi.fn() + debug: vi.fn(), + warn: vi.fn() } })); @@ -140,6 +157,10 @@ vi.mock('@/modules/common/slashCommands', () => ({ import { runOpencode } from './runOpencode'; import { createRunnerLifecycle } from '@/agent/runnerLifecycle'; +import { configuration } from '@/configuration'; +import { hashObject } from '@/utils/deterministicJson'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; describe('runOpencode set-session-config handler', () => { beforeEach(() => { @@ -147,6 +168,10 @@ describe('runOpencode set-session-config handler', () => { harness.bootstrapExistingArgs.length = 0; harness.opencodeLoopArgs.length = 0; harness.opencodeLoopError = null; + harness.lifecycleOptions = undefined; + harness.killLifecycle = undefined; + mockOpencodeSession.localHistoryPublisher = null; + mockOpencodeSession.kill.mockClear(); harness.triggerClear = false; harness.triggerCleanupFailure = false; harness.clearOpenCodeSession.mockReset(); @@ -167,6 +192,8 @@ describe('runOpencode set-session-config handler', () => { harness.session.sendSessionEvent.mockReset(); harness.session.emitMessagesConsumed.mockReset(); harness.session.updateAgentState.mockReset(); + harness.session.getMetadata.mockReset(); + harness.session.getMetadata.mockReturnValue(null); harness.session.rpcHandlerManager.registerHandler.mockReset(); harness.listSlashCommands.mockReset(); harness.listSlashCommands.mockResolvedValue([]); @@ -190,6 +217,117 @@ describe('runOpencode set-session-config handler', () => { return configHandler![1] as (payload: unknown) => Promise; } + it('publishes model configuration within synchronous runtime admission, without a late onAfterApply mutation', async () => { + await runOpencode({ startingMode: 'remote' }); + const gate = harness.opencodeLoopArgs[0]!.runtimeGate as import('./rewind').OpenCodeRuntimeGate; + mockOpencodeSession.setModel.mockClear(); + const pending = getConfigHandler()({ model: 'admitted-model' }); + expect(mockOpencodeSession.setModel).toHaveBeenCalledWith('admitted-model'); + gate.reserve(); + const calls = mockOpencodeSession.setModel.mock.calls.length; + await pending; + expect(mockOpencodeSession.setModel).toHaveBeenCalledTimes(calls); + gate.release(); + }); + + it.each(['reserved', 'prepared', 'unknown', 'committed'] as const)('blocks preparation/config/handoff before replaying a %s rewind operation', async (phase) => { + harness.session.getMetadata.mockReturnValue({ path: '/fixture', host: 'fixture', opencodeRewind: { + operationId: 'op', nativeSessionId: 'native', nativeMessageId: 'target', workerId: 'old-worker', requestedLocalId: 'local', + cutoffSeq: 1, sourceEpoch: 0, sourceMaxSeq: 1, reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase + } }); + await runOpencode({ startingMode: 'remote' }); + const gate = harness.opencodeLoopArgs[0]!.runtimeGate as import('./rewind').OpenCodeRuntimeGate; + expect(gate.isBlocked()).toBe(true); + await expect(getConfigHandler()({ model: 'must-not-apply' })).rejects.toThrow('reconciliation'); + const handoff = harness.session.rpcHandlerManager.registerHandler.mock.calls.find(call => call[0] === RPC_METHODS.HandoffLocal)![1] as () => unknown; + expect(() => handoff()).toThrow('reconciliation'); + expect(mockOpencodeSession.setModel).not.toHaveBeenCalledWith('must-not-apply'); + }); + + it.each([ + { slow: false, rpc: false }, + { slow: true, rpc: false }, + { slow: true, rpc: true } + ])('drains queued local publications before production shutdown closes the client (%j)', async ({ slow, rpc }) => { + if (slow) vi.useFakeTimers(); + let release!: () => void; + const guard = new Promise((resolve) => { release = resolve; }); + let metadata: Metadata = { path: '/tmp/project', host: 'fixture', + opencodeHistoryCheckpoint: { sessionId: 'native', messageIds: [], userMessageIds: [], localMessageIds: [] } }; + const changes: Array<(value: Metadata) => Metadata> = []; + const order: string[] = []; + let guards = 0; + const client = { + updateMetadata(handler: (value: Metadata) => Metadata) { changes.push(handler); }, + materialize: async () => true, + flushMetadata: vi.fn(async () => { + if (++guards === 1) await guard; + if (slow) await new Promise((resolve) => setTimeout(resolve, 2000)); + for (const handler of changes.splice(0)) metadata = handler(metadata); + return true; + }), + flush: async (options?: { timeoutMs?: number }) => { + await guard; + if (slow) await new Promise((resolve) => setTimeout(resolve, 1000)); + for (const handler of changes.splice(0)) metadata = handler(metadata); + order.push(options ? 'archive-flush' : 'content-flush'); + return true; + }, + sendSessionDeath() { order.push('death'); }, + close() { order.push('close'); } + }; + const publisher = createLocalHistoryPublisher(client, vi.fn()); + mockOpencodeSession.localHistoryPublisher = publisher; + await runOpencode({ workingDirectory: '/tmp/project' }); + const hook = harness.lifecycleOptions?.onBeforeClose as () => Promise | void; + expect(hook).toBeTypeOf('function'); + const { createRunnerLifecycle } = await vi.importActual('@/agent/runnerLifecycle'); + const lifecycle = createRunnerLifecycle({ session: client as never, logTag: 'shutdown-test', onBeforeClose: hook }); + publisher.publish('native', 'msg_a', () => { order.push('send-a'); }); + publisher.publish('native', 'msg_b', () => { order.push('send-b'); }); + await vi.waitFor(() => expect(client.flushMetadata).toHaveBeenCalledTimes(1)); + let acknowledged = false; + const { registerKillSessionHandler } = await vi.importActual('@/claude/registerKillSessionHandler'); + let kill!: () => Promise; + expect(harness.killLifecycle?.machineId).toBe('machine-1'); + registerKillSessionHandler({ registerHandler: (method: string, handler: typeof kill) => { + if (method === RPC_METHODS.KillSession) kill = handler; + } } as never, { + ...harness.killLifecycle, + cleanupAndExit: () => lifecycle.cleanup() + }); + const shutdown = rpc ? kill().then(async () => { + acknowledged = true; + // Hub archive follows the KillSession ACK with StopSession. The + // runner allows only two seconds before force-killing the child. + await new Promise((resolve) => setTimeout(resolve, 2000)); + expect(order).toContain('send-b'); + return lifecycle.cleanup(); + }) : lifecycle.cleanup(); + void shutdown.catch(() => {}); + try { + await Promise.resolve(); + expect(order).not.toContain('close'); + if (rpc) { + await vi.advanceTimersByTimeAsync(2000); + expect(acknowledged).toBe(false); + } + release(); + if (slow) await vi.advanceTimersByTimeAsync(12000); + await shutdown; + expect(order).toContain('send-a'); + expect(order).toContain('send-b'); + expect(order.indexOf('send-b')).toBeLessThan(order.indexOf('death')); + expect(order.indexOf('send-b')).toBeLessThan(order.indexOf('close')); + } finally { + release(); + if (slow) await vi.runAllTimersAsync(); + await shutdown; + publisher.stop(); + if (slow) vi.useRealTimers(); + } + }); + it('routes reservedSessionId from buildCliArgs into bootstrapSession (adopt, not reopen)', async () => { const runnerArgs = buildCliArgs('opencode', { directory: '/tmp/project', @@ -362,6 +500,104 @@ describe('runOpencode set-session-config handler', () => { expect(harness.session.sendAgentMessage).toHaveBeenCalled(); }); + it('delivers a prompt whose chain admission races a re-block and closes its preparing window', async () => { + await runOpencode({}); + + const gate = harness.opencodeLoopArgs[0]!.runtimeGate as import('./rewind').OpenCodeRuntimeGate; + const messageQueue = harness.opencodeLoopArgs[0]?.messageQueue as MessageQueue2; + const userMessageHandler = harness.session.onUserMessage.mock.calls[0]?.[0] as + ((msg: { content: { text: string; attachments?: unknown[] } }, localId?: string) => void) + | undefined; + expect(userMessageHandler).toBeDefined(); + const cancelHandler = harness.session.onCancelQueuedMessage.mock.calls[0]?.[0] as + ((localId: string) => boolean | 'in-flight' | 'indeterminate' | 'consumed') | undefined; + expect(cancelHandler).toBeDefined(); + + // Arrival while the gate is blocked: admission must wait inside the + // serialized chain, not throw outside the handler's try/finally. + gate.block(); + let waits = 0; + const realWait = gate.waitUntilOpen.bind(gate); + const waitSpy = vi.spyOn(gate, 'waitUntilOpen').mockImplementation(async (signal?: AbortSignal) => { + waits++; + await realWait(signal); + // Deterministic re-block in the microtask window between the open + // notification and the admission retry. + if (waits === 1) gate.block(); + }); + try { + userMessageHandler!({ content: { text: 'race prompt' } }, 'race-prompt'); + gate.release(); + // The re-check loop must wait again instead of failing admission. + await vi.waitFor(() => expect(waits).toBe(2)); + gate.release(); + await vi.waitFor(() => expect(messageQueue.queue.some(item => item.localId === 'race-prompt')).toBe(true)); + // The delivered prompt is cancellable through the queue... + expect(cancelHandler!('race-prompt')).toBe(true); + expect(messageQueue.queue.some(item => item.localId === 'race-prompt')).toBe(false); + // ...and its preparing window is closed: a second cancel falls + // through to the best-effort "not found" answer instead of the + // leaked pre-enqueue mark. + expect(cancelHandler!('race-prompt')).toBe(false); + } finally { + waitSpy.mockRestore(); + } + }); + + describe('direct local resume with a terminal rewind tombstone', () => { + const tombstone = (phase: 'committed' | 'rejected') => ({ + operationId: 'resume-op', nativeSessionId: 'native-1', workerId: 'worker', + requestedLocalId: 'local-1', nativeMessageId: 'u1', cutoffSeq: 1, sourceEpoch: 0, sourceMaxSeq: 1, + reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), workerPid: 4242, + workerStartMarker: 'fixed-marker', phase + }); + + it('reconciles a terminal rewind without an unconsumed journal so enterLocalRuntime admits the launch', async () => { + harness.session.getMetadata.mockReturnValue({ opencodeRewind: tombstone('committed') } as never); + await runOpencode({ startingMode: 'local' }); + + const gate = harness.opencodeLoopArgs[0]!.runtimeGate as import('./rewind').OpenCodeRuntimeGate; + const operation = harness.session.getMetadata()!.opencodeRewind; + expect(gate.isBlocked()).toBe(false); + expect(() => gate.enterLocalRuntime(operation)).not.toThrow(); + }); + + it('reconciles a rejected rewind whose journal is finalized so enterLocalRuntime admits the launch', async () => { + const operation = tombstone('rejected'); + const journalDir = join(configuration.happyHomeDir, 'opencode-rewind', hashObject('source-session')); + mkdirSync(journalDir, { recursive: true }); + const backupPath = join(journalDir, 'resume-backup.json'); + writeFileSync(backupPath, JSON.stringify({ info: { id: operation.nativeSessionId }, messages: [] })); + writeFileSync(join(journalDir, 'intent.json'), JSON.stringify({ + operation, phase: 'finalized', backupPath, source: [], prefix: [], + sourceHash: hashObject([]), prefixHash: hashObject([]), pendingRequest: false, ownerWorkerId: 'previous-worker' + })); + harness.session.getMetadata.mockReturnValue({ opencodeRewind: operation } as never); + await runOpencode({ startingMode: 'local' }); + + const gate = harness.opencodeLoopArgs[0]!.runtimeGate as import('./rewind').OpenCodeRuntimeGate; + expect(gate.isBlocked()).toBe(false); + expect(() => gate.enterLocalRuntime(operation)).not.toThrow(); + }); + + it('still defers to remote reconciliation when the terminal rewind has an unconsumed journal', async () => { + const operation = tombstone('committed'); + const journalDir = join(configuration.happyHomeDir, 'opencode-rewind', hashObject('source-session')); + mkdirSync(journalDir, { recursive: true }); + const backupPath = join(journalDir, 'resume-backup.json'); + writeFileSync(backupPath, JSON.stringify({ info: { id: operation.nativeSessionId }, messages: [] })); + writeFileSync(join(journalDir, 'intent.json'), JSON.stringify({ + operation, phase: 'prepared', backupPath, source: [], prefix: [], + sourceHash: hashObject([]), prefixHash: hashObject([]), pendingRequest: false, ownerWorkerId: 'previous-worker' + })); + harness.session.getMetadata.mockReturnValue({ opencodeRewind: operation } as never); + await runOpencode({ startingMode: 'local' }); + + const gate = harness.opencodeLoopArgs[0]!.runtimeGate as import('./rewind').OpenCodeRuntimeGate; + expect(() => gate.enterLocalRuntime(operation)).toThrow(/reconciliation before local launch/); + }); + }); + it('queues a /compact request (isolated, with operation:"compact") once compact becomes available', async () => { await runOpencode({}); @@ -521,6 +757,20 @@ describe('runOpencode set-session-config handler', () => { expect(harness.session.sendAgentMessage).not.toHaveBeenCalled(); }); + it('kills the session before draining the local transcript', async () => { + const order: string[] = []; + mockOpencodeSession.kill.mockImplementationOnce(async () => { order.push('kill'); }); + mockOpencodeSession.localHistoryPublisher = { + finish: async () => { order.push('finish'); return true; } + } as unknown as LocalHistoryPublisher; + await runOpencode({ startedBy: 'runner' }); + const lifecycleOptions = vi.mocked(createRunnerLifecycle).mock.calls[0]?.[0]; + + await lifecycleOptions?.onBeforeClose?.(); + + expect(order).toEqual(['kill', 'finish']); + }); + it('runs the session kill handler before the runner lifecycle closes the session', async () => { await runOpencode({ startedBy: 'runner' }); const lifecycleOptions = vi.mocked(createRunnerLifecycle).mock.calls[0]?.[0]; diff --git a/cli/src/opencode/runOpencode.ts b/cli/src/opencode/runOpencode.ts index 030da69e..a731ab74 100644 --- a/cli/src/opencode/runOpencode.ts +++ b/cli/src/opencode/runOpencode.ts @@ -19,6 +19,9 @@ import { listSlashCommands } from '@/modules/common/slashCommands'; import { resolveOpencodeSlashCommand } from './utils/slashCommands'; import { isRetryableConnectionError } from '@/utils/errorUtils'; import { withRetry } from '@/utils/time'; +import { configuration } from '@/configuration'; +import { join } from 'node:path'; +import { OpenCodeRuntimeGate, readOpenCodeRewindIntent, sameOperation } from './rewind'; export async function runOpencode(opts: { startedBy?: 'runner' | 'terminal'; @@ -76,6 +79,23 @@ export async function runOpencode(opts: { reservedSessionId: opts.reservedSessionId }); const { api, session } = bootstrap; + const runtimeGate = new OpenCodeRuntimeGate(startingMode === 'remote'); + const pendingRewind = session.getMetadata()?.opencodeRewind; + if (startingMode !== 'remote' && pendingRewind && pendingRewind.phase !== 'rejected') runtimeGate.block(); + // A terminal rewind with no unconsumed journal is already settled: mark + // it reconciled so a direct local resume is admitted (the hub's local + // resume preparation only fences reserved|prepared|unknown phases). + if (startingMode !== 'remote' && pendingRewind + && (pendingRewind.phase === 'committed' || pendingRewind.phase === 'rejected')) { + let settled = false; + try { + const intent = readOpenCodeRewindIntent(join(configuration.happyHomeDir, 'opencode-rewind'), session.sessionId); + settled = !intent || (intent.phase === 'finalized' && sameOperation(intent.operation, pendingRewind)); + } catch { + settled = false; // A malformed journal is a blocking error: defer to remote reconciliation. + } + if (settled) runtimeGate.release(pendingRewind.operationId); + } setControlledByUser(session, startingMode); @@ -144,19 +164,37 @@ export async function runOpencode(opts: { }); const hookUrl = `http://127.0.0.1:${hookServer.port}/hook/opencode`; + const finishLocalHistory = async () => { + const publisher = sessionWrapperRef.current?.localHistoryPublisher; + if (publisher && !await publisher.finish()) { + logger.warn('[opencode] Local transcript shutdown drain was not confirmed'); + } + }; const lifecycle = createRunnerLifecycle({ session, logTag: 'opencode', stopKeepAlive: () => sessionWrapperRef.current?.stopKeepAlive(), - onBeforeClose: () => sessionWrapperRef.current?.kill(), + onBeforeClose: async () => { + // Cancel pending permission/question forms first so none can publish after the history is finalized. + await sessionWrapperRef.current?.kill(); + await finishLocalHistory(); + }, onAfterClose: () => { hookServer.stop(); } }); lifecycle.registerProcessHandlers(); - registerKillSessionHandler(session.rpcHandlerManager, lifecycle, session); - registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle); + registerKillSessionHandler(session.rpcHandlerManager, { ...lifecycle, machineId: bootstrap.machineId, + beforeKill: async (lease) => await sessionWrapperRef.current?.localHistoryPublisher?.prepare(lease) ?? true + }, session); + registerLocalHandoffHandler({ registerHandler: (method, handler) => { + session.rpcHandlerManager.registerHandler(method, (payload) => { + const release = runtimeGate.enterRuntime(); + // An accepted handoff owns admission until this process exits. + try { return handler(payload); } catch (error) { release(); throw error; } + }); + } }, lifecycle); const syncSessionMode = () => { const sessionInstance = sessionWrapperRef.current; @@ -231,6 +269,8 @@ export async function runOpencode(opts: { let userMessageChain: Promise = Promise.resolve(); session.onUserMessage((message, localId) => { + // Admission is synchronous, including async slash/config preparation. + let release = runtimeGate.isBlocked() ? undefined : runtimeGate.enterRuntime(); if (localId) preparingLocalIds.add(localId); userMessageChain = userMessageChain.then(async () => { const wasCancelled = (): boolean => { @@ -250,6 +290,16 @@ export async function runOpencode(opts: { messageQueue.push(formattedText, buildMode(), localId); }; try { + // A blocked arrival admits inside the try with a re-check loop: + // the gate can re-block between the open notification and the + // retry, and that race must fall into the handler's catch/ + // finally instead of dropping the prompt and leaking its + // preparing window. + while (!release) { + if (wasCancelled()) return; + await runtimeGate.waitUntilOpen(); + if (!runtimeGate.isBlocked()) release = runtimeGate.enterRuntime(); + } if (wasCancelled()) return; if (clearTransitionLatched) { heldDuringClear.push({ message, localId }); @@ -430,6 +480,7 @@ export async function runOpencode(opts: { pushPlain(); } } finally { + release?.(); if (localId) { preparingLocalIds.delete(localId); cancelledBeforeEnqueue.delete(localId); @@ -496,6 +547,8 @@ export async function runOpencode(opts: { modelMode: 'nullable', modelReasoningEffortMode: 'nullable', onApply: (config) => { + const release = runtimeGate.enterRuntime(); + try { if (config.permissionMode !== undefined) { currentPermissionMode = config.permissionMode; } @@ -505,8 +558,11 @@ export async function runOpencode(opts: { if (config.modelReasoningEffort !== undefined) { sessionModelReasoningEffort = config.modelReasoningEffort; } - }, - onAfterApply: syncSessionMode + // Publish within the same synchronous admission, not after the + // config helper's await, where rewind could already own the gate. + syncSessionMode(); + } finally { release(); } + } }); let crashed = false; @@ -514,6 +570,7 @@ export async function runOpencode(opts: { try { await opencodeLoop({ + runtimeGate, path: workingDirectory, startingMode, startedBy, diff --git a/cli/src/opencode/session.dequeueRelease.test.ts b/cli/src/opencode/session.dequeueRelease.test.ts new file mode 100644 index 00000000..d6ecd475 --- /dev/null +++ b/cli/src/opencode/session.dequeueRelease.test.ts @@ -0,0 +1,50 @@ +// Regression test: a stale dequeue admission is released when the +// next batch collects after an aborted collectBatch. +import { describe, expect, it, vi } from 'vitest'; +import { MessageQueue2 } from '@/utils/MessageQueue2'; +import type { OpencodeMode } from './types'; +import { OpenCodeRuntimeGate } from './rewind'; +import { OpencodeSession } from './session'; + +function makeSession() { + const gate = new OpenCodeRuntimeGate(); + const session = new OpencodeSession({ + api: {} as never, + client: { keepAlive: vi.fn(), emitMessagesConsumed: vi.fn() } as never, + path: '/tmp/hapi-opencode-dequeue-test', + logPath: '/tmp/hapi-opencode-dequeue-test.log', + sessionId: 'dequeue-release-test', + messageQueue: new MessageQueue2((mode) => JSON.stringify(mode)), + onModeChange: vi.fn(), + startedBy: 'runner', + startingMode: 'local', + runtimeGate: gate + }); + session.stopKeepAlive(); + return { session, gate }; +} + +describe('OpencodeSession dequeue admission', () => { + it('releases a stale admission when the next batch collects after an onBatchConsumed throw', async () => { + const { session, gate } = makeSession(); + const queue = session.queue; + queue.onBatchConsumed = vi.fn(() => { throw new Error('ack failed'); }); + + queue.push('first', { permissionMode: 'default' } as OpencodeMode, 'first'); + // collectBatch aborts after admitting the runtime: the launcher never + // reaches takeDequeuedRuntimeRelease, so the admission is orphaned. + await expect(queue.waitForMessagesAndGetAsString()).rejects.toThrow('ack failed'); + expect(gate.isRuntimeActive()).toBe(true); + + // The next collection must take the orphaned admission before + // acquiring its own, leaving exactly one live admission. + queue.onBatchConsumed = null; + queue.push('second', { permissionMode: 'default' } as OpencodeMode, 'second'); + const batch = await queue.waitForMessagesAndGetAsString(); + expect(batch?.message).toBe('second'); + const release = session.takeDequeuedRuntimeRelease(); + expect(release).toBeTypeOf('function'); + release!(); + expect(gate.isRuntimeActive()).toBe(false); + }); +}); \ No newline at end of file diff --git a/cli/src/opencode/session.ts b/cli/src/opencode/session.ts index 7ab14cb4..75bce15c 100644 --- a/cli/src/opencode/session.ts +++ b/cli/src/opencode/session.ts @@ -3,6 +3,8 @@ import { MessageQueue2 } from '@/utils/MessageQueue2'; import { AgentSessionBase } from '@/agent/sessionBase'; import type { OpencodeHookEvent, OpencodeMode, PermissionMode } from './types'; import type { LocalLaunchExitReason } from '@/agent/localLaunchPolicy'; +import type { LocalHistoryPublisher } from './localHistory'; +import { OpenCodeRuntimeGate } from './rewind'; type LocalLaunchFailure = { message: string; @@ -13,6 +15,12 @@ export class OpencodeSession extends AgentSessionBase { readonly startedBy: 'runner' | 'terminal'; readonly startingMode: 'local' | 'remote'; localLaunchFailure: LocalLaunchFailure | null = null; + localHistoryPublisher: LocalHistoryPublisher | null = null; + readonly runtimeGate: OpenCodeRuntimeGate; + private dequeueRelease: (() => void) | undefined; + takeDequeuedRuntimeRelease(): (() => void) | undefined { + const release = this.dequeueRelease; this.dequeueRelease = undefined; return release; + } private hookEventHandlers: Array<(event: OpencodeHookEvent) => void> = []; @@ -29,6 +37,7 @@ export class OpencodeSession extends AgentSessionBase { startingMode: 'local' | 'remote'; permissionMode?: PermissionMode; modelReasoningEffort?: string | null; + runtimeGate?: OpenCodeRuntimeGate; }) { super({ api: opts.api, @@ -50,6 +59,14 @@ export class OpencodeSession extends AgentSessionBase { }); this.startedBy = opts.startedBy; + this.runtimeGate = opts.runtimeGate ?? new OpenCodeRuntimeGate(); + this.queue.beforeDequeue = () => { + // An aborted collectBatch (an onBatchConsumed throw) leaves the + // previous admission unreleased and the launcher never reaches + // takeDequeuedRuntimeRelease: take it before acquiring the next. + this.dequeueRelease?.(); + this.dequeueRelease = this.runtimeGate.enterRuntime(); + }; this.startingMode = opts.startingMode; this.permissionMode = opts.permissionMode; this.modelReasoningEffort = opts.modelReasoningEffort; diff --git a/cli/src/opencode/utils/opencodeCompactionProjector.test.ts b/cli/src/opencode/utils/opencodeCompactionProjector.test.ts index 1e253640..35cfd605 100644 --- a/cli/src/opencode/utils/opencodeCompactionProjector.test.ts +++ b/cli/src/opencode/utils/opencodeCompactionProjector.test.ts @@ -10,6 +10,27 @@ function setup() { return { onSummary, onText, projector: new OpencodeCompactionProjector({ sessionId: 'ses', onSummary, onText }) }; } describe('OpenCode native compaction projection', () => { + it('observes only structurally identified hidden v1 records and deduplicates replay', () => { + const onControlMessage = vi.fn(); + const projector = new OpencodeCompactionProjector({ sessionId: 'ses', onSummary: vi.fn(), onControlMessage }); + projector.message(summary); + projector.message({ ...summary, id: 'unlinked', parentID: 'missing' }); + projector.message({ ...summary, id: 'foreign', sessionID: 'other' }); + projector.message(marker); + projector.message({ id: 'continue', sessionID: 'ses', role: 'user' }); + projector.message({ id: 'real', sessionID: 'ses', role: 'user' }); + projector.message({ id: 'assistant', sessionID: 'ses', role: 'assistant' }); + projector.part({ id: 'marker-part', sessionID: 'ses', messageID: 'marker', type: 'compaction', auto: true }); + for (const [id, messageID, metadata] of [ + ['continue-part', 'continue', { compaction_continue: true }], + ['real-part', 'real', {}], + ['assistant-part', 'assistant', { compaction_continue: true }], + ['foreign-part', 'missing', { compaction_continue: true }] + ] as const) projector.part({ id, messageID, sessionID: 'ses', type: 'text', synthetic: true, metadata, text: 'Continue' }); + projector.flush(); + projector.flush(); + expect(onControlMessage.mock.calls.flat().sort()).toEqual(['continue', 'marker', 'summary']); + }); it('holds summary text, validates its parent, and emits one stable card across replay', () => { const { projector, onSummary, onText } = setup(); projector.message(summary); diff --git a/cli/src/opencode/utils/opencodeCompactionProjector.ts b/cli/src/opencode/utils/opencodeCompactionProjector.ts index b7a11d88..a67df708 100644 --- a/cli/src/opencode/utils/opencodeCompactionProjector.ts +++ b/cli/src/opencode/utils/opencodeCompactionProjector.ts @@ -18,6 +18,7 @@ export class OpencodeCompactionProjector { private readonly emitted = new Set(); private readonly started = new Set(); private readonly emittedText = new Map(); + private readonly observedControls = new Set(); constructor(private readonly options: { sessionId: string; @@ -25,6 +26,7 @@ export class OpencodeCompactionProjector { onText?: (part: OpencodeNativeText) => void; onFailure?: (id: string, trigger: OpencodeCompactionTrigger) => void; onStart?: (id: string, trigger: OpencodeCompactionTrigger) => void; + onControlMessage?: (messageId: string) => void; }) {} message(info: RecordValue): void { @@ -71,6 +73,7 @@ export class OpencodeCompactionProjector { /** Call after a terminal native update or a complete storage scan. */ flush(): void { + this.observeControlMessages(); for (const info of this.messages.values()) { const id = info.id as string; if (info.type === 'compaction') { @@ -98,6 +101,36 @@ export class OpencodeCompactionProjector { this.projectText(); } + /** Hidden v1 records still belong to native history, independently of the card's stable marker ID. */ + private observeControlMessages(): void { + const onControlMessage = this.options.onControlMessage; + if (!onControlMessage) return; + const observe = (id: string) => { + if (this.observedControls.has(id)) return; + this.observedControls.add(id); + onControlMessage(id); + }; + const markers = new Set(); + for (const part of this.parts.values()) { + const info = typeof part.messageID === 'string' ? this.messages.get(part.messageID) : undefined; + if (info?.role !== 'user') continue; + if (part.type === 'compaction') { + markers.add(info.id as string); + observe(info.id as string); + } else if (part.type === 'text' && part.synthetic === true + && isObject(part.metadata) && part.metadata.compaction_continue === true) { + observe(info.id as string); + } + } + for (const info of this.messages.values()) { + if (info.role !== 'assistant' || info.summary !== true || typeof info.parentID !== 'string' + || !markers.has(info.parentID)) continue; + const siblings = [...this.messages.values()].filter(message => message.role === 'assistant' + && message.summary === true && message.parentID === info.parentID); + if (siblings.length === 1) observe(info.id as string); + } + } + private projectText(parts: Iterable = this.parts.values()): void { for (const part of parts) { if ((part.type !== 'text' && part.type !== 'reasoning') || typeof part.text !== 'string') continue; diff --git a/cli/src/opencode/utils/opencodeNativeTranscript.test.ts b/cli/src/opencode/utils/opencodeNativeTranscript.test.ts index de321628..25174985 100644 --- a/cli/src/opencode/utils/opencodeNativeTranscript.test.ts +++ b/cli/src/opencode/utils/opencodeNativeTranscript.test.ts @@ -121,6 +121,111 @@ describe('OpenCode native transcript reconciliation', () => { await recovering; expect(onText).not.toHaveBeenCalled(); }); + it('suppresses inherited compaction outcomes while post-baseline ones still publish', async () => { + const inherited = [ + { info: { id: 'marker', sessionID: 'ses', role: 'user' }, parts: [{ id: 'marker-part', messageID: 'marker', sessionID: 'ses', type: 'compaction', auto: true }] }, + { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', finish: 'stop' }, parts: [{ id: 'summary-part', messageID: 'summary', sessionID: 'ses', type: 'text', text: 'inherited', time: { end: 1 } }] } + ]; + const onSummary = vi.fn(); + const onFailure = vi.fn(); + const transcript = new OpencodeNativeTranscript({ baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v1', + suppressInheritedCompactions: true, onSummary, onFailure, onText: vi.fn(), fetchImpl: async () => Response.json(inherited) }); + await transcript.refresh(); + expect(onSummary).not.toHaveBeenCalled(); + expect(onFailure).not.toHaveBeenCalled(); + // Replays after the baseline applied stay published. + transcript.event('message.updated', { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', finish: 'stop' } }); + expect(onSummary).not.toHaveBeenCalled(); + transcript.event('message.updated', { info: { id: 'new-marker', sessionID: 'ses', role: 'user' } }); + transcript.event('message.part.updated', { part: { id: 'new-marker-part', messageID: 'new-marker', sessionID: 'ses', type: 'compaction', auto: true } }); + transcript.event('message.updated', { info: { id: 'new-summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'new-marker' } }); + transcript.event('message.part.updated', { part: { id: 'new-summary-part', messageID: 'new-summary', sessionID: 'ses', type: 'text', text: 'fresh', time: { end: 2 } } }); + transcript.event('message.updated', { info: { id: 'new-summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'new-marker', finish: 'stop' } }); + expect(onSummary).toHaveBeenCalledExactlyOnceWith('new-marker', 'fresh', 'auto'); + transcript.close(); + }); + it('publishes a compaction that completes live during baseline recovery exactly once', async () => { + // The first read fails, so the baseline never applies. A fork child's + // own compaction then completes over the live stream: it belongs to + // this runtime, must publish, and must not be lost to the baseline + // suppression window. + const persisted = [ + { info: { id: 'marker', sessionID: 'ses', role: 'user' }, parts: [{ id: 'marker-part', messageID: 'marker', sessionID: 'ses', type: 'compaction', auto: true }] }, + { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', finish: 'stop' }, parts: [{ id: 'summary-part', messageID: 'summary', sessionID: 'ses', type: 'text', text: 'live summary', time: { end: 1 } }] } + ]; + const fetchImpl = vi.fn().mockResolvedValueOnce(new Response('', { status: 503 })) + .mockResolvedValue(Response.json(persisted)); + const onSummary = vi.fn(); + const transcript = new OpencodeNativeTranscript({ baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v1', + suppressInheritedCompactions: true, onSummary, onText: vi.fn(), fetchImpl }); + await transcript.refresh(); + transcript.event('message.updated', { info: { id: 'marker', sessionID: 'ses', role: 'user' } }); + transcript.event('message.part.updated', { part: { id: 'marker-part', messageID: 'marker', sessionID: 'ses', type: 'compaction', auto: true } }); + transcript.event('message.updated', { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker' } }); + transcript.event('message.part.updated', { part: { id: 'summary-part', messageID: 'summary', sessionID: 'ses', type: 'text', text: 'live summary', time: { end: 1 } } }); + transcript.event('message.updated', { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', finish: 'stop' } }); + expect(onSummary).toHaveBeenCalledExactlyOnceWith('marker', 'live summary', 'auto'); + transcript.close(); + }); + it('publishes a compaction failure that surfaces live during baseline recovery exactly once', async () => { + const persisted = [ + { info: { id: 'marker', sessionID: 'ses', role: 'user' }, parts: [{ id: 'marker-part', messageID: 'marker', sessionID: 'ses', type: 'compaction', auto: true }] }, + { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', error: true, finish: 'stop' }, parts: [] } + ]; + const fetchImpl = vi.fn().mockResolvedValueOnce(new Response('', { status: 503 })) + .mockResolvedValue(Response.json(persisted)); + const onSummary = vi.fn(); + const onFailure = vi.fn(); + const transcript = new OpencodeNativeTranscript({ baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v1', + suppressInheritedCompactions: true, onSummary, onFailure, onText: vi.fn(), fetchImpl }); + await transcript.refresh(); + transcript.event('message.updated', { info: { id: 'marker', sessionID: 'ses', role: 'user' } }); + transcript.event('message.part.updated', { part: { id: 'marker-part', messageID: 'marker', sessionID: 'ses', type: 'compaction', auto: true } }); + transcript.event('message.updated', { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', error: true, finish: 'stop' } }); + expect(onFailure).toHaveBeenCalledExactlyOnceWith('marker', 'auto'); + await transcript.refresh(); + expect(onFailure).toHaveBeenCalledTimes(1); + expect(onSummary).not.toHaveBeenCalled(); + transcript.close(); + }); + it('still suppresses an inherited compaction that only the baseline snapshot reports', async () => { + const inherited = [ + { info: { id: 'marker', sessionID: 'ses', role: 'user' }, parts: [{ id: 'marker-part', messageID: 'marker', sessionID: 'ses', type: 'compaction', auto: true }] }, + { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', finish: 'stop' }, parts: [{ id: 'summary-part', messageID: 'summary', sessionID: 'ses', type: 'text', text: 'inherited summary', time: { end: 1 } }] } + ]; + const fetchImpl = vi.fn().mockResolvedValue(Response.json(inherited)); + const onSummary = vi.fn(); + const transcript = new OpencodeNativeTranscript({ baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v1', + suppressInheritedCompactions: true, onSummary, onText: vi.fn(), fetchImpl }); + await transcript.refresh(); + expect(onSummary).not.toHaveBeenCalled(); + await transcript.refresh(); + expect(onSummary).not.toHaveBeenCalled(); + transcript.close(); + }); + it('does not double publish a live compaction when the baseline recovers with the same row', async () => { + const persisted = [ + { info: { id: 'marker', sessionID: 'ses', role: 'user' }, parts: [{ id: 'marker-part', messageID: 'marker', sessionID: 'ses', type: 'compaction', auto: true }] }, + { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', finish: 'stop' }, parts: [{ id: 'summary-part', messageID: 'summary', sessionID: 'ses', type: 'text', text: 'live summary', time: { end: 1 } }] } + ]; + const fetchImpl = vi.fn().mockResolvedValueOnce(new Response('', { status: 503 })) + .mockResolvedValue(Response.json(persisted)); + const onSummary = vi.fn(); + const transcript = new OpencodeNativeTranscript({ baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v1', + suppressInheritedCompactions: true, onSummary, onText: vi.fn(), fetchImpl }); + await transcript.refresh(); + transcript.event('message.updated', { info: { id: 'marker', sessionID: 'ses', role: 'user' } }); + transcript.event('message.part.updated', { part: { id: 'marker-part', messageID: 'marker', sessionID: 'ses', type: 'compaction', auto: true } }); + transcript.event('message.updated', { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker' } }); + transcript.event('message.part.updated', { part: { id: 'summary-part', messageID: 'summary', sessionID: 'ses', type: 'text', text: 'live summary', time: { end: 1 } } }); + transcript.event('message.updated', { info: { id: 'summary', sessionID: 'ses', role: 'assistant', summary: true, parentID: 'marker', finish: 'stop' } }); + // The recovered baseline holds the same completed row; the live + // publication must already have marked it. + await transcript.refresh(); + await transcript.refresh(); + expect(onSummary).toHaveBeenCalledTimes(1); + transcript.close(); + }); it('drops a stale read and honors an idle/reconnect refresh requested while it was in flight', async () => { let resolve!: (r: Response) => void; const fetchImpl = vi.fn().mockImplementationOnce(() => new Promise(r => { resolve = r; })).mockResolvedValue(Response.json([])); diff --git a/cli/src/opencode/utils/opencodeNativeTranscript.ts b/cli/src/opencode/utils/opencodeNativeTranscript.ts index 6fbf0bc8..211d6a92 100644 --- a/cli/src/opencode/utils/opencodeNativeTranscript.ts +++ b/cli/src/opencode/utils/opencodeNativeTranscript.ts @@ -15,6 +15,10 @@ export class OpencodeNativeTranscript { private readFailureReported = false; private closed = false; private initializing = true; + /** Compaction identities this runtime observed through live events; never part of the inherited baseline. */ + private readonly liveCompactionIds = new Set(); + /** True only while the first successful snapshot's synchronous flush decides compaction outcomes. */ + private suppressingBaselineFlush = false; private readonly liveTextParts = new Set(); private readonly initialText = new Map(); private readonly unbasedDeltas = new Map(); @@ -32,12 +36,31 @@ export class OpencodeNativeTranscript { onFailure?: (id: string, trigger: OpencodeCompactionTrigger) => void; onStart?: (id: string, trigger: OpencodeCompactionTrigger) => void; onReadFailure?: () => void; + /** + * Fork children resume a native session whose history already holds + * the source's compactions, and the hub's transcript copy already + * published their cards under the source session's localId. Outcomes + * reported only by the first successful snapshot are inherited and + * dropped; anything this runtime observed through live events + * publishes normally, including while a failed baseline read is + * still recovering. + */ + suppressInheritedCompactions?: boolean; fetchImpl?: FetchLike; }) { + const { onFailure } = options; this.projector = new OpencodeCompactionProjector({ sessionId: options.sessionId, - onSummary: options.onSummary, - onFailure: options.onFailure, + onSummary: (id, summary, trigger) => { + if (this.suppressingBaselineFlush && !this.liveCompactionIds.has(id)) return; + options.onSummary(id, summary, trigger); + }, + onFailure: onFailure + ? (id, trigger) => { + if (this.suppressingBaselineFlush && !this.liveCompactionIds.has(id)) return; + onFailure(id, trigger); + } + : undefined, onStart: options.onStart, onText: part => { if (this.closed) return; @@ -55,14 +78,17 @@ export class OpencodeNativeTranscript { && properties.sessionID === this.options.sessionId && typeof eventId === 'string' && eventId.startsWith('evt_')) { // Session.Message.ID.fromEvent: the persisted row shares this durable event identity. const id = typeof properties.inputID === 'string' ? properties.inputID : eventId.replace(/^evt_/, 'msg_'); + this.liveCompactionIds.add(id); this.projector.start(id, properties.reason === 'auto' ? 'auto' : properties.reason === 'manual' ? 'manual' : undefined); } if (type === 'message.updated' && isObject(properties.info)) { + this.observeLiveCompaction(properties.info); this.projector.message(properties.info); if (typeof properties.info.finish === 'string') this.projector.flush(); } if (type === 'message.part.updated' && isObject(properties.part)) { const part = properties.part; + if (part.type === 'compaction' && typeof part.messageID === 'string') this.liveCompactionIds.add(part.messageID); if (typeof part.id === 'string') { this.parts.set(part.id, part); this.unbasedDeltas.delete(part.id); @@ -88,6 +114,12 @@ export class OpencodeNativeTranscript { if (type.startsWith('session.compaction.')) void this.refresh(); } + /** Compaction identities carried by live events: v2 compaction rows, v1 summary links, and marker parts. */ + private observeLiveCompaction(info: Record): void { + if (info.type === 'compaction' && typeof info.id === 'string') this.liveCompactionIds.add(info.id); + if (info.summary === true && typeof info.parentID === 'string') this.liveCompactionIds.add(info.parentID); + } + refresh(): Promise { if (this.closed) return Promise.resolve(); if (this.refreshing) { this.refreshAgain = true; return this.refreshing; } @@ -167,10 +199,19 @@ export class OpencodeNativeTranscript { const liveParts = [...this.liveTextParts] .flatMap(id => this.parts.has(id) ? [this.parts.get(id)!] : []); this.initialText.clear(); - this.projector.snapshot(this.options.mode === 'v2' - ? entries.filter(entry => isObject(entry) && (entry.sessionID === undefined || entry.sessionID === this.options.sessionId)) - .map(entry => isObject(entry) ? { ...entry, sessionID: this.options.sessionId } : entry) - : entries, liveParts, this.initializing); + // The first successful snapshot is the inherited baseline: its + // never-live-observed compaction outcomes are already published + // on the hub (fork transcript copy). Outcomes this runtime saw + // live belong to it and publish even during recovery. + this.suppressingBaselineFlush = this.initializing && this.options.suppressInheritedCompactions === true; + try { + this.projector.snapshot(this.options.mode === 'v2' + ? entries.filter(entry => isObject(entry) && (entry.sessionID === undefined || entry.sessionID === this.options.sessionId)) + .map(entry => isObject(entry) ? { ...entry, sessionID: this.options.sessionId } : entry) + : entries, liveParts, this.initializing); + } finally { + this.suppressingBaselineFlush = false; + } this.readFailureReported = false; if (this.initializing && !this.closed) { // Only an applied baseline primes historical text. Keep the diff --git a/cli/src/runner/orphanReap.test.ts b/cli/src/runner/orphanReap.test.ts index bdb0932d..e6289c05 100644 --- a/cli/src/runner/orphanReap.test.ts +++ b/cli/src/runner/orphanReap.test.ts @@ -151,6 +151,48 @@ describe('orphanReap argv matching', () => { }) describe('reapRunnerSpawnedOrphans (stopSession orphan path)', () => { + it.each(['same', 'reused', 'unknown', 'exited'] as const)('awaits async identity and liveness after preparation (%s)', async state => { + let prepared = false + const killed: number[] = [] + const result = await reapRunnerSpawnedOrphans('async-preparation', { + findTargets: async () => [{ pid: 4200, startMarker: 'generation' }], + getStartMarker: async () => prepared + ? state === 'reused' ? 'replacement' : state === 'unknown' ? null : 'generation' + : 'generation', + isAlive: async () => state !== 'exited', + prepare: async () => { prepared = true; return true }, + killTree: async pid => { killed.push(pid); return true }, + }) + expect(prepared).toBe(true) + expect(result).toBe(state === 'reused' || state === 'unknown' ? 'still_alive' : 'stopped') + expect(killed).toEqual(state === 'same' ? [4200] : []) + }) + + it('does not signal an orphan whose own preparation was not confirmed', async () => { + const killed: number[] = [] + const status = await reapRunnerSpawnedOrphans('same-session', { + findTargets: async () => [{ pid: 123, startMarker: 'gen-a' }], + getStartMarker: () => 'gen-a', isAlive: () => true, + prepare: async () => false, + killTree: async (pid) => { killed.push(pid); return true } + }) + expect(status).toBe('still_alive') + expect(killed).toEqual([]) + }) + + it('rechecks an orphan generation after its preparation await', async () => { + let generation = 'gen-a' + const killed: number[] = [] + const status = await reapRunnerSpawnedOrphans('same-session', { + findTargets: async () => [{ pid: 123, startMarker: 'gen-a' }], + getStartMarker: () => generation, isAlive: () => true, + prepare: async () => { generation = 'gen-b'; return true }, + killTree: async (pid) => { killed.push(pid); return true } + }) + expect(status).toBe('still_alive') + expect(killed).toEqual([]) + }) + const stableMarker = (marker = 'gen-a') => { let reads = 0 return () => { diff --git a/cli/src/runner/orphanReap.ts b/cli/src/runner/orphanReap.ts index 58d7d26b..46191209 100644 --- a/cli/src/runner/orphanReap.ts +++ b/cli/src/runner/orphanReap.ts @@ -34,6 +34,8 @@ export type OrphanTarget = { pid: number /** Marker captured in the argv-match snapshot (not a later probe). */ startMarker: string | null + /** MCP bridge helpers have no local transcript publisher to prepare. */ + needsPublicationDrain?: false } /** True when cmd looks like a HAPI driver CLI (binary or bun/node src/index.ts). */ @@ -108,6 +110,8 @@ export function selectOrphanTargetsForSession( targets.push({ pid, startMarker: proc.startMarker === undefined ? null : proc.startMarker, + ...(!commandMatchesRunnerSpawnedSession(cmd, sessionId) && commandMatchesHapiMcpBridgeForSession(cmd, sessionId) + ? { needsPublicationDrain: false as const } : {}), }) } return targets @@ -293,6 +297,7 @@ export async function reapRunnerSpawnedOrphans( /** @deprecated Prefer findTargets (includes same-snapshot markers). */ findOrphans?: (sessionId: string) => Promise killTree?: (pid: number) => Promise + prepare?: (target: OrphanTarget) => Promise getStartMarker?: (pid: number) => string | null | Promise isAlive?: (pid: number) => boolean | Promise } = {} @@ -334,7 +339,8 @@ export async function reapRunnerSpawnedOrphans( // do not downgrade to stopped based on root liveness alone (#1910 / #1911 B2). let anyUnconfirmed = false let resolved = 0 - for (const { pid: orphanPid, startMarker: expectedMarker } of targets) { + for (const target of targets) { + const { pid: orphanPid, startMarker: expectedMarker } = target if (expectedMarker === null) { // No generation identity from the match snapshot. If the PID is // already dead the orphan is gone; if still alive, skip kill and @@ -366,6 +372,11 @@ export async function reapRunnerSpawnedOrphans( continue } + if (deps.prepare) { + if (!await deps.prepare(target)) { anyUnconfirmed = true; continue } + if (!await isAlive(orphanPid)) { resolved++; continue } + if (await getStartMarker(orphanPid) !== expectedMarker) { anyUnconfirmed = true; continue } + } if (!(await killTree(orphanPid))) { anyUnconfirmed = true continue diff --git a/cli/src/runner/run.recoveredStop.test.ts b/cli/src/runner/run.recoveredStop.test.ts new file mode 100644 index 00000000..bdd066ee --- /dev/null +++ b/cli/src/runner/run.recoveredStop.test.ts @@ -0,0 +1,153 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { startRunnerControlServer } from './controlServer' + +const mocks = vi.hoisted(() => ({ + controlServer: vi.fn(), + readRuntimes: vi.fn(), + findRuntime: vi.fn(), + reapOrphans: vi.fn(), + kill: vi.fn(), + prepare: vi.fn(), + alive: vi.fn(() => true), + marker: vi.fn(() => 'generation'), +})) + +vi.mock('./controlServer', () => ({ startRunnerControlServer: mocks.controlServer })) +vi.mock('./controlClient', () => ({ + isRunnerRunningCurrentlyInstalledHappyVersion: async () => false, + stopRunner: async () => {}, +})) +vi.mock('@/api/api', () => ({ + ApiClient: { create: async () => ({ prepareOpenCodeSessionStop: mocks.prepare }) }, +})) +vi.mock('@/persistence', async importOriginal => ({ + ...await importOriginal(), + acquireRunnerLock: async () => ({}), +})) +vi.mock('@/ui/auth', () => ({ authAndSetupMachineIfNeeded: async () => ({ machineId: 'machine' }) })) +vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn(), debugLargeJson: vi.fn(), warn: vi.fn() } })) +vi.mock('@/ui/doctor', () => ({ getEnvironmentInfo: () => ({}) })) +vi.mock('@/codex/shared/registry', () => ({ + readRuntimes: mocks.readRuntimes, + findRuntime: mocks.findRuntime, + runtimeAuthHash: () => 'test-auth', + runtimeMayBeAlive: () => true, +})) +vi.mock('@/runner/orphanReap', () => ({ + reapRunnerSpawnedOrphans: mocks.reapOrphans, + findStopSessionOrphanTargets: vi.fn(), +})) +vi.mock('@/utils/process', async importOriginal => ({ + ...await importOriginal(), + isWindows: () => false, + isProcessAlive: () => mocks.alive(), + getProcessStartMarker: () => mocks.marker(), + killProcess: mocks.kill, + killProcessTreeByPid: mocks.kill, + killProcessByChildProcess: mocks.kill, +})) + +import { configuration } from '@/configuration' +import { startRunner } from './run' + +describe('runner stop of recovered persisted sessions while the Hub is unavailable', () => { + let stopSession: Parameters[0]['stopSession'] + let home: string + + const startWith = async (records: unknown[]) => { + home = mkdtempSync(join(tmpdir(), 'hapi-stop-recovered-')) + const originalStateFile = configuration.runnerStateFile + const captured = new Error('control handlers captured before runner networking') + mocks.controlServer.mockImplementation(async handlers => { + stopSession = handlers.stopSession + throw captured + }) + vi.spyOn(process, 'on').mockReturnValue(process) + vi.spyOn(process, 'exit').mockImplementation(() => { throw captured }) + vi.stubEnv('HAPI_RUNNER_HANDOFF_FROM_PID', '') + const stateFile = join(home, 'runner.json') + writeFileSync(`${stateFile}.resume-processes.json`, JSON.stringify(records)) + Object.defineProperty(configuration, 'runnerStateFile', { value: stateFile, configurable: true }) + try { + await expect(startRunner()).rejects.toBe(captured) + } finally { + Object.defineProperty(configuration, 'runnerStateFile', { value: originalStateFile, configurable: true }) + vi.restoreAllMocks() + vi.unstubAllEnvs() + } + } + + beforeEach(() => { + vi.clearAllMocks() + mocks.alive.mockReturnValue(true) + mocks.marker.mockReturnValue('generation') + mocks.readRuntimes.mockResolvedValue([]) + mocks.findRuntime.mockResolvedValue(undefined) + mocks.reapOrphans.mockResolvedValue(null) + mocks.prepare.mockRejectedValue(new Error('hub unavailable')) + mocks.kill.mockResolvedValue(true) + }) + + afterEach(() => rmSync(home, { recursive: true, force: true })) + + it('still kills a recovered non-OpenCode process tree without Hub preparation', async () => { + await startWith([{ + requestedSessionId: 'claude-session', confirmedSessionId: 'claude-session', + pid: 4242, processStartMarker: 'generation', flavor: 'claude', + }]) + await expect(stopSession('claude-session')).resolves.toBe('stopped') + expect(mocks.prepare).not.toHaveBeenCalled() + expect(mocks.kill).toHaveBeenCalled() + }) + + it('keeps the mandatory Hub preparation for a recovered OpenCode process', async () => { + await startWith([{ + requestedSessionId: 'opencode-session', confirmedSessionId: 'opencode-session', + pid: 4242, processStartMarker: 'generation', flavor: 'opencode', + }]) + await expect(stopSession('opencode-session')).resolves.toBe('still_alive') + expect(mocks.kill).not.toHaveBeenCalled() + }) + + it('keeps the mandatory Hub preparation when the recovered flavor is unknown', async () => { + await startWith([{ + requestedSessionId: 'legacy-session', confirmedSessionId: 'legacy-session', + pid: 4242, processStartMarker: 'generation', + }]) + await expect(stopSession('legacy-session')).resolves.toBe('still_alive') + expect(mocks.kill).not.toHaveBeenCalled() + }) + + it('reports already_gone when a recovered OpenCode process exits during Hub preparation', async () => { + await startWith([{ + requestedSessionId: 'opencode-session', confirmedSessionId: 'opencode-session', + pid: 4242, processStartMarker: 'generation', flavor: 'opencode', + }]) + mocks.prepare.mockImplementation(async () => { + // The process dies inside the preparation round-trip window; the + // Hub grants no lease (undefined expiry). + mocks.alive.mockReturnValue(false) + return undefined as unknown as boolean + }) + await expect(stopSession('opencode-session')).resolves.toBe('already_gone') + expect(mocks.kill).not.toHaveBeenCalled() + }) + + it('refuses to signal a recycled PID after Hub preparation', async () => { + await startWith([{ + requestedSessionId: 'opencode-session', confirmedSessionId: 'opencode-session', + pid: 4242, processStartMarker: 'generation', flavor: 'opencode', + }]) + mocks.prepare.mockImplementation(async () => { + // The Hub grants no lease; the OS recycles the PID right after + // preparation's own verification, before the kill signal. + mocks.marker.mockReturnValueOnce('generation').mockReturnValue('recycled-generation') + return undefined as unknown as boolean + }) + await expect(stopSession('opencode-session')).resolves.toBe('unknown') + expect(mocks.kill).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/runner/run.ts b/cli/src/runner/run.ts index aecf2bb3..018f4ee8 100644 --- a/cli/src/runner/run.ts +++ b/cli/src/runner/run.ts @@ -34,7 +34,7 @@ import { } from '@/runner/sharedSessionStop'; import { PERMISSION_MODES } from '@hapi/protocol/modes'; import { RUNNER_CAPABILITIES } from '@hapi/protocol'; -import { withRetry } from '@/utils/time'; +import { monotonicTimeMs, withRetry } from '@/utils/time'; import { isRetryableConnectionError } from '@/utils/errorUtils'; import { cleanupRunnerState, getInstalledCliMtimeMs, isRunnerRunningCurrentlyInstalledHappyVersion, stopRunner, waitForRunnerHandoff } from './controlClient'; @@ -373,6 +373,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pid: number; processStartMarker: string; bootId?: string; + // Agent flavor, so a recovered process can skip OpenCode-only stop preparation. + flavor?: string; }; const resumeProcessFile = `${configuration.runnerStateFile}.resume-processes.json`; const persistedResumeProcesses = (() => { @@ -393,6 +395,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pid: record.pid, processStartMarker: record.processStartMarker, bootId: normalizeBootId(record.bootId) ?? undefined, + flavor: typeof record.flavor === 'string' ? record.flavor : undefined, }]]; })); } catch (error) { @@ -508,6 +511,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const persisted = persistedResumeProcesses.get(pid); if (persisted) { persisted.confirmedSessionId = sessionId; + persisted.flavor = sessionMetadata.flavor ?? persisted.flavor; persistResumeProcesses(); } else { // Fresh Claude/etc. spawns often have no reserved HAPI id at spawn @@ -522,6 +526,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pid, processStartMarker, bootId: getSystemBootId() ?? undefined, + flavor: sessionMetadata.flavor ?? undefined, }); persistResumeProcesses(); } @@ -610,6 +615,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pid, processStartMarker, bootId: getSystemBootId() ?? undefined, + flavor: sessionMetadata.flavor ?? undefined, }); persistResumeProcesses(); } @@ -989,6 +995,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pid, processStartMarker, bootId: getSystemBootId() ?? undefined, + flavor: agent, }); persistResumeProcesses(); } @@ -1230,6 +1237,25 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): terminated: Set = new Set() ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { logger.debug(`[RUNNER RUN] Attempting to stop session ${sessionId}`); + const signalDeadlines = new Map(); + const prepareSessionStop = async (id: string, pid: number, expectedMarker?: string): Promise => { + if (!isProcessAlive(pid)) return true; + const flavor = pidToTrackedSession.get(pid)?.happySessionMetadataFromLocalWebhook?.flavor + ?? persistedResumeProcesses.get(pid)?.flavor; + if (flavor && flavor !== 'opencode') return true; + const marker = expectedMarker ?? getProcessStartMarker(pid); + if (!marker) return false; + try { + const client = await ApiClient.create(); + const expiresAt = await client.prepareOpenCodeSessionStop(id, machineId, pid, marker); + if (expiresAt !== undefined) signalDeadlines.set(pid, expiresAt); + return (!isProcessAlive(pid) || getProcessStartMarker(pid) === marker) + && (expiresAt === undefined || monotonicTimeMs() < expiresAt); + } catch (error) { + logger.debug(`[RUNNER RUN] Session ${id} shutdown preparation unconfirmed: ${error instanceof Error ? error.message : 'Unknown error'}`); + return false; + } + }; // After a mapped/persisted PID path succeeds, still scan argv for other // generations of the same HAPI id (untracked orphans from an earlier @@ -1318,6 +1344,9 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): sessionId ); const orphanStatus = await reapRunnerSpawnedOrphans(sessionId, { + killTree: (pid) => killProcessTreeByPid(pid, false, undefined, signalDeadlines.get(pid)), + prepare: (target) => target.needsPublicationDrain === false ? Promise.resolve(true) + : prepareSessionStop(sessionId, target.pid, target.startMarker ?? undefined), findTargets: (id) => findStopSessionOrphanTargets( id, (sid, pid) => shouldSkipOrphanPid(liveRuntimes, protectedTrackedPids, sid, pid) @@ -1409,7 +1438,17 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): ); return await finishWithOrphanSweep('stopped'); } - if (!(await killProcessTreeByPid(pid))) return 'still_alive'; + const tracked = pidToTrackedSession.get(pid); + const logicalId = tracked?.happySessionId ?? pidToConfirmedSessionId.get(pid) + ?? persistedResumeProcesses.get(pid)?.confirmedSessionId ?? pidToRequestedSessionId.get(pid); + const flavor = tracked?.happySessionMetadataFromLocalWebhook?.flavor; + if (logicalId && (!flavor || flavor === 'opencode') + && !await prepareSessionStop(logicalId, pid, opts?.processStartMarker)) return 'still_alive'; + // Preparation can outlive the target generation. Recheck after that + // await before signalling a raw PID that the OS may have reused. + if (!isProcessAlive(pid)) return await finishWithOrphanSweep('already_gone'); + if (getProcessStartMarker(pid) !== opts?.processStartMarker) return 'unknown'; + if (!(await killProcessTreeByPid(pid, false, undefined, signalDeadlines.get(pid)))) return 'still_alive'; terminated.add(pid); rememberVerifiedExit(sessionId); return await finishWithOrphanSweep('stopped'); @@ -1505,12 +1544,18 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } } try { + if (!await prepareSessionStop(sessionId, pid, persistedResumeProcesses.get(pid)?.processStartMarker)) return 'still_alive'; + // Preparation can outlive the target generation (same recheck as + // the raw-PID path): never signal a dead or recycled PID. + if (!isProcessAlive(pid)) return await finishWithOrphanSweep('already_gone'); + const trackedMarker = persistedResumeProcesses.get(pid)?.processStartMarker; + if (trackedMarker && getProcessStartMarker(pid) !== trackedMarker) return 'unknown'; const reportStop: Parameters[2] = report => { logger.debug('[RUNNER RUN] Windows tree stop confirmation', { sessionId, pid, ...report }); }; const treeStopped = session.childProcess - ? await killProcessByChildProcess(session.childProcess, false, reportStop) - : await killProcessTreeByPid(pid, false, reportStop); + ? await killProcessByChildProcess(session.childProcess, false, reportStop, signalDeadlines.get(pid)) + : await killProcessTreeByPid(pid, false, reportStop, signalDeadlines.get(pid)); if (!treeStopped) { logger.debug(`[RUNNER RUN] Process tree for session ${sessionId} is still alive after stop request`); return 'still_alive'; @@ -1525,7 +1570,9 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } else { // For externally started sessions, try to kill by PID try { - if (!(await killProcess(pid))) return 'still_alive'; + if (!await prepareSessionStop(sessionId, pid)) return 'still_alive'; + if (!isProcessAlive(pid)) return await finishWithOrphanSweep('already_gone'); + if (!(await killProcess(pid, false, signalDeadlines.get(pid)))) return 'still_alive'; terminated.add(pid); logger.debug(`[RUNNER RUN] Requested termination for external session PID ${pid}`); } catch (error) { @@ -1603,7 +1650,12 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): ); return decision; } - if (!(await killProcessTreeByPid(pid))) return 'still_alive'; + if (!await prepareSessionStop(sessionId, pid, persisted.processStartMarker)) return 'still_alive'; + // Preparation can outlive the target generation (same recheck as + // the raw-PID path): never signal a dead or recycled PID. + if (!isProcessAlive(pid)) return await finishWithOrphanSweep('already_gone'); + if (persisted.processStartMarker && getProcessStartMarker(pid) !== persisted.processStartMarker) return 'unknown'; + if (!(await killProcessTreeByPid(pid, false, undefined, signalDeadlines.get(pid)))) return 'still_alive'; terminated.add(pid); if (requestedSessionId) rememberVerifiedExit(requestedSessionId); if (confirmedSessionId) rememberVerifiedExit(confirmedSessionId); @@ -1636,6 +1688,9 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): sessionId ); const orphanStatus = await reapRunnerSpawnedOrphans(sessionId, { + killTree: (pid) => killProcessTreeByPid(pid, false, undefined, signalDeadlines.get(pid)), + prepare: (target) => target.needsPublicationDrain === false ? Promise.resolve(true) + : prepareSessionStop(sessionId, target.pid, target.startMarker ?? undefined), findTargets: (id) => findStopSessionOrphanTargets( id, (sid, pid) => shouldSkipOrphanPid(liveRuntimes, protectedTrackedPids, sid, pid) diff --git a/cli/src/utils/MessageQueue2.ts b/cli/src/utils/MessageQueue2.ts index 010ec777..8fe39867 100644 --- a/cli/src/utils/MessageQueue2.ts +++ b/cli/src/utils/MessageQueue2.ts @@ -40,6 +40,8 @@ export class MessageQueue2 { private closed = false; private onMessageHandler: ((message: string, mode: T) => void) | null = null; onBatchConsumed: ((localIds: string[]) => void) | null = null; + /** Optional synchronous admission, before removing or acknowledging a batch. */ + beforeDequeue: (() => void) | null = null; modeHasher: (mode: T) => string; private readonly reservations = new Map>(); private readonly consumedReservations = new Set(); @@ -625,6 +627,8 @@ export class MessageQueue2 { return null; } + this.beforeDequeue?.(); + const firstItem = this.queue[0]; const sameModeMessages: string[] = []; const consumedLocalIds: string[] = []; diff --git a/cli/src/utils/process.test.ts b/cli/src/utils/process.test.ts index 036d2802..f630be03 100644 --- a/cli/src/utils/process.test.ts +++ b/cli/src/utils/process.test.ts @@ -10,7 +10,12 @@ vi.mock('cross-spawn', () => ({ } })) -import { getHapiRunnerProcessIdentity, killProcess } from './process' +import { getHapiRunnerProcessIdentity, killProcess, killProcessTreeByPid } from './process' +import { monotonicTimeMs } from './time' + +vi.mock('@/utils/time', async (original) => ({ + ...await original(), monotonicTimeMs: () => Date.now() +})) const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform') @@ -40,6 +45,31 @@ function unavailable(command: string) { } } +describe('preparation signal deadline on POSIX', () => { + beforeEach(() => { + setPlatform('linux') + vi.useFakeTimers() + spawnSyncMock.mockReset() + spawnSyncMock.mockReturnValue({ status: 1, stdout: '', stderr: '' }) + vi.spyOn(process, 'kill').mockReturnValue(true) + }) + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + if (originalPlatformDescriptor) Object.defineProperty(process, 'platform', originalPlatformDescriptor) + }) + it('does not signal a tree after its preparation authorization expired', async () => { + expect(await killProcessTreeByPid(5544, false, undefined, monotonicTimeMs() - 1)).toBe(false) + expect(vi.mocked(process.kill).mock.calls.filter(([, signal]) => signal !== 0)).toEqual([]) + }) + it('does not escalate to SIGKILL after the lease expires during the graceful wait', async () => { + const stopped = killProcess(5544, false, monotonicTimeMs() + 100) + await vi.advanceTimersByTimeAsync(2500) + expect(await stopped).toBe(false) + expect(vi.mocked(process.kill).mock.calls.filter(([, signal]) => signal !== 0)).toEqual([[5544, 'SIGTERM']]) + }) +}) + describe('getHapiRunnerProcessIdentity on Windows', () => { it.each(['', '[]', '{}', '{broken', JSON.stringify([{ ProcessId: 100, CreationDate: 'generation' }]), JSON.stringify([{ ProcessId: process.pid }, { ProcessId: process.pid }]), @@ -293,6 +323,50 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => { } }) + it('retains the upstream stop report while an expired lease prevents signalling', async () => { + const reports: Array = [] + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'tasklist') return completed('hapi.exe 5544 Console') + if (cmd === 'powershell') return completed(args.join(' ').includes('$children=') ? 'OK:5544' : 'generation') + return completed('') + }) + const stopped = killProcessTreeByPid(5544, false, (report) => reports.push(report), monotonicTimeMs() - 1) + await vi.advanceTimersByTimeAsync(2500) + expect(await stopped).toBe(false) + expect(spawnSyncMock.mock.calls.filter(([cmd]) => cmd === 'taskkill')).toHaveLength(0) + expect(reports).toHaveLength(1) + expect(reports[0]).toMatchObject({ confirmed: false, phase: 'initial-snapshot' }) + }) + + it.each([false, true])('does not invoke taskkill when authority expires inside its liveness probe (force=%s)', async (force) => { + const deadline = monotonicTimeMs() + 100 + let delayed = false + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') { + if (!delayed) { delayed = true; vi.advanceTimersByTime(100) } + return completed('hapi.exe 5544 Console') + } + return completed('') + }) + const stopped = killProcess(5544, force, deadline) + await vi.advanceTimersByTimeAsync(2500) + expect(await stopped).toBe(false) + expect(spawnSyncMock.mock.calls.filter(([cmd]) => cmd === 'taskkill')).toHaveLength(0) + }) + + it('does not force taskkill when preparation expires during a refused soft signal', async () => { + const deadline = monotonicTimeMs() + 100 + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return completed('hapi.exe 5544 Console') + if (cmd === 'taskkill') { vi.advanceTimersByTime(100); return completed('', 1) } + return completed('') + }) + const stopped = killProcess(5544, false, deadline) + await vi.advanceTimersByTimeAsync(2500) + expect(await stopped).toBe(false) + expect(spawnSyncMock.mock.calls.filter(([cmd]) => cmd === 'taskkill')).toHaveLength(1) + }) + it('escalates soft taskkill to /F when the process stays alive (mirrors SIGTERM→SIGKILL)', async () => { // Soft taskkill on win32 console trees often fails with // "can only be terminated forcefully" — orphanReap must escalate. diff --git a/cli/src/utils/process.ts b/cli/src/utils/process.ts index 2e366261..3ca42cd6 100644 --- a/cli/src/utils/process.ts +++ b/cli/src/utils/process.ts @@ -1,6 +1,7 @@ import type { ChildProcess } from 'node:child_process'; import spawn from 'cross-spawn'; import { readFileSync } from 'node:fs'; +import { monotonicTimeMs } from '@/utils/time'; import { stopWindowsProcessTree, type WindowsStopReport } from './windowsProcessStop'; export const isWindows = (): boolean => process.platform === 'win32'; @@ -233,10 +234,11 @@ function getPosixProcessCommandLine(pid: number): string | null { return commandLine.trim() ? commandLine : null; } -function killProcessWindows(pid: number, force: boolean): boolean { +function killProcessWindows(pid: number, force: boolean, deadlineMs?: number): boolean { if (!isProcessAlive(pid)) { return true; } + if (!signalAllowed(deadlineMs)) return false; const args = ['/T', '/PID', pid.toString()]; if (force) { @@ -343,22 +345,27 @@ export function collectWindowsProcessTree(pid: number): number[] | 'scan_failed' return parseWindowsProcessTreeStdout((result.stdout ?? '').toString(), n) } -async function signalAndWaitWindowsRoot(pid: number, force: boolean): Promise { - if (force) { - killProcessWindows(pid, true); - await waitForProcessToDie(pid, true); - return; - } - const softOk = killProcessWindows(pid, false); - if (!softOk && isProcessAlive(pid)) { - killProcessWindows(pid, true); - await waitForProcessToDie(pid, true); - return; - } - await waitForProcessToDie(pid, false); +function signalAllowed(deadlineMs?: number): boolean { + return deadlineMs === undefined || monotonicTimeMs() < deadlineMs; } -export async function killProcess(pid: number, force: boolean = false): Promise { +async function signalAndWaitWindowsRoot(pid: number, force: boolean, deadlineMs?: number): Promise { + if (!signalAllowed(deadlineMs)) return; + if (force) { + killProcessWindows(pid, true, deadlineMs); + await waitForProcessToDie(pid, true, deadlineMs); + return; + } + const softOk = killProcessWindows(pid, false, deadlineMs); + if (!softOk && isProcessAlive(pid) && signalAllowed(deadlineMs)) { + killProcessWindows(pid, true, deadlineMs); + await waitForProcessToDie(pid, true, deadlineMs); + return; + } + await waitForProcessToDie(pid, false, deadlineMs); +} + +export async function killProcess(pid: number, force: boolean = false, deadlineMs?: number): Promise { const n = typeof pid === 'number' ? pid : Number(pid) if (!Number.isFinite(n) || n <= 0) { return false; @@ -371,14 +378,15 @@ export async function killProcess(pid: number, force: boolean = false): Promise< // but the PID is still draining, honor the grace wait before /F so archive // flush can finish. // Root-only verify — callers that need full-tree proof use killProcessTreeByPid. - await signalAndWaitWindowsRoot(n, force); + await signalAndWaitWindowsRoot(n, force, deadlineMs); return !isProcessAlive(n); } try { + if (!signalAllowed(deadlineMs)) return !isProcessAlive(n); process.kill(n, force ? 'SIGKILL' : 'SIGTERM'); - await waitForProcessToDie(n, force); - return true; + await waitForProcessToDie(n, force, deadlineMs); + return deadlineMs === undefined || !isProcessAlive(n); } catch { return false; } @@ -425,11 +433,8 @@ function collectProcessTree(pid: number): number[] | 'scan_failed' { * Signals are sent synchronously (children first) to work in exit handlers, * then waits asynchronously for processes to die. */ -async function killProcessTree( - pid: number, - force: boolean, - signal: NodeJS.Signals = 'SIGTERM' -): Promise { +async function killProcessTree(pid: number, force: boolean, deadlineMs?: number, + signal: NodeJS.Signals = 'SIGTERM'): Promise { // Collect all PIDs first (sync) - returns in child-first order const pids = collectProcessTree(pid); if (pids === 'scan_failed') { @@ -437,11 +442,12 @@ async function killProcessTree( // stopped without a full-tree verify (#1911 Opus Major / debian-slim no pgrep). const killSignal = force ? 'SIGKILL' : signal; try { + if (!signalAllowed(deadlineMs)) return false; process.kill(pid, killSignal); } catch { // already gone } - await waitForProcessToDie(pid, force); + await waitForProcessToDie(pid, force, deadlineMs); return false; } @@ -451,6 +457,7 @@ async function killProcessTree( const killSignal = force ? 'SIGKILL' : signal; for (const p of pids) { try { + if (!signalAllowed(deadlineMs)) return false; process.kill(p, killSignal); } catch { // Process may have already exited @@ -459,7 +466,7 @@ async function killProcessTree( // Wait for processes to die (async) - wait for root last for (const p of pids) { - await waitForProcessToDie(p, force); + await waitForProcessToDie(p, force, deadlineMs); } return pids.every((candidate) => !isProcessAlive(candidate)); @@ -471,23 +478,29 @@ export async function killProcessTreeByPid( force: boolean = false, // 3rd arg: soft POSIX signal (#1424 job Ctrl-C → exit 130) OR Windows stop report (#1911). signalOrReport: NodeJS.Signals | ((report: WindowsStopReport) => void) = 'SIGTERM', - onReportMaybe?: (report: WindowsStopReport) => void + // 4th arg: stop deadline (signal-lease budget) when numeric, else the Windows + // report fallback used when the 3rd arg is a signal (#1911). + deadlineOrFallbackReport?: number | ((report: WindowsStopReport) => void), + fallbackReport?: (report: WindowsStopReport) => void ): Promise { - const signal: NodeJS.Signals = typeof signalOrReport === 'function' ? 'SIGTERM' : signalOrReport - const onReport = typeof signalOrReport === 'function' ? signalOrReport : onReportMaybe + const deadlineMs = typeof deadlineOrFallbackReport === 'number' ? deadlineOrFallbackReport : undefined; + const onReport = typeof signalOrReport === 'function' ? signalOrReport + : typeof deadlineOrFallbackReport === 'function' ? deadlineOrFallbackReport + : fallbackReport; + const signal: NodeJS.Signals = typeof signalOrReport === 'function' ? 'SIGTERM' : signalOrReport; const n = typeof pid === 'number' ? pid : Number(pid) if (!Number.isFinite(n) || n <= 0) return false; if (isWindows()) { - return stopWindowsProcessTree(n, force, onReport); + return stopWindowsProcessTree(n, force, onReport, deadlineMs); } - return killProcessTree(n, force, signal); + return killProcessTree(n, force, deadlineMs, signal); } /** * Waits for a process to die, escalating if the graceful signal didn't work. * POSIX: SIGTERM → SIGKILL. Windows: taskkill /T → taskkill /F /T. */ -async function waitForProcessToDie(pid: number, force: boolean): Promise { +async function waitForProcessToDie(pid: number, force: boolean, deadlineMs?: number): Promise { const maxWait = 2000; // Windows isProcessAlive shells out to tasklist; keep the poll coarse so a // stop cannot burn the runner event loop for seconds (#1911 Overseer). @@ -504,10 +517,10 @@ async function waitForProcessToDie(pid: number, force: boolean): Promise { } // Graceful kill didn't finish — escalate (same structure on both platforms). - if (!force && isProcessAlive(pid)) { + if (!force && isProcessAlive(pid) && signalAllowed(deadlineMs)) { try { if (isWindows()) { - killProcessWindows(pid, true); + killProcessWindows(pid, true, deadlineMs); } else { process.kill(pid, 'SIGKILL'); } @@ -527,13 +540,16 @@ export async function killProcessByChildProcess( child: ChildProcess, force: boolean = false, signalOrReport: NodeJS.Signals | ((report: WindowsStopReport) => void) = 'SIGTERM', - onReportMaybe?: (report: WindowsStopReport) => void + deadlineOrFallbackReport?: number | ((report: WindowsStopReport) => void), + fallbackReport?: (report: WindowsStopReport) => void ): Promise { const pid = child.pid; if (!pid) { return false; } - // Soft signal forwarded on POSIX so job Ctrl-C stays exit 130 (#1424). - return killProcessTreeByPid(pid, force, signalOrReport, onReportMaybe); + // Both platforms: tree-kill + full-tree verify (win32 must not trust + // root-only). The soft signal rides along on POSIX so job Ctrl-C stays + // exit 130 (#1424). + return killProcessTreeByPid(pid, force, signalOrReport, deadlineOrFallbackReport, fallbackReport); } diff --git a/cli/src/utils/time.ts b/cli/src/utils/time.ts index 01f00326..090ec1a5 100644 --- a/cli/src/utils/time.ts +++ b/cli/src/utils/time.ts @@ -1,3 +1,10 @@ +import { uptime } from 'node:os'; + +/** OS-wide clock; whole seconds also match Bun's uptime precision across processes. */ +export function monotonicTimeMs(): number { + return Math.floor(uptime()) * 1000; +} + export async function delay(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); } @@ -105,4 +112,4 @@ export async function withRetry( await delay(nextDelayMs) } } -} \ No newline at end of file +} diff --git a/cli/src/utils/windowsProcessStop.test.ts b/cli/src/utils/windowsProcessStop.test.ts index 48fb1b2e..4fdb2e6d 100644 --- a/cli/src/utils/windowsProcessStop.test.ts +++ b/cli/src/utils/windowsProcessStop.test.ts @@ -1,8 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { execFileMock, syncMock } = vi.hoisted(() => ({ execFileMock: vi.fn(), syncMock: vi.fn() })) +const authority = vi.hoisted(() => ({ now: 0 })) vi.mock('node:child_process', () => ({ execFile: execFileMock })) vi.mock('cross-spawn', () => ({ default: { sync: syncMock } })) +vi.mock('./time', () => ({ monotonicTimeMs: () => authority.now })) import { killProcessTreeByPid } from './process' import { readWindowsProcessTable, windowsGenerationMayBeAlive } from './windowsProcessStop' @@ -20,6 +22,7 @@ describe('Windows asynchronous tree stop', () => { beforeEach(() => { Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) rows = [row(0, 0, null), row(100), row(200, 100)] + authority.now = 0 kills = [] rejectSoft = false onKill = pid => { rows = rows.filter(p => p.ProcessId !== pid) } @@ -50,6 +53,100 @@ describe('Windows asynchronous tree stop', () => { expect(syncMock).not.toHaveBeenCalled() }) + it('retains the upstream stop report while an expired lease prevents signalling', async () => { + const reports: Array = [] + authority.now = 100 + expect(await killProcessTreeByPid(100, true, report => reports.push(report), 100)).toBe(false) + expect(kills).toEqual([]) + expect(reports).toEqual([expect.objectContaining({ confirmed: false, phase: 'initial-snapshot' })]) + expect(syncMock).not.toHaveBeenCalled() + }) + + it.each([1, 2])('does not signal after caller authority expires during async snapshot %s', async scan => { + let scans = 0 + const implementation = execFileMock.getMockImplementation()! + execFileMock.mockImplementation((file, ...args) => { + if (file === 'powershell' && ++scans === scan) authority.now = 100 + return implementation(file, ...args) + }) + expect(await killProcessTreeByPid(100, true, undefined, 100)).toBe(false) + expect(kills).toEqual([]) + }) + + it.each([false, true])('rejects a deferred generation snapshot completed after lease expiry (force=%s)', async force => { + let scans = 0 + let snapshotBudget = 0 + let resumeSnapshot!: () => void + let snapshotStarted!: () => void + const pendingSnapshot = new Promise(resolve => { snapshotStarted = resolve }) + const implementation = execFileMock.getMockImplementation()! + execFileMock.mockImplementation((file, args, options, callback) => { + if (file === 'powershell' && ++scans === 2) { + snapshotBudget = options.timeout + resumeSnapshot = () => callback(null, JSON.stringify({ complete: true, processes: rows }), '') + snapshotStarted() + return { kill: vi.fn() } + } + return implementation(file, args, options, callback) + }) + const operation = killProcessTreeByPid(100, force, undefined, 100) + await pendingSnapshot + expect(authority.now).toBe(0) + expect(execFileMock.mock.calls.filter(([file]) => file === 'taskkill')).toEqual([]) + authority.now = 100 + resumeSnapshot() + expect(await operation).toBe(false) + expect(snapshotBudget).toBeLessThanOrEqual(100) + expect(execFileMock.mock.calls.filter(([file]) => file === 'taskkill')).toEqual([]) + expect(kills).toEqual([]) + expect(syncMock).not.toHaveBeenCalled() + }) + + it('caps async OS query budgets by remaining caller authority', async () => { + const budgets: number[] = [] + const implementation = execFileMock.getMockImplementation()! + execFileMock.mockImplementation((file, args, options, callback) => { + budgets.push(options.timeout) + return implementation(file, args, options, callback) + }) + expect(await killProcessTreeByPid(100, true, undefined, 100)).toBe(true) + expect(budgets.length).toBeGreaterThan(0) + expect(budgets.every(budget => budget > 0 && budget <= 100)).toBe(true) + }) + + it('does not escalate a refused soft stop after its caller lease expires', async () => { + rejectSoft = true + onKill = (_pid, force) => { + if (!force) { authority.now = 100; rows.push(row(300, 100)) } + else rows = [row(0, 0, null)] + } + expect(await killProcessTreeByPid(100, false, undefined, 100)).toBe(false) + expect(kills).toEqual([{ pid: 100, force: false, tree: true }]) + }) + + it('does not signal surviving descendants after authority expires following root exit', async () => { + onKill = pid => { + rows = rows.filter(p => p.ProcessId !== pid) + if (pid === 100) authority.now = 100 + } + expect(await killProcessTreeByPid(100, true, undefined, 100)).toBe(false) + expect(kills).toEqual([{ pid: 100, force: true, tree: true }]) + }) + + it('does not use the CIM fallback root probe after its caller lease expires', async () => { + execFileMock.mockImplementation((file, args, _options, callback) => { + queueMicrotask(() => { + if (file === 'powershell') { + if (String(args.at(-1)).includes('Get-CimInstance')) callback(new Error('CIM failed'), '', '') + else { authority.now = 100; callback(null, JSON.stringify({ complete: true, processes: [row(100)] }), '') } + } else { kills.push({ pid: 100, force: true, tree: true }); callback(null, '', '') } + }) + return { kill: vi.fn() } + }) + expect(await killProcessTreeByPid(100, true, undefined, 100)).toBe(false) + expect(kills).toEqual([]) + }) + it('does not terminate a PID reused after the original descendant exits', async () => { onKill = pid => { rows = rows.filter(p => p.ProcessId !== pid) diff --git a/cli/src/utils/windowsProcessStop.ts b/cli/src/utils/windowsProcessStop.ts index b084007a..ae90eb52 100644 --- a/cli/src/utils/windowsProcessStop.ts +++ b/cli/src/utils/windowsProcessStop.ts @@ -1,4 +1,5 @@ import { execFile } from 'node:child_process' +import { monotonicTimeMs } from './time' export type WindowsProcessEntry = { parentPid: number; marker: string | null; name: string; commandLine: string } export type WindowsProcessTable = Map @@ -76,7 +77,8 @@ export function windowsGenerationMayBeAlive(table: WindowsProcessTable | null, p } export type WindowsStopReport = { confirmed: boolean; phase: string; elapsedMs: number; snapshots: number } -export async function stopWindowsProcessTree(rootPid: number, force: boolean, report?: (result: WindowsStopReport) => void): Promise { +export async function stopWindowsProcessTree(rootPid: number, force: boolean, report?: (result: WindowsStopReport) => void, + callerDeadlineMs?: number): Promise { // Includes command startup, queries, signalling and verification, independent // of tree size. Each async child is killed when its remaining budget expires. const started = performance.now() @@ -86,13 +88,17 @@ export async function stopWindowsProcessTree(rootPid: number, force: boolean, re report?.({ confirmed, phase, elapsedMs: Math.round(performance.now() - started), snapshots }) return confirmed } - const remaining = () => Math.max(0, deadline - performance.now()) + // The cross-process preparation lease uses the OS-wide clock, not this + // process's performance origin. Cap budgets without comparing origins. + const remaining = () => Math.max(0, Math.min(deadline - performance.now(), + callerDeadlineMs === undefined ? Infinity : callerDeadlineMs - monotonicTimeMs())) const signal = async (pid: number, hard: boolean, tree: boolean) => { phase = 'signal' return execute('taskkill', [ ...(hard ? ['/F'] : []), ...(tree ? ['/T'] : []), '/PID', String(pid), ], Math.min(5_000, remaining())) } + if (!remaining()) return finish(false) const initial = await readWindowsProcessTable(Math.min(15_000, remaining())) if (!initial) { // A transient CIM failure must not leave the cancellation path with no @@ -137,7 +143,7 @@ export async function stopWindowsProcessTree(rootPid: number, force: boolean, re if (unresolved.has(rootPid) && rootMarker && current.get(rootPid)?.marker === rootMarker) { const softAccepted = await signal(rootPid, force, true) if (!force && softAccepted !== null) { - const graceDeadline = Math.min(deadline, performance.now() + 2_000) + const graceDeadline = performance.now() + Math.min(2_000, remaining()) while (unresolved.size && performance.now() < graceDeadline) { current = await snapshot() if (!current) return finish(false) diff --git a/e2e/opencode-fork-buttons.spec.ts b/e2e/opencode-fork-buttons.spec.ts new file mode 100644 index 00000000..3d152ae2 --- /dev/null +++ b/e2e/opencode-fork-buttons.spec.ts @@ -0,0 +1,103 @@ +import { expect, test } from '@playwright/test' + +// OpenCode-flavor historical fork affordance: with conversationHistory +// points on every completed user turn, the Fork button must render on +// every historical user message that has a point — not only on the last +// message. The latest completed boundary keeps current-fork-only behavior. +// Holds in both `tail` and `history` view modes. +test('historical fork buttons render on every user message with a history point', async ({ page }) => { + await page.goto('/e2e-fixtures/opencode-fork-buttons-fixture.html') + const userMessages = page.locator('[data-hapi-message-role="user"]') + await expect(userMessages).toHaveCount(12, { timeout: 15_000 }) + + const expectForksOnEveryUserCard = async () => { + const count = await userMessages.count() + expect(count).toBe(12) + for (let index = 0; index < count; index += 1) { + const card = userMessages.nth(index) + await expect(card.getByTestId('message-fork')).toHaveCount(1) + await expect(card.getByTestId('message-fork')).toBeVisible() + } + } + + // Tail mode: every pointed user card renders its historical Fork button. + await expectForksOnEveryUserCard() + + // The latest completed boundary keeps only-current behavior: it is an + // assistant card (not a user card) and carries a single Fork button + // that forks the current conversation rather than a historical point. + const boundaryId = await page.evaluate(() => window.__probe.boundaryId) + expect(typeof boundaryId).toBe('string') + expect(boundaryId).toMatch(/^agent-text:/) + const boundaryForkCount = await page.evaluate((id) => { + const anchor = document.getElementById(`hapi-message-${id}`) + return anchor?.querySelectorAll('[data-testid="message-fork"]').length ?? -1 + }, boundaryId) + expect(boundaryForkCount).toBe(1) + + // History mode: scroll away from the bottom, then the remembered tail + // boundary still applies and every pointed user card keeps its button. + const viewport = page.locator('.app-scroll-y') + await expect(viewport).toBeVisible() + const overflow = await page.evaluate(() => { + const el = document.querySelector('.app-scroll-y') as HTMLElement + return { scrollHeight: el.scrollHeight, clientHeight: el.clientHeight, scrollTop: el.scrollTop } + }) + expect(overflow.scrollHeight).toBeGreaterThan(overflow.clientHeight) + expect(overflow.scrollTop).toBeGreaterThan(0) + // Scroll away from the bottom with a real wheel gesture: the smart-scroll + // controller only honors explicit upward intent (wheel/pointer) as a mode + // switch, and programmatic scrollTop can be swallowed by initial settling. + await viewport.hover() + for (let i = 0; i < 12; i += 1) { + await page.mouse.wheel(0, -800) + await page.waitForTimeout(100) + } + await expect.poll(async () => await page.evaluate(() => window.__probe.viewMode)).toBe('history') + await expectForksOnEveryUserCard() + const historyBoundaryId = await page.evaluate(() => window.__probe.boundaryId) + expect(historyBoundaryId).toBe(boundaryId) +}) + +test('historical assistant replies fork at the next user boundary; latest forks current', async ({ page }, testInfo) => { + await page.goto('/e2e-fixtures/opencode-fork-buttons-fixture.html') + const replies = page.locator('[data-hapi-message-role="assistant"]') + await expect(replies).toHaveCount(12) + for (let i = 0; i < 12; i += 1) { + await expect(replies.nth(i).getByTestId('message-fork')).toHaveCount(1) + } + await page.waitForTimeout(2000) + await replies.nth(2).hover() + await replies.nth(2).getByTestId('message-fork').click() + await page.getByRole('dialog').getByRole('button', { name: 'Fork', exact: true }).click() + await expect.poll(() => page.evaluate(() => window.__probe.forkCalls)).toEqual(['u-local-4']) + await replies.nth(2).hover() + await page.screenshot({ path: testInfo.outputPath('historical-fork-fixed.png') }) + await replies.last().hover() + await replies.last().getByTestId('message-fork').click() + await page.getByRole('dialog').getByRole('button', { name: 'Fork', exact: true }).click() + await expect.poll(() => page.evaluate(() => window.__probe.forkCalls)).toEqual(['u-local-4', undefined]) +}) + +test('does not offer an assistant fork across a missing native boundary', async ({ page }) => { + await page.goto('/e2e-fixtures/opencode-fork-buttons-fixture.html?missingPoint=1') + const replies = page.locator('[data-hapi-message-role="assistant"]') + await expect(replies).toHaveCount(12) + await expect(replies.nth(2).getByTestId('message-fork')).toHaveCount(0) + await expect(replies.nth(1).getByTestId('message-fork')).toHaveCount(1) + await expect(replies.last().getByTestId('message-fork')).toHaveCount(1) +}) + +test('reasoning replies keep historical fork controls on the rendered card', async ({ page }) => { + await page.goto('/e2e-fixtures/opencode-fork-buttons-fixture.html?reasoning=1') + const replies = page.locator('[data-hapi-message-role="assistant"]') + await expect(replies).toHaveCount(12) + for (let i = 0; i < 12; i += 1) { + await expect(replies.nth(i).getByTestId('message-fork')).toHaveCount(1) + } + await page.waitForTimeout(2000) + await replies.nth(2).hover() + await replies.nth(2).getByTestId('message-fork').click() + await page.getByRole('dialog').getByRole('button', { name: 'Fork', exact: true }).click() + await expect.poll(() => page.evaluate(() => window.__probe.forkCalls)).toEqual(['u-local-4']) +}) diff --git a/hub/src/socket/handlers/cli/sessionHandlers.test.ts b/hub/src/socket/handlers/cli/sessionHandlers.test.ts index 13f7dc7f..0c95a99d 100644 --- a/hub/src/socket/handlers/cli/sessionHandlers.test.ts +++ b/hub/src/socket/handlers/cli/sessionHandlers.test.ts @@ -493,9 +493,10 @@ describe('cli session handlers', () => { expect(uuids).toEqual(['msg-1', 'msg-2']) }) - it.each([ +it.each([ ['supersededBySessionId', 'foreign-session'], ['opencodeClearOperation', { replacementSessionId: 'foreign-session', state: 'reserved', updatedAt: Date.now() }], + ['opencodeForkPending', true], ['titleSuggestionAutoAttemptedAt', 1234], ['titleSuggestionTurn', { first: false, completed: true }], ['promptTitle', 'Forged title'], @@ -531,6 +532,7 @@ describe('cli session handlers', () => { const session = store.sessions.getOrCreateSession('preserve-clear-link', { supersededBySessionId: 'owned-target', opencodeClearOperation: operation, + opencodeForkPending: true, jobsAcceptedFromSessionIds: ['old-session'], jobsTransferredToSessionId: 'merge-target', jobKeyRedirects: { 'old-session/beets': 'beets.oldsess1' }, @@ -546,7 +548,7 @@ describe('cli session handlers', () => { expectedVersion: session.metadataVersion, metadata: { lifecycleState: 'archived', - supersededBySessionId: 'forged-target', + supersededBySessionId: 'forged-target', opencodeForkPending: false, opencodeClearOperation: { replacementSessionId: 'forged-target', state: 'reserved', updatedAt: 0 }, jobsAcceptedFromSessionIds: ['forged-session'], jobsTransferredToSessionId: 'forged-target', @@ -556,6 +558,7 @@ describe('cli session handlers', () => { expect(store.sessions.getSessionByNamespace(session.id, 'default')?.metadata).toMatchObject({ supersededBySessionId: 'owned-target', opencodeClearOperation: operation, + opencodeForkPending: true, jobsAcceptedFromSessionIds: ['old-session'], jobsTransferredToSessionId: 'merge-target', jobKeyRedirects: { 'old-session/beets': 'beets.oldsess1' }, diff --git a/hub/src/socket/handlers/cli/sessionHandlers.ts b/hub/src/socket/handlers/cli/sessionHandlers.ts index 5eb80605..3b212170 100644 --- a/hub/src/socket/handlers/cli/sessionHandlers.ts +++ b/hub/src/socket/handlers/cli/sessionHandlers.ts @@ -71,8 +71,10 @@ const updateStateSchema = z.object({ // Hub-only merge/clear/title links. CLI update-metadata must not forge or erase them // (same strip/restore as supersededBySessionId — see sessionHandlers.test.ts). const HUB_OWNED_METADATA_KEYS = [ + 'opencodeRewind', 'supersededBySessionId', 'opencodeClearOperation', + 'opencodeForkPending', 'titleSuggestionAutoAttemptedAt', 'titleSuggestionTurn', 'jobsAcceptedFromSessionIds', @@ -91,6 +93,10 @@ function preserveHubOwnedMetadata(incoming: unknown, current: unknown): unknown if (Object.prototype.hasOwnProperty.call(existing, key)) next[key] = existing[key] else delete next[key] } + const rewind = existing.opencodeRewind as { phase?: string } | undefined + if (rewind && ['reserved', 'prepared', 'unknown'].includes(rewind.phase ?? '')) { + for (const key of ['opencodeHistoryCheckpoint', 'conversationHistoryIndexes', 'conversationHistoryPoints']) next[key] = existing[key] + } return next } diff --git a/hub/src/store/messageStore.ts b/hub/src/store/messageStore.ts index baf4e729..9b4f2f7f 100644 --- a/hub/src/store/messageStore.ts +++ b/hub/src/store/messageStore.ts @@ -46,6 +46,7 @@ import { getMessageSeqById, getMessageById, truncateMessagesFromLocalId, + truncateOpenCodeRewind, type CancelQueuedMessageResult, type LookupQueuedMessageResult, type LocalMessageState, @@ -67,6 +68,10 @@ export class MessageStore { this.db = db } + truncateOpenCodeRewind(sessionId: string, cutoffSeq: number, boundaryId: string): number { + return truncateOpenCodeRewind(this.db, sessionId, cutoffSeq, boundaryId) + } + addMessage(sessionId: string, content: unknown, localId?: string, scheduledAt?: number | null, createdAt?: number): StoredMessage { return addMessage(this.db, sessionId, content, localId, scheduledAt, createdAt) } diff --git a/hub/src/store/messages.truncate.test.ts b/hub/src/store/messages.truncate.test.ts index 128d2cc1..20c7741d 100644 --- a/hub/src/store/messages.truncate.test.ts +++ b/hub/src/store/messages.truncate.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'bun:test' +import type { Database } from 'bun:sqlite' import { Store } from './index' describe('truncateMessagesFromLocalId', () => { @@ -26,3 +27,66 @@ describe('truncateMessagesFromLocalId', () => { expect(remaining.some((message) => message.localId === 'local-1')).toBe(true) }) }) + +describe('truncateOpenCodeRewind invocation position', () => { + for (const cutoffFirst of [true, false]) { + it(`removes the invocation suffix when ${cutoffFirst ? 'the boundary' : 'a later turn'} was inserted first`, () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('ordered-rewind', { path: '/tmp' }, null, 'default') + const at = Date.now() - 10_000 + const input = (localId: string, created: number, invoked: number) => { + const message = store.messages.addMessage(session.id, + { role: 'user', content: { type: 'text', text: localId } }, localId, at + invoked, at + created) + store.messages.markMessagesInvoked(session.id, [localId], at + invoked) + return message + } + try { + const first = input(cutoffFirst ? 'boundary' : 'later', 0, cutoffFirst ? 300 : 400) + const prefix = input('prefix', 100, 100) + const second = input(cutoffFirst ? 'later' : 'boundary', 200, cutoffFirst ? 400 : 300) + const boundary = cutoffFirst ? first : second + const beforeEpoch = store.messages.getMessageEpoch(session.id) + expect(store.messages.truncateOpenCodeRewind(session.id, boundary.seq, boundary.id)).toBe(beforeEpoch + 1) + expect(store.messages.getAllMessages(session.id).map(message => message.id)).toEqual([prefix.id]) + expect(store.messages.searchContentInSession('prefix', 'default', session.id).matches.map(match => match.messageId)).toEqual([prefix.id]) + expect(store.messages.searchContent('boundary', 'default')).toEqual([]) + expect(store.messages.searchContent('later', 'default')).toEqual([]) + } finally { store.close() } + }) + } + + it('uses created_at for null invocation times and seq to break equal-position ties', () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('rewind-ties', { path: '/tmp' }, null, 'default') + const db = (store as unknown as { db: Database }).db + const at = Date.now() - 10_000 + try { + const add = (text: string) => store.messages.addMessage(session.id, + { role: 'agent', content: { type: 'text', text } }, undefined, undefined, at) + const prefix = add('tieprefix') + const boundary = add('tieboundary') + const suffix = add('tiesuffix') + db.query('UPDATE messages SET invoked_at = NULL WHERE id IN (?, ?)').run(prefix.id, suffix.id) + store.messages.truncateOpenCodeRewind(session.id, boundary.seq, boundary.id) + expect(store.messages.getAllMessages(session.id).map(message => message.id)).toEqual([prefix.id]) + } finally { store.close() } + }) + + it('refuses a missing session boundary without deleting rows or bumping epoch', () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('missing-rewind', { path: '/tmp' }, null, 'default') + try { + const first = store.messages.addMessage(session.id, { role: 'agent', content: 'keep' }) + const second = store.messages.addMessage(session.id, { role: 'agent', content: 'also keep' }) + const otherSession = store.sessions.getOrCreateSession('other-rewind', { path: '/tmp' }, null, 'other') + const other = store.messages.addMessage(otherSession.id, { role: 'agent', content: 'other session' }) + const before = store.messages.getAllMessages(session.id) + const epoch = store.messages.getMessageEpoch(session.id) + for (const [seq, id] of [[999, first.id], [first.seq, second.id], [first.seq, other.id]] as const) { + expect(() => store.messages.truncateOpenCodeRewind(session.id, seq, id)).toThrow('Rewind boundary not found') + } + expect(store.messages.getAllMessages(session.id)).toEqual(before) + expect(store.messages.getMessageEpoch(session.id)).toBe(epoch) + } finally { store.close() } + }) +}) diff --git a/hub/src/store/messages.ts b/hub/src/store/messages.ts index f159ffca..480cf73d 100644 --- a/hub/src/store/messages.ts +++ b/hub/src/store/messages.ts @@ -1459,10 +1459,38 @@ export function mergeSessionMessages( } /** - * Truncate transcript at/after the message with `localId`, optionally replacing - * the removed suffix with `replacement` messages. Bumps message epoch so web - * clients reset their window. + * Truncate the invocation-ordered suffix at the boundary identified by seq. + * Bumps message epoch so web clients reset their window. */ +export function truncateOpenCodeRewind(db: Database, sessionId: string, cutoffSeq: number, boundaryId: string): number { + return db.transaction(() => { + const target = prepareCached(db, ` + SELECT seq, COALESCE(invoked_at, created_at) AS position_at + FROM messages WHERE session_id = ? AND id = ? AND seq = ? + `).get(sessionId, boundaryId, cutoffSeq) as { seq: number; position_at: number } | undefined + if (!target) throw new Error('Rewind boundary not found') + const deletedRows = prepareCached(db, ` + SELECT id FROM messages WHERE session_id = ? AND ( + COALESCE(invoked_at, created_at) > ? + OR (COALESCE(invoked_at, created_at) = ? AND seq >= ?) + ) + `).all(sessionId, target.position_at, target.position_at, target.seq) as Array<{ id: string }> + prepareCached(db, ` + DELETE FROM messages WHERE session_id = ? AND ( + COALESCE(invoked_at, created_at) > ? + OR (COALESCE(invoked_at, created_at) = ? AND seq >= ?) + ) + `).run(sessionId, target.position_at, target.position_at, target.seq) + invalidateMessageContentSearchInjectedTurnCache(db, [sessionId]) + for (const row of deletedRows) removeMessageContentSearchIndex(db, row.id) + prepareCached(db, `UPDATE sessions SET read_revision = content_revision, read_state_version = read_state_version + 1 + WHERE id = ? AND read_revision < content_revision AND NOT EXISTS ( + SELECT 1 FROM messages WHERE session_id = sessions.id AND content_revision > sessions.read_revision + )`).run(sessionId) + return bumpMessageEpoch(db, sessionId) + })() +} + export function truncateMessagesFromLocalId( db: Database, sessionId: string, diff --git a/hub/src/sync/conversationHistoryPi.test.ts b/hub/src/sync/conversationHistoryPi.test.ts index 71ac1ef0..f4123a6b 100644 --- a/hub/src/sync/conversationHistoryPi.test.ts +++ b/hub/src/sync/conversationHistoryPi.test.ts @@ -146,6 +146,68 @@ describe('Pi conversation-history hub integration', () => { } }) + it.each([true, false])('requires a child checkpoint and exact native binding for opencode (checkpoint=%s)', async (validCheckpoint) => { + const { store, engine } = createEngine() + try { + const source = engine.getOrCreateSession('oc-source', { + path: '/tmp/project', + host: 'localhost', + machineId: 'machine-1', + flavor: 'opencode', + capabilities: { conversationHistory: { forkCurrent: true, forkAtMessage: true, rewindToMessage: false } }, + }, null, 'default') + engine.handleSessionAlive({ sid: source.id, time: Date.now(), mode: 'remote' }) + store.messages.addMessage(source.id, { role: 'user', content: 'one' }, 'local1') + store.messages.markMessagesInvoked(source.id, ['local1'], Date.now()) + + const checkpoint = { sessionId: 'oc-clone-native', messageIds: ['child-user'], userMessageIds: ['child-user'], localMessageIds: [] } + ;(engine as any).rpcGateway.forkConversation = async () => ({ nativeSessionId: 'oc-clone-native', opencodeHistoryCheckpoint: validCheckpoint ? checkpoint : undefined }) + let spawnCalls = 0 + ;(engine as any).rpcGateway.spawnSession = async (...args: unknown[]) => { + spawnCalls++ + return { type: 'success', sessionId: args[12] } + } + ;(engine as any).rpcGateway.stopSession = async () => true + const exactBinds: unknown[][] = [] + ;(engine as any).waitForExactNativeForkBound = async (...args: unknown[]) => { + expect(engine.getSession(String(args[0]))?.metadata?.opencodeForkPending).toBe(true) + exactBinds.push(args) + return true + } + + const result = await engine.forkConversation(source.id, 'default') + if (!validCheckpoint) { + expect(result).toEqual({ type: 'error', message: 'OpenCode fork did not return a verified child history checkpoint' }) + expect(spawnCalls).toBe(0) + return + } + if (result.type !== 'success') throw new Error(result.message) + expect(exactBinds).toEqual([[result.sessionId, 'oc-clone-native', 'opencodeSessionId', true]]) + expect((store.sessions.getSession(result.sessionId)?.metadata as { opencodeHistoryCheckpoint?: unknown })?.opencodeHistoryCheckpoint).toEqual(checkpoint) + expect(engine.getSession(result.sessionId)?.metadata?.opencodeForkPending).toBeUndefined() + } finally { + engine.stop() + } + }) + + it.each(['matching', 'mismatch', 'pending-publication'])('commits OpenCode child readiness even after requester loss only for verified identities (%s)', (state) => { + const matches = state === 'matching' + const { engine } = createEngine() + try { + const child = engine.getOrCreateSession('recovered-oc-child', { + path: '/tmp/project', host: 'fixture', flavor: 'opencode', opencodeForkPending: true, + opencodeSessionId: 'native-child', + opencodeHistoryCheckpoint: { sessionId: state === 'mismatch' ? 'wrong-native' : 'native-child', messageIds: [], userMessageIds: [], localMessageIds: [], + ...(state === 'pending-publication' ? { localPublicationPending: true as const } : {}) } + }, null, 'default') + engine.handleSessionReady({ sid: child.id, time: Date.now() }) + expect((engine as any).sessionReadyIds.has(child.id)).toBe(matches) + expect(engine.getSession(child.id)?.metadata?.opencodeForkPending).toBe(matches ? undefined : true) + } finally { + engine.stop() + } + }) + it('scrubs Pi entry-id locators when rewind truncates their HAPI messages', () => { const { store, engine } = createEngine() try { diff --git a/hub/src/sync/forkWhileRunning.test.ts b/hub/src/sync/forkWhileRunning.test.ts index 83acbc02..cc084a2d 100644 --- a/hub/src/sync/forkWhileRunning.test.ts +++ b/hub/src/sync/forkWhileRunning.test.ts @@ -97,6 +97,68 @@ describe('historical forks while the source runs', () => { }) }) +describe('opencode fork-at-message exclusive boundary', () => { + it('pins the copied hub prefix to the native before-boundary user message', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) + const source = engine.getOrCreateSession('source', { + path: '/tmp/work', host: 'test', machineId: 'machine', flavor: 'opencode', + capabilities: { conversationHistory: { forkCurrent: true, forkAtMessage: true, rewindToMessage: true } }, + conversationHistoryPoints: { first: true, second: true }, + conversationHistoryIndexes: { first: 0, second: 1 }, + opencodeHistoryCheckpoint: { sessionId: 'acp-1', messageIds: ['n_first', 'n_a1', 'n_second'], userMessageIds: ['n_first', 'n_second'], localMessageIds: [] } + }, { controlledByUser: false }, 'default') + engine.handleSessionAlive({ sid: source.id, time: Date.now(), mode: 'remote' }) + for (const id of ['first', 'second']) { + store.messages.addMessage(source.id, { role: 'user', content: id }, id) + store.messages.markMessagesInvoked(source.id, [id], Date.now()) + } + const checkpoint = source.metadata!.opencodeHistoryCheckpoint! + const indexes = source.metadata!.conversationHistoryIndexes! + const rpc = (engine as unknown as { rpcGateway: RpcGateway }).rpcGateway + try { + let requestedBefore: string | undefined + rpc.forkConversation = async (_id, payload) => { + expect(payload).toEqual({ messageLocalId: 'second' }) + // The CLI forks at the native user message identified by the + // boundary's index; the copied prefix must end before it. + requestedBefore = checkpoint.userMessageIds[indexes.second] + expect(requestedBefore).toBe('n_second') + return { nativeSessionId: 'child-native', + opencodeHistoryCheckpoint: { sessionId: 'child-native', messageIds: ['n_first'], userMessageIds: ['n_first'], localMessageIds: [] } } + } + rpc.spawnSession = async (...args) => { + const childId = args[12]! + const resumeNative = args[8]! + const current = store.sessions.getSession(childId)! + store.sessions.updateSessionMetadata(childId, + { ...current.metadata as Record, opencodeSessionId: resumeNative }, + current.metadataVersion, 'default', { touchUpdatedAt: false }) + ;(engine as unknown as { sessionCache: { refreshSession(id: string): void } }).sessionCache.refreshSession(childId) + engine.handleSessionAlive({ sid: childId, time: Date.now(), mode: 'remote' }) + engine.handleSessionReady({ sid: childId, time: Date.now() }) + return { type: 'success', sessionId: childId } + } + const result = await engine.forkConversation(source.id, 'default', 'second') + expect(result.type).toBe('success') + if (result.type !== 'success') throw new Error(result.message) + // The child's copied hub transcript ends exactly before the forked + // prompt: its last user localId is the prompt before the boundary, + // and the child's native checkpoint holds exactly the user messages + // preceding the native `before` id — the same exclusive boundary. + const copiedUsers = store.messages.getAllMessages(result.sessionId) + .filter(row => (row.content as { role?: string } | null)?.role === 'user').map(row => row.localId) + expect(copiedUsers).toEqual(['first']) + const nativeBeforePrevious = checkpoint.userMessageIds[indexes.second - 1] + expect(nativeBeforePrevious).toBe('n_first') + const child = engine.getSession(result.sessionId) + expect(child?.metadata?.opencodeHistoryCheckpoint?.userMessageIds).toEqual([nativeBeforePrevious]) + expect(child?.metadata?.opencodeSessionId).toBe('child-native') + expect(requestedBefore).toBe('n_second') + } finally { engine.stop() } + }) +}) + describe('latest completed mode admission', () => { it('fails closed for old Runner capabilities and non-Codex sessions', async () => { const { engine, source, rpc } = fixture(); diff --git a/hub/src/sync/opencodeRewind.test.ts b/hub/src/sync/opencodeRewind.test.ts new file mode 100644 index 00000000..6f8e5a54 --- /dev/null +++ b/hub/src/sync/opencodeRewind.test.ts @@ -0,0 +1,579 @@ +import { describe, expect, it, spyOn } from 'bun:test' +import type { Database } from 'bun:sqlite' +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Store } from '../store' +import { RpcRegistry } from '../socket/rpcRegistry' +import { SyncEngine } from './syncEngine' +import { registerSessionHandlers } from '../socket/handlers/cli/sessionHandlers' +import type { CliSocketWithData } from '../socket/socketTypes' +import type { OpenCodeRewindOperation } from '@hapi/protocol/schemas' + +function fixture(searchable = false, dbPath = ':memory:') { + const store = new Store(dbPath) + const engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession('opencode-rewind', { path: '/tmp/project', host: 'fixture', flavor: 'opencode', + opencodeSessionId: 'native', opencodeWorkerId: 'worker', opencodeWorkerProcess: { workerId: 'worker', pid: 4321, startMarker: 'worker-generation' }, conversationHistoryIndexes: { one: 0, two: 1 }, + opencodeHistoryCheckpoint: { sessionId: 'native', messageIds: ['u1', 'a1', 'u2', 'a2'], userMessageIds: ['u1', 'u2'], localMessageIds: [] }, + capabilities: { conversationHistory: { rewindToMessage: true } } }, null, 'default') + engine.handleSessionAlive({ sid: session.id, time: Date.now(), mode: 'remote' }) + for (const [role, localId, text] of [ + ['user', 'one', 'retainedprefix user'], ['agent', undefined, 'retainedprefix assistant'], + ['user', 'two', 'removedsuffix user'], ['agent', undefined, 'removedsuffix assistant'] + ] as const) { + const content = !searchable ? 'synthetic' : role === 'user' + ? { type: 'text', text } + : { type: 'codex', data: { type: 'message', id: text, message: text } } + store.messages.addMessage(session.id, { role, content }, localId) + if (localId) store.messages.markMessagesInvoked(session.id, [localId], Date.now()) + } + const version = () => store.sessions.getSession(session.id)!.metadataVersion + return { store, engine, id: session.id, version } +} + +describe('OpenCode durable Hub rewind commit', () => { + it('snapshots the worker process generation into the reservation and correlates it on reports', async () => { + const f = fixture() + const current = f.store.sessions.getSession(f.id)! + f.store.sessions.updateSessionMetadata(f.id, { ...current.metadata as object, + opencodeWorkerProcess: { workerId: 'worker', pid: 4321, startMarker: 'worker-generation' } }, f.version(), 'default') + ;(f.engine as any).sessionCache.refreshSession(f.id) + let operation!: OpenCodeRewindOperation + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + operation = request.opencodeRewind + return { success: false, outcome: 'unknown', error: 'synthetic transport failure' } + } + await f.engine.rewindConversation(f.id, 'default', 'two') + expect(operation).toMatchObject({ workerId: 'worker', workerPid: 4321, workerStartMarker: 'worker-generation' }) + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation: { ...operation, workerPid: 4322 }, phase: 'rejected' }, f.version())).toThrow('mismatch') + expect(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'rejected' }, f.version()).phase).toBe('rejected') + } finally { f.engine.stop(); f.store.close() } + }) + + it('does not create a new reservation without an immutable worker process generation', async () => { + const f = fixture() + try { + const current = f.store.sessions.getSession(f.id)! + f.store.sessions.updateSessionMetadata(f.id, { ...current.metadata as object, + opencodeWorkerProcess: undefined }, f.version(), 'default') + ;(f.engine as any).sessionCache.refreshSession(f.id) + expect(await f.engine.rewindConversation(f.id, 'default', 'two')).toMatchObject({ type: 'error' }) + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind).toBeUndefined() + } finally { f.engine.stop(); f.store.close() } + }) + + it('refuses a new reservation when an older CLI changes only the outer worker ID', async () => { + const f = fixture() + const handlers = new Map void) => void>() + const socket = { on: (name: string, handler: (data: unknown, ack: (result: unknown) => void) => void) => handlers.set(name, handler), + to: () => ({ emit() {} }) } + registerSessionHandlers(socket as unknown as CliSocketWithData, { store: f.store, + resolveSessionAccess: () => ({ ok: true, value: f.store.sessions.getSession(f.id)! }), emitAccessError() {} }) + let rpcCount = 0 + ;(f.engine as any).rpcGateway.rewindConversation = async () => { rpcCount++; throw new Error('must not dispatch') } + try { + const before = f.store.sessions.getSession(f.id)! + let acknowledgement: any + handlers.get('update-metadata')!({ sid: f.id, expectedVersion: before.metadataVersion, + metadata: { ...before.metadata as object, opencodeWorkerId: 'older-wrapper' } }, result => { acknowledgement = result }) + expect(acknowledgement.result).toBe('success') + const changed = f.store.sessions.getSession(f.id)!.metadata as any + expect(changed.opencodeWorkerProcess.workerId).toBe('worker') + ;(f.engine as any).sessionCache.refreshSession(f.id) + expect(await f.engine.rewindConversation(f.id, 'default', 'two')).toMatchObject({ type: 'error' }) + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind).toBeUndefined() + expect(rpcCount).toBe(0) + } finally { f.engine.stop(); f.store.close() } + }) + + it.each([{ workerId: 'other', pid: 4321, startMarker: 'worker-generation' }, + { workerId: 'worker', pid: 4321 }, { workerId: 'worker', startMarker: 'worker-generation' }])( + 'refuses an unmatched or incomplete worker process proof', async proof => { + const f = fixture(); const current = f.store.sessions.getSession(f.id)! + f.store.sessions.updateSessionMetadata(f.id, { ...current.metadata as object, opencodeWorkerProcess: proof }, f.version(), 'default') + ;(f.engine as any).sessionCache.refreshSession(f.id) + let rpcCount = 0 + ;(f.engine as any).rpcGateway.rewindConversation = async () => { rpcCount++; throw new Error('must not dispatch') } + try { + expect(await f.engine.rewindConversation(f.id, 'default', 'two')).toMatchObject({ type: 'error' }) + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind).toBeUndefined() + expect(rpcCount).toBe(0) + } finally { f.engine.stop(); f.store.close() } + }) + + it.each(['prepare-first', 'reject-first'] as const)('serializes preparation and rejection with file SQLite (%s)', async order => { + const f = fixture(true, join(mkdtempSync(join(tmpdir(), 'hapi-rewind-cas-')), 'hub.sqlite')) + let operation!: OpenCodeRewindOperation + const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + operation = request.opencodeRewind + return { success: false, outcome: 'unknown', error: 'synthetic lost RPC' } + } + await f.engine.rewindConversation(f.id, 'default', 'two') + const reservedVersion = f.version() + if (order === 'prepare-first') { + expect(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, reservedVersion).phase).toBe('prepared') + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'rejected' }, reservedVersion)).toThrow('version changed') + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'rejected' }, f.version())).toThrow('without recovery evidence') + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind.phase).toBe('prepared') + } else { + expect(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'rejected' }, reservedVersion).phase).toBe('rejected') + expect(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, reservedVersion).phase).toBe('rejected') + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind.phase).toBe('rejected') + } + expect(f.store.messages.getAllMessages(f.id)).toHaveLength(4) + } finally { f.engine.stop(); f.store.close() } + }) + + it('keeps an unprepared unknown report reserved and admission blocked until rejection', async () => { + const f = fixture(true) + let operation!: OpenCodeRewindOperation + const reports: OpenCodeRewindOperation[] = [] + const before = f.store.messages.getAllMessages(f.id) + const epoch = f.store.messages.getMessageEpoch(f.id) + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + operation = request.opencodeRewind + reports.push(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase:'unknown' }, f.version())) + reports.push(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase:'unknown' }, f.version())) + return { success:false, outcome:'unknown', error:'prepared report failed before persistence' } + } + expect((await f.engine.rewindConversation(f.id, 'default', 'two')).type).toBe('error') + expect(reports.map(report => report.phase)).toEqual(['reserved', 'reserved']) + expect(reports.every(report => report.sourceHash === undefined && report.prefixHash === undefined)).toBe(true) + await expect(f.engine.sendMessage(f.id, { text:'must remain blocked' })).rejects.toThrow('in progress') + expect(f.store.messages.getAllMessages(f.id)).toEqual(before) + expect(f.store.messages.getMessageEpoch(f.id)).toBe(epoch) + expect(f.store.messages.searchContentInSession('removedsuffix', 'default', f.id).total).toBe(2) + expect(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase:'rejected', unchanged:true, + sourceHash:'a'.repeat(64), prefixHash:'b'.repeat(64) }, f.version()).phase).toBe('rejected') + } finally { f.engine.stop(); f.store.close() } + }) + + it('keeps prepared unknown proofs and refuses rejection without matching unchanged-source evidence', async () => { + const f = fixture(true) + let operation!: OpenCodeRewindOperation + const hashes = { sourceHash:'a'.repeat(64), prefixHash:'b'.repeat(64) } + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + operation = request.opencodeRewind + f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase:'prepared', ...hashes }, f.version()) + return { success:false, outcome:'unknown', error:'prepared ACK lost' } + } + await f.engine.rewindConversation(f.id, 'default', 'two') + expect(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase:'unknown' }, f.version())) + .toMatchObject({ phase:'unknown', ...hashes }) + const before = { rows:f.store.messages.getAllMessages(f.id), session:f.store.sessions.getSession(f.id), + epoch:f.store.messages.getMessageEpoch(f.id) } + for (const report of [{ operation, phase:'rejected' as const }, + { operation, phase:'rejected' as const, unchanged:true as const, sourceHash:'c'.repeat(64), prefixHash:hashes.prefixHash }]) { + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', report, f.version())).toThrow('without recovery evidence') + expect({ rows:f.store.messages.getAllMessages(f.id), session:f.store.sessions.getSession(f.id), + epoch:f.store.messages.getMessageEpoch(f.id) }).toEqual(before) + } + expect(f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase:'rejected', unchanged:true, ...hashes }, f.version()).phase) + .toBe('rejected') + } finally { f.engine.stop(); f.store.close() } + }) + + for (const requestedQueuedBoundary of [false, true]) { + it(`refuses uninvoked boundaries before reservation (${requestedQueuedBoundary ? 'requested boundary' : 'another future scheduled input'})`, async () => { + const f = fixture(true) + let nativeCalls = 0 + try { + const queued = f.store.messages.addMessage(f.id, { role: 'user', content: { type: 'text', text: 'pending scheduled input' } }, + 'pending', Date.now() + 60_000) + const before = { rows: f.store.messages.getAllMessages(f.id), session: f.store.sessions.getSession(f.id), + epoch: f.store.messages.getMessageEpoch(f.id), search: f.store.messages.searchContent('removedsuffix', 'default') } + ;(f.engine as any).rpcGateway.rewindConversation = async () => { nativeCalls++; throw new Error('must not reach native') } + expect(await f.engine.rewindConversation(f.id, 'default', requestedQueuedBoundary ? 'pending' : 'two')) + .toMatchObject({ type: 'error', message: 'Session has queued messages' }) + expect(nativeCalls).toBe(0) + expect({ rows: f.store.messages.getAllMessages(f.id), session: f.store.sessions.getSession(f.id), + epoch: f.store.messages.getMessageEpoch(f.id), search: f.store.messages.searchContent('removedsuffix', 'default') }).toEqual(before) + expect(f.store.messages.getMessageById(f.id, queued.id)?.invokedAt).toBeNull() + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind).toBeUndefined() + } finally { f.engine.stop(); f.store.close() } + }) + } + + for (const phase of ['reserved', 'prepared'] as const) { + for (const invoked of [false, true]) { + it(`preserves post-reservation changes instead of truncating (${phase}, ${invoked ? 'newly invoked' : 'uninvoked scheduled'})`, async () => { + const f = fixture(true) + const db = (f.store as unknown as { db: Database }).db + const invalidations: unknown[] = [] + const unsubscribe = f.engine.subscribe(event => { if (event.type === 'messages-invalidated') invalidations.push(event) }) + const snapshot = () => ({ rows: f.store.messages.getAllMessages(f.id), session: f.store.sessions.getSession(f.id), + epoch: f.store.messages.getMessageEpoch(f.id), + read: db.query('SELECT content_revision, read_revision, read_state_version, manual_unread FROM sessions WHERE id = ?').get(f.id), + lookup: db.query('SELECT * FROM message_content_search_lookup ORDER BY search_rowid').all(), + fts: db.query('SELECT rowid, * FROM message_content_search ORDER BY rowid').all(), + short: db.query('SELECT * FROM message_content_search_short ORDER BY gram, search_rowid').all() }) + let checkedRejection = false + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + const operation = request.opencodeRewind + const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + if (phase === 'prepared') f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, f.version()) + const queued = f.store.messages.addMessage(f.id, { role: 'user', content: { type: 'text', text: 'post reservation input' } }, + 'new-input', Date.now() + (invoked ? -1 : 60_000)) + if (invoked) f.store.messages.markMessagesInvoked(f.id, ['new-input'], Date.now()) + const before = snapshot() + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation, + phase: phase === 'reserved' ? 'prepared' : 'applied', ...hashes, + checkpoint: { sessionId: 'native', messageIds: ['u1', 'a1'], userMessageIds: ['u1'], localMessageIds: [] }, + indexes: { one: 0 } }, f.version())).toThrow('OpenCode source transcript changed') + expect(snapshot()).toEqual(before) + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind.phase).toBe(phase) + expect(f.store.messages.getMessageById(f.id, queued.id)).not.toBeNull() + expect(invalidations).toEqual([]) + checkedRejection = true + return { success: false, outcome: 'unknown', error: 'source changed' } + } + expect((await f.engine.rewindConversation(f.id, 'default', 'two')).type).toBe('error') + expect(checkedRejection).toBe(true) + const beforeAdmission = snapshot() + expect(f.engine.getDeliverableMessagesAfter(f.id, { afterSeq: 0, limit: 100, now: Date.now() + 120_000 })).toEqual([]) + await expect(f.engine.sendMessage(f.id, { text: 'blocked input', localId: 'must-not-create' })).rejects.toThrow('in progress') + expect(snapshot()).toEqual(beforeAdmission) + } finally { unsubscribe(); f.engine.stop(); f.store.close() } + }) + } + } + + it('preserves the native prefix when an earlier-inserted scheduled boundary is invoked after an ordinary turn', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) + const sourceCheckpoint = { sessionId: 'native', messageIds: ['u1', 'a1', 'u2', 'a2'], + userMessageIds: ['u1', 'u2'], localMessageIds: [] } + const checkpoint = { ...sourceCheckpoint, messageIds: ['u1', 'a1'], userMessageIds: ['u1'] } + const session = engine.getOrCreateSession('scheduled-rewind', { path: '/tmp/project', host: 'fixture', flavor: 'opencode', + opencodeSessionId: 'native', opencodeWorkerId: 'worker', opencodeWorkerProcess: { workerId: 'worker', pid: 4321, startMarker: 'worker-generation' }, conversationHistoryIndexes: { one: 0, two: 1 }, + opencodeHistoryCheckpoint: sourceCheckpoint, + capabilities: { conversationHistory: { rewindToMessage: true } } }, null, 'default') + engine.handleSessionAlive({ sid: session.id, time: Date.now(), mode: 'remote' }) + const db = (store as unknown as { db: Database }).db + const at = Date.now() - 10_000 + const version = () => store.sessions.getSession(session.id)!.metadataVersion + const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + const invalidations: unknown[] = [] + let operation!: OpenCodeRewindOperation + const unsubscribe = engine.subscribe(event => { + if (event.type === 'messages-invalidated') invalidations.push({ inTransaction: db.inTransaction, + phase: (store.sessions.getSession(session.id)!.metadata as any).opencodeRewind.phase, + retained: store.messages.searchContentInSession('ordinaryprefix', 'default', session.id).total, + removed: store.messages.searchContentInSession('scheduledsuffix', 'default', session.id).total }) + }) + try { + const scheduled = store.messages.addMessage(session.id, { role: 'user', content: { type: 'text', text: 'scheduledsuffix' } }, + 'two', at + 3_000, at) + const ordinary = store.messages.addMessage(session.id, { role: 'user', content: { type: 'text', text: 'ordinaryprefix' } }, + 'one', undefined, at + 1_000) + store.messages.markMessagesInvoked(session.id, ['one'], at + 1_000) + const ordinaryReply = store.messages.addMessage(session.id, + { role: 'agent', content: { type: 'codex', data: { type: 'message', id: 'ordinary', message: 'ordinaryprefix' } } }, + undefined, undefined, at + 2_000) + store.messages.markMessagesInvoked(session.id, ['two'], at + 3_000) + const scheduledReply = store.messages.addMessage(session.id, + { role: 'agent', content: { type: 'codex', data: { type: 'message', id: 'scheduled', message: 'scheduledsuffix' } } }, + undefined, undefined, at + 4_000) + expect(scheduled.seq).toBeLessThan(ordinary.seq) + expect(store.messages.getMessageById(session.id, scheduled.id)!.invokedAt).toBeGreaterThan(ordinaryReply.invokedAt!) + const epoch = store.messages.getMessageEpoch(session.id) + const lookups = db.query('SELECT * FROM message_content_search_lookup WHERE target_message_id IN (?, ?) ORDER BY search_rowid') + .all(ordinary.id, ordinaryReply.id) + ;(engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + operation = request.opencodeRewind + engine.reportOpenCodeRewind(session.id, 'default', { operation, phase: 'prepared', ...hashes }, version()) + engine.reportOpenCodeRewind(session.id, 'default', { operation, phase: 'applied', ...hashes, checkpoint, indexes: { one: 0 } }, version()) + return { success: true, truncateFromLocalId: 'two' } + } + expect(await engine.rewindConversation(session.id, 'default', 'two')).toEqual({ type: 'success' }) + expect(operation.cutoffSeq).toBe(scheduled.seq) + expect(store.messages.getAllMessages(session.id).map(row => row.id)).toEqual([ordinary.id, ordinaryReply.id]) + expect(store.messages.searchContentInSession('ordinaryprefix', 'default', session.id).total).toBe(2) + expect(store.messages.searchContent('scheduledsuffix', 'default')).toEqual([]) + expect(store.messages.searchContentInSession('sc', 'default', session.id).matches).toEqual([]) + expect(db.query('SELECT * FROM message_content_search_lookup ORDER BY search_rowid').all()).toEqual(lookups) + for (const row of [scheduled, scheduledReply]) { + expect(store.messages.getMessageById(session.id, row.id)).toBeNull() + expect(engine.getMessageContext(session.id, row.id)).toBeNull() + } + expect(engine.getMessageContext(session.id, ordinary.id)?.messages.map(row => row.id)).toEqual([ordinary.id, ordinaryReply.id]) + expect(store.sessions.getSession(session.id)!.metadata).toMatchObject({ opencodeHistoryCheckpoint: checkpoint, + conversationHistoryIndexes: { one: 0 }, opencodeRewind: { phase: 'committed' } }) + expect(store.messages.getMessageEpoch(session.id)).toBe(epoch + 1) + expect(invalidations).toEqual([{ inTransaction: false, phase: 'committed', retained: 2, removed: 0 }]) + const later = store.messages.addMessage(session.id, { role: 'user', content: { type: 'text', text: 'afterrewind' } }, 'later') + store.messages.markMessagesInvoked(session.id, ['later'], Date.now()) + const committedVersion = version() + expect(engine.reportOpenCodeRewind(session.id, 'default', { operation, phase: 'applied', ...hashes, + checkpoint, indexes: { one: 0 } }, 0).phase).toBe('committed') + expect(store.messages.getMessageById(session.id, later.id)).not.toBeNull() + expect(store.messages.getMessageEpoch(session.id)).toBe(epoch + 1) + expect(version()).toBe(committedVersion) + expect(invalidations).toHaveLength(1) + } finally { unsubscribe(); engine.stop(); store.close() } + }) + + it('atomically removes only cutoff search rows before invalidation and preserves later rows on committed replay', async () => { + const f = fixture(true) + const rows = f.store.messages.getAllMessages(f.id) + const db = (f.store as unknown as { db: Database }).db + const invalidations: unknown[] = [] + const unsubscribe = f.engine.subscribe(event => { + if (event.type === 'messages-invalidated') invalidations.push({ + inTransaction: db.inTransaction, + phase: (f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind.phase, + matches: f.store.messages.searchContent('removedsuffix', 'default') + }) + }) + const checkpoint = { sessionId: 'native', messageIds: ['u1', 'a1'], userMessageIds: ['u1'], localMessageIds: [] } + const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + let operation!: OpenCodeRewindOperation + try { + const prefixContext = f.engine.getMessageContext(f.id, rows[0]!.id) + expect(prefixContext).not.toBeNull() + expect(f.store.messages.searchContentInSession('removedsuffix', 'default', f.id).total).toBe(2) + expect(f.store.messages.searchContentInSession('re', 'default', f.id).total).toBe(4) + const prefixLookups = db.query('SELECT * FROM message_content_search_lookup WHERE target_message_id IN (?, ?) ORDER BY search_rowid') + .all(rows[0]!.id, rows[1]!.id) + const beforeRevision = f.store.sessions.getSession(f.id)!.contentRevision + db.query(`UPDATE sessions SET manual_unread = 1, read_revision = ( + SELECT MAX(content_revision) FROM messages WHERE session_id = ? AND seq < 3 + ) WHERE id = ?`).run(f.id, f.id) + const beforeRead = db.query('SELECT read_revision, content_revision, read_state_version FROM sessions WHERE id = ?') + .get(f.id) as { read_revision: number; content_revision: number; read_state_version: number } + expect(beforeRead.read_revision).toBeLessThan(beforeRead.content_revision) + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + operation = request.opencodeRewind + f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, f.version()) + f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'applied', ...hashes, checkpoint, indexes: { one: 0 } }, f.version()) + return { success: true, truncateFromLocalId: 'two' } + } + expect(await f.engine.rewindConversation(f.id, 'default', 'two')).toEqual({ type: 'success' }) + expect(f.store.messages.getAllMessages(f.id).map(row => row.id)).toEqual(rows.slice(0, 2).map(row => row.id)) + expect(f.store.messages.searchContent('removedsuffix', 'default')).toEqual([]) + expect(f.store.messages.searchContentInSession('removedsuffix', 'default', f.id)).toMatchObject({ total: 0, matches: [] }) + expect(f.store.messages.searchContentInSession('re', 'default', f.id).matches.map(match => match.messageId).sort()) + .toEqual(rows.slice(0, 2).map(row => row.id).sort()) + expect(f.store.messages.searchContent('retainedprefix', 'default')).toHaveLength(1) + expect(f.store.messages.searchContentInSession('retainedprefix', 'default', f.id).total).toBe(2) + for (const row of rows.slice(2)) { + expect(f.store.messages.getMessageById(f.id, row.id)).toBeNull() + expect(f.engine.getMessageContext(f.id, row.id)).toBeNull() + expect(db.query('SELECT * FROM message_content_search_lookup WHERE target_message_id = ? OR message_id = ?').all(row.id, row.id)).toEqual([]) + } + expect(db.query('SELECT * FROM message_content_search_lookup ORDER BY search_rowid').all()).toEqual(prefixLookups) + expect(db.query('SELECT * FROM message_content_search_short WHERE search_rowid NOT IN (SELECT search_rowid FROM message_content_search_lookup)').all()).toEqual([]) + expect(db.query('SELECT rowid FROM message_content_search WHERE rowid NOT IN (SELECT search_rowid FROM message_content_search_lookup)').all()).toEqual([]) + expect(f.engine.getMessageContext(f.id, rows[0]!.id)?.messages.map(row => row.id)).toEqual(rows.slice(0, 2).map(row => row.id)) + expect(f.store.messages.getMessageEpoch(f.id)).toBe(1) + expect(f.store.sessions.getSession(f.id)!.contentRevision).toBe(beforeRevision) + expect(db.query('SELECT read_revision, content_revision, read_state_version, manual_unread FROM sessions WHERE id = ?').get(f.id)) + .toEqual({ read_revision: beforeRead.content_revision, content_revision: beforeRead.content_revision, + read_state_version: beforeRead.read_state_version + 1, manual_unread: 1 }) + expect(invalidations).toEqual([{ inTransaction: false, phase: 'committed', matches: [] }]) + + const later = f.store.messages.addMessage(f.id, { role: 'user', content: { type: 'text', text: 'latersearch' } }, 'later') + f.store.messages.markMessagesInvoked(f.id, ['later'], Date.now()) + expect(later.seq).toBe(operation.cutoffSeq) + const beforeReplay = f.store.messages.searchContentInSession('latersearch', 'default', f.id) + const metadataVersion = f.version() + const result = f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'applied', ...hashes, checkpoint, indexes: { one: 0 } }, 0) + expect(result.phase).toBe('committed') + expect(f.store.messages.getMessageById(f.id, later.id)).not.toBeNull() + expect(f.store.messages.searchContentInSession('latersearch', 'default', f.id)).toEqual(beforeReplay) + expect(beforeReplay.matches[0]?.messageId).toBe(later.id) + expect(f.engine.getMessageContext(f.id, later.id)?.targetMessageId).toBe(later.id) + expect(f.store.messages.getMessageEpoch(f.id)).toBe(1) + expect(f.version()).toBe(metadataVersion) + expect(invalidations).toHaveLength(1) + } finally { unsubscribe(); f.engine.stop(); f.store.close() } + }) + + for (const failureAt of ['metadata CAS', 'search cleanup'] as const) { + it(`rolls back transcript, every search table and read state when ${failureAt} fails`, async () => { + const f = fixture(true) + const db = (f.store as unknown as { db: Database }).db + const invalidations: unknown[] = [] + let checkedRollback = false + const unsubscribe = f.engine.subscribe(event => { if (event.type === 'messages-invalidated') invalidations.push(event) }) + const snapshot = () => ({ + rows: f.store.messages.getAllMessages(f.id), + epoch: f.store.messages.getMessageEpoch(f.id), + readState: db.query('SELECT content_revision, read_revision, read_state_version, manual_unread FROM sessions WHERE id = ?').get(f.id), + fts: db.query('SELECT rowid, * FROM message_content_search ORDER BY rowid').all(), + lookup: db.query('SELECT * FROM message_content_search_lookup ORDER BY search_rowid').all(), + short: db.query('SELECT * FROM message_content_search_short ORDER BY gram, search_rowid').all(), + global: f.store.messages.searchContent('removedsuffix', 'default'), + inSession: f.store.messages.searchContentInSession('removedsuffix', 'default', f.id), + shortSearch: f.store.messages.searchContentInSession('re', 'default', f.id) + }) + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + const operation = request.opencodeRewind + const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, f.version()) + const before = snapshot() + const failure = failureAt === 'metadata CAS' + ? spyOn(f.store.sessions, 'updateSessionMetadata').mockReturnValue({ result: 'error' }) : null + if (failureAt === 'search cleanup') db.exec(` + CREATE TRIGGER fail_rewind_search_cleanup BEFORE DELETE ON message_content_search_lookup + BEGIN SELECT RAISE(ABORT, 'forced search cleanup failure'); END; + `) + try { + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'applied', ...hashes, + checkpoint: { sessionId: 'native', messageIds: ['u1', 'a1'], userMessageIds: ['u1'], localMessageIds: [] }, + indexes: { one: 0 } }, f.version())).toThrow(failureAt === 'metadata CAS' ? 'CAS failed' : 'forced search cleanup failure') + } finally { failure?.mockRestore() } + expect(snapshot()).toEqual(before) + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind.phase).toBe('prepared') + expect(invalidations).toEqual([]) + checkedRollback = true + return { success: false, outcome: 'unknown', error: failureAt } + } + expect((await f.engine.rewindConversation(f.id, 'default', 'two')).type).toBe('error') + expect(checkedRollback).toBe(true) + expect(f.store.messages.getAllMessages(f.id)).toHaveLength(4) + expect(f.store.messages.searchContentInSession('removedsuffix', 'default', f.id).total).toBe(2) + } finally { unsubscribe(); f.engine.stop(); f.store.close() } + }) + } + + for (const rollback of [false, true]) { + it(`invalidates injected-turn cache for the exact cutoff${rollback ? ' and lazily restores it after rollback' : ''}`, () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('rewind-cache', { path: '/tmp/project' }, null, 'default') + const db = (store as unknown as { db: Database }).db + const injected = (uuid: string) => ({ role: 'agent', content: { type: 'output', data: { + type: 'user', uuid, message: { content: 'injected' } + } } }) + const sentinel = (parentUuid: string) => ({ role: 'agent', content: { type: 'output', data: { + type: 'assistant', parentUuid, message: { content: [{ type: 'text', text: 'No response requested.' }] } + } } }) + try { + store.messages.addMessage(session.id, injected('retained-injected')) + store.messages.addMessage(session.id, sentinel('retained-injected')) + const cutoff = store.messages.addMessage(session.id, injected('removed-injected')) + store.messages.addMessage(session.id, sentinel('removed-injected')) + expect(store.messages.searchContent('No response requested', 'default')).toEqual([]) + if (rollback) { + expect(() => store.runInTransaction(() => { + store.messages.truncateOpenCodeRewind(session.id, cutoff.seq, cutoff.id) + throw new Error('rollback cache cleanup') + })).toThrow('rollback cache cleanup') + expect(store.messages.getAllMessages(session.id)).toHaveLength(4) + expect(store.messages.getMessageEpoch(session.id)).toBe(0) + } else store.messages.truncateOpenCodeRewind(session.id, cutoff.seq, cutoff.id) + store.messages.addMessage(session.id, sentinel('retained-injected')) + const removedParentReply = store.messages.addMessage(session.id, sentinel('removed-injected')) + const matches = store.messages.searchContentInSession('No response requested', 'default', session.id) + expect(matches.matches.map(match => match.messageId)).toEqual(rollback ? [] : [removedParentReply.id]) + expect(matches.total).toBe(rollback ? 0 : 1) + expect(db.inTransaction).toBe(false) + } finally { store.close() } + }) + } + + it('reserves before RPC and atomically commits exact cutoff, metadata and epoch; replay cannot delete a new turn', async () => { + const f = fixture(); let operation!: OpenCodeRewindOperation + const checkpoint = { sessionId: 'native', messageIds: ['u1', 'a1'], userMessageIds: ['u1'], localMessageIds: [] } + const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + operation = request.opencodeRewind + expect((f.store.sessions.getSession(f.id)!.metadata as any).opencodeRewind.operationId).toBe(operation.operationId) + f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, f.version()) + f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'applied', ...hashes, checkpoint, indexes: { one: 0 } }, f.version()) + return { success: true, truncateFromLocalId: 'two' } + } + expect(await f.engine.rewindConversation(f.id, 'default', 'two')).toEqual({ type: 'success' }) + expect(f.store.messages.getAllMessages(f.id)).toHaveLength(2) + const epoch = f.store.messages.getMessageEpoch(f.id) + expect(epoch).toBe(1) + f.store.messages.addMessage(f.id, { role: 'user', content: 'new turn' }, 'later') + const replay = f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'applied', ...hashes, checkpoint, indexes: { one: 0 } }, 0) + expect(replay.phase).toBe('committed') + expect(f.store.messages.getAllMessages(f.id).at(-1)?.localId).toBe('later') + expect(f.store.messages.getMessageEpoch(f.id)).toBe(epoch) + } finally { f.engine.stop() } + }) + + it('preserves both histories on output/epoch change instead of applying a stale cutoff', async () => { + const f = fixture() + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + const operation = request.opencodeRewind + const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, f.version()) + f.store.messages.addMessage(f.id, { role: 'agent', content: 'late peer output' }) + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'applied', ...hashes, + checkpoint: { sessionId: 'native', messageIds: ['u1', 'a1'], userMessageIds: ['u1'], localMessageIds: [] }, indexes: { one: 0 } }, f.version())).toThrow() + return { success: false, outcome: 'unknown', error: 'conflict' } + } + expect((await f.engine.rewindConversation(f.id, 'default', 'two')).type).toBe('error') + expect(f.store.messages.getAllMessages(f.id)).toHaveLength(5) + expect(f.store.messages.getMessageEpoch(f.id)).toBe(0) + await expect(f.engine.sendMessage(f.id, { text: 'do not admit', localId: 'blocked' })).rejects.toThrow() + } finally { f.engine.stop() } + }) + + it('retains durable admission locks after Hub reconstruction, independent of the volatile history set', async () => { + const f = fixture(); let restarted: SyncEngine | undefined + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + f.engine.reportOpenCodeRewind(f.id, 'default', { operation: request.opencodeRewind, phase: 'unknown' }, f.version()) + throw new Error('CLI disconnected') + } + expect((await f.engine.rewindConversation(f.id, 'default', 'two')).type).toBe('error') + f.engine.stop() + restarted = new SyncEngine(f.store, {} as never, new RpcRegistry(), { broadcast() {} } as never) + expect(restarted.getDeliverableMessagesAfter(f.id, { afterSeq: 0, limit: 100, now: Date.now() })).toEqual([]) + await expect(restarted.sendMessage(f.id, { text: 'blocked' })).rejects.toThrow('in progress') + await expect(restarted.applySessionConfig(f.id, { model: 'blocked-model' })).rejects.toThrow('reconciliation') + await expect(restarted.switchSession(f.id, 'local')).rejects.toThrow('reconciliation') + expect(f.store.messages.getAllMessages(f.id)).toHaveLength(4) + } finally { restarted?.stop(); f.engine.stop() } + }) + + it('rolls back deletion/epoch when metadata CAS fails and emits no premature invalidation', async () => { + const f = fixture(); const invalidations: unknown[] = [] + const unsubscribe = f.engine.subscribe(event => { if (event.type === 'messages-invalidated') invalidations.push(event) }) + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + const operation = request.opencodeRewind; const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, f.version()) + const failure = spyOn(f.store.sessions, 'updateSessionMetadata').mockReturnValue({ result: 'error' }) + try { + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'applied', ...hashes, + checkpoint: { sessionId: 'native', messageIds: ['u1', 'a1'], userMessageIds: ['u1'], localMessageIds: [] }, indexes: { one: 0 } }, f.version())).toThrow('CAS failed') + } finally { failure.mockRestore() } + return { success: false, outcome: 'unknown', error: 'CAS failed' } + } + await f.engine.rewindConversation(f.id, 'default', 'two') + expect(f.store.messages.getAllMessages(f.id)).toHaveLength(4) + expect(f.store.messages.getMessageEpoch(f.id)).toBe(0) + expect(invalidations).toHaveLength(0) + } finally { unsubscribe(); f.engine.stop() } + }) + + it('rejects namespace, operation identity and current-version mismatches before native completion', async () => { + const f = fixture() + try { + ;(f.engine as any).rpcGateway.rewindConversation = async (_id: string, request: { opencodeRewind: OpenCodeRewindOperation }) => { + const operation = request.opencodeRewind; const hashes = { sourceHash: 'a'.repeat(64), prefixHash: 'b'.repeat(64) } + expect(() => f.engine.reportOpenCodeRewind(f.id, 'other-namespace', { operation, phase: 'prepared', ...hashes }, f.version())).toThrow('access denied') + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation: { ...operation, cutoffSeq: 1 }, phase: 'prepared', ...hashes }, f.version())).toThrow('mismatch') + expect(() => f.engine.reportOpenCodeRewind(f.id, 'default', { operation, phase: 'prepared', ...hashes }, f.version() - 1)).toThrow('version changed') + return { success: false, outcome: 'unknown', error: 'pending' } + } + await f.engine.rewindConversation(f.id, 'default', 'two') + expect(f.store.messages.getAllMessages(f.id)).toHaveLength(4) + } finally { f.engine.stop() } + }) +}) diff --git a/hub/src/sync/rpcGateway.test.ts b/hub/src/sync/rpcGateway.test.ts index 4ebc8915..82183c3e 100644 --- a/hub/src/sync/rpcGateway.test.ts +++ b/hub/src/sync/rpcGateway.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'bun:test' -import type { Server } from 'socket.io' -import { PERMISSION_REQUEST_NOT_FOUND_MESSAGE } from '@hapi/protocol/rpcMethods' -import type { RpcRegistry } from '../socket/rpcRegistry' +import type { Server, Socket } from 'socket.io' +import { getSessionStopPreparationMethod, PERMISSION_REQUEST_NOT_FOUND_MESSAGE, RPC_METHODS } from '@hapi/protocol/rpcMethods' +import { RpcRegistry } from '../socket/rpcRegistry' import { PermissionRequestNotFoundError, RpcGateway, RpcTargetMissingError } from './rpcGateway' function createGateway() { @@ -178,6 +178,48 @@ describe('RpcGateway RPC timeouts', () => { // target CLI is unreachable, so syncEngine.archiveSession can narrow on it // and treat the kill as a benign no-op. describe('RpcGateway no-target diagnostics (tiann/hapi#916)', () => { + it('targets an older process alias while the generic session method belongs to a newer wrapper', async () => { + const registry = new RpcRegistry() + const calls: string[] = [] + const fixture = (id: string, pid: number) => ({ id, timeout: () => ({ emitWithAck: async (_event: string, request: { params: string }) => { + calls.push(id) + const params = JSON.parse(request.params) + return JSON.stringify({ success: true, pid, machineId: params.expectedMachineId, + processStartMarker: params.expectedProcessStartMarker, preparationLease: params.preparationLease }) + } }) }) + const old = fixture('old', 42) + const newer = fixture('new', 43) + registry.register(old as unknown as Socket, `session-1:${RPC_METHODS.KillSession}`) + registry.register(newer as unknown as Socket, `session-1:${RPC_METHODS.KillSession}`) + registry.register(old as unknown as Socket, `session-1:${getSessionStopPreparationMethod('machine-1', 42)}`) + registry.register(newer as unknown as Socket, `session-1:${getSessionStopPreparationMethod('machine-1', 43)}`) + const sockets = new Map([['old', old], ['new', newer]]) + const gateway = new RpcGateway({ of: () => ({ sockets }) } as unknown as Server, registry) + const options = { prepareOnly: true, expectedMachineId: 'machine-1', expectedPid: 42, expectedProcessStartMarker: 'old-generation' } + expect((await gateway.killSession('session-1', options)).pid).toBe(42) + registry.unregisterAll(newer as unknown as Socket) + sockets.delete('new') + expect((await gateway.killSession('session-1', options)).pid).toBe(42) + expect(calls).toEqual(['old', 'old']) + }) + + it('does not fall back to the newer generic wrapper when an older process alias is unavailable', async () => { + const registry = new RpcRegistry() + const newer = { id: 'new' } as Socket + registry.register(newer, `session-1:${RPC_METHODS.KillSession}`) + const gateway = new RpcGateway({ of: () => { throw new Error('must not call generic socket') } } as unknown as Server, registry) + await expect(gateway.killSession('session-1', { prepareOnly: true, expectedMachineId: 'machine-1', + expectedPid: 42, expectedProcessStartMarker: 'old-generation' })).rejects.toBeInstanceOf(RpcTargetMissingError) + }) + + it('rejects a KillSession error envelope instead of allowing runner force termination', async () => { + const io = { of: () => ({ sockets: { get: () => ({ timeout: () => ({ + emitWithAck: async () => JSON.stringify({ error: 'publication drain failed' }) + }) }) } }) } as unknown as Server + const registry = { getSocketIdForMethod: () => 'socket-1' } as unknown as RpcRegistry + await expect(new RpcGateway(io, registry).killSession('session-1')).rejects.toThrow('publication drain failed') + }) + it('throws RpcTargetMissingError(handler-not-registered) when no socket is registered for the method', async () => { const io = { of() { diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index 05c02b34..65ff342a 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -1,5 +1,5 @@ import type { AgentFlavor, CodexCollaborationMode, CopilotAgentMode, PermissionMode } from '@hapi/protocol/types' -import { PERMISSION_REQUEST_NOT_FOUND_MESSAGE, RPC_METHODS } from '@hapi/protocol/rpcMethods' +import { DEFAULT_RPC_TIMEOUT_MS, getSessionStopPreparationMethod, PERMISSION_REQUEST_NOT_FOUND_MESSAGE, RPC_METHODS, type SessionStopPreparationLease } from '@hapi/protocol/rpcMethods' import { ArchiveCodexSessionRpcResponseSchema, AgentAvailabilityResponseSchema, @@ -57,7 +57,6 @@ import type { import type { Server } from 'socket.io' import type { RpcRegistry } from '../socket/rpcRegistry' -const DEFAULT_RPC_TIMEOUT_MS = 30_000 const MODEL_LIST_RPC_TIMEOUT_MS = 120_000 // Codex can spend 30s awaiting startup after preflight and process creation. const CODEX_SPAWN_RPC_TIMEOUT_MS = 60_000 @@ -212,14 +211,31 @@ export class RpcGateway { return await this.sessionRpc(sessionId, RPC_METHODS.SetSessionConfig, config) } - async killSession(sessionId: string): Promise<{ pid?: number; processStartMarker?: string }> { - const result = await this.sessionRpc(sessionId, RPC_METHODS.KillSession, {}) + async killSession(sessionId: string, options: { + prepareOnly?: boolean; expectedMachineId?: string; expectedPid?: number; expectedProcessStartMarker?: string; preparationLease?: SessionStopPreparationLease + } = {}): Promise<{ pid?: number; machineId?: string; processStartMarker?: string; preparationLease?: SessionStopPreparationLease }> { + let method: string = RPC_METHODS.KillSession + if (options.prepareOnly) { + if (!options.expectedMachineId || !options.expectedPid || !options.expectedProcessStartMarker) { + throw new Error('Process shutdown preparation requires machine and process generation') + } + method = getSessionStopPreparationMethod(options.expectedMachineId, options.expectedPid) + } + const result = await this.sessionRpc(sessionId, method, options) + if (result && typeof result === 'object' && ('error' in result || ('success' in result && result.success === false))) { + throw new Error(typeof (result as { error?: unknown }).error === 'string' + ? (result as { error: string }).error : 'Session shutdown was not confirmed') + } if (!result || typeof result !== 'object') return {} const pid = (result as { pid?: unknown }).pid const processStartMarker = (result as { processStartMarker?: unknown }).processStartMarker + const preparationLease = (result as { preparationLease?: SessionStopPreparationLease }).preparationLease + const machineId = (result as { machineId?: unknown }).machineId return { ...(typeof pid === 'number' ? { pid } : {}), ...(typeof processStartMarker === 'string' ? { processStartMarker } : {}), + ...(preparationLease ? { preparationLease } : {}), + ...(typeof machineId === 'string' ? { machineId } : {}), } } @@ -679,7 +695,7 @@ export class RpcGateway { async rewindConversation( sessionId: string, - params: { messageLocalId: string } + params: { messageLocalId: string; opencodeRewind?: import('@hapi/protocol/schemas').OpenCodeRewindOperation } ): Promise { return await this.sessionRpc( sessionId, diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 289e6d9e..02ff383b 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -14,11 +14,12 @@ import { } from '@hapi/protocol/runnerCapabilities' import type { CursorChatStoreStatus, CursorMigrateOutcome, CursorMigrateToAcpRequest, MessageContextResponse, MessageDeliveryMode, MessagesResponse, QueuedStateResponse, RewindConversationErrorCode, SlashCommandsResponse } from '@hapi/protocol/apiTypes' import type { SteerQueuedMessageResponse } from '@hapi/protocol/schemas' +import type { SessionStopPreparationLease } from '@hapi/protocol/rpcMethods' import type { CopilotReasoningEffortResponse, ImplementCodexPlanResult, KimiReasoningEffortResponse } from '@hapi/protocol/apiTypes' import type { AgentFlavor, BackgroundTask, CodexCollaborationMode, CopilotAgentMode, DecryptedMessage, PermissionMode, Session, SyncEvent } from '@hapi/protocol/types' import { hasConversationMessageContent, unwrapRoleWrappedRecordEnvelope } from '@hapi/protocol/messages' import type { Server } from 'socket.io' -import { randomUUID } from 'node:crypto' +import { randomUUID, createHash } from 'node:crypto' import type { Store, CancelQueuedMessageResult } from '../store' import type { MessageContentSearchMatch, @@ -86,6 +87,9 @@ import { AutomaticTitleSuggestionService } from './automaticTitleSuggestion' import { extractMessageEventType } from '../notifications/eventParsing' import { SessionEnumerationCache } from './sessionEnumerationCache' import { ingestNotifySummaryFromMessage } from './workGraphNotifyIngest' +import { MetadataSchema, type OpenCodeRewindOperation } from '@hapi/protocol/schemas' +import type { OpenCodeRewindReport } from '@hapi/protocol/apiTypes' +import { extractTodoWriteTodosFromMessageContent } from './todos' type PiResumeAttempt = NonNullable['piResumeAttempt']> type PtyResumeAttempt = NonNullable['ptyResumeAttempt']> @@ -210,6 +214,11 @@ function extractClaudeUserMessageTextFromAgentOutput(content: unknown): string | export class SyncEngine { private readonly archiveRequests = new Map>() + // KillSession's beforeKill drain completes before the CLI's async cleanup + // closes the session socket, so a runner prepare-stop that loses that race + // can still be honored for the exact killed generation while its archive + // is in flight. + private readonly archiveDrainedGenerations = new Map() private readonly eventPublisher: EventPublisher private readonly sessionCache: SessionCache private readonly machineCache: MachineCache @@ -674,6 +683,7 @@ export class SyncEngine { } getDeliverableMessagesAfter(sessionId: string, options: { afterSeq: number; limit: number; now: number }): DecryptedMessage[] { + if (this.openCodeRewindPending(sessionId)) return [] return this.messageService.getDeliverableMessagesAfter(sessionId, options) } @@ -824,8 +834,19 @@ export class SyncEngine { } handleSessionReady(payload: { sid: string; time: number }): void { - this.sessionReadyIds.add(payload.sid) const session = this.sessionCache.getSession(payload.sid) + if (session?.metadata?.flavor === 'opencode' && session.metadata.opencodeForkPending) { + if (session.metadata.conversationHistoryDiverged + || session.metadata.opencodeHistoryCheckpoint?.sessionId !== session.metadata.opencodeSessionId + || session.metadata.opencodeHistoryCheckpoint?.localMessageIds?.length !== 0 + || session.metadata.opencodeHistoryCheckpoint?.localPublicationPending) return + try { + this.completeOpencodeForkValidation(payload.sid, session.namespace) + } catch { + return + } + } + this.sessionReadyIds.add(payload.sid) if (session?.active && session.metadata?.codexResumePending && session.metadata.codexResumePending.nativeSessionId === session.metadata.codexSessionId) { this.writeCodexResumePending(session.id, session.namespace, undefined) @@ -1694,7 +1715,9 @@ export class SyncEngine { this.sessionCache.reconcileKeepaliveIdle() // Piggybacked on the inactivity tick; not a logical part of expireInactive // but shares its 5s cadence (avoids a second timer). - this.messageService.releaseMatureScheduledMessages(Date.now(), this.historyActionsInFlight) + const held = new Set(this.historyActionsInFlight) + for (const session of this.sessionCache.getSessions()) if (this.openCodeRewindPending(session.id)) held.add(session.id) + this.messageService.releaseMatureScheduledMessages(Date.now(), held) void this.reconcileOpenCodeClears() } @@ -1793,7 +1816,7 @@ export class SyncEngine { deliveryMode?: MessageDeliveryMode } ): Promise { - if (this.historyActionsInFlight.has(sessionId)) { + if (this.historyActionsInFlight.has(sessionId) || this.openCodeRewindPending(sessionId)) { throw new Error('Conversation history action already in progress') } if (!this.sessionCache.getSession(sessionId)?.thinking) { @@ -1815,6 +1838,7 @@ export class SyncEngine { sessionId: string, messageId: string ): Promise { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') return this.messageService.retryIndeterminateMessage(sessionId, messageId) } @@ -1829,6 +1853,7 @@ export class SyncEngine { sessionId: string, messageId: string ): Promise { + if (this.openCodeRewindPending(sessionId)) return { status: 'failed', error: 'OpenCode rewind requires reconciliation', localId: null } const session = this.getSession(sessionId) if (!session) { return { status: 'failed', error: 'Session not found', localId: null } @@ -1918,10 +1943,12 @@ export class SyncEngine { } async abortSession(sessionId: string): Promise { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') await this.rpcGateway.abortSession(sessionId) } private assertConversationHistoryIdle(session: Session, allowRunningHistoricalFork = false): void { + if (this.openCodeRewindPending(session.id)) throw new Error('OpenCode rewind requires reconciliation') if (!session.active) { throw new Error('Session must be active') } @@ -2010,7 +2037,7 @@ export class SyncEngine { private async waitForExactNativeForkBound( childId: string, expectedNativeSessionId: string, - metadataKey: 'grokSessionId' | 'piSessionId' | 'codexSessionId', + metadataKey: 'grokSessionId' | 'piSessionId' | 'opencodeSessionId' | 'codexSessionId', requireSessionReady: boolean, timeoutMs: number = 60_000 ): Promise { @@ -2123,6 +2150,22 @@ export class SyncEngine { } } + private completeOpencodeForkValidation(sessionId: string, namespace: string): void { + for (let attempt = 0; attempt < 3; attempt += 1) { + const session = this.sessionCache.refreshSession(sessionId) + if (!session?.metadata || session.namespace !== namespace) throw new Error('OpenCode fork child disappeared') + if (!session.metadata.opencodeForkPending) return + const result = this.store.sessions.updateSessionMetadata(sessionId, + { ...session.metadata, opencodeForkPending: undefined }, session.metadataVersion, namespace, { touchUpdatedAt: false }) + if (result.result === 'success') { + this.sessionCache.refreshSession(sessionId) + return + } + if (result.result !== 'version-mismatch') break + } + throw new Error('OpenCode fork child validation could not be committed') + } + private markConversationHistoryDiverged(sessionId: string, namespace: string): void { for (let attempt = 0; attempt < 3; attempt += 1) { const session = this.sessionCache.getSessionByNamespace(sessionId, namespace) @@ -2410,6 +2453,12 @@ export class SyncEngine { source = refreshedSource const flavor = this.resolveFlavor(source) + if (flavor === 'opencode' + && (rpcResult.opencodeHistoryCheckpoint?.sessionId !== rpcResult.nativeSessionId + || rpcResult.opencodeHistoryCheckpoint.localMessageIds?.length !== 0 + || rpcResult.opencodeHistoryCheckpoint.localPublicationPending)) { + return { type: 'error', message: 'OpenCode fork did not return a verified child history checkpoint' } + } const childId = randomUUID() let prefix try { @@ -2449,6 +2498,9 @@ export class SyncEngine { } if (flavor === 'codex') { childMetadata.codexSessionId = rpcResult.nativeSessionId + } else if (flavor === 'opencode') { + childMetadata.opencodeHistoryCheckpoint = rpcResult.opencodeHistoryCheckpoint + childMetadata.opencodeForkPending = true } else if (flavor === 'grok') { childMetadata.grokSessionId = rpcResult.nativeSessionId } else if (flavor === 'pi') { @@ -2554,6 +2606,19 @@ export class SyncEngine { } } + if (flavor === 'opencode') { + // The CLI seeds opencodeSessionId from the resume id before ACP + // initialize, so only the validated session-ready fence proves + // the forked native session actually loaded. + const bound = await this.waitForExactNativeForkBound( + childId, rpcResult.nativeSessionId, 'opencodeSessionId', true + ) + if (!bound) { + throw new Error('OpenCode fork could not load the forked native session') + } + this.completeOpencodeForkValidation(childId, namespace) + } + return { type: 'success', sessionId: childId } } catch (error) { if (childCreated) { @@ -2627,6 +2692,8 @@ export class SyncEngine { return { type: 'error', message: error instanceof Error ? error.message : String(error) } } + if (session.metadata?.flavor === 'opencode') return await this.rewindOpenCode(session, namespace, messageLocalId) + let rpcResult: Awaited> try { rpcResult = await this.rpcGateway.rewindConversation(sessionId, { messageLocalId }) @@ -2678,13 +2745,167 @@ export class SyncEngine { } } + private openCodeRewindPending(sessionId: string): boolean { + const phase = (this.store.sessions.getSession(sessionId)?.metadata as Session['metadata'])?.opencodeRewind?.phase + return phase === 'reserved' || phase === 'prepared' || phase === 'unknown' + } + + private async rewindOpenCode(session: Session, namespace: string, localId: string): Promise<{ type: 'success' } | { type: 'error'; message: string }> { + const current = this.store.sessions.getSession(session.id)! + const metadata = MetadataSchema.parse(current.metadata) + const checkpoint = metadata.opencodeHistoryCheckpoint + const index = metadata.conversationHistoryIndexes?.[localId] + const nativeMessageId = index === undefined ? undefined : checkpoint?.userMessageIds[index] + if (!metadata.opencodeWorkerId || !metadata.opencodeWorkerProcess + || metadata.opencodeWorkerProcess.workerId !== metadata.opencodeWorkerId + || !checkpoint || !nativeMessageId || checkpoint.localPublicationPending + || checkpoint.localMessageIds === undefined || checkpoint.sessionId !== metadata.opencodeSessionId) { + return { type: 'error', message: 'OpenCode rewind requires a verified native boundary and worker' } + } + const messages = this.store.messages.getAllMessages(session.id) + const boundary = messages.find(m => m.localId === localId && m.invokedAt != null) + if (!boundary) return { type: 'error', message: 'History boundary is not invoked' } + const operation: OpenCodeRewindOperation = { operationId: randomUUID(), nativeSessionId: checkpoint.sessionId, + workerId: metadata.opencodeWorkerId, workerPid: metadata.opencodeWorkerProcess.pid, workerStartMarker: metadata.opencodeWorkerProcess.startMarker, + requestedLocalId: localId, nativeMessageId, cutoffSeq: boundary.seq, + sourceEpoch: this.store.messages.getMessageEpoch(session.id), sourceMaxSeq: Math.max(0, ...messages.map(m => m.seq)), + sourceTranscriptHash: createHash('sha256').update(JSON.stringify(messages)).digest('hex'), + reservationVersion: current.metadataVersion + 1, phase: 'reserved' } + // Durable reservation before the first native/RPC await. No generic + // metadata retry can reserve against a different source version. + const reserved = this.store.sessions.updateSessionMetadata(session.id, { ...metadata, opencodeRewind: operation }, current.metadataVersion, namespace) + if (reserved.result !== 'success') return { type: 'error', message: 'OpenCode source metadata changed before reservation' } + this.sessionCache.refreshSession(session.id) + try { + await this.rpcGateway.rewindConversation(session.id, { messageLocalId: localId, opencodeRewind: operation }) + } catch { /* durable state below is authoritative, never an RPC success alone */ } + const latest = (this.store.sessions.getSession(session.id)?.metadata as Session['metadata'])?.opencodeRewind + if (latest?.operationId === operation.operationId && latest.phase === 'committed') return { type: 'success' } + return { type: 'error', message: 'OpenCode rewind remains blocked pending native/Hub reconciliation' } + } + + reportOpenCodeRewind(sessionId: string, namespace: string, report: OpenCodeRewindReport, expectedVersion: number): OpenCodeRewindOperation { + let invalidated = false + const operation = this.store.runInTransaction(() => { + const current = this.store.sessions.getSession(sessionId) + if (!current || current.namespace !== namespace) throw new Error('Session access denied') + const metadata = MetadataSchema.parse(current.metadata) + const op = metadata.opencodeRewind + const incoming = report.operation + const keys = ['operationId', 'nativeSessionId', 'workerId', 'workerPid', 'workerStartMarker', 'requestedLocalId', 'nativeMessageId', + 'cutoffSeq', 'sourceEpoch', 'sourceMaxSeq', 'reservationVersion', 'sourceTranscriptHash'] as const + if (!op || keys.some(key => op[key] !== incoming[key]) || metadata.opencodeSessionId !== op.nativeSessionId) throw new Error('OpenCode rewind operation mismatch') + // Check the operation tombstone BEFORE the optimistic version/cutoff. + // An old report after a new turn cannot truncate that turn again. + if (op.phase === 'committed') { + if (report.phase === 'applied' && (report.sourceHash !== op.sourceHash || report.prefixHash !== op.prefixHash)) throw new Error('Committed proof mismatch') + return op + } + if (op.phase === 'rejected') return op + if (current.metadataVersion !== expectedVersion) throw new Error('OpenCode rewind metadata version changed') + let next: OpenCodeRewindOperation = { ...op } + let nextMetadata = metadata + // A reserved operation has not durably authorized native mutation. + // Keep it rejectable when preparation failed before persistence. + if (report.phase === 'unknown') next.phase = op.phase === 'reserved' ? 'reserved' : 'unknown' + else if (report.phase === 'rejected') { + if (op.phase !== 'reserved' && !(report.unchanged && op.sourceHash === report.sourceHash && op.prefixHash === report.prefixHash)) { + throw new Error('Native mutation cannot be rejected without recovery evidence') + } + next.phase = 'rejected' + } else { + const rows = this.store.messages.getAllMessages(sessionId) + const hubBoundary = rows.find(m => m.localId === op.requestedLocalId && m.seq === op.cutoffSeq && m.invokedAt != null) + if (this.store.messages.getMessageEpoch(sessionId) !== op.sourceEpoch + || createHash('sha256').update(JSON.stringify(rows)).digest('hex') !== op.sourceTranscriptHash + || Math.max(0, ...rows.map(m => m.seq)) !== op.sourceMaxSeq + || !hubBoundary + || this.store.messages.getUninvokedLocalMessages(sessionId).length) throw new Error('OpenCode source transcript changed') + if (!report.sourceHash?.match(/^[a-f0-9]{64}$/) || !report.prefixHash?.match(/^[a-f0-9]{64}$/)) throw new Error('Missing native source/prefix proof') + if (report.phase === 'prepared') { + if (op.phase !== 'reserved') throw new Error('OpenCode preparation is not repeatable after mutation') + next = { ...op, phase: 'prepared', sourceHash: report.sourceHash, prefixHash: report.prefixHash } + } else { + if (op.sourceHash !== report.sourceHash || op.prefixHash !== report.prefixHash) throw new Error('Native proof does not match the prepared operation') + const checkpoint = report.checkpoint + const source = metadata.opencodeHistoryCheckpoint + const boundary = source?.messageIds.indexOf(op.nativeMessageId) ?? -1 + const expected = source?.messageIds.slice(0, boundary) + if (!checkpoint || boundary < 0 || checkpoint.sessionId !== op.nativeSessionId || checkpoint.localPublicationPending + || checkpoint.localMessageIds === undefined || JSON.stringify(checkpoint.messageIds) !== JSON.stringify(expected) + || JSON.stringify(checkpoint.userMessageIds) !== JSON.stringify(source!.userMessageIds.slice(0, source!.userMessageIds.indexOf(op.nativeMessageId)))) { + throw new Error('Retained native checkpoint does not match the requested boundary') + } + const indexes: Record = {} + for (const [local, index] of Object.entries(metadata.conversationHistoryIndexes ?? {})) { + const target = source!.userMessageIds[index] + const nextIndex = checkpoint.userMessageIds.indexOf(target!) + if (nextIndex >= 0) indexes[local] = nextIndex + } + if (JSON.stringify(Object.entries(indexes).sort()) !== JSON.stringify(Object.entries(report.indexes ?? {}).sort())) throw new Error('Retained locator mismatch') + this.store.messages.truncateOpenCodeRewind(sessionId, op.cutoffSeq, hubBoundary.id) + next = { ...op, phase: 'committed' } + nextMetadata = { ...metadata, opencodeHistoryCheckpoint: checkpoint, conversationHistoryIndexes: indexes, + conversationHistoryPoints: Object.fromEntries(Object.keys(indexes).map(key => [key, true as const])) } + invalidated = true + } + } + const updated = this.store.sessions.updateSessionMetadata(sessionId, { ...nextMetadata, opencodeRewind: next }, current.metadataVersion, namespace) + if (updated.result !== 'success') throw new Error('OpenCode rewind metadata CAS failed') + if (invalidated) { + const todos = this.store.messages.getAllMessages(sessionId).map(m => extractTodoWriteTodosFromMessageContent(m.content)).filter(Boolean).at(-1) ?? null + this.store.sessions.replaceSessionTodos(sessionId, todos, namespace) + } + return next + }) + // Only publish after the encompassing database transaction commits. + this.sessionCache.refreshSession(sessionId) + if (invalidated) this.eventPublisher.emit({ type: 'messages-invalidated', sessionId, namespace, reason: 'rewind', truncateFromLocalId: operation.requestedLocalId }) + return operation + } + + async prepareOpenCodeSessionStop(sessionId: string, pid: number, processStartMarker: string, + preparationLease: SessionStopPreparationLease, machineId: string): Promise<'ready' | 'not_required'> { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') + const metadata = this.sessionCache.getSession(sessionId)?.metadata + if (metadata?.machineId !== machineId) throw new Error('Session machine does not match runner') + if (metadata?.flavor !== 'opencode') return 'not_required' + // Only request the session RPC here. Calling archiveSession would + // recurse into the runner's StopSession handler that is awaiting us. + const requestPreparation = async () => this.rpcGateway.killSession(sessionId, { + prepareOnly: true, expectedMachineId: machineId, expectedPid: pid, expectedProcessStartMarker: processStartMarker, preparationLease + }) + let result: Awaited> + try { + result = await requestPreparation() + } catch (error) { + // KillSession's beforeKill drain may already have completed while + // the CLI's async cleanup closed the session socket: honor the + // remembered drained generation for this exact target instead of + // failing the runner's stop coordination. + const drained = this.archiveDrainedGenerations.get(sessionId) + if (!drained || drained.machineId !== machineId || drained.pid !== pid + || drained.processStartMarker !== processStartMarker) throw error + result = { pid, machineId, processStartMarker, preparationLease } + } + if (result.pid !== pid || result.processStartMarker !== processStartMarker || result.machineId !== machineId) { + throw new Error('Session shutdown preparation did not confirm the target generation') + } + if (result.preparationLease?.id !== preparationLease.id || result.preparationLease.expiresAt !== preparationLease.expiresAt) { + throw new Error('Session shutdown preparation did not confirm the lease') + } + return 'ready' + } + async archiveSession(sessionId: string): Promise { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') const existing = this.archiveRequests.get(sessionId) if (existing) return existing const operation = this.archiveSessionOnce(sessionId) this.archiveRequests.set(sessionId, operation) try { await operation } finally { if (this.archiveRequests.get(sessionId) === operation) this.archiveRequests.delete(sessionId) + this.archiveDrainedGenerations.delete(sessionId) } } @@ -2736,6 +2957,12 @@ export class SyncEngine { const sessionMeta = this.sessionCache.getSession(sessionId)?.metadata const machineId = sessionMeta?.codexResumePending?.machineId ?? sessionMeta?.machineId + // Remember the drained generation so a concurrent prepare-stop can + // still be honored after the CLI's cleanup disconnects the socket. + if (machineId && typeof killPid === 'number' && killPid > 0 + && typeof killProcessStartMarker === 'string' && killProcessStartMarker.length > 0) { + this.archiveDrainedGenerations.set(sessionId, { machineId, pid: killPid, processStartMarker: killProcessStartMarker }) + } const runnerSpawned = Boolean(sessionMeta?.codexResumePending) || sessionMeta?.startedBy === 'runner' || sessionMeta?.startedFromRunner === true if (machineId && runnerSpawned) { @@ -3025,6 +3252,7 @@ export class SyncEngine { } async clearConversation(sessionId: string, namespace: string): Promise<{ sessionId: string }> { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') const access = this.sessionCache.resolveSessionAccess(sessionId, namespace) if (!access.ok || !access.session.active || !access.session.metadata?.capabilities?.concurrentClients) { throw new Error('Clear requires an active shared session') @@ -3048,6 +3276,7 @@ export class SyncEngine { } async switchSession(sessionId: string, to: 'remote' | 'local'): Promise { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') if (this.getSession(sessionId)?.metadata?.capabilities?.concurrentClients) throw new Error('control_mode_not_applicable') if (this.historyActionsInFlight.has(sessionId)) { throw new Error('Conversation history action already in progress') @@ -3068,6 +3297,7 @@ export class SyncEngine { } async deleteSession(sessionId: string): Promise { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') if (this.sessionCache.getSession(sessionId)?.metadata?.codexResumePending) throw new Error('Codex resume startup is unconfirmed; archive to confirm termination before deleting') if (this.historyActionsInFlight.has(sessionId) || this.archivedForkPending(sessionId)) { throw new Error('Archived fork is pending; reconcile it before deleting the source') @@ -3091,6 +3321,7 @@ export class SyncEngine { } ): Promise { const session = this.sessionCache.getSession(sessionId) + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') if (!session?.active) { // For inactive sessions, update the in-memory cache directly without // an RPC call — the CLI is not running yet. The updated value will be @@ -3279,6 +3510,7 @@ export class SyncEngine { * source still owns an in-flight OpenCode turn or native compaction. */ async clearOpenCodeSession(sessionId: string, namespace: string): Promise { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') const clearTailKey = `${namespace}:${sessionId}` const existing = this.opencodeClearTails.get(clearTailKey) if (existing) { @@ -4850,6 +5082,7 @@ export class SyncEngine { } async handoffSessionToLocal(sessionId: string, namespace: string): Promise { + if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') const access = this.sessionCache.resolveSessionAccess(sessionId, namespace) if (!access.ok) { return { diff --git a/hub/src/sync/syncEngineArchiveSession.test.ts b/hub/src/sync/syncEngineArchiveSession.test.ts index db70db69..63578375 100644 --- a/hub/src/sync/syncEngineArchiveSession.test.ts +++ b/hub/src/sync/syncEngineArchiveSession.test.ts @@ -13,6 +13,7 @@ import type { SessionCache } from './sessionCache' * when the runner reports the process still alive (or unknown). */ describe('SyncEngine.archiveSession runner reaping (#1910)', () => { + const preparationLease = { id: 'fixture', expiresAt: 123456 } let store: Store let engine: SyncEngine const NAMESPACE = 'default' @@ -25,7 +26,7 @@ describe('SyncEngine.archiveSession runner reaping (#1910)', () => { tag: string, machineId?: string, hostPid?: number, - opts?: { startedBy?: 'runner' | 'terminal'; startedFromRunner?: boolean } + opts?: { startedBy?: 'runner' | 'terminal'; startedFromRunner?: boolean; flavor?: 'claude' | 'opencode' } ): string { const startedBy = opts?.startedBy ?? 'runner' const created = cache().getOrCreateSession( @@ -33,7 +34,7 @@ describe('SyncEngine.archiveSession runner reaping (#1910)', () => { { path: '/tmp/proj', host: 'localhost', - flavor: 'claude', + flavor: opts?.flavor ?? 'claude', startedBy, ...(opts?.startedFromRunner !== undefined ? { startedFromRunner: opts.startedFromRunner } @@ -66,6 +67,166 @@ describe('SyncEngine.archiveSession runner reaping (#1910)', () => { engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) }) + function setRewindPhase(id: string, phase: 'reserved' | 'prepared' | 'unknown' | 'rejected'): void { + const current = store.sessions.getSession(id)! + const operation = { operationId: 'archive-guard', nativeSessionId: 'native', workerId: 'worker', + requestedLocalId: 'turn', nativeMessageId: 'native-turn', cutoffSeq: 1, sourceEpoch: 0, + sourceMaxSeq: 1, reservationVersion: 1, sourceTranscriptHash: 'a'.repeat(64), phase } + expect(store.sessions.updateSessionMetadata(id, { ...current.metadata as object, opencodeRewind: operation }, + current.metadataVersion, NAMESPACE).result).toBe('success') + cache().refreshSession(id) + } + + it.each(['reserved', 'prepared', 'unknown'] as const)('blocks archive and process preparation before side effects during %s rewind', async phase => { + const id = insertActiveSession(`archive-${phase}`, 'machine-x', 123, { flavor: 'opencode' }) + setRewindPhase(id, phase) + let calls = 0 + ;(engine as unknown as { rpcGateway: { killSession: unknown } }).rpcGateway.killSession = async () => { calls++; return {} } + await expect(engine.archiveSession(id)).rejects.toThrow('reconciliation') + await expect(engine.prepareOpenCodeSessionStop(id, 123, 'gen', preparationLease, 'machine-x')).rejects.toThrow('reconciliation') + expect(calls).toBe(0) + expect(cache().getSession(id)?.active).toBe(true) + }) + + it('checks rewind before joining archive singleflight and releases failed cleanup for a safe retry', async () => { + const id = insertActiveSession('archive-combined', 'machine-x', 123, { flavor: 'opencode' }) + store.messages.addMessage(id, { role: 'user', content: 'preserve' }, 'turn') + let killCalls = 0, runnerCalls = 0 + let fail!: (error: Error) => void, entered!: () => void + const runnerEntered = new Promise(resolve => { entered = resolve }) + ;(engine as unknown as { rpcGateway: { killSession: unknown } }).rpcGateway.killSession = async () => { killCalls++; return {} } + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = async () => { + runnerCalls++ + if (runnerCalls > 1) return 'already_gone' + return new Promise((_resolve, reject) => { fail = reject; entered() }) + } + const outcomes = Promise.allSettled([engine.archiveSession(id), engine.archiveSession(id)]) + await runnerEntered + expect(killCalls).toBe(1) + expect(runnerCalls).toBe(1) + setRewindPhase(id, 'unknown') + await expect(engine.archiveSession(id)).rejects.toThrow('reconciliation') + fail(new RunnerStopRpcError(true, new Error('ACK timed out'))) + for (const result of await outcomes) { + expect(result.status).toBe('rejected') + if (result.status === 'rejected') { + expect(result.reason).toBeInstanceOf(ArchiveCleanupError) + expect(result.reason.status).toBe(504) + } + } + expect(cache().getSession(id)?.active).toBe(true) + expect(store.messages.getAllMessages(id)).toHaveLength(1) + expect(store.messages.getMessageEpoch(id)).toBe(0) + setRewindPhase(id, 'rejected') + await engine.archiveSession(id) + expect(killCalls).toBe(2) + expect(runnerCalls).toBe(2) + expect(cache().getSession(id)?.metadata?.lifecycleState).toBe('archived') + expect(store.messages.getAllMessages(id)).toHaveLength(1) + }) + + it('prepares a direct OpenCode stop by awaiting KillSession without recursing into StopSession', async () => { + const id = insertActiveSession('opencode-stop', 'machine-x', 123, { flavor: 'opencode' }) + let release!: () => void + let runnerCalls = 0 + ;(engine as unknown as { rpcGateway: { killSession: unknown } }).rpcGateway.killSession = (_id: string, options: unknown) => { + expect(options).toEqual({ prepareOnly: true, expectedMachineId: 'machine-x', expectedPid: 123, expectedProcessStartMarker: 'gen-a', preparationLease }) + return new Promise((resolve) => { release = () => resolve({ pid: 123, machineId: 'machine-x', processStartMarker: 'gen-a', preparationLease }) }) + } + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = () => { runnerCalls++; throw new Error('recursive stop') } + let ready = false + const preparation = engine.prepareOpenCodeSessionStop(id, 123, 'gen-a', preparationLease, 'machine-x').then((status) => { ready = true; return status }) + await Promise.resolve() + expect(ready).toBe(false) + release() + expect(await preparation).toBe('ready') + expect(runnerCalls).toBe(0) + }) + + it('keeps direct OpenCode shutdown unconfirmed when its RPC is unreachable', async () => { + const id = insertActiveSession('opencode-offline', 'machine-x', 123, { flavor: 'opencode' }) + setKillSessionMissingTarget() + await expect(engine.prepareOpenCodeSessionStop(id, 123, 'gen-a', preparationLease, 'machine-x')).rejects.toBeInstanceOf(RpcTargetMissingError) + expect(cache().getSession(id)?.active).toBe(true) + }) + + it('honors the archive-drained generation when the session socket dies before prepare-stop', async () => { + const id = insertActiveSession('opencode-drained', 'machine-x', 123, { flavor: 'opencode' }) + const gateway = engine as unknown as { rpcGateway: { killSession: unknown; stopRunnerSession: unknown } } + gateway.rpcGateway.killSession = async (_id: string, options?: { prepareOnly?: boolean }) => { + if (options?.prepareOnly) throw new RpcTargetMissingError('KillSession', 'socket-disconnected') + return { pid: 123, processStartMarker: 'gen-a' } + } + let enteredRunner!: () => void + let releaseRunner!: () => void + const runnerEntered = new Promise(resolve => { enteredRunner = resolve }) + const holdRunner = new Promise(resolve => { releaseRunner = resolve }) + gateway.rpcGateway.stopRunnerSession = async () => { + // Park the archive mid-flight: KillSession drained, the CLI socket + // is closing, the runner prepare-stop is about to arrive. + enteredRunner() + await holdRunner + return 'already_gone' + } + const archive = engine.archiveSession(id) + await runnerEntered + await expect(engine.prepareOpenCodeSessionStop(id, 123, 'gen-a', preparationLease, 'machine-x')).resolves.toBe('ready') + releaseRunner() + await archive + // The remembered generation is scoped to the archive in flight: after + // cleanup, an unreachable socket is unconfirmed again. + setKillSessionMissingTarget() + await expect(engine.prepareOpenCodeSessionStop(id, 123, 'gen-a', preparationLease, 'machine-x')).rejects.toBeInstanceOf(RpcTargetMissingError) + }) + + it('does not honor a drained generation for a different wrapper generation', async () => { + const id = insertActiveSession('opencode-drained-other', 'machine-x', 123, { flavor: 'opencode' }) + const gateway = engine as unknown as { rpcGateway: { killSession: unknown; stopRunnerSession: unknown } } + gateway.rpcGateway.killSession = async (_id: string, options?: { prepareOnly?: boolean }) => { + if (options?.prepareOnly) throw new RpcTargetMissingError('KillSession', 'socket-disconnected') + return { pid: 123, processStartMarker: 'gen-a' } + } + let enteredRunner!: () => void + let releaseRunner!: () => void + const runnerEntered = new Promise(resolve => { enteredRunner = resolve }) + const holdRunner = new Promise(resolve => { releaseRunner = resolve }) + gateway.rpcGateway.stopRunnerSession = async () => { + enteredRunner() + await holdRunner + return 'already_gone' + } + const archive = engine.archiveSession(id) + await runnerEntered + await expect(engine.prepareOpenCodeSessionStop(id, 999, 'gen-a', preparationLease, 'machine-x')).rejects.toBeInstanceOf(RpcTargetMissingError) + await expect(engine.prepareOpenCodeSessionStop(id, 123, 'gen-other', preparationLease, 'machine-x')).rejects.toBeInstanceOf(RpcTargetMissingError) + releaseRunner() + await archive + }) + + it('skips other flavors but does not trust archived metadata as preparation for a live OpenCode process', async () => { + setKillSessionMissingTarget() + const claude = insertActiveSession('claude-stop', 'machine-x') + expect(await engine.prepareOpenCodeSessionStop(claude, 123, 'gen-a', preparationLease, 'machine-x')).toBe('not_required') + const archived = cache().getOrCreateSession('archived-opencode', { + path: '/tmp/proj', host: 'localhost', flavor: 'opencode', lifecycleState: 'archived', machineId: 'machine-x' + }, null, NAMESPACE) + await expect(engine.prepareOpenCodeSessionStop(archived.id, 123, 'gen-a', preparationLease, 'machine-x')).rejects.toBeInstanceOf(RpcTargetMissingError) + }) + + it('rejects preparation acknowledged by a different wrapper generation', async () => { + const id = insertActiveSession('opencode-other-generation', 'machine-x', 123, { flavor: 'opencode' }) + setKillSessionOk({ pid: 456, processStartMarker: 'gen-b' }) + await expect(engine.prepareOpenCodeSessionStop(id, 123, 'gen-a', preparationLease, 'machine-x')).rejects.toThrow('target generation') + }) + + it('rechecks the runner machine before addressing a process alias', async () => { + const id = insertActiveSession('machine-transition', 'machine-new', 123, { flavor: 'opencode' }) + let called = false + ;(engine as unknown as { rpcGateway: { killSession: unknown } }).rpcGateway.killSession = async () => { called = true; return {} } + await expect(engine.prepareOpenCodeSessionStop(id, 123, 'gen-a', preparationLease, 'machine-old')).rejects.toThrow('machine') + expect(called).toBe(false) + }) + it('coalesces concurrent archive requests and releases the operation after completion', async () => { const sessionId = insertActiveSession('concurrent-archive', 'machine-x') setKillSessionOk() diff --git a/hub/src/web/routes/cli.test.ts b/hub/src/web/routes/cli.test.ts index a6ddc92f..35e83e6c 100644 --- a/hub/src/web/routes/cli.test.ts +++ b/hub/src/web/routes/cli.test.ts @@ -22,6 +22,42 @@ beforeAll(async () => { config._setCliApiToken('test-token', 'env', false) }) +describe('cli shutdown preparation', () => { + function fixture(machineId = 'machine-1') { + let calls = 0 + let fail = false + const app = createApp({ + resolveSessionAccess: (_id: string, namespace: string) => namespace === 'default' + ? { ok: true, sessionId: 'session-1', session: { metadata: { machineId } } } + : { ok: false, reason: 'access-denied' }, + prepareOpenCodeSessionStop: async () => { calls++; if (fail) throw new Error('offline'); return 'ready' } + } as never) + const request = (runner: string, token = 'test-token') => app.request('/cli/sessions/session-1/prepare-stop', { + method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ machineId: runner, pid: 123, processStartMarker: 'gen-a', + preparationLease: { id: 'fixture', expiresAt: 123456 } }) + }) + return { request, calls: () => calls, offline: () => { fail = true } } + } + + it('requires the same namespace and runner machine before requesting shutdown', async () => { + const f = fixture() + expect((await f.request('machine-1', 'test-token:other')).status).toBe(403) + expect((await f.request('machine-2')).status).toBe(403) + expect(f.calls()).toBe(0) + const response = await f.request('machine-1') + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ status: 'ready', preparationLease: { id: 'fixture', expiresAt: 123456 } }) + expect(f.calls()).toBe(1) + }) + + it('returns an unconfirmed failure when the OpenCode drain cannot be acknowledged', async () => { + const f = fixture() + f.offline() + expect((await f.request('machine-1')).status).toBe(503) + }) +}) + describe('cli resume routes', () => { it('returns local resumable sessions', async () => { const app = createApp({ diff --git a/hub/src/web/routes/cli.ts b/hub/src/web/routes/cli.ts index 71fe5a1b..e57386b9 100644 --- a/hub/src/web/routes/cli.ts +++ b/hub/src/web/routes/cli.ts @@ -209,7 +209,7 @@ export function createCliRoutes(getSyncEngine: () => SyncEngine | null): Hono { +app.post('/sessions/:id/prepare-local-resume', async (c) => { const engine = getSyncEngine() if (!engine) { return c.json({ error: 'Not ready' }, 503) @@ -231,6 +231,40 @@ export function createCliRoutes(getSyncEngine: () => SyncEngine | null): Hono { + const engine = getSyncEngine() + if (!engine) return c.json({ error: 'Not ready' }, 503) + const { OpenCodeRewindReportSchema } = await import('@hapi/protocol/apiTypes') + const parsed = z.object({ report: OpenCodeRewindReportSchema, expectedVersion: z.number().int().nonnegative() }).safeParse(await c.req.json().catch(() => null)) + if (!parsed.success) return c.json({ error: 'Invalid rewind report' }, 400) + try { + const operation = engine.reportOpenCodeRewind(c.req.param('id'), c.get('namespace'), parsed.data.report, parsed.data.expectedVersion) + return c.json({ operation }) + } catch (error) { + return c.json({ error: error instanceof Error ? error.message : String(error) }, 409) + } + }) + + app.post('/sessions/:id/prepare-stop', async (c) => { + const engine = getSyncEngine() + if (!engine) return c.json({ error: 'Not ready' }, 503) + const access = resolveSessionForNamespace(engine, c.req.param('id'), c.get('namespace')) + if (!access.ok) return c.json({ error: access.error }, access.status) + const body = z.object({ machineId: z.string().min(1), pid: z.number().int().positive(), + processStartMarker: z.string().min(1), preparationLease: z.object({ id: z.string().min(1), + expiresAt: z.number().int().positive() }) }).safeParse(await c.req.json().catch(() => null)) + if (!body.success) return c.json({ error: 'Invalid body' }, 400) + if (access.session.metadata?.machineId !== body.data.machineId) { + return c.json({ error: 'Session machine does not match runner' }, 403) + } + try { + const status = await engine.prepareOpenCodeSessionStop(access.sessionId, body.data.pid, body.data.processStartMarker, body.data.preparationLease, body.data.machineId) + return c.json({ status, ...(status === 'ready' ? { preparationLease: body.data.preparationLease } : {}) }) + } catch { + return c.json({ error: 'Session shutdown preparation was not confirmed' }, 503) + } + }) + app.post('/sessions/:id/handoff-local', async (c) => { const engine = getSyncEngine() if (!engine) { diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 6ce1ac7d..02db0d73 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -6,7 +6,9 @@ import { DecryptedMessageSchema, MachineSchema, PermissionModeSchema, - SessionSchema + SessionSchema, + MetadataSchema, + OpenCodeRewindSchema } from './schemas' import { AgentFlavorSchema } from './modes' import { @@ -60,6 +62,7 @@ export const CliMessagesResponseSchema = z.object({ seq: z.number(), createdAt: z.number(), localId: z.string().nullable().optional(), + invokedAt: z.number().nullable().optional(), content: z.unknown() })) }) @@ -695,6 +698,7 @@ export type RewindConversationResponse = { export type ForkConversationRpcResult = { completedTurnId?: string nativeSessionId: string + opencodeHistoryCheckpoint?: NonNullable['opencodeHistoryCheckpoint'] /** Shared runtimes bind the child themselves; hub must not spawn another engine. */ sessionId?: string /** When true, hub must spawn with --fork-session (Claude). */ @@ -722,6 +726,17 @@ export type RewindConversationErrorCode = | 'ambiguous_native_boundary' | 'ambiguous_native_boundary_fork_safe' +export const OpenCodeRewindReportSchema = z.object({ + operation: OpenCodeRewindSchema, + phase: z.enum(['prepared', 'applied', 'unknown', 'rejected']), + sourceHash: z.string().regex(/^[a-f0-9]{64}$/).optional(), + prefixHash: z.string().regex(/^[a-f0-9]{64}$/).optional(), + unchanged: z.literal(true).optional(), + checkpoint: MetadataSchema.shape.opencodeHistoryCheckpoint, + indexes: z.record(z.string(), z.number().int().nonnegative()).optional() +}) +export type OpenCodeRewindReport = z.infer + export type RewindConversationRpcResult = { success: true /** Truncate HAPI transcript at/after this localId, then accept rehydrated history. */ diff --git a/shared/src/conversationHistory.ts b/shared/src/conversationHistory.ts index 60d31b76..dc84b1ea 100644 --- a/shared/src/conversationHistory.ts +++ b/shared/src/conversationHistory.ts @@ -64,6 +64,12 @@ export const GROK_CONVERSATION_HISTORY_INITIAL: ConversationHistoryCapabilitySta rewindToMessage: 'unknown' } +export const OPENCODE_CONVERSATION_HISTORY_INITIAL: ConversationHistoryCapabilityStates = { + forkCurrent: 'unknown', + forkAtMessage: 'unknown', + rewindToMessage: 'unknown' +} + export const PI_CONVERSATION_HISTORY_INITIAL: ConversationHistoryCapabilityStates = { forkCurrent: 'unknown', forkAtMessage: 'unknown', diff --git a/shared/src/rpcMethods.ts b/shared/src/rpcMethods.ts index e311983a..be0e1991 100644 --- a/shared/src/rpcMethods.ts +++ b/shared/src/rpcMethods.ts @@ -1,3 +1,8 @@ +export const DEFAULT_RPC_TIMEOUT_MS = 30_000 + +/** expiresAt uses the Runner/target machine's monotonic milliseconds, not wall time. */ +export type SessionStopPreparationLease = { id: string; expiresAt: number } + export const RPC_METHODS = { Permission: 'permission', Abort: 'abort', @@ -72,6 +77,11 @@ export const RPC_METHODS = { export const RPC_TARGET_MISSING_ERROR_CODE = 'rpc_target_missing' as const +/** Select the exact machine/PID; the handler still validates the OS start marker. */ +export function getSessionStopPreparationMethod(machineId: string, pid: number): string { + return `${RPC_METHODS.KillSession}/process/${encodeURIComponent(machineId)}/${pid}` +} + /** * Thrown by a permission handler's handleMissingPendingResponse when a * Permission RPC response arrives for a request the CLI no longer has diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index c34e2090..2f8fe63c 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -12,6 +12,18 @@ export const CopilotAgentModeSchema = z.union([ z.literal('fleet').transform((): CopilotAgentMode => 'interactive'), ]) export const SessionEndReasonSchema = z.enum(['completed', 'terminated', 'error', 'handoff', 'cleared']) +/** OpenCode-only durable operation. No native identity change or filesystem rewind. */ +export const OpenCodeRewindSchema = z.object({ + operationId: z.string().min(1), nativeSessionId: z.string().min(1), workerId: z.string().min(1), + workerPid: z.number().int().positive().optional(), workerStartMarker: z.string().min(1).optional(), + requestedLocalId: z.string().min(1), nativeMessageId: z.string().min(1), + cutoffSeq: z.number().int().positive(), sourceEpoch: z.number().int().nonnegative(), + sourceMaxSeq: z.number().int().nonnegative(), reservationVersion: z.number().int().nonnegative(), + sourceTranscriptHash: z.string().regex(/^[a-f0-9]{64}$/), + phase: z.enum(['reserved', 'prepared', 'unknown', 'committed', 'rejected']), + sourceHash: z.string().optional(), prefixHash: z.string().optional() +}) +export type OpenCodeRewindOperation = z.infer export type SessionEndReason = z.infer const MetadataSummarySchema = z.object({ @@ -187,6 +199,20 @@ export const MetadataSchema = z.object({ // Native locators for historical fork/rewind (e.g. Grok prompt indexes). // Kept separately from the boolean UI markers above. conversationHistoryIndexes: z.record(z.string(), z.number().int().nonnegative()).optional(), + opencodeHistoryCheckpoint: z.object({ + sessionId: z.string().min(1), + messageIds: z.array(z.string().min(1)), + userMessageIds: z.array(z.string().min(1)), + // Present even when empty once local publication tracking is enabled. + localMessageIds: z.array(z.string().min(1)).optional(), + localPublicationPending: z.literal(true).optional() + }).optional(), + // Hub-owned until the child's first validated session-ready is committed. + opencodeForkPending: z.literal(true).optional(), + opencodeWorkerId: z.string().optional(), + opencodeWorkerProcess: z.object({ workerId: z.string().min(1), pid: z.number().int().positive(), + startMarker: z.string().min(1) }).optional(), + opencodeRewind: OpenCodeRewindSchema.optional(), // Codex localId → turnId mapping (durable across runner relaunches). conversationHistoryTurns: z.record(z.string(), z.string().min(1)).optional(), // Pi localId → append-only session entry id mapping. Pi entry ids are the diff --git a/web/e2e-fixtures/opencode-fork-buttons-fixture.html b/web/e2e-fixtures/opencode-fork-buttons-fixture.html new file mode 100644 index 00000000..9bddb73a --- /dev/null +++ b/web/e2e-fixtures/opencode-fork-buttons-fixture.html @@ -0,0 +1,12 @@ + + + + + + HAPI opencode fork buttons e2e fixture + + +
+ + + diff --git a/web/e2e-fixtures/opencode-fork-buttons-fixture.tsx b/web/e2e-fixtures/opencode-fork-buttons-fixture.tsx new file mode 100644 index 00000000..a6261443 --- /dev/null +++ b/web/e2e-fixtures/opencode-fork-buttons-fixture.tsx @@ -0,0 +1,280 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import ReactDOM from 'react-dom/client' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { AssistantRuntimeProvider } from '@assistant-ui/react' +import '../src/index.css' +import type { ApiClient } from '../src/api/client' +import type { DecryptedMessage, MessagesResponse, Session } from '../src/types/api' +import { I18nProvider } from '../src/lib/i18n-context' +import { useMessages } from '../src/hooks/queries/useMessages' +import { normalizeDecryptedMessage } from '../src/chat/normalize' +import { reduceChatBlocks } from '../src/chat/reducer' +import { reconcileChatBlocks } from '../src/chat/reconcile' +import { buildVisibleChatBlocks } from '../src/chat/toolGroups' +import { isQueuedForInvocation } from '../src/lib/messages' +import { findLatestCompletedBoundaryId, useHappyRuntime } from '../src/lib/assistant-runtime' +import { resolveAssistantForkPoints } from '../src/lib/assistant-fork-points' +import { HappyThread } from '../src/components/AssistantChat/HappyThread' +import { resolveLatestCompletedBoundaryIdForView } from '../src/components/SessionChat' +import type { ChatBlock, NormalizedMessage } from '../src/chat/types' + +// OpenCode-flavor historical fork affordance: 3 completed user turns served +// through the real message-window store + chat pipeline into the real +// HappyThread. Every user message carries a localId that is present in +// metadata.conversationHistoryPoints, so every non-latest user card must +// render the historical Fork button — not just the last message. +const SESSION_ID = 'opencode-fork-buttons-fixture' +const BASE_AT = 1_700_000_000_000 +// Enough turns that the thread overflows the 900px e2e viewport, so the +// spec can scroll away from the bottom into `history` view mode. +const TURNS = 12 + +declare global { + interface Window { + __probe: { + boundaryId: string | null + viewMode: string + userCount: number + forkCountPerUser: number[] + forkCalls: (string | undefined)[] + } + } +} + +window.__probe = { boundaryId: null, viewMode: 'tail', userCount: 0, forkCountPerUser: [], forkCalls: [] } + +function wireUser(turn: number, seq: number): DecryptedMessage { + const at = BASE_AT + turn * 10_000 + return { + id: `u-msg-${turn}`, + seq, + localId: `u-local-${turn}`, + content: { + role: 'user', + content: { type: 'text', text: `Fixture user message ${turn}` }, + meta: { sentFrom: 'webapp' }, + }, + createdAt: at, + invokedAt: at, + } as unknown as DecryptedMessage +} + +function wireAgentReply(turn: number, seq: number): DecryptedMessage { + const at = BASE_AT + turn * 10_000 + return { + id: `a-msg-${turn}`, + seq, + localId: null, + content: { + role: 'agent', + content: { type: 'codex', data: new URLSearchParams(window.location.search).has('reasoning') + ? { type: 'reasoning', message: `Fixture reasoning reply ${turn}`, id: `native-${turn}` } + : { type: 'message', message: `Fixture assistant reply ${turn}`, id: `native-${turn}` } }, + meta: { sentFrom: 'cli' }, + }, + createdAt: at + 1_000, + invokedAt: at + 1_000, + } as unknown as DecryptedMessage +} + +const allMessages: DecryptedMessage[] = Array.from({ length: TURNS }, (_, index) => index + 1).flatMap((turn) => { + const seqBase = turn * 2 - 1 + return [wireUser(turn, seqBase), wireAgentReply(turn, seqBase + 1)] +}) + +const historyPoints = Object.fromEntries( + Array.from({ length: TURNS }, (_, index) => [`u-local-${index + 1}`, true]), +) +if (new URLSearchParams(window.location.search).has('missingPoint')) { + delete historyPoints['u-local-4'] +} + +const fakeApi = { + getMachines: async () => ({ machines: [] }), + getHubSettings: async () => ({}), + getMessages: async (): Promise => { + await new Promise((resolve) => setTimeout(resolve, 25)) + const newest = allMessages[allMessages.length - 1]! + return { + messages: allMessages, + page: { + direction: 'latest', + limit: 200, + epoch: 1, + reset: true, + nextBeforeSeq: allMessages[0]!.seq ?? null, + nextBeforeAt: null, + nextAfterSeq: null, + nextAfterAt: null, + snapshotHeadSeq: newest.seq ?? null, + snapshotHeadAt: newest.invokedAt ?? newest.createdAt, + hasMore: false, + }, + } + }, +} as unknown as ApiClient + +const fakeMetadata = { + path: '/tmp/fork-fixture', + host: 'fixture', + flavor: 'opencode', + capabilities: { + conversationHistory: { forkCurrent: true, forkAtMessage: true }, + }, + conversationHistoryPoints: historyPoints, +} as unknown as Session['metadata'] + +const fakeSession = { + id: SESSION_ID, + active: true, + thinking: false, + activeTurnStartedAt: null, + agentState: null, + metadata: fakeMetadata, +} as unknown as Session + +const noop = () => {} +const noopAsync = async () => {} + +const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: Infinity } }, +}) + +function FixtureThread() { + const { + messages, + warning, + isSyncingTail, + isLoadingMore, + hasMore, + messagesVersion, + historyVersion, + tailRevision, + viewMode, + loadMore, + cancelLoadMore, + setViewMode, + } = useMessages(fakeApi, SESSION_ID) + + const blocksByIdRef = useRef>(new Map()) + + const normalizedMessages = useMemo(() => { + const normalized: NormalizedMessage[] = [] + for (const message of messages) { + if (isQueuedForInvocation(message)) continue + const next = normalizeDecryptedMessage(message) + if (next) normalized.push(next) + } + return normalized + }, [messages]) + + const reduced = useMemo(() => reduceChatBlocks(normalizedMessages, null, {}), [normalizedMessages]) + const reconciled = useMemo( + () => reconcileChatBlocks(reduced.blocks, blocksByIdRef.current), + [reduced.blocks], + ) + blocksByIdRef.current = reconciled.byId + const visibleBlocks = useMemo( + () => buildVisibleChatBlocks(reconciled.blocks, { hasMoreMessages: hasMore }), + [reconciled.blocks, hasMore], + ) + + // Same boundary resolution as SessionChat: computed from the tail window, + // remembered while reading history so loading older pages cannot move it. + const currentTailBoundaryId = useMemo(() => { + if (viewMode !== 'tail') return null + return findLatestCompletedBoundaryId( + visibleBlocks, + fakeSession.thinking, + fakeSession.activeTurnStartedAt ?? null, + ) + }, [viewMode, visibleBlocks]) + const [rememberedTailBoundary, setRememberedTailBoundary] = useState<{ + id: string | null + tailRevision: number + } | null>(null) + useEffect(() => { + if (viewMode !== 'tail') return + setRememberedTailBoundary((previous) => ( + previous?.id === currentTailBoundaryId && previous.tailRevision === tailRevision + ? previous + : { id: currentTailBoundaryId, tailRevision } + )) + }, [currentTailBoundaryId, tailRevision, viewMode]) + const latestCompletedBoundaryId = resolveLatestCompletedBoundaryIdForView( + viewMode, + currentTailBoundaryId, + rememberedTailBoundary, + tailRevision, + ) + const isLatestCompletedBoundary = useCallback( + (messageId: string) => latestCompletedBoundaryId === messageId, + [latestCompletedBoundaryId], + ) + const assistantForkPoints = useMemo( + () => resolveAssistantForkPoints(visibleBlocks, historyPoints as Record), + [visibleBlocks] + ) + + const runtime = useHappyRuntime({ + session: fakeSession, + blocks: visibleBlocks, + messagesVersion, + historyVersion, + viewMode, + isSending: false, + onSendMessage: noop, + onAbort: noopAsync, + }) + + useEffect(() => { + window.__probe.boundaryId = latestCompletedBoundaryId + window.__probe.viewMode = viewMode + window.__probe.userCount = document.querySelectorAll('[data-hapi-message-role="user"]').length + window.__probe.forkCountPerUser = Array.from( + document.querySelectorAll('[data-hapi-message-role="user"]'), + ).map((card) => card.querySelectorAll('[data-testid="message-fork"]').length) + }) + + return ( + +
+ { window.__probe.forkCalls.push(localId) }} + isLatestCompletedBoundary={isLatestCompletedBoundary} + assistantForkPoints={assistantForkPoints} + onViewModeChange={setViewMode} + isSyncingTail={isSyncingTail} + messagesWarning={warning} + hasMoreMessages={hasMore} + isLoadingMoreMessages={isLoadingMore} + onLoadMore={loadMore} + onCancelLoadMore={cancelLoadMore} + unseenCount={0} + rawMessagesCount={messages.length} + normalizedMessagesCount={normalizedMessages.length} + messagesVersion={messagesVersion} + historyVersion={historyVersion} + forceScrollToken={0} + outlineOpen={false} + outlineItems={[]} + onOutlineOpenChange={noop} + /> +
+
+ ) +} + +ReactDOM.createRoot(document.getElementById('root')!).render( + + + + + , +) diff --git a/web/src/components/AssistantChat/HappyThread.tsx b/web/src/components/AssistantChat/HappyThread.tsx index f6860192..5f12eccd 100644 --- a/web/src/components/AssistantChat/HappyThread.tsx +++ b/web/src/components/AssistantChat/HappyThread.tsx @@ -696,6 +696,7 @@ export function HappyThread(props: { onForkConversation?: (messageLocalId?: string) => Promise onRewindConversation?: (messageLocalId: string) => Promise isLatestCompletedBoundary?: (messageId: string) => boolean + assistantForkPoints?: ReadonlyMap onViewModeChange: (mode: 'tail' | 'history') => void onJumpToTail?: () => void readThroughRevision?: number @@ -2522,6 +2523,7 @@ export function HappyThread(props: { onForkConversation: props.onForkConversation, onRewindConversation: props.onRewindConversation, isLatestCompletedBoundary: props.isLatestCompletedBoundary, + assistantForkPoints: props.assistantForkPoints, onShareTurn: handleShareTurn, hasMoreMessages: props.hasMoreMessages, isSyncingTail: props.isSyncingTail, diff --git a/web/src/components/AssistantChat/context.tsx b/web/src/components/AssistantChat/context.tsx index 3ddd09ec..b170fff9 100644 --- a/web/src/components/AssistantChat/context.tsx +++ b/web/src/components/AssistantChat/context.tsx @@ -24,6 +24,7 @@ export type HappyChatContextValue = { onForkConversation?: (messageLocalId?: string) => Promise onRewindConversation?: (messageLocalId: string) => Promise isLatestCompletedBoundary?: (messageId: string) => boolean + assistantForkPoints?: ReadonlyMap onShareTurn?: ( messageElement: HTMLElement | string | null, clientY?: number, diff --git a/web/src/components/AssistantChat/messages/AssistantMessage.tsx b/web/src/components/AssistantChat/messages/AssistantMessage.tsx index 7e1340be..47eb5f8a 100644 --- a/web/src/components/AssistantChat/messages/AssistantMessage.tsx +++ b/web/src/components/AssistantChat/messages/AssistantMessage.tsx @@ -65,12 +65,20 @@ export function HappyAssistantMessage() { const metadata = { durationMs, usage, model: messageModel ?? null, turnCount, roundSummary } const history = ctx.metadata?.capabilities?.conversationHistory + const historicalForkLocalId = ctx.assistantForkPoints?.get(messageId) const showForkCurrent = Boolean( (history?.forkCurrent || ctx.allowInactiveFork) && ctx.isLatestCompletedBoundary?.(messageId) && (!ctx.disabled || ctx.allowInactiveFork === true) && ctx.onForkConversation ) + const showHistoricalFork = Boolean( + !showForkCurrent + && history?.forkAtMessage + && historicalForkLocalId + && !ctx.disabled + && ctx.onForkConversation + ) const rootClass = toolOnly ? 'py-1 min-w-0 max-w-full overflow-x-hidden' @@ -93,9 +101,13 @@ export function HappyAssistantMessage() { copyText={copyText || undefined} metadata={metadata} messageElementId={elementId} - showFork={showForkCurrent} + showFork={showForkCurrent || showHistoricalFork} historyActionPending={ctx.historyActionPending} - onFork={showForkCurrent ? () => ctx.onForkConversation!() : undefined} + onFork={showForkCurrent + ? () => ctx.onForkConversation!() + : showHistoricalFork + ? () => ctx.onForkConversation!(historicalForkLocalId!) + : undefined} /> ) diff --git a/web/src/components/AssistantChat/messages/MessageActions.tsx b/web/src/components/AssistantChat/messages/MessageActions.tsx index 668fade7..cee26157 100644 --- a/web/src/components/AssistantChat/messages/MessageActions.tsx +++ b/web/src/components/AssistantChat/messages/MessageActions.tsx @@ -89,6 +89,7 @@ export function MessageActions({ {showFork && onFork && (!threadIsRunning || allowForkWhileRunning) ? ( setForkOpen(true)} > diff --git a/web/src/components/AssistantChat/messages/UserMessage.fork.test.tsx b/web/src/components/AssistantChat/messages/UserMessage.fork.test.tsx new file mode 100644 index 00000000..90d180a4 --- /dev/null +++ b/web/src/components/AssistantChat/messages/UserMessage.fork.test.tsx @@ -0,0 +1,194 @@ +import type { PropsWithChildren } from 'react' +import { useMemo, useRef } from 'react' +import { render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { + AssistantRuntimeProvider, + ThreadPrimitive, + unstable_useThreadMessageIds, +} from '@assistant-ui/react' +import { I18nProvider } from '@/lib/i18n-context' +import { reduceChatBlocks } from '@/chat/reducer' +import { reconcileChatBlocks } from '@/chat/reconcile' +import { buildVisibleChatBlocks } from '@/chat/toolGroups' +import { findLatestCompletedBoundaryId, useHappyRuntime } from '@/lib/assistant-runtime' +import { HappyChatProvider } from '@/components/AssistantChat/context' +import { HappyUserMessage } from '@/components/AssistantChat/messages/UserMessage' +import { HappyAssistantMessage } from '@/components/AssistantChat/messages/AssistantMessage' +import { HappySystemMessage } from '@/components/AssistantChat/messages/SystemMessage' +import type { ChatBlock, NormalizedMessage } from '@/chat/types' +import type { Session } from '@/types/api' + +vi.mock('@/hooks/useCopyToClipboard', () => ({ + useCopyToClipboard: () => ({ copied: false, copy: vi.fn() }), +})) + +vi.mock('@radix-ui/react-popover', () => ({ + Root: ({ children }: PropsWithChildren) => <>{children}, + Trigger: ({ children }: PropsWithChildren) => <>{children}, + Portal: ({ children }: PropsWithChildren) =>
{children}
, + Content: ({ children }: PropsWithChildren) =>
{children}
, +})) + +const BASE_AT = 1_700_000_000_000 + +function buildMessages(): NormalizedMessage[] { + return [1, 2, 3].flatMap((turn) => { + const at = BASE_AT + turn * 10_000 + return [ + { + id: `u-msg-${turn}`, + localId: `u-local-${turn}`, + createdAt: at, + invokedAt: at, + role: 'user', + content: { type: 'text', text: `Fixture user message ${turn}` }, + isSidechain: false, + }, + { + id: `a-msg-${turn}`, + localId: null, + createdAt: at + 1_000, + invokedAt: at + 1_000, + role: 'agent', + content: [{ type: 'text', text: `Fixture assistant reply ${turn}`, uuid: `a-uuid-${turn}`, parentUUID: null }], + isSidechain: false, + }, + ] as NormalizedMessage[] + }) +} + +const fakeMetadata = { + path: '/tmp/fork-fixture', + host: 'fixture', + flavor: 'opencode', + capabilities: { conversationHistory: { forkCurrent: true, forkAtMessage: true } }, + conversationHistoryPoints: { + 'u-local-1': true, + 'u-local-2': true, + 'u-local-3': true, + }, +} + +const fakeSession = { + id: 'fork-regression-session', + active: true, + thinking: false, + activeTurnStartedAt: null, + agentState: null, + metadata: fakeMetadata, +} as unknown as Session + +function ThreadMessages() { + const ids = unstable_useThreadMessageIds() + return ( + <> + {ids.map((id) => ( + + ))} + + ) +} + +function Harness({ boundaryProbe }: { boundaryProbe: { id: string | null } }) { + const blocksByIdRef = useRef>(new Map()) + const messages = useMemo(() => buildMessages(), []) + const reduced = useMemo(() => reduceChatBlocks(messages, null, {}), [messages]) + const reconciled = useMemo( + () => reconcileChatBlocks(reduced.blocks, blocksByIdRef.current), + [reduced.blocks], + ) + blocksByIdRef.current = reconciled.byId + const visibleBlocks = useMemo( + () => buildVisibleChatBlocks(reconciled.blocks, { hasMoreMessages: false }), + [reconciled.blocks], + ) + const boundaryId = useMemo( + () => findLatestCompletedBoundaryId(visibleBlocks, false, null), + [visibleBlocks], + ) + boundaryProbe.id = boundaryId + const runtime = useHappyRuntime({ + session: fakeSession, + blocks: visibleBlocks, + messagesVersion: 1, + historyVersion: 1, + viewMode: 'tail', + isSending: false, + onSendMessage: () => {}, + onAbort: async () => {}, + }) + return ( + + {}, + onForkConversation: async () => {}, + onRewindConversation: undefined, + isLatestCompletedBoundary: (id: string) => id === boundaryId, + onShareTurn: () => {}, + hasMoreMessages: false, + isSyncingTail: false, + isLoadingMoreMessages: false, + onNestedScrollFollowChange: () => {}, + loadOlderMessagesPreservingScroll: async () => ({ kind: 'stopped', reason: 'exhausted' }) as never, + }} + > + + + + + + ) +} + +// Regression guard for the OpenCode historical-fork affordance: with +// conversationHistory points on every completed user turn, the Fork button +// must render on every user message that has a point — not only on the +// last one. Mirrors e2e/opencode-fork-buttons.spec.ts, which covers the +// same contract in a real browser. +describe('UserMessage historical fork affordance', () => { + it('renders a Fork button on every user message that has a history point', async () => { + const boundaryProbe: { id: string | null } = { id: null } + render( + + + , + ) + const userCards = await screen.findAllByText(/Fixture user message \d/) + expect(userCards).toHaveLength(3) + for (const text of userCards) { + const card = text.closest('[data-hapi-message-role="user"]') + expect(card).not.toBeNull() + expect(card!.querySelectorAll('[data-testid="message-fork"]')).toHaveLength(1) + } + }) + + it('keeps current-only behavior on the latest completed boundary', async () => { + const boundaryProbe: { id: string | null } = { id: null } + render( + + + , + ) + await screen.findAllByText(/Fixture user message \d/) + expect(boundaryProbe.id).toMatch(/^agent-text:/) + const anchor = document.getElementById(`hapi-message-${boundaryProbe.id}`) + expect(anchor).not.toBeNull() + expect(anchor!.querySelectorAll('[data-testid="message-fork"]')).toHaveLength(1) + }) +}) diff --git a/web/src/components/SessionChat.tsx b/web/src/components/SessionChat.tsx index 2ada969c..ba4afa97 100644 --- a/web/src/components/SessionChat.tsx +++ b/web/src/components/SessionChat.tsx @@ -59,6 +59,7 @@ import { getSessionLastSeenAt } from '@/lib/sessionLastSeen' import { formatRelativeTime } from '@/lib/relativeTime' import { ScratchlistMigrationBanner } from '@/components/AssistantChat/ScratchlistMigrationBanner' import { assignThreadMessageIds, findLatestCompletedBoundaryId, useHappyRuntime } from '@/lib/assistant-runtime' +import { resolveAssistantForkPointsForCanonicalBlocks } from '@/lib/assistant-fork-points' import { getRestoredComposerSendIntent, resolveMessageDeliveryMode, @@ -1721,6 +1722,20 @@ function SessionChatInner(props: SessionChatProps) { isRunning: props.session.thinking } ) + const assistantForkPoints = useMemo( + // Resolve against the canonical thread: concise filtering hides + // compact-summary/system/CLI boundaries and would bridge an + // assistant fork point across them. + () => resolveAssistantForkPointsForCanonicalBlocks(reconciled.blocks, { + hasMoreMessages: props.hasMoreMessages, + previousGroups: visibleGroupsRef.current, + previousGroupingMode: visibleGroupsModeRef.current, + groupingMode: toolGroupingMode, + codexExplorationCollapsed + }, props.session.metadata?.conversationHistoryPoints), + [reconciled.blocks, props.hasMoreMessages, toolGroupingMode, codexExplorationCollapsed, + props.session.metadata?.conversationHistoryPoints] + ) const isLatestCompletedBoundary = useCallback((messageId: string) => { return latestCompletedBoundaryId === messageId }, [latestCompletedBoundaryId]) @@ -2193,6 +2208,7 @@ function SessionChatInner(props: SessionChatProps) { onForkConversation={controlledByUser && !sessionInactive ? undefined : onForkConversation} onRewindConversation={controlledByUser ? undefined : onRewindConversation} isLatestCompletedBoundary={isLatestCompletedBoundary} + assistantForkPoints={assistantForkPoints} onViewModeChange={props.onViewModeChange} onJumpToTail={props.onJumpToTail} readThroughRevision={!terminalVisible && props.viewMode === 'tail' ? props.readThroughRevision : undefined} diff --git a/web/src/lib/assistant-fork-points.test.ts b/web/src/lib/assistant-fork-points.test.ts new file mode 100644 index 00000000..b0245eca --- /dev/null +++ b/web/src/lib/assistant-fork-points.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import type { ChatBlock } from '@/chat/types' +import { assignThreadMessageIds } from '@/lib/assistant-runtime' +import { buildVisibleChatBlocks, type VisibleChatBlock } from '@/chat/toolGroups' +import { filterConciseChatBlocks } from '@/chat/conciseView' +import { resolveAssistantForkPoints, resolveAssistantForkPointsForCanonicalBlocks } from './assistant-fork-points' + +const user = (id: string): VisibleChatBlock => ({ + kind: 'user-text', id, localId: id, createdAt: 1, invokedAt: 1, text: id +}) +const assistant = (id: string): VisibleChatBlock => ({ + kind: 'agent-text', id, localId: null, createdAt: 2, text: id +}) + +describe('resolveAssistantForkPoints', () => { + it('uses the next prompt as an exclusive boundary after the assistant turn', () => { + const result = resolveAssistantForkPoints([ + user('u1'), assistant('a1'), assistant('a1-continuation'), + user('u2'), assistant('a2'), user('u3'), assistant('a3') + ], { u1: true, u2: true, u3: true }) + expect([...result]).toEqual([['agent-text:a1', 'u2'], ['agent-text:a2', 'u3']]) + }) + + it('does not skip a missing point to find a later usable prompt', () => { + const result = resolveAssistantForkPoints([ + user('u1'), assistant('a1'), user('u2'), assistant('a2'), user('u3') + ], { u3: true }) + expect([...result]).toEqual([['agent-text:a2', 'u3']]) + }) + + it('does not guess boundaries for imported history without native points', () => { + expect(resolveAssistantForkPoints([assistant('a1'), user('u2')], undefined).size).toBe(0) + }) + + it('preserves the rendered card id when reasoning starts or continues a reply', () => { + const reasoning: VisibleChatBlock = { kind: 'agent-reasoning', id: 'r1', localId: null, createdAt: 2, text: 'thinking' } + expect([...resolveAssistantForkPoints([ + user('u1'), reasoning, assistant('a1'), { ...reasoning, id: 'r2' }, user('u2') + ], { u2: true })]).toEqual([['agent-reasoning:r1', 'u2']]) + }) + + it('does not bridge an assistant turn across a compact-summary boundary hidden by the concise view', () => { + const canonical: ChatBlock[] = [ + { kind: 'user-text', id: 'u1', localId: 'u1', createdAt: 1, invokedAt: 1, text: 'u1' }, + { kind: 'agent-text', id: 'a1', localId: null, createdAt: 2, text: 'a1' }, + { kind: 'agent-event', id: 'e1', createdAt: 3, event: { type: 'compact-summary', summary: 'compacted' } }, + { kind: 'user-text', id: 'u2', localId: 'u2', createdAt: 4, invokedAt: 4, text: 'u2' }, + { kind: 'agent-text', id: 'a2', localId: null, createdAt: 5, text: 'a2' } + ] + const filtered = buildVisibleChatBlocks(filterConciseChatBlocks(canonical), { hasMoreMessages: false }) + // Ids are per-block (`kind:id`), so a1's rendered card id survives the + // concise filter unchanged and fork-map keys stay valid for the + // filtered render. + const filteredIds = new Set(assignThreadMessageIds(filtered).map(entry => entry.threadMessageId)) + expect(filteredIds.has('agent-text:a1')).toBe(true) + // SessionChat resolves fork points from the canonical projection; the + // hidden compact-summary boundary must reset the anchor, so a1 never + // anchors the post-compaction prompt u2. + const points = resolveAssistantForkPointsForCanonicalBlocks(canonical, { hasMoreMessages: false }, { u2: true }) + expect(points.has('agent-text:a1')).toBe(false) + expect([...points.keys()].every(key => filteredIds.has(key))).toBe(true) + }) +}) diff --git a/web/src/lib/assistant-fork-points.ts b/web/src/lib/assistant-fork-points.ts new file mode 100644 index 00000000..63698e85 --- /dev/null +++ b/web/src/lib/assistant-fork-points.ts @@ -0,0 +1,41 @@ +import type { ChatBlock } from '@/chat/types' +import type { VisibleChatBlock } from '@/chat/toolGroups' +import { buildVisibleChatBlocks, visibleBlockRole } from '@/chat/toolGroups' +import { assignThreadMessageIds } from '@/lib/assistant-runtime' + +// Native historical forks exclude the selected user prompt. The next +// recorded user prompt therefore anchors a fork after an assistant turn. +export function resolveAssistantForkPoints( + blocks: readonly VisibleChatBlock[], + points: Record | undefined +): Map { + const result = new Map() + let assistantId: string | null = null + for (const { block, threadMessageId } of assignThreadMessageIds(blocks)) { + if (block.kind === 'user-text') { + if (assistantId && block.localId && points?.[block.localId] === true) { + result.set(assistantId, block.localId) + } + assistantId = null + } else if (visibleBlockRole(block) === 'assistant') { + assistantId ??= threadMessageId + } else { + // Never bridge across unrepresented events or system boundaries. + assistantId = null + } + } + return result +} + +/** Fork points must be resolved against the canonical thread: the concise + * filter drops compact-summary/system/CLI boundaries, and scanning the + * filtered projection would bridge an assistant turn across them. Card ids + * are per-block (`kind:id`), so keys resolved here stay valid for the + * filtered render. */ +export function resolveAssistantForkPointsForCanonicalBlocks( + blocks: readonly ChatBlock[], + visibleOptions: Parameters[1], + points: Record | undefined +): Map { + return resolveAssistantForkPoints(buildVisibleChatBlocks([...blocks], visibleOptions), points) +}