Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 本轮产出文件卡不再随流式更新整页抖动 (#3476)
Dashc3814d6d8b04
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex c328841d20..d62b46ee34 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4345,7 +4345,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void} else if (event.type === 'tool_result_full') {const r = onToolResultFullEvent(session.id,- event.data as { toolUseId?: unknown; fullText?: unknown },+ event.data as { toolUseId?: unknown; fullText?: unknown; isError?: unknown },eventAgentMeta,event.turnScope === 'background' ? 'background' : 'turn',);diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex 9319c46059..96163d2096 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -1216,7 +1216,7 @@ export function prepareSyntheticToolEventForBroadcast(if (event.type === 'tool_result_full') {const r = onToolResultFullEvent(sessionId,- event.data as { toolUseId?: unknown; fullText?: unknown },+ event.data as { toolUseId?: unknown; fullText?: unknown; isError?: unknown },agentMeta,);return { persistId: r?.persistId, resolvedContent: r?.content };@@ -1432,14 +1432,21 @@ export function onToolResultEvent(* 对齐老 renderer:有映射 → 覆盖更新;无映射但 tool_use 已到 → eager-create;* tool_use 也没到 → buffer。*/+function markFailedToolResultText(text: string, isError: boolean): string {+ if (!isError || text.includes('<tool_use_error>')) return text;+ return `<tool_use_error>${text}</tool_use_error>`;+}+export function onToolResultFullEvent(sessionId: string,- data: { toolUseId?: unknown; fullText?: unknown },+ data: { toolUseId?: unknown; fullText?: unknown; isError?: unknown },agentMeta: AgentMeta | null,scope: 'turn' | 'background' = 'turn',): { persistId: string; content: string } | null {const toolUseId = typeof data.toolUseId === 'string' ? data.toolUseId : '';- const fullText = typeof data.fullText === 'string' ? data.fullText : null;+ const rawText = typeof data.fullText === 'string' ? data.fullText : null;+ const fullText =+ rawText === null ? null : markFailedToolResultText(rawText, data.isError === true);if (!toolUseId || fullText === null) return null; // guard,对齐老 rendererconst backgroundState = scope === 'background'diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.tsindex 893a429892..30c0bc5886 100644--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts@@ -24,6 +24,7 @@ import {collectDeleteAnchorClientIds,collectStableLocalFileRefs,collectTurnFinalAssistantClientIds,+ isGeneratedFilesTurnSealed,findRestorableViewportItemIdx,groupWorkRuns,insertForkOriginItem,@@ -31,6 +32,7 @@ import {pickDeleteCompensationAnchorKey,isPlanCardVisibleInViewport,planSessionBelongsToLatestUserTurn,+ reuseGeneratedFilesRenderItems,shouldBlockAssistantFork,type RenderItem,} from '../components/chat/MessageStream';@@ -336,6 +338,58 @@ describe('collectTurnFinalAssistantClientIds', () => {});});+describe('isGeneratedFilesTurnSealed', () => {+ it('stays open on the latest turn until the tail sub-turn finishes', () => {+ const open = [mkUser('u1'), mkTool('write-1', 'Write', { file_path: 'C:/work/a.md' })];+ expect(isGeneratedFilesTurnSealed(open, false)).toBe(false);++ const sealed = [...open, { ...mkAssistant('done'), turnCompleted: true }];+ expect(isGeneratedFilesTurnSealed(sealed, false)).toBe(true);+ });++ it('does not inherit the previous sub-turn seal after auto-continue', () => {+ const afterContinue = [+ mkUser('u1'),+ { ...mkAssistant('main-summary'), turnCompleted: true },+ mkTool('write-2', 'Write', { file_path: 'C:/work/b.md' }),+ ];+ expect(isGeneratedFilesTurnSealed(afterContinue, false)).toBe(false);++ const afterSynthetic = [+ mkUser('u1'),+ { ...mkAssistant('main-summary'), turnCompleted: true },+ { ...mkUser('continue'), isSyntheticTrigger: true },+ ];+ expect(isGeneratedFilesTurnSealed(afterSynthetic, false)).toBe(false);+ });++ it('reseals only after the current tail sub-turn finishes', () => {+ const resealed = [+ mkUser('u1'),+ { ...mkAssistant('main-summary'), turnCompleted: true },+ mkTool('write-2', 'Write', { file_path: 'C:/work/b.md' }),+ mkResult('write-2-result', 'tu-write-2'),+ { ...mkAssistant('gate-followup'), turnCompleted: true },+ ];+ expect(isGeneratedFilesTurnSealed(resealed, false)).toBe(true);+ });++ it('treats an explicit failed tail sub-turn as sealed', () => {+ const failedTail = [+ mkUser('u1'),+ { ...mkAssistant('main-summary'), turnCompleted: true },+ mkTool('write-2', 'Write', { file_path: 'C:/work/b.md' }),+ { ...mkAssistant('failed'), turnCompleted: false },+ ];+ expect(isGeneratedFilesTurnSealed(failedTail, false)).toBe(true);+ });++ it('seals historical turns that already have a following user boundary', () => {+ const historical = [mkUser('u1'), mkTool('write-1', 'Write', { file_path: 'C:/work/a.md' })];+ expect(isGeneratedFilesTurnSealed(historical, true)).toBe(true);+ });+});+// ── case 1: 流式追加 token 不改变 message item key ────────────────────────describe('buildRenderItems — key stability', () => {@@ -494,6 +548,86 @@ describe('buildRenderItems — key stability', () => {expect(deduped).toHaveLength(0);});+ it('reuses the generated-files item when only unrelated messages change', () => {+ const messages = [+ mkUser('u1'),+ mkTool('write-1', 'Write', { file_path: 'C:/work/report.md', content: 'x' }),+ mkResult('write-result', 'tu-write-1'),+ mkAssistant('a1', 'done'),+ ];+ const first = buildRenderItems(messages, undefined, undefined, { workingDir: 'C:/work' });+ const cache = new Map();+ const reusedOnce = reuseGeneratedFilesRenderItems(first.items, cache);+ const second = buildRenderItems(+ [...messages.slice(0, -1), { ...messages[3], content: 'done plus more' }],+ undefined,+ undefined,+ { workingDir: 'C:/work' },+ );+ const reusedTwice = reuseGeneratedFilesRenderItems(second.items, cache);+ const firstCard = reusedOnce.find(+ (item): item is Extract<RenderItem, { type: 'generated_files' }> =>+ item.type === 'generated_files',+ );+ const secondCard = reusedTwice.find(+ (item): item is Extract<RenderItem, { type: 'generated_files' }> =>+ item.type === 'generated_files',+ );+ expect(firstCard).toBeDefined();+ expect(secondCard).toBe(firstCard);+ });++ it('unseals generated files when the same visible turn auto-continues after turnCompleted', () => {+ const workingDir = 'C:/work';+ const firstWrite = mkTool('write-1', 'Write', { file_path: 'C:/work/a.md', content: 'x' });+ const firstResult = mkResult('write-1-result', 'tu-write-1');+ const sealed = buildRenderItems(+ [mkUser('u1'), firstWrite, firstResult, { ...mkAssistant('main-summary'), turnCompleted: true }],+ undefined,+ undefined,+ { workingDir },+ ).items.find(+ (item): item is Extract<RenderItem, { type: 'generated_files' }> =>+ item.type === 'generated_files',+ );+ const continued = buildRenderItems(+ [+ mkUser('u1'),+ firstWrite,+ firstResult,+ { ...mkAssistant('main-summary'), turnCompleted: true },+ mkTool('write-2', 'Write', { file_path: 'C:/work/b.md', content: 'y' }),+ ],+ undefined,+ undefined,+ { workingDir },+ ).items.find(+ (item): item is Extract<RenderItem, { type: 'generated_files' }> =>+ item.type === 'generated_files',+ );+ const resealed = buildRenderItems(+ [+ mkUser('u1'),+ firstWrite,+ firstResult,+ { ...mkAssistant('main-summary'), turnCompleted: true },+ mkTool('write-2', 'Write', { file_path: 'C:/work/b.md', content: 'y' }),+ mkResult('write-2-result', 'tu-write-2'),+ { ...mkAssistant('gate-followup'), turnCompleted: true },+ ],+ undefined,+ undefined,+ { workingDir },+ ).items.find(+ (item): item is Extract<RenderItem, { type: 'generated_files' }> =>+ item.type === 'generated_files',+ );++ expect(sealed?.turnSealed).toBe(true);+ expect(continued?.turnSealed).toBe(false);+ expect(resealed?.turnSealed).toBe(true);+ });+it('streaming token append to an assistant message keeps the same item key', () => {const m1: ChatMessage = { ...mkAssistant('a1', 'partial'), isStreaming: true };const before = buildRenderItems([mkUser('u1'), m1]);diff --git a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts b/apps/desktop/src/renderer/__tests__/generatedFiles.test.tsindex fef0891dd5..6383f5153e 100644--- a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts+++ b/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts@@ -4,6 +4,7 @@ import {collectGeneratedFiles,extractCommandOutputPathCandidates,extractDocumentArtifactMetadata,+ isExplicitFailedToolResult,} from '../lib/generatedFiles';const WORKDIR = '/work';@@ -12,6 +13,21 @@ function toolUse(toolName: string, toolInput: unknown) {return { role: 'tool_use', toolName, toolInput };}+describe('isExplicitFailedToolResult', () => {+ it('fails closed on structured error envelopes', () => {+ expect(isExplicitFailedToolResult(JSON.stringify({ ok: false }))).toBe(true);+ expect(isExplicitFailedToolResult(JSON.stringify({ success: false }))).toBe(true);+ expect(isExplicitFailedToolResult(JSON.stringify({ status: 'error' }))).toBe(true);+ expect(isExplicitFailedToolResult('<tool_use_error>denied</tool_use_error>')).toBe(true);+ });++ it('does not treat ordinary success text as a failure', () => {+ expect(isExplicitFailedToolResult('Wrote a.md')).toBe(false);+ expect(isExplicitFailedToolResult(JSON.stringify({ ok: true }))).toBe(false);+ expect(isExplicitFailedToolResult(undefined)).toBe(false);+ });+});+describe('collectGeneratedFiles', () => {it('turns a top-level cindy docs tool result into artifact metadata', () => {const files = collectGeneratedFiles(@@ -138,6 +154,181 @@ describe('collectGeneratedFiles', () => {expect(extractDocumentArtifactMetadata('make_docx', input)).toBeDefined();});+ it('does not list a file whose tool result is an explicit failure', () => {+ const files = collectGeneratedFiles(+ [+ {+ role: 'tool_use',+ toolName: 'Write',+ toolUseId: 'w-fail',+ toolInput: { file_path: 'a.md', content: 'x' },+ },+ {+ role: 'tool_result',+ toolUseId: 'w-fail',+ content: JSON.stringify({ ok: false, errorCode: 'FILE_EXISTS' }),+ },+ ],+ WORKDIR,+ );+ expect(files).toEqual([]);+ });++ it('does not drop a created path when the later delete is wrapped as a tool_use_error', () => {+ const files = collectGeneratedFiles(+ [+ {+ role: 'tool_use',+ toolName: 'Write',+ toolUseId: 'w1',+ toolInput: { file_path: 'new.txt', content: 'hi' },+ },+ { role: 'tool_result', toolUseId: 'w1', content: 'ok' },+ {+ role: 'tool_use',+ toolName: 'file_change',+ toolUseId: 'd1',+ toolInput: {+ changes: [{ path: 'new.txt', kind: { type: 'delete' }, diff: '-hi' }],+ },+ },+ {+ role: 'tool_result',+ toolUseId: 'd1',+ content: '<tool_use_error>delete new.txt</tool_use_error>',+ },+ ],+ WORKDIR,+ );+ expect(files.map((file) => file.name)).toEqual(['new.txt']);+ });++ it('drops a created path that the same turn later deletes', () => {+ const files = collectGeneratedFiles(+ [+ toolUse('Write', { file_path: 'new.txt', content: 'hi' }),+ toolUse('file_change', {+ changes: [{ path: 'new.txt', kind: { type: 'delete' }, diff: '-hi' }],+ }),+ ],+ WORKDIR,+ );+ expect(files).toEqual([]);+ });++ it('keeps a path that is deleted and then recreated later in the same turn', () => {+ const files = collectGeneratedFiles(+ [+ toolUse('Write', { file_path: 'new.txt', content: 'old' }),+ toolUse('file_change', {+ changes: [{ path: 'new.txt', kind: { type: 'delete' }, diff: '-old' }],+ }),+ toolUse('Write', { file_path: 'new.txt', content: 'new' }),+ ],+ WORKDIR,+ );+ expect(files.map((file) => file.name)).toEqual(['new.txt']);+ });++ it('keeps a confirmed document preview while a second write is still in flight', () => {+ const files = collectGeneratedFiles(+ [+ {+ role: 'tool_use',+ toolName: 'make_xlsx',+ toolUseId: 'x1',+ toolInput: {+ outPath: 'documents/progress.xlsx',+ sheets: [{ name: '旧表', header: ['A'] }],+ },+ },+ {+ role: 'tool_result',+ toolUseId: 'x1',+ content: JSON.stringify({ ok: true }),+ },+ {+ role: 'tool_use',+ toolName: 'make_xlsx',+ toolUseId: 'x2',+ toolInput: {+ outPath: 'documents/progress.xlsx',+ sheets: [{ name: '新表', header: ['B'] }],+ },+ },+ ],+ WORKDIR,+ );+ expect(files).toHaveLength(1);+ expect(files[0].artifactConfirmed).toBe(true);+ expect(files[0].ready).not.toBe(false);+ expect(files[0].artifact?.preview).toMatchObject({+ kind: 'sheet',+ hasHeader: true,+ rows: [['A']],+ });+ });++ it('keeps a created path when the later delete result is an explicit failure', () => {+ const files = collectGeneratedFiles(+ [+ {+ role: 'tool_use',+ toolName: 'Write',+ toolUseId: 'w1',+ toolInput: { file_path: 'new.txt', content: 'hi' },+ },+ { role: 'tool_result', toolUseId: 'w1', content: 'ok' },+ {+ role: 'tool_use',+ toolName: 'file_change',+ toolUseId: 'd1',+ toolInput: {+ changes: [{ path: 'new.txt', kind: { type: 'delete' }, diff: '-hi' }],+ },+ },+ {+ role: 'tool_result',+ toolUseId: 'd1',+ content: JSON.stringify({ ok: false, status: 'failed' }),+ },+ ],+ WORKDIR,+ );+ expect(files.map((file) => file.name)).toEqual(['new.txt']);+ });++ it('marks in-flight tool_use files as not ready until the result arrives', () => {+ const inflight = collectGeneratedFiles(+ [+ {+ role: 'tool_use',+ toolName: 'Write',+ toolUseId: 'w1',+ toolInput: { file_path: 'a.md', content: 'x' },+ },+ ],+ WORKDIR,+ );+ expect(inflight).toHaveLength(1);+ expect(inflight[0].ready).toBe(false);++ const settled = collectGeneratedFiles(+ [+ {+ role: 'tool_use',+ toolName: 'Write',+ toolUseId: 'w1',+ toolInput: { file_path: 'a.md', content: 'x' },+ },+ { role: 'tool_result', toolUseId: 'w1', content: 'ok' },+ ],+ WORKDIR,+ );+ expect(settled).toHaveLength(1);+ expect(settled[0].ready).toBeUndefined();+ });+it('collects Write (claude) and write (pi) created files', () => {const files = collectGeneratedFiles([diff --git a/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.tsindex 84a3903381..4bc79b3b07 100644--- a/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts@@ -4,9 +4,16 @@ import { describe, expect, it } from 'vitest';import {ArtifactPreview,+ generatedFileVisibleSignature,+ generatedFilesCheckKey,getDocumentCoverThemeStyle,isConfirmedRemoteGeneratedFile,+ isGeneratedFileStatable,isLocalGeneratedFileInTurn,+ mergeGeneratedFileStatResults,+ planGeneratedFilesVisibility,+ retainVisibleGeneratedFiles,+ reuseGeneratedFilesIfUnchanged,} from '../components/chat/GeneratedFilesCard';import type { DocumentArtifactMetadata, GeneratedFileRef } from '../lib/generatedFiles';@@ -19,6 +26,11 @@ const toolFile: GeneratedFileRef = {source: 'tool',};const commandFile: GeneratedFileRef = { ...toolFile, source: 'command' };+const extraToolFile: GeneratedFileRef = {+ path: 'C:\\work\\notes.ts',+ name: 'notes.ts',+ source: 'tool',+};const confirmedDocumentFile: GeneratedFileRef = {...toolFile,name: 'report.docx',@@ -114,6 +126,278 @@ describe('remote generated-file visibility', () => {});});+describe('generatedFileVisibleSignature', () => {+ it('stays stable when only the object identity changes', () => {+ expect(generatedFileVisibleSignature({ ...toolFile })).toBe(+ generatedFileVisibleSignature(toolFile),+ );+ });++ it('changes when the path, source, or artifact changes', () => {+ const base = generatedFileVisibleSignature(toolFile);+ expect(generatedFileVisibleSignature({ ...toolFile, path: 'C:\\work\\other.md' })).not.toBe(+ base,+ );+ expect(generatedFileVisibleSignature(commandFile)).not.toBe(base);+ expect(generatedFileVisibleSignature(confirmedDocumentFile)).not.toBe(base);+ expect(+ generatedFileVisibleSignature({+ ...confirmedDocumentFile,+ artifact: { format: 'docx', theme: 'dark' },+ }),+ ).not.toBe(generatedFileVisibleSignature(confirmedDocumentFile));+ expect(+ generatedFileVisibleSignature({+ ...toolFile,+ artifact: {+ format: 'xlsx',+ preview: { kind: 'sheet', hasHeader: false, rows: [['a,b', 'c']] },+ },+ }),+ ).not.toBe(+ generatedFileVisibleSignature({+ ...toolFile,+ artifact: {+ format: 'xlsx',+ preview: { kind: 'sheet', hasHeader: false, rows: [['a', 'b,c']] },+ },+ }),+ );+ });+});++describe('generatedFilesCheckKey', () => {+ it('ignores in-flight files until the turn is sealed', () => {+ const readyOnly = generatedFilesCheckKey([toolFile], START, null);+ const withInFlight = generatedFilesCheckKey(+ [toolFile, { ...extraToolFile, ready: false }],+ START,+ null,+ );+ expect(withInFlight).toBe(readyOnly);+ expect(+ generatedFilesCheckKey([toolFile, { ...extraToolFile, ready: false }], START, END),+ ).not.toBe(readyOnly);+ });++ it('changes when a file becomes ready', () => {+ const pending = generatedFilesCheckKey([{ ...toolFile, ready: false }], START, null);+ const ready = generatedFilesCheckKey([toolFile], START, null);+ expect(ready).not.toBe(pending);+ });+});++describe('isGeneratedFileStatable', () => {+ it('waits for in-flight tool results while the turn is open', () => {+ expect(isGeneratedFileStatable({ ...toolFile, ready: false }, null)).toBe(false);+ expect(isGeneratedFileStatable({ ...toolFile, ready: false }, END)).toBe(true);+ expect(isGeneratedFileStatable(toolFile, null)).toBe(true);+ });++ it('treats a sealed latest turn like a closed time window', () => {+ expect(isGeneratedFileStatable({ ...toolFile, ready: false }, null, true)).toBe(true);+ const openKey = generatedFilesCheckKey([toolFile], START, null, false);+ const sealedKey = generatedFilesCheckKey([toolFile], START, null, true);+ expect(sealedKey).not.toBe(openKey);+ });+});++describe('planGeneratedFilesVisibility', () => {+ it('does not stat in-flight files and keeps the first paint empty', () => {+ expect(+ planGeneratedFilesVisibility({+ previousVisible: null,+ candidates: [{ ...toolFile, ready: false }],+ turnEndMs: null,+ envChanged: false,+ turnWindowChanged: false,+ }),+ ).toEqual({ visible: null, toStat: [] });+ });++ it('only stats newly ready files', () => {+ const plan = planGeneratedFilesVisibility({+ previousVisible: [toolFile],+ candidates: [toolFile, extraToolFile],+ turnEndMs: null,+ envChanged: false,+ turnWindowChanged: false,+ });+ expect(plan.visible).toBeDefined();+ expect(plan.toStat).toEqual([extraToolFile]);+ });++ it('restats every statable file when the turn window changes', () => {+ const plan = planGeneratedFilesVisibility({+ previousVisible: [toolFile],+ candidates: [toolFile, extraToolFile],+ turnEndMs: END,+ envChanged: false,+ turnWindowChanged: true,+ });+ expect(plan.toStat).toEqual([toolFile, extraToolFile]);+ });++ it('clears the card and restats when the session origin changes', () => {+ expect(+ planGeneratedFilesVisibility({+ previousVisible: [toolFile],+ candidates: [toolFile],+ turnEndMs: null,+ envChanged: true,+ turnWindowChanged: false,+ }),+ ).toEqual({ visible: null, toStat: [toolFile] });+ });++ it('drops a confirmed chip immediately when it disappears with no replacement', () => {+ expect(+ planGeneratedFilesVisibility({+ previousVisible: [toolFile],+ candidates: [],+ turnEndMs: null,+ envChanged: false,+ turnWindowChanged: false,+ }),+ ).toEqual({ visible: [], toStat: [] });+ });++ it('holds the old chip when candidates churn mid-stream', () => {+ const plan = planGeneratedFilesVisibility({+ previousVisible: [toolFile],+ candidates: [extraToolFile],+ turnEndMs: null,+ envChanged: false,+ turnWindowChanged: false,+ });+ expect(plan.visible).toEqual([toolFile]);+ expect(plan.toStat).toEqual([extraToolFile]);+ });++ it('drops held chips once the turn is sealed', () => {+ const plan = planGeneratedFilesVisibility({+ previousVisible: [toolFile],+ candidates: [extraToolFile],+ turnEndMs: END,+ envChanged: false,+ turnWindowChanged: false,+ });+ expect(plan.visible).toEqual([]);+ expect(plan.toStat).toEqual([extraToolFile]);+ });++ it('restats confirmed files when the remote verdict cache changes', () => {+ const plan = planGeneratedFilesVisibility({+ previousVisible: [toolFile],+ candidates: [toolFile],+ turnEndMs: null,+ envChanged: false,+ turnWindowChanged: false,+ forceRestat: true,+ });+ expect(plan.toStat).toEqual([toolFile]);+ });+});++describe('mergeGeneratedFileStatResults', () => {+ it('keeps previously confirmed files and appends newly confirmed ones', () => {+ expect(+ mergeGeneratedFileStatResults({+ previousVisible: [toolFile],+ candidates: [toolFile, extraToolFile],+ checked: [extraToolFile],+ confirmedPaths: new Set([extraToolFile.path]),+ turnWindowChanged: false,+ }),+ ).toEqual([toolFile, extraToolFile]);+ });++ it('swaps a held chip for the newly confirmed replacement in one update', () => {+ expect(+ mergeGeneratedFileStatResults({+ previousVisible: [toolFile],+ candidates: [extraToolFile],+ checked: [extraToolFile],+ confirmedPaths: new Set([extraToolFile.path]),+ turnWindowChanged: false,+ }),+ ).toEqual([extraToolFile]);+ });++ it('replaces a held chip once the new candidate is confirmed', () => {+ expect(+ mergeGeneratedFileStatResults({+ previousVisible: [toolFile],+ candidates: [extraToolFile],+ checked: [extraToolFile],+ confirmedPaths: new Set([extraToolFile.path]),+ turnWindowChanged: false,+ }),+ ).toEqual([extraToolFile]);+ });++ it('drops previously confirmed files that fail a turn-window restat', () => {+ expect(+ mergeGeneratedFileStatResults({+ previousVisible: [toolFile, extraToolFile],+ candidates: [toolFile, extraToolFile],+ checked: [toolFile, extraToolFile],+ confirmedPaths: new Set([extraToolFile.path]),+ turnWindowChanged: true,+ }),+ ).toEqual([extraToolFile]);+ });+});++describe('retainVisibleGeneratedFiles', () => {+ it('keeps the first paint empty until the existence check finishes', () => {+ expect(retainVisibleGeneratedFiles(null, [toolFile])).toBeNull();+ });++ it('keeps already-confirmed chips when the next list still contains them', () => {+ const previous = [toolFile];+ expect(retainVisibleGeneratedFiles(previous, [{ ...toolFile }, extraToolFile])).toBe(previous);+ });++ it('upgrades a visible chip when its artifact metadata arrives', () => {+ const previous = [toolFile];+ expect(retainVisibleGeneratedFiles(previous, [confirmedDocumentFile, extraToolFile])).toEqual([+ confirmedDocumentFile,+ ]);+ });++ it('holds chips whose paths disappeared until the caller asks to drop them', () => {+ expect(retainVisibleGeneratedFiles([toolFile, extraToolFile], [extraToolFile])).toEqual([+ toolFile,+ extraToolFile,+ ]);+ expect(+ retainVisibleGeneratedFiles([toolFile, extraToolFile], [extraToolFile], {+ dropMissing: true,+ }),+ ).toEqual([extraToolFile]);+ });++ it('returns the previous reference when the visible set is unchanged', () => {+ const previous = [toolFile];+ expect(retainVisibleGeneratedFiles(previous, previous)).toBe(previous);+ });+});++describe('reuseGeneratedFilesIfUnchanged', () => {+ it('returns the previous list when signatures match in order', () => {+ const previous = [toolFile, extraToolFile];+ expect(reuseGeneratedFilesIfUnchanged(previous, [{ ...toolFile }, { ...extraToolFile }])).toBe(+ previous,+ );+ });++ it('returns the next list when a newly confirmed file appears', () => {+ const next = [toolFile, extraToolFile];+ expect(reuseGeneratedFilesIfUnchanged([toolFile], next)).toBe(next);+ });+});+describe('document cover theme tokens', () => {it('maps each artifact theme to semantic preview tokens', () => {const light = getDocumentCoverThemeStyle('light');diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsxindex b22b9688ab..46eef1e5d4 100644--- a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx@@ -16,7 +16,9 @@* 存在性门槛(DESIGN.md §14.5「可点必存在」):本地会话渲染前 stat 过滤,不存在* 的文件不出 chip,整卡为空则不渲染。远程会话经 verifyRemotePathCached 远端 stat* 复核:仅在远端明确确认是普通文件后呈现;检查中、断链或限流都不先展示一张- * 可能无法打开的完成卡。+ * 可能无法打开的完成卡。首屏等检查完成再出现。流式期间只 stat 已完成+ * (ready !== false,或本轮已封口)且尚未确认的路径;内容指纹不变就不发 IPC,+ * 已确认的 chip 留在原地,避免 messages 换引用把整页带着跳。** 本地文件统一要求时间戳落在本轮 `[turnStartMs, turnEndMs)` 窗口内。tool 来源* (Write / file-change add)也不能只凭存在性:Write 可能覆盖既有文件,失败路径也可能@@ -25,7 +27,7 @@* 时间窗约束。远程会话无法读取创建时间,维持远端 stat 的存在性复核。*/-import { useEffect, useState } from 'react';+import { memo, useEffect, useRef, useState } from 'react';import { ChevronDown, ChevronUp, FileText } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -35,7 +37,9 @@ import { classifyMarkdownHref, toLocalFileUrl } from '@/lib/localPathResolver';import { isRemoteFileOrigin, toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';import {fetchChatFileWithToasts,+ remotePathVerdictKey,revealRemoteChatFile,+ subscribeRemotePathVerdictChange,type RemotePathVerdict,verifyRemotePathCached,} from '@/lib/remoteFileOpen';@@ -387,61 +391,326 @@ export function isLocalGeneratedFileInTurn(return typeof ts === 'number' && ts >= lowerBound && (turnEndMs === null || ts < turnEndMs);}+function artifactVisibleSignature(artifact: DocumentArtifactMetadata | undefined): string {+ if (!artifact) return '';+ const preview = artifact.preview ? JSON.stringify(artifact.preview) : '';+ return [+ artifact.format,+ artifact.title ?? '',+ artifact.subtitle ?? '',+ artifact.theme ?? '',+ artifact.cover === undefined ? '' : artifact.cover ? '1' : '0',+ artifact.summary?.kind ?? '',+ String(artifact.summary?.value ?? ''),+ preview,+ ].join('\t');+}++/** 决定 chip 是否换样的字段;故意不含数组引用。 */+export function generatedFileVisibleSignature(file: GeneratedFileRef): string {+ return [+ file.path,+ file.source,+ file.artifactConfirmed ? '1' : '0',+ artifactVisibleSignature(file.artifact),+ ].join('\t');+}++/** 未完成的 tool_use 在本轮还没封口时不 stat:文件多半还没落盘。 */+export function isGeneratedFileStatable(+ file: GeneratedFileRef,+ turnEndMs: number | null,+ turnSealed = false,+): boolean {+ return file.ready !== false || turnEndMs !== null || turnSealed;+}++/**+ * 卡片是否要重查的内容指纹。只计入当前可 stat 的文件,流式 token /+ * 未完成的 Write 换新数组不会触发 IPC。+ */+export function generatedFilesCheckKey(+ files: readonly GeneratedFileRef[],+ turnStartMs: number | null,+ turnEndMs: number | null,+ turnSealed = false,+): string {+ return [+ String(turnStartMs ?? ''),+ String(turnEndMs ?? ''),+ turnSealed ? '1' : '0',+ ...files+ .filter((file) => isGeneratedFileStatable(file, turnEndMs, turnSealed))+ .map((file) => generatedFileVisibleSignature(file)),+ ].join('\0');+}++/**+ * 文件列表增量更新时,先留下已经确认过的 chip。+ * 流式中候选从 A 换成 C 时先留着 A,等 C 的 stat 完成再替换,避免整卡先卸再挂。+ * 本轮封口或环境变了才允许立刻丢掉已消失的路径。+ * 首屏 previous 为 null,保持「检查完成前不展示」。+ */+export function retainVisibleGeneratedFiles(+ previous: GeneratedFileRef[] | null,+ nextCandidates: readonly GeneratedFileRef[],+ options?: { dropMissing?: boolean },+): GeneratedFileRef[] | null {+ if (!previous || previous.length === 0) return previous;+ const dropMissing = options?.dropMissing === true;+ const nextByPath = new Map(nextCandidates.map((file) => [file.path, file]));+ const kept: GeneratedFileRef[] = [];+ let changed = false;+ for (const file of previous) {+ const next = nextByPath.get(file.path);+ if (!next) {+ if (dropMissing) {+ changed = true;+ continue;+ }+ kept.push(file);+ continue;+ }+ if (generatedFileVisibleSignature(next) !== generatedFileVisibleSignature(file)) {+ changed = true;+ kept.push(next);+ } else {+ kept.push(file);+ }+ }+ if (kept.length !== previous.length) changed = true;+ return changed ? kept : previous;+}++/** stat 结果没变时沿用旧数组,避免无意义的 setState 把卡片再刷一遍。 */+export function reuseGeneratedFilesIfUnchanged(+ previous: GeneratedFileRef[] | null,+ next: GeneratedFileRef[],+): GeneratedFileRef[] {+ if (+ previous &&+ previous.length === next.length &&+ previous.every(+ (file, index) =>+ generatedFileVisibleSignature(file) === generatedFileVisibleSignature(next[index]),+ )+ ) {+ return previous;+ }+ return next;+}++export function planGeneratedFilesVisibility(input: {+ previousVisible: GeneratedFileRef[] | null;+ candidates: readonly GeneratedFileRef[];+ turnEndMs: number | null;+ envChanged: boolean;+ turnWindowChanged: boolean;+ forceRestat?: boolean;+ turnSealed?: boolean;+}): { visible: GeneratedFileRef[] | null; toStat: GeneratedFileRef[] } {+ const turnSealed = input.turnSealed === true;+ const statable = input.candidates.filter((file) =>+ isGeneratedFileStatable(file, input.turnEndMs, turnSealed),+ );+ if (input.envChanged) {+ return { visible: null, toStat: statable };+ }+ const previousPaths = new Set((input.previousVisible ?? []).map((file) => file.path));+ const hasIncomingReplacement = statable.some((file) => !previousPaths.has(file.path));+ const visible = retainVisibleGeneratedFiles(input.previousVisible, input.candidates, {+ // 有新候选在 stat 时暂留旧 chip,避免 A→C 中间卸卡;单纯删除没有替补则立刻撤。+ // 最新一轮没有后续 user 边界时 turnEndMs 仍是 null,要用封口信号触发复核。+ dropMissing: input.turnEndMs !== null || turnSealed || !hasIncomingReplacement,+ });+ if (input.turnWindowChanged || input.forceRestat) {+ return { visible, toStat: statable };+ }+ const confirmedPaths = new Set((input.previousVisible ?? []).map((file) => file.path));+ return {+ visible,+ toStat: statable.filter((file) => !confirmedPaths.has(file.path)),+ };+}++export function mergeGeneratedFileStatResults(input: {+ previousVisible: GeneratedFileRef[] | null;+ candidates: readonly GeneratedFileRef[];+ checked: readonly GeneratedFileRef[];+ confirmedPaths: ReadonlySet<string>;+ turnWindowChanged: boolean;+}): GeneratedFileRef[] {+ const trusted = new Set<string>();+ if (!input.turnWindowChanged && input.previousVisible) {+ const checkedPaths = new Set(input.checked.map((file) => file.path));+ for (const file of input.previousVisible) {+ if (!checkedPaths.has(file.path)) trusted.add(file.path);+ }+ }+ for (const path of input.confirmedPaths) trusted.add(path);+ return input.candidates.filter((file) => trusted.has(file.path));+}+/** 折叠阈值:约两行 chip。超过则收起为「前 N 个 + 再显示 M 个文件」。 */const MAX_VISIBLE_FILES = 6;-export function GeneratedFilesCard({+function generatedFilesCardPropsEqual(+ prev: {+ files: readonly GeneratedFileRef[];+ turnStartMs: number | null;+ turnEndMs: number | null;+ turnSealed?: boolean;+ },+ next: {+ files: readonly GeneratedFileRef[];+ turnStartMs: number | null;+ turnEndMs: number | null;+ turnSealed?: boolean;+ },+): boolean {+ return (+ generatedFilesCheckKey(prev.files, prev.turnStartMs, prev.turnEndMs, prev.turnSealed) ===+ generatedFilesCheckKey(next.files, next.turnStartMs, next.turnEndMs, next.turnSealed)+ );+}++export const GeneratedFilesCard = memo(function GeneratedFilesCard({files,turnStartMs,turnEndMs,+ turnSealed = false,}: {files: readonly GeneratedFileRef[];turnStartMs: number | null;turnEndMs: number | null;+ turnSealed?: boolean;}) {const { t } = useTranslation();const fileCtx = useChatSessionFile();const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;- // 本地与远程都先保持 null,等存在性检查完成后再展示,避免完成卡闪现后消失。- // 远程 command 候选无法验证 mtime,一律不出(见文件头注释)。+ // 首屏保持 null。之后按内容指纹增量 stat:未完成的 tool_use 不查,+ // 已确认的路径不重复 IPC,工作目录 / 远端来源变了才整卡重来。const [existing, setExisting] = useState<GeneratedFileRef[] | null>(null);const [expanded, setExpanded] = useState(false);+ const [remoteVerdictGen, setRemoteVerdictGen] = useState(0);+ const checkKey = generatedFilesCheckKey(files, turnStartMs, turnEndMs, turnSealed);+ const filesRef = useRef(files);+ filesRef.current = files;+ const visibleRef = useRef<GeneratedFileRef[] | null>(null);+ const checkEnvRef = useRef({ remoteOrigin, workingDir: fileCtx.workingDir });+ const turnWindowRef = useRef({ turnStartMs, turnEndMs, turnSealed });+ const remoteVerdictGenRef = useRef(remoteVerdictGen);++ useEffect(() => {+ if (!remoteOrigin) return;+ const watched = new Set(+ files+ .filter(+ (file) => file.source === 'tool' && isGeneratedFileStatable(file, turnEndMs, turnSealed),+ )+ .map((file) => remotePathVerdictKey(remoteOrigin, fileCtx.workingDir, file.path)),+ );+ if (watched.size === 0) return;+ return subscribeRemotePathVerdictChange((key) => {+ if (watched.has(key)) setRemoteVerdictGen((generation) => generation + 1);+ });+ }, [remoteOrigin, fileCtx.workingDir, checkKey, files, turnEndMs, turnSealed]);useEffect(() => {let cancelled = false;- setExisting(null);- if (remoteOrigin) {- const toolFiles = files.filter((f) => f.source === 'tool');- void (async () => {- const checks = await Promise.all(- toolFiles.map(async (f) => {- const verdict = await verifyRemotePathCached(remoteOrigin, fileCtx.workingDir, f.path);- return isConfirmedRemoteGeneratedFile(verdict);- }),- );- if (!cancelled) setExisting(toolFiles.filter((_, idx) => checks[idx]));- })();+ const currentFiles = filesRef.current;+ const envChanged =+ checkEnvRef.current.remoteOrigin !== remoteOrigin ||+ checkEnvRef.current.workingDir !== fileCtx.workingDir;+ const turnWindowChanged =+ turnWindowRef.current.turnStartMs !== turnStartMs ||+ turnWindowRef.current.turnEndMs !== turnEndMs ||+ turnWindowRef.current.turnSealed !== turnSealed;+ const forceRestat = remoteVerdictGenRef.current !== remoteVerdictGen;+ checkEnvRef.current = { remoteOrigin, workingDir: fileCtx.workingDir };+ turnWindowRef.current = { turnStartMs, turnEndMs, turnSealed };+ remoteVerdictGenRef.current = remoteVerdictGen;++ const plan = planGeneratedFilesVisibility({+ previousVisible: envChanged ? null : visibleRef.current,+ candidates: currentFiles,+ turnEndMs,+ envChanged,+ turnWindowChanged,+ forceRestat,+ turnSealed,+ });+ visibleRef.current = plan.visible;+ if (plan.visible === null) {+ setExisting(null);+ } else {+ setExisting((prev) => reuseGeneratedFilesIfUnchanged(prev, plan.visible ?? []));+ }++ const toStat = remoteOrigin+ ? plan.toStat.filter((file) => file.source === 'tool')+ : plan.toStat;+ if (toStat.length === 0) {return () => {cancelled = true;};}+void (async () => {- const checks = await Promise.all(- files.map(async (f) => {- try {- const r = await window.electronAPI.fsBrowse.statPath(f.path);- return isLocalGeneratedFileInTurn(f, r, turnStartMs, turnEndMs);- } catch {- return false;- }- }),- );- if (!cancelled) setExisting(files.filter((_, idx) => checks[idx]));+ const confirmedPaths = new Set<string>();+ if (remoteOrigin) {+ const checks = await Promise.all(+ toStat.map(async (file) => {+ const verdict = await verifyRemotePathCached(+ remoteOrigin,+ fileCtx.workingDir,+ file.path,+ );+ return isConfirmedRemoteGeneratedFile(verdict);+ }),+ );+ checks.forEach((ok, index) => {+ if (ok) confirmedPaths.add(toStat[index].path);+ });+ } else {+ const checks = await Promise.all(+ toStat.map(async (file) => {+ try {+ const stat = await window.electronAPI.fsBrowse.statPath(file.path);+ return isLocalGeneratedFileInTurn(file, stat, turnStartMs, turnEndMs);+ } catch {+ return false;+ }+ }),+ );+ checks.forEach((ok, index) => {+ if (ok) confirmedPaths.add(toStat[index].path);+ });+ }+ if (cancelled) return;+ const merged = mergeGeneratedFileStatResults({+ previousVisible: envChanged ? null : visibleRef.current,+ candidates: filesRef.current,+ checked: toStat,+ confirmedPaths,+ turnWindowChanged,+ });+ visibleRef.current = merged;+ setExisting((prev) => reuseGeneratedFilesIfUnchanged(prev, merged));})();+return () => {cancelled = true;};- }, [files, remoteOrigin, turnStartMs, turnEndMs, fileCtx.workingDir]);+ }, [+ checkKey,+ remoteOrigin,+ turnStartMs,+ turnEndMs,+ turnSealed,+ fileCtx.workingDir,+ remoteVerdictGen,+ ]);if (!existing || existing.length === 0) return null;@@ -495,4 +764,4 @@ export function GeneratedFilesCard({</div></div>);-}+}, generatedFilesCardPropsEqual);diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 8bf2c03be5..629b1730a1 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -252,7 +252,7 @@ import { ThinkingCard } from './ThinkingCard';import { AgentActionsBlock } from './AgentActionsBlock';import { AgentTaskCard } from './AgentTaskCard';import { TurnChangesCard } from './TurnChangesCard';-import { GeneratedFilesCard } from './GeneratedFilesCard';+import { GeneratedFilesCard, generatedFilesCheckKey } from './GeneratedFilesCard';import { WorkGroupBlock, type WorkGroupChild } from './WorkGroupBlock';import {extractAnchorCardId,@@ -493,6 +493,8 @@ type GeneratedFilesRenderItem = {files: GeneratedFileRef[];turnStartMs: number | null;turnEndMs: number | null;+ /** 最新一轮没有后续 user 边界时 turnEndMs 仍为空,用封口信号触发完成后复核。 */+ turnSealed?: boolean;};/** 原子工作子项:tool / agent task / thinking / assistant 工作文字。 */@@ -952,6 +954,35 @@ function isCompletedAssistantMessage(message: ChatMessage): boolean {);}+function isGeneratedFilesSubTurnTerminal(message: ChatMessage): boolean {+ // 显式失败也是子轮终态:后续没有新工作就该封口复核,不能把失败当成「还在跑」。+ return message.turnCompleted === false || isCompletedAssistantMessage(message);+}++/**+ * 产物卡封口只看当前尾部子轮。同一可见 user turn 在 turnCompleted 后自动续跑时,+ * 前一子轮的收尾信号不得让后续 ready:false 的文件立刻 stat。+ * export 仅供单测使用。+ */+export function isGeneratedFilesTurnSealed(+ slice: readonly ChatMessage[],+ hasFollowingUser: boolean,+): boolean {+ if (hasFollowingUser) return true;+ let lastTerminalIdx = -1;+ for (let i = 0; i < slice.length; i++) {+ if (isGeneratedFilesSubTurnTerminal(slice[i])) lastTerminalIdx = i;+ }+ if (lastTerminalIdx < 0) return false;+ for (let i = lastTerminalIdx + 1; i < slice.length; i++) {+ const message = slice[i];+ if (message.role === 'tool_use') return false;+ if (message.role === 'user' && message.isSyntheticTrigger === true) return false;+ if (message.role === 'assistant' && !message.systemCardType) return false;+ }+ return true;+}+export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessage[]): Set<string> {const out = new Set<string>();let sealedAnswerFound = false;@@ -1727,12 +1758,15 @@ export function buildRenderItems(}}const boundaryTimestamp = Date.parse(messages[hi]?.createdAt ?? '');+ const hasFollowingUser = hi < messages.length;+ const turnSealed = isGeneratedFilesTurnSealed(slice, hasFollowingUser);items.push({type: 'generated_files',key: `genfiles-${messages[lo].clientId}`,files: generatedFiles,turnStartMs,turnEndMs: Number.isFinite(boundaryTimestamp) ? boundaryTimestamp : null,+ turnSealed,});};let i = 0;@@ -2123,6 +2157,43 @@ export function buildRenderItems(return { items, singleResultMap };}+type GeneratedFilesRenderItemRef = Extract<RenderItem, { type: 'generated_files' }>;++/**+ * 产物卡内容没变时沿用上一轮 item。buildRenderItems 每次都 new 一个 files+ * 数组,不收口的话 memo 住的 GeneratedFilesCard 仍会因 props 引用变化而重渲。+ */+export function reuseGeneratedFilesRenderItems(+ items: RenderItem[],+ cache: Map<string, GeneratedFilesRenderItemRef>,+): RenderItem[] {+ const seen = new Set<string>();+ let swapped = false;+ const next = items.map((item) => {+ if (item.type !== 'generated_files') return item;+ seen.add(item.key);+ const previous = cache.get(item.key);+ if (+ previous &&+ generatedFilesCheckKey(+ previous.files,+ previous.turnStartMs,+ previous.turnEndMs,+ previous.turnSealed,+ ) === generatedFilesCheckKey(item.files, item.turnStartMs, item.turnEndMs, item.turnSealed)+ ) {+ if (previous !== item) swapped = true;+ return previous;+ }+ cache.set(item.key, item);+ return item;+ });+ for (const key of cache.keys()) {+ if (!seen.has(key)) cache.delete(key);+ }+ return swapped ? next : items;+}+// ---------------------------------------------------------------------------// Work-group pass(buildRenderItems 之后的第二层后处理)// ---------------------------------------------------------------------------@@ -3198,25 +3269,29 @@ export function MessageStream({// 全量 build:折叠 / 丢弃 / 反向膨胀的所有规则一次性吸收 — 窗口看到的就是// 用户看到的。流式中每 token messages 引用变 → 这里跑一次 O(n) 单线性扫描,// 实测 N=1000 < 2ms (Windows),如果未来发现瓶颈再走增量化(out of scope)。- const { items: ungroupedRenderItems, singleResultMap } = useMemo(- () =>- buildRenderItems(messages, taskUpdates, ghostCardSnapshot, {- historyWindowIncomplete:- !historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,- turnChangeSets,- workingDir,- }),- [- messages,- taskUpdates,- ghostCardSnapshot,- historyLoaded,- hasMoreMessages,- historyWindowHasIsland,+ const generatedFilesItemCacheRef = useRef(+ new Map<string, Extract<RenderItem, { type: 'generated_files' }>>(),+ );+ const { items: ungroupedRenderItems, singleResultMap } = useMemo(() => {+ const built = buildRenderItems(messages, taskUpdates, ghostCardSnapshot, {+ historyWindowIncomplete: !historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,turnChangeSets,workingDir,- ],- );+ });+ return {+ items: reuseGeneratedFilesRenderItems(built.items, generatedFilesItemCacheRef.current),+ singleResultMap: built.singleResultMap,+ };+ }, [+ messages,+ taskUpdates,+ ghostCardSnapshot,+ historyLoaded,+ hasMoreMessages,+ historyWindowHasIsland,+ turnChangeSets,+ workingDir,+ ]);const assistantsWithFollowingUserBoundary = useMemo(() => collectAssistantsWithFollowingUserBoundary(visibleMessages),[visibleMessages],@@ -5870,6 +5945,7 @@ export function MessageStream({files={item.files}turnStartMs={item.turnStartMs}turnEndMs={item.turnEndMs}+ turnSealed={item.turnSealed === true}/>);}diff --git a/apps/desktop/src/renderer/lib/generatedFiles.ts b/apps/desktop/src/renderer/lib/generatedFiles.tsindex 7386d31eb8..5e22d4894c 100644--- a/apps/desktop/src/renderer/lib/generatedFiles.ts+++ b/apps/desktop/src/renderer/lib/generatedFiles.ts@@ -34,6 +34,11 @@ export interface GeneratedFileRef {* 'command' = 命令文本启发式候选,渲染前还需 mtime 时间窗校验。*/source: 'tool' | 'command';+ /**+ * false = 创建它的 tool_use 还在跑(有 toolUseId、结果未到),文件多半没落盘。+ * 缺省 / true = 可以做存在性检查。历史消息没有 toolUseId 时按已完成处理。+ */+ ready?: boolean;/** 文档工具返回的轻量交付信息;普通源码文件没有此字段。 */artifact?: DocumentArtifactMetadata;/** true 仅表示同一 tool_use 有结构化 ok:true 结果,可用本轮 mtime 证明成功覆盖。 */@@ -90,6 +95,20 @@ function asRecord(value: unknown): Record<string, unknown> | null {: null;}+/**+ * 只认结构化失败:ok/success=false、status=error/failed,或 `<tool_use_error>`。+ * 普通 Write 失败文案不在这里猜,避免把成功输出误杀。+ */+export function isExplicitFailedToolResult(content: string | undefined): boolean {+ if (!content) return false;+ if (content.includes('<tool_use_error>')) return true;+ const parsed = parseToolResult(content);+ if (!parsed) return false;+ if (parsed.ok === false || parsed.success === false) return true;+ const status = typeof parsed.status === 'string' ? parsed.status.toLowerCase() : '';+ return status === 'error' || status === 'failed' || status === 'failure';+}+function parseToolResult(content: string | undefined): Record<string, unknown> | null {if (!content) return null;try {@@ -711,6 +730,9 @@ export function collectGeneratedFiles(const editedKeys = new Set<string>();for (const msg of messages) {if (msg.role !== 'tool_use' || !msg.toolName) continue;+ const resultContent = msg.toolUseId ? resultByToolUseId.get(msg.toolUseId) : undefined;+ if (msg.toolUseId && resultContent === undefined) continue;+ if (isExplicitFailedToolResult(resultContent)) continue;const d = describeToolUse(msg.toolName, msg.toolInput);if (d.kind === 'file' && d.action === 'edit' && d.filePath) {editedKeys.add(dedupeKeyForPath(resolveToolFilePath(d.filePath, workingDir)));@@ -729,22 +751,31 @@ export function collectGeneratedFiles(const toolName = msg.toolName ?? '';if (!toolName) continue;+ const resultContent = msg.toolUseId ? resultByToolUseId.get(msg.toolUseId) : undefined;+ const toolFailed = isExplicitFailedToolResult(resultContent);+ const toolReady = !msg.toolUseId || resultByToolUseId.has(msg.toolUseId);const addPath = (rawPath: string, source: GeneratedFileRef['source']): void => {+ if (toolFailed) return;const abs = canonicalizeWindowsShape(resolveToolFilePath(rawPath, workingDir));const key = dedupeKeyForPath(abs);if (source === 'command' && editedKeys.has(key)) return;const prev = byKey.get(key);if (prev) {if (prev.source === 'command' && source === 'tool') prev.source = 'tool';+ if (toolReady) delete prev.ready;return;}- byKey.set(key, { path: abs, name: basename(abs), source });+ byKey.set(key, {+ path: abs,+ name: basename(abs),+ source,+ ...(toolReady ? {} : { ready: false }),+ });};for (const rawPath of createdPathsFromToolUse(toolName, msg.toolInput)) {addPath(rawPath, 'tool');}- const resultContent = msg.toolUseId ? resultByToolUseId.get(msg.toolUseId) : undefined;const artifact = extractDocumentArtifactMetadata(toolName, msg.toolInput, resultContent);if (artifact) {const outputPath =@@ -757,8 +788,14 @@ export function collectGeneratedFiles(const existing = byKey.get(key);const artifactConfirmed = parseToolResult(resultContent)?.ok === true;if (existing) {- existing.artifact = artifact;- if (artifactConfirmed) existing.artifactConfirmed = true;+ // 同路径第二次文档工具还在跑时,保留第一次已确认的交付,不要用未落地预览覆盖。+ if (!toolReady || toolFailed) {+ /* keep existing */+ } else {+ existing.artifact = artifact;+ if (artifactConfirmed) existing.artifactConfirmed = true;+ delete existing.ready;+ }} else {byKey.set(key, {path: abs,@@ -766,6 +803,7 @@ export function collectGeneratedFiles(source: 'tool',artifact,...(artifactConfirmed ? { artifactConfirmed: true } : {}),+ ...(toolReady ? {} : { ready: false }),});}}@@ -776,6 +814,13 @@ export function collectGeneratedFiles(addPath(rawPath, 'command');}}+ if (descriptor.kind === 'fileChange' && toolReady && !toolFailed) {+ for (const change of descriptor.changes) {+ if ((change.action === 'delete' || change.action === 'move') && change.path) {+ byKey.delete(dedupeKeyForPath(resolveToolFilePath(change.path, workingDir)));+ }+ }+ }}return [...byKey.values()];}