mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-21 07:32:54 +00:00
fix: address Codex review on PR #3604
This commit is contained in:
1 parent
9a8bed5bfa
commit
11e716dd49
6 files changed
+138
-11
No files matched your search
@@ -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<AISessionScope, 'type' | 'targetId'>,
|
||||
): AISession | null => {
|
||||
): Promise<AISession | null> => {
|
||||
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);
|
||||
|
||||
@@ -1692,10 +1692,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
// 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,
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@ export interface AIChatSidePanelProps {
|
||||
sessionId: string,
|
||||
messageId: string,
|
||||
viewingScope?: Pick<AISessionScope, 'type' | 'targetId'>,
|
||||
) => AISession | null;
|
||||
) => Promise<AISession | null>;
|
||||
// Provider config
|
||||
providers: ProviderConfig[];
|
||||
activeProviderId: string;
|
||||
|
||||
@@ -181,6 +181,31 @@ export function planSessionFork<M extends ForkMessageLike>(
|
||||
} as ForkPlan<M>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string>();
|
||||
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[];
|
||||
|
||||
@@ -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<string, { record: PersistedToolOutputRecord; content: string }>();
|
||||
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`;
|
||||
|
||||
@@ -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<void> {
|
||||
async rehomeChatSession(
|
||||
sourceChatSessionId: string,
|
||||
targetChatSessionId: string,
|
||||
retainHandleIds?: readonly string[],
|
||||
): Promise<void> {
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user