diff --git a/application/state/useAIState.ts b/application/state/useAIState.ts index aca72a00d..267662f91 100644 --- a/application/state/useAIState.ts +++ b/application/state/useAIState.ts @@ -55,7 +55,7 @@ import { import { convertFilesToUploads } from './useFileUpload'; import { removeProviderReferences } from './aiProviderCleanup'; import { publishAISessionsSnapshot } from './aiSessionsStore'; -import { planSessionFork } from '../../domain/aiSessionFork'; +import { collectForkHandleIds, planSessionFork } from '../../domain/aiSessionFork'; import { getAgentRuntime } from '../../infrastructure/ai/harness/globalAgentRuntime'; import { AI_STATE_CHANGED_DRAFTS_BY_SCOPE, @@ -689,11 +689,11 @@ export function useAIState() { // is created there so the fork is active and visible in the very scope that // is viewing it, even when the source session carries a stale scope (e.g. a // terminal chat resumed in a reconnected terminal or a merged workspace). - const forkSessionFromMessage = useCallback(( + const forkSessionFromMessage = useCallback(async ( sessionId: string, messageId: string, viewingScope?: Pick, - ): AISession | null => { + ): Promise => { const source = sessionsRef.current.find(s => s.id === sessionId); if (!source) return null; const plan = planSessionFork(source, messageId); @@ -720,9 +720,20 @@ export function useAIState() { // Saved-output handles are scoped per chat session; rehome the ones the // retained prefix references so tool_output_read still resolves in the // fork (with the original handle ids, keeping the notices valid). - // Rehoming spilled handles re-writes target-owned durable records - // asynchronously; the fork's reads fall back gracefully until it lands. - void getAgentRuntime().getToolOutputStore(sessionId).rehomeChatSession(sessionId, fork.id); + // Rehome before the fork is exposed: rehoming spilled handles re-writes + // target-owned durable records, and the fork must not become readable or + // active until those records exist under its own session id, or the very + // first turn could see handles as missing. + try { + await getAgentRuntime().getToolOutputStore(sessionId).rehomeChatSession( + sessionId, + fork.id, + collectForkHandleIds(plan.messages), + ); + } catch { + // Rehoming is best-effort; the fork is still usable (reads fall back + // to the live cache or restore path under the target namespace). + } setSessionsRaw(prev => { const next = [fork, ...prev]; setLatestAISessionsSnapshot(next); diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index 20cb3835e..4c719b6d3 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -1692,10 +1692,12 @@ const AIChatSidePanelActive: React.FC = ({ // This panel's scope is passed so the branch is created in the scope viewing // it, even when the source session's own scope went stale (e.g. a terminal // chat resumed after reconnecting under a new terminal id). - const handleForkFromMessage = useCallback((messageId: string) => { + const handleForkFromMessage = useCallback(async (messageId: string) => { const sourceSessionId = activeSessionRef.current?.id ?? activeSessionId; if (!sourceSessionId) return; - const fork = forkSessionFromMessage?.(sourceSessionId, messageId, { + // Fork completion awaits handle rehoming (target-owned durable records), + // so the new session is fully readable the moment it is exposed. + const fork = await forkSessionFromMessage?.(sourceSessionId, messageId, { type: scopeType, targetId: scopeTargetId, }); diff --git a/components/AIChatSidePanel.types.ts b/components/AIChatSidePanel.types.ts index b9cafc4bb..66988122a 100644 --- a/components/AIChatSidePanel.types.ts +++ b/components/AIChatSidePanel.types.ts @@ -58,7 +58,7 @@ export interface AIChatSidePanelProps { sessionId: string, messageId: string, viewingScope?: Pick, - ) => AISession | null; + ) => Promise; // Provider config providers: ProviderConfig[]; activeProviderId: string; diff --git a/domain/aiSessionFork.ts b/domain/aiSessionFork.ts index 1c99b2fa6..c28250041 100644 --- a/domain/aiSessionFork.ts +++ b/domain/aiSessionFork.ts @@ -181,6 +181,31 @@ export function planSessionFork( } as ForkPlan; } +/** + * Saved-output handle ids are advertised in tool-result notices as + * `handleId=tool-output-…`. Collect the ids the retained prefix references so + * the fork's handles can be rehomed/restored into the new session's namespace + * (keeps the notices valid for `tool_output_read` after the fork). + */ +export function collectForkHandleIds(messages: readonly ForkMessageLike[]): string[] { + const ids: string[] = []; + const seen = new Set(); + const scan = (value: string | undefined) => { + if (!value) return; + for (const match of value.matchAll(/\bhandleId=(tool-output-[A-Za-z0-9-]+)/g)) { + if (seen.has(match[1])) continue; + seen.add(match[1]); + ids.push(match[1]); + } + }; + for (const message of messages) { + scan(message.content); + scan(message.thinking); + for (const result of message.toolResults ?? []) scan(result.content); + } + return ids; +} + export function canForkFromMessage( source: { messages: readonly ForkMessageLike[]; diff --git a/infrastructure/ai/harness/toolOutputStore.test.ts b/infrastructure/ai/harness/toolOutputStore.test.ts index 3f14a31d7..9eda42fcf 100644 --- a/infrastructure/ai/harness/toolOutputStore.test.ts +++ b/infrastructure/ai/harness/toolOutputStore.test.ts @@ -129,6 +129,71 @@ test('ToolOutputStore rehomed spilled handles become durably owned by the target assert.equal(stillReadable?.content, 'B'.repeat(50)); }); +test('ToolOutputStore restores retained source handles when rehoming after a restart', async () => { + const files = new Map(); + const persistence: ToolOutputPersistence = { + write: async (record, content) => { + const path = `/netcatty/${record.handleId}-${record.chatSessionId}.log`; + files.set(path, { record, content }); + return path; + }, + restore: async (handleId, chatSessionId) => { + for (const [path, entry] of files) { + if (entry.record.handleId !== handleId || entry.record.chatSessionId !== chatSessionId) continue; + return { path, record: entry.record }; + } + return null; + }, + read: async (path, input) => { + const content = files.get(path)?.content; + if (content == null) return null; + const startOffset = input.mode === 'tail' + ? Math.max(0, content.length - (input.maxChars ?? 12_000)) + : Math.max(0, input.offset ?? 0); + const selected = content.slice(startOffset, startOffset + (input.maxChars ?? 12_000)); + const endOffset = startOffset + selected.length; + return { + mode: input.mode ?? 'head', + content: selected, + totalChars: content.length, + startOffset, + endOffset, + nextOffset: endOffset, + hasMore: endOffset < content.length, + }; + }, + delete: async path => { + files.delete(path); + }, + }; + + const firstRun = new ToolOutputStore({ spillThresholdChars: 0, persistence }); + const handle = firstRun.store({ + chatSessionId: 'chat-source', + capabilityId: 'terminal.execute', + content: 'C'.repeat(20_000), + }); + await handle.spillPromise; + + // Simulate an app restart: a fresh store with no live-cache entry for the + // source session, forking with the retained handle ids. + const afterRestart = new ToolOutputStore({ spillThresholdChars: 0, persistence }); + await afterRestart.rehomeChatSession('chat-source', 'chat-fork', [handle.id]); + const restored = await afterRestart.readChunkAsync({ handleId: handle.id, mode: 'head', maxChars: 100 }, 'chat-fork'); + assert.equal(restored?.content, 'C'.repeat(100)); + // The fork owns its own durable record under the target chat session id. + const forkCopy = afterRestart.get(handle.id, 'chat-fork'); + assert.ok(forkCopy); + const forkRecord = files.get(forkCopy.filePath!)?.record; + assert.ok(forkRecord); + assert.equal(forkRecord.chatSessionId, 'chat-fork'); + + // Without the retained ids (and with no live cache), rehome stays a no-op. + const freshForkTarget = new ToolOutputStore({ spillThresholdChars: 0, persistence }); + await freshForkTarget.rehomeChatSession('chat-source', 'chat-fork-2'); + assert.equal(await freshForkTarget.readChunkAsync({ handleId: handle.id }, 'chat-fork-2'), null); +}); + test('ToolOutputStore pages large output with a hard per-read cap', () => { const store = new ToolOutputStore(); const content = `${'0123456789'.repeat(3_000)}END`; diff --git a/infrastructure/ai/harness/toolOutputStore.ts b/infrastructure/ai/harness/toolOutputStore.ts index 58b985f35..b5f89784c 100644 --- a/infrastructure/ai/harness/toolOutputStore.ts +++ b/infrastructure/ai/harness/toolOutputStore.ts @@ -345,10 +345,30 @@ export class ToolOutputStore { * are copied in memory and pick up their own durable record through the * normal spill path. If the persisted content cannot be read back, the * target falls back to sharing the source-owned spill path so live reads - * still resolve while both namespaces exist. + * still resolve while both namespaces exist. `retainHandleIds` may pass the + * handle ids referenced by the retained fork prefix: handles missing from + * the live cache (e.g. after an app restart or cache expiry) are restored + * from persistence under the source session before cloning, so forking a + * historical session still produces target-owned records instead of a + * no-op. */ - async rehomeChatSession(sourceChatSessionId: string, targetChatSessionId: string): Promise { + async rehomeChatSession( + sourceChatSessionId: string, + targetChatSessionId: string, + retainHandleIds?: readonly string[], + ): Promise { this.pruneExpired(); + const missingIds = (retainHandleIds ?? []) + .filter(handleId => !this.bySession.get(sourceChatSessionId)?.has(handleId)); + if (missingIds.length > 0 && this.persistence?.restore) { + // After an app restart (or once the live-cache entry expires), the + // retained handles exist only behind `persistence.restore`. Restore + // them under the source session before cloning so the fork gets real + // records instead of a silent no-op that breaks `tool_output_read`. + await Promise.allSettled(missingIds.map( + handleId => this.restoreHandle(handleId, sourceChatSessionId).catch(() => undefined), + )); + } const sourceMap = this.bySession.get(sourceChatSessionId); if (!sourceMap || sourceMap.size === 0) return; // Let pending spills settle so each source handle's durable ownership is @@ -381,6 +401,10 @@ export class ToolOutputStore { } this.bySession.set(targetChatSessionId, targetMap); this.enforceSessionLimits(targetChatSessionId, targetMap); + // Cloning adds whole sessions' worth of handles with each fork; keep the + // registry within the global handle/char bounds (matching `store` and + // `restoreHandleImpl`). + this.enforceGlobalLimits(); // Copies still holding in-memory content (fresh or read-back) become // target-owned through the normal spill path, which re-writes a durable // record carrying the target's chat session id. Await the writes so the