diff --git a/application/state/useAIState.ts b/application/state/useAIState.ts index e03b2000d..91fed6260 100644 --- a/application/state/useAIState.ts +++ b/application/state/useAIState.ts @@ -726,7 +726,8 @@ export function useAIState() { // active until those records exist under its own session id, or the very // first turn could see handles as missing. try { - const store = getAgentRuntime().getToolOutputStore(sessionId); + const runtime = getAgentRuntime(); + const store = runtime.getToolOutputStore(sessionId); // The persistence adapter is normally configured when a turn starts; // forking can be the very first action after an app restart, so // configure it here too or retained handles cannot be restored from @@ -735,15 +736,31 @@ export function useAIState() { // A carried-over compaction summary can reference archive handles not // present in any retained message; collect those too so the summary // stays readable via tool_output_read in the fork. - await store.rehomeChatSession( + const rehomed = await store.rehomeChatSession( sessionId, fork.id, collectForkHandleIds(plan.messages, plan.contextCompaction?.summary), ); + if (!rehomed) { + // The tool-output store refused the fork because its global quota + // cannot hold both the source and the fork's fresh clones without + // evicting output a live conversation still resolves. Publishing the + // fork would advertise retained handle ids that miss on + // `tool_output_read`, so abort instead; the boundary stays forkable + // if the user retries later. + return null; + } } catch { // Rehoming is best-effort; the fork is still usable (reads fall back // to the live cache or restore path under the target namespace). } + // Structured runtime state (active background jobs and their poll + // offsets, read cursors, decisions, plan, blockers) is keyed by chat + // session id; rebuild it for the fork from the retained prefix so a + // later compaction re-injects the state the branch actually kept, not + // the source's latest state (which may describe turns discarded by the + // branch). + getAgentRuntime().getSessionStateStore().rebuildFromMessages(fork.id, plan.messages); setSessionsRaw(prev => { const next = [fork, ...prev]; setLatestAISessionsSnapshot(next); diff --git a/infrastructure/ai/harness/sessionState.test.ts b/infrastructure/ai/harness/sessionState.test.ts index d7a05bb4e..d73dcc48f 100644 --- a/infrastructure/ai/harness/sessionState.test.ts +++ b/infrastructure/ai/harness/sessionState.test.ts @@ -133,3 +133,58 @@ test('SessionStateStore reinjects edited files and unfinished plan items', () => assert.match(text, /\[done\] inspect failure/); assert.match(text, /\[todo\] run regression tests/); }); + +test('SessionStateStore rebuilds fork state from the retained prefix only', () => { + const store = new SessionStateStore(); + // Pre-populate state derived from turns discarded by the branch: rebuild + // must clear it instead of copying the source's latest state. + store.mergeFromUserGoal('chat-fork', 'Older goal from a discarded turn'); + store.updateFromToolResult( + 'chat-fork', + 'terminal_start', + { sessionId: 'sess-9', command: 'npm run build' }, + JSON.stringify({ jobId: 'discarded-job', status: 'running', nextOffset: 99 }), + ); + + store.rebuildFromMessages('chat-fork', [ + { + role: 'user', + content: 'Run the dev server and watch nginx for errors', + }, + { + role: 'assistant', + content: 'I decided to tail the nginx error log on the edge host.', + toolCalls: [ + { id: 'call-1', name: 'terminal_execute', arguments: { sessionId: 'sess-1', command: 'tail -f /var/log/nginx/error.log' } }, + { id: 'call-2', name: 'terminal_start', arguments: { sessionId: 'sess-1', command: 'npm run dev' } }, + ], + }, + { + role: 'tool', + content: 'upstream timed out', + toolResults: [{ toolCallId: 'call-1', content: 'upstream timed out', isError: true }], + }, + { + role: 'tool', + content: JSON.stringify({ jobId: 'job-1', status: 'running', nextOffset: 0 }), + toolResults: [{ toolCallId: 'call-2', content: JSON.stringify({ jobId: 'job-1', status: 'running', nextOffset: 0 }) }], + }, + { + role: 'tool', + content: JSON.stringify({ jobId: 'job-1', status: 'running', nextOffset: 420 }), + toolResults: [{ toolCallId: 'call-3', content: JSON.stringify({ jobId: 'job-1', status: 'running', nextOffset: 420 }), toolName: 'terminal_poll' }], + }, + ]); + + const text = store.toReinjectionText('chat-fork') ?? ''; + assert.ok(text.includes('Run the dev server')); + assert.ok(!text.includes('Older goal from a discarded turn')); + assert.ok(!text.includes('discarded-job')); + assert.ok(text.includes('edge host')); + // The background job survives with the replayed poll offset and the + // reinjected "keep polling" instruction. + assert.equal(store.get('chat-fork').activeJobs['job-1'].nextOffset, 420); + assert.match(text, /offset=420/); + // The failed tail surfaces as an open blocker, as it does live. + assert.match(text, /Open blockers/); +}); diff --git a/infrastructure/ai/harness/sessionState.ts b/infrastructure/ai/harness/sessionState.ts index dc064cc76..c5ece46d0 100644 --- a/infrastructure/ai/harness/sessionState.ts +++ b/infrastructure/ai/harness/sessionState.ts @@ -10,6 +10,26 @@ export interface ActiveTerminalJobState { nextOffset: number; } +/** + * Structural message subset used to rebuild a session's runtime state from a + * retained conversation prefix (e.g. when forking a session at a message). + */ +export interface SessionStateReplayMessage { + role: 'user' | 'assistant' | 'system' | 'tool'; + content: string; + toolCalls?: ReadonlyArray<{ + id: string; + name?: string; + arguments?: Record; + }>; + toolResults?: ReadonlyArray<{ + toolCallId: string; + toolName?: string; + content?: string; + isError?: boolean; + }>; +} + export interface TerminalReadCursorState { range: string; startLine?: number; @@ -289,6 +309,46 @@ export class SessionStateStore { if (lines.length === 0) return undefined; return lines.join('\n'); } + + /** + * Rebuild `chatSessionId`'s state from a retained conversation prefix + * (e.g. when a session is forked at a message): the fork replays only the + * messages kept by the boundary, so runtime state derived from turns + * discarded by the branch (active jobs, poll offsets, cursors, blockers) + * is not copied from the source's latest state. + */ + rebuildFromMessages( + chatSessionId: string, + messages: readonly SessionStateReplayMessage[], + ): void { + this.clear(chatSessionId); + // Pair each result with the nearest preceding unresolved call carrying + // the same id (same rule as the historical replay maps) so tool names and + // arguments survive the walk across messages. + const pendingCalls = new Map }>(); + for (const message of messages) { + for (const call of message.toolCalls ?? []) { + if (!call?.id || typeof call.name !== 'string' || !call.name) continue; + pendingCalls.set(call.id, { name: call.name, arguments: call.arguments }); + } + if (message.role === 'user') this.mergeFromUserGoal(chatSessionId, message.content); + if (message.role === 'assistant') this.mergeFromAssistantContent(chatSessionId, message.content); + for (const result of message.toolResults ?? []) { + const callId = result?.toolCallId; + if (!callId) continue; + const call = pendingCalls.get(callId) + ?? (result.toolName ? { name: result.toolName } : undefined); + pendingCalls.delete(callId); + this.updateFromToolResult( + chatSessionId, + call?.name ?? 'unknown', + call?.arguments, + result.content ?? '', + result.isError, + ); + } + } + } } export const globalSessionStateStore = new SessionStateStore(); diff --git a/infrastructure/ai/harness/toolOutputStore.test.ts b/infrastructure/ai/harness/toolOutputStore.test.ts index fbfe43add..023941c66 100644 --- a/infrastructure/ai/harness/toolOutputStore.test.ts +++ b/infrastructure/ai/harness/toolOutputStore.test.ts @@ -136,7 +136,8 @@ test('ToolOutputStore rehomed spilled handles become durably owned by the target }); await handle.spillPromise; - await original.rehomeChatSession('chat-source', 'chat-fork'); + // A rehome that fits the quota reports success. + assert.equal(await original.rehomeChatSession('chat-source', 'chat-fork'), true); const forkCopy = original.get(handle.id, 'chat-fork'); assert.ok(forkCopy); // The copy owns its own durable record under the target's chat session id. @@ -404,7 +405,9 @@ test('ToolOutputStore global quotas refuse a fork whose copies cannot fit', asyn }); await handle.spillPromise; - await original.rehomeChatSession('chat-source', 'chat-fork'); + // The refusal is reported to the caller so it can abort publishing the + // fork instead of leaving it with unresolvable retained handle ids. + assert.equal(await original.rehomeChatSession('chat-source', 'chat-fork'), false); // The source copy survives untouched with its durable spill file. const sourceCopy = original.get(handle.id, 'chat-source'); diff --git a/infrastructure/ai/harness/toolOutputStore.ts b/infrastructure/ai/harness/toolOutputStore.ts index 1060e5c55..077d6f086 100644 --- a/infrastructure/ai/harness/toolOutputStore.ts +++ b/infrastructure/ai/harness/toolOutputStore.ts @@ -357,12 +357,17 @@ export class ToolOutputStore { * no-op. When `retainHandleIds` is provided, only those handles are * cloned; outputs saved by turns after the fork boundary stay in the * source session. + * Returns `true` when the target namespace resolves every advertised handle + * id, and `false` when the global quota cannot hold both the source and the + * fresh clones (the clones are rolled back): the caller must then abort + * publishing the fork, because its retained messages would reference handle + * ids that resolve to "not found". */ async rehomeChatSession( sourceChatSessionId: string, targetChatSessionId: string, retainHandleIds?: readonly string[], - ): Promise { + ): Promise { this.pruneExpired(); const missingIds = (retainHandleIds ?? []) .filter(handleId => !this.bySession.get(sourceChatSessionId)?.has(handleId)); @@ -376,7 +381,7 @@ export class ToolOutputStore { )); } const sourceMap = this.bySession.get(sourceChatSessionId); - if (!sourceMap || sourceMap.size === 0) return; + if (!sourceMap || sourceMap.size === 0) return true; // When the caller names the handles the retained prefix references, clone // only those: copying the whole source session would pull in outputs the // fork never reads and could evict still-valid handles (source or other @@ -450,9 +455,9 @@ export class ToolOutputStore { // alias — leave the fork publishing a handle id that immediately // misses. Refuse the fork instead: roll back the fresh clones so the // registry returns to its pre-fork (compliant) state, keeping the - // source record intact. The fork's retained messages then miss on - // `tool_output_read`, but no existing conversation's output is - // invalidated. + // source record intact, and report the refusal (`false`) so the caller + // aborts publishing the fork: no existing conversation's output is + // invalidated and no fork advertises unresolvable handle ids. const withinQuota = this.enforceGlobalLimits(new Set([ ...selected.map(([, handle]) => handle), ...freshClones, @@ -471,6 +476,9 @@ export class ToolOutputStore { // The registry the clones were added to was within quota, so rolling // them back is guaranteed to restore compliance; no further eviction // pass runs here. + // Communicate the refusal so the caller aborts the fork instead of + // publishing a conversation whose retained handles miss. + return false; } // Copies still holding in-memory content (fresh or read-back) become // target-owned through the normal spill path, which re-writes a durable @@ -483,6 +491,7 @@ export class ToolOutputStore { if (handle.spillPromise) spillWrites.push(handle.spillPromise); } await Promise.allSettled(spillWrites); + return true; } /**