Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 补齐本轮变更捕获与生成文件卡

DavidShen0b9cdb53be9c
diff --git a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
index 9c522b009f..e1db4ddda8 100644
--- a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
+++ b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
@@ -751,6 +751,114 @@ describe('turn change-set sidecar store', () => {
});
});
+ it.each([
+ ['absolute path', 'diff --git /outside.txt /outside.txt'],
+ ['parent traversal', 'diff --git a/../escape.txt b/../escape.txt'],
+ ])('fails closed for Codex diffs with an unsafe %s', async (_label, header) => {
+ await beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ cwd: workdir,
+ });
+ noteTurnDiffEvent('session-1', {
+ type: 'turn_diff',
+ source: 'codex',
+ data: {
+ turnId: 'turn-unsafe-path',
+ cwd: workdir,
+ diff: [
+ header,
+ '--- a/../escape.txt',
+ '+++ b/../escape.txt',
+ '@@ -1 +1 @@',
+ '-secret',
+ '+leaked',
+ '',
+ ].join('\n'),
+ },
+ });
+ await finalizeTurnChangeSet('session-1', 'turn-unsafe-path', 'complete');
+
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({
+ state: 'partial',
+ fileCount: 0,
+ incompleteReasons: ['outside-workspace'],
+ });
+ const [detail] = await getTurnChangeSets('session-1', [summary!.id]);
+ expect(detail?.diffs).toHaveLength(0);
+ expect(JSON.stringify(detail)).not.toContain('secret');
+ });
+
+ it('fails closed for a malformed Codex diff block while retaining valid blocks', async () => {
+ await beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ cwd: workdir,
+ });
+ noteTurnDiffEvent('session-1', {
+ type: 'turn_diff',
+ source: 'codex',
+ data: {
+ turnId: 'turn-malformed-diff',
+ cwd: workdir,
+ diff: [
+ 'diff --git',
+ '---',
+ '+++',
+ '',
+ 'diff --git a/ok.txt b/ok.txt',
+ '--- a/ok.txt',
+ '+++ b/ok.txt',
+ '@@ -1 +1 @@',
+ '-old',
+ '+new',
+ '',
+ ].join('\n'),
+ },
+ });
+ await finalizeTurnChangeSet('session-1', 'turn-malformed-diff', 'complete');
+
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({
+ state: 'partial',
+ fileCount: 1,
+ incompleteReasons: ['outside-workspace'],
+ });
+ expect(summary?.files[0]?.path).toBe('ok.txt');
+ });
+
+ it('fails closed when a rename diff oldPath escapes the workspace', async () => {
+ await beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ cwd: workdir,
+ });
+ noteTurnDiffEvent('session-1', {
+ type: 'turn_diff',
+ source: 'codex',
+ data: {
+ turnId: 'turn-rename-unsafe',
+ cwd: workdir,
+ diff: [
+ 'diff --git a/../secret.txt b/renamed.txt',
+ 'similarity index 100%',
+ 'rename from ../secret.txt',
+ 'rename to renamed.txt',
+ '',
+ ].join('\n'),
+ },
+ });
+ await finalizeTurnChangeSet('session-1', 'turn-rename-unsafe', 'complete');
+
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary?.fileCount).toBe(0);
+ expect(summary?.incompleteReasons).toContain('outside-workspace');
+ });
+
it('does not persist remote workspace patches while remote review is unsupported', async () => {
await beginTurnChangeSet({
sessionId: 'session-1',
diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.ts
index 70e4d260dc..6f6327e542 100644
--- a/apps/desktop/src/main/turn-change-set/store.ts
+++ b/apps/desktop/src/main/turn-change-set/store.ts
@@ -211,6 +211,20 @@ function filterSensitiveDiffBlocks(
const safeBlocks: string[] = [];
for (const block of blocks) {
const files = parseDiffs(pending.id, block);
+ // Diff payloads are persisted in the sidecar before any Undo/Reapply
+ // validation runs. Fail closed here so malformed or out-of-workspace
+ // paths can never be written to userData or exposed by the review UI.
+ if (
+ files.length !== 1
+ || files.some((file) => (
+ !file.path
+ || !safeRelativeTarget(pending.cwd, file.path)
+ || (file.oldPath !== null && (!file.oldPath || !safeRelativeTarget(pending.cwd, file.oldPath)))
+ ))
+ ) {
+ addIncompleteReason(pending, 'outside-workspace');
+ continue;
+ }
const isSensitive = files.some((file) =>
detectSensitivePath(file.path, { allowEnvTemplates: true })
|| (file.oldPath && detectSensitivePath(file.oldPath, { allowEnvTemplates: true })),
diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
index d9480797f3..eed553b354 100644
--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
@@ -327,6 +327,58 @@ describe('buildRenderItems — key stability', () => {
expect(items.indexOf(cards[0])).toBeGreaterThan(items.findIndex((item) => item.key === 'msg-a1'));
});
+ it('keeps opaque command artifacts as fallback chips without duplicating exact files', () => {
+ const messages = [
+ mkUser('u1'),
+ mkTool('bash-1', 'Bash', { command: 'python gen.py > C:/work/out/report.xlsx' }),
+ mkResult('bash-result', 'tu-bash-1'),
+ mkUser('u2'),
+ ];
+ const exact: TurnChangeSetSummary = {
+ id: 'cs-opaque',
+ sessionId: 's1',
+ anchorClientId: 'u1',
+ provider: 'codex',
+ providerTurnId: 'turn-1',
+ cwd: 'C:/work',
+ state: 'partial',
+ workspaceState: 'applied',
+ isReversible: false,
+ incompleteReasons: ['opaque-tool'],
+ createdAt: 1,
+ completedAt: 2,
+ files: [],
+ fileCount: 0,
+ additions: 0,
+ deletions: 0,
+ };
+ const fallback = buildRenderItems(messages, undefined, undefined, {
+ workingDir: 'C:/work',
+ turnChangeSets: [exact],
+ }).items.filter((item): item is Extract<RenderItem, { type: 'generated_files' }> => item.type === 'generated_files');
+ expect(fallback).toHaveLength(1);
+ expect(fallback[0]?.files[0]?.name).toBe('report.xlsx');
+
+ const exactFile = {
+ ...exact,
+ files: [{
+ id: 'turn-1:out/report.xlsx',
+ path: 'out/report.xlsx',
+ oldPath: null,
+ status: 'added' as const,
+ additions: 1,
+ deletions: 0,
+ }],
+ fileCount: 1,
+ additions: 1,
+ };
+ const deduped = buildRenderItems(messages, undefined, undefined, {
+ workingDir: 'C:/work',
+ turnChangeSets: [exactFile],
+ }).items.filter((item): item is Extract<RenderItem, { type: 'generated_files' }> => item.type === 'generated_files');
+ expect(deduped).toHaveLength(0);
+ });
+
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.ts
new file mode 100644
index 0000000000..d5d598e830
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
@@ -0,0 +1,186 @@
+import { describe, expect, it } from 'vitest';
+
+import { collectGeneratedFiles, extractCommandPathCandidates } from '../lib/generatedFiles';
+
+const WORKDIR = '/work';
+
+function toolUse(toolName: string, toolInput: unknown) {
+ return { role: 'tool_use', toolName, toolInput };
+}
+
+describe('collectGeneratedFiles', () => {
+ it('collects Write (claude) and write (pi) created files', () => {
+ const files = collectGeneratedFiles(
+ [
+ toolUse('Write', { file_path: 'report.md', content: 'x' }),
+ toolUse('write', { path: 'data/out.csv', content: 'y' }),
+ ],
+ WORKDIR,
+ );
+ expect(files.map((f) => f.name)).toEqual(['report.md', 'out.csv']);
+ // 相对路径按 workingDir 解析成绝对路径。
+ expect(files[0].path.replace(/\\/g, '/')).toContain('/work/report.md');
+ });
+
+ it('collects codex file_change add entries but not updates', () => {
+ // codex 协议形态:change 需带 kind.type 与 diff 字符串,缺任一整次降级 generic。
+ const files = collectGeneratedFiles(
+ [
+ toolUse('file_change', {
+ changes: [
+ { path: 'new.txt', kind: { type: 'add' }, diff: '+hi' },
+ { path: 'existing.txt', kind: { type: 'update' }, diff: '-a\n+b' },
+ ],
+ }),
+ ],
+ WORKDIR,
+ );
+ expect(files.map((f) => f.name)).toEqual(['new.txt']);
+ });
+
+ it('excludes edits, reads and searches', () => {
+ const files = collectGeneratedFiles(
+ [
+ toolUse('Edit', { file_path: 'a.ts', old_string: 'a', new_string: 'b' }),
+ toolUse('Read', { file_path: 'b.ts' }),
+ toolUse('Grep', { pattern: 'foo' }),
+ ],
+ WORKDIR,
+ );
+ expect(files).toEqual([]);
+ });
+
+ it('dedupes the same created path across tool calls, keeping first order', () => {
+ const files = collectGeneratedFiles(
+ [
+ toolUse('Write', { file_path: 'dup.md', content: '1' }),
+ toolUse('Write', { file_path: 'other.md', content: '2' }),
+ toolUse('Write', { file_path: 'dup.md', content: '3' }),
+ ],
+ WORKDIR,
+ );
+ expect(files.map((f) => f.name)).toEqual(['dup.md', 'other.md']);
+ });
+
+ it('folds case only for Windows-shaped paths, keeps POSIX case-sensitive', () => {
+ // Windows 绝对路径:大小写不敏感,C:/A.md 与 c:/a.md 视为同一文件。
+ const win = collectGeneratedFiles(
+ [
+ toolUse('Write', { file_path: 'C:/work/A.md', content: '1' }),
+ toolUse('Write', { file_path: 'c:/work/a.md', content: '2' }),
+ ],
+ 'C:/work',
+ );
+ expect(win).toHaveLength(1);
+
+ // POSIX 绝对路径:大小写敏感,/w/A.txt 与 /w/a.txt 是两个不同文件,不合并。
+ const posix = collectGeneratedFiles(
+ [
+ toolUse('write', { path: '/w/A.txt', content: '1' }),
+ toolUse('write', { path: '/w/a.txt', content: '2' }),
+ ],
+ '/w',
+ );
+ expect(posix.map((f) => f.name).sort()).toEqual(['A.txt', 'a.txt']);
+ });
+
+ it('ignores non-tool_use messages', () => {
+ const files = collectGeneratedFiles(
+ [
+ { role: 'assistant', toolName: 'Write', toolInput: { file_path: 'no.md' } },
+ toolUse('Write', { file_path: 'yes.md', content: 'x' }),
+ ],
+ WORKDIR,
+ );
+ expect(files.map((f) => f.name)).toEqual(['yes.md']);
+ });
+
+ it('collects script-generated paths from Bash commands as command-source candidates', () => {
+ // Issue 场景:xlsx 由 python openpyxl 脚本生成,没有文件工具记录。
+ const cmd =
+ 'python -c "\nimport openpyxl\nwb = openpyxl.Workbook()\n' +
+ "wb.save(r'C:\\Users\\Admin\\Documents\\测试表格.xlsx')\nprint('done')\n\"\n";
+ const files = collectGeneratedFiles([toolUse('Bash', { command: cmd })], 'C:/work');
+ expect(files).toHaveLength(1);
+ expect(files[0].name).toBe('测试表格.xlsx');
+ expect(files[0].source).toBe('command');
+ });
+
+ it('canonicalizes Windows-shaped paths to backslashes and dedupes across slash forms', () => {
+ // 正斜杠 Windows 路径(命令文本常见)必须归一成反斜杠本机形态:Explorer
+ // /select 与 shell.openPath 对正斜杠会失败;且与 Write 记录的反斜杠形态
+ // 是同一文件,不归一会重复出 chip。
+ const files = collectGeneratedFiles(
+ [
+ toolUse('Write', { file_path: 'C:\\work\\report.docx', content: 'x' }),
+ toolUse('Bash', { command: "open 'C:/work/report.docx'" }),
+ toolUse('Bash', { command: "save 'C:/work/输出/表格.xlsx'" }),
+ ],
+ 'C:\\work',
+ );
+ expect(files.map((f) => f.path)).toEqual(['C:\\work\\report.docx', 'C:\\work\\输出\\表格.xlsx']);
+ expect(files[0].source).toBe('tool');
+ });
+
+ it('excludes command mentions of files edited by file tools this turn', () => {
+ // 编码会话形态:Edit 改了源码文件,随后命令引用它(跑测试)。它是编辑不是
+ // 新建,不能因 mtime 落在本轮窗口就被当成产物。
+ const files = collectGeneratedFiles(
+ [
+ toolUse('Bash', { command: 'pnpm vitest run C:/work/src/openWithApps.test.ts' }),
+ toolUse('Edit', {
+ file_path: 'C:/work/src/openWithApps.test.ts',
+ old_string: 'a',
+ new_string: 'b',
+ }),
+ toolUse('Bash', { command: "python gen.py > 'C:/work/out/report.csv'" }),
+ ],
+ 'C:/work',
+ );
+ // Edit 出现在命令之后也要生效(两遍扫描),真产物 report.csv 不受影响。
+ expect(files.map((f) => f.name)).toEqual(['report.csv']);
+ });
+
+ it('marks file-tool creates as tool source and wins over command mentions of the same path', () => {
+ const files = collectGeneratedFiles(
+ [
+ toolUse('Bash', { command: 'ls C:/work/report.md' }),
+ toolUse('Write', { file_path: 'C:/work/report.md', content: 'x' }),
+ ],
+ 'C:/work',
+ );
+ expect(files).toHaveLength(1);
+ expect(files[0].source).toBe('tool');
+ });
+});
+
+describe('extractCommandPathCandidates', () => {
+ it('extracts quoted paths (CJK, spaces) and bare absolute paths', () => {
+ expect(
+ extractCommandPathCandidates("wb.save(r'C:\\Users\\A\\My Docs\\报表 v2.xlsx')"),
+ ).toEqual(['C:\\Users\\A\\My Docs\\报表 v2.xlsx']);
+ expect(extractCommandPathCandidates('node gen.js > C:/out/result.json')).toContain(
+ 'C:/out/result.json',
+ );
+ expect(extractCommandPathCandidates('cp a "/home/u/输出/report.pdf"')).toContain(
+ '/home/u/输出/report.pdf',
+ );
+ });
+
+ it('skips temp dirs, extension-less tokens, plain filenames and URLs', () => {
+ expect(extractCommandPathCandidates("save('/tmp/x.xlsx')")).toEqual([]);
+ expect(extractCommandPathCandidates("save('C:\\Users\\A\\AppData\\Local\\Temp\\x.xlsx')")).toEqual([]);
+ expect(extractCommandPathCandidates('cat /dev/null && echo done')).toEqual([]);
+ // 纯文件名不收(随机带点 token 误报率太高),相对路径需含分隔符。
+ expect(extractCommandPathCandidates("save('输出.xlsx')")).toEqual([]);
+ expect(extractCommandPathCandidates("save('out/输出.xlsx')")).toEqual(['out/输出.xlsx']);
+ expect(extractCommandPathCandidates('curl https://x.com/a.js')).toEqual([]);
+ expect(extractCommandPathCandidates('')).toEqual([]);
+ });
+
+ it('dedupes the same path appearing quoted and bare', () => {
+ expect(
+ extractCommandPathCandidates('python gen.py C:/out/a.csv && stat "C:/out/a.csv"'),
+ ).toEqual(['C:/out/a.csv']);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts
new file mode 100644
index 0000000000..874bfea9dd
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+
+import { isLocalGeneratedFileInTurn } from '../components/chat/GeneratedFilesCard';
+import type { GeneratedFileRef } from '../lib/generatedFiles';
+
+const START = Date.parse('2026-08-05T10:00:00.000Z');
+const END = Date.parse('2026-08-05T10:01:00.000Z');
+
+const toolFile: GeneratedFileRef = {
+ path: 'C:\\work\\report.md',
+ name: 'report.md',
+ source: 'tool',
+};
+const commandFile: GeneratedFileRef = { ...toolFile, source: 'command' };
+
+describe('isLocalGeneratedFileInTurn', () => {
+ it('accepts a tool-created file whose birthtime falls in the turn', () => {
+ expect(
+ isLocalGeneratedFileInTurn(
+ toolFile,
+ { kind: 'file', birthtimeMs: START + 5_000, mtimeMs: START + 5_000 },
+ START,
+ END,
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects Write against an existing file even when mtime is current', () => {
+ expect(
+ isLocalGeneratedFileInTurn(
+ toolFile,
+ { kind: 'file', birthtimeMs: START - 60_000, mtimeMs: START + 5_000 },
+ START,
+ END,
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a failed tool path that only appears in a later turn', () => {
+ expect(
+ isLocalGeneratedFileInTurn(
+ toolFile,
+ { kind: 'file', birthtimeMs: END + 5_000, mtimeMs: END + 5_000 },
+ START,
+ END,
+ ),
+ ).toBe(false);
+ });
+
+ it('fails closed for tool entries when birthtime is unavailable', () => {
+ expect(
+ isLocalGeneratedFileInTurn(
+ toolFile,
+ { kind: 'file', birthtimeMs: 0, mtimeMs: START + 5_000 },
+ START,
+ END,
+ ),
+ ).toBe(false);
+ });
+
+ it('keeps the mtime fallback for command candidates on filesystems without birthtime', () => {
+ expect(
+ isLocalGeneratedFileInTurn(
+ commandFile,
+ { kind: 'file', birthtimeMs: 0, mtimeMs: START + 5_000 },
+ START,
+ END,
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
new file mode 100644
index 0000000000..c7b6a75c52
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
@@ -0,0 +1,287 @@
+/**
+ * GeneratedFilesCard — 每个 user turn 结尾的「本轮产出文件」卡。
+ * ---------------------------------------------------------------------------
+ * 对标 Codex Desktop 回复尾部的 artifact 文件卡:agent 本轮新建的文件不再只能
+ * 靠模型在正文里写对 Markdown 链接才可见(Issue #1811 场景),而是从 tool_use
+ * 结构化派生后集中呈现。文件来源判定见 lib/generatedFiles.ts。
+ *
+ * 交互:
+ * - 左键 → 与正文文件链接同策(对齐 MarkdownRenderer activateResolvedLocalTarget):
+ * 可识别文件直接在 Cindy 内打开——文本/代码 → TextLightbox,图片 → ImageLightbox,
+ * glb/gltf → ModelLightbox;其余(xlsx / pdf 等)交系统默认应用(远程会话取回
+ * 缓存副本再打开)。
+ * - 右键 → 共享文件 chip 菜单(复制 / 路径 / 定位 / 打开方式…),与聊天里其它
+ * 文件 chip 一致。
+ *
+ * 存在性门槛(DESIGN.md §14.5「可点必存在」):本地会话渲染前 stat 过滤,不存在
+ * 的文件不出 chip,整卡为空则不渲染。远程会话经 verifyRemotePathCached 远端 stat
+ * 复核:先按 tool_use 记录乐观呈现,verdict 回来后 nonfile/directory 摘掉;
+ * unknown(断链 / 限流)保持乐观——与正文 chip 的远程点亮不变量同策。
+ *
+ * 本地文件统一要求时间戳落在本轮 `[turnStartMs, turnEndMs)` 窗口内。tool 来源
+ * (Write / file-change add)也不能只凭存在性:Write 可能覆盖既有文件,失败路径也可能
+ * 被后续轮次创建;因此它必须有落在窗口内的 birthtime,不可用时宁可不出。
+ * command 来源为兼容不提供 birthtime 的 Linux FS 允许 mtime 回退,但同样受完整
+ * 时间窗约束。远程会话无法读取创建时间,维持远端 stat 的存在性复核。
+ */
+
+import { useEffect, useState } from 'react';
+import { ChevronDown, ChevronUp, FileText } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { cn } from '@/lib/utils';
+import type { GeneratedFileRef } from '@/lib/generatedFiles';
+import { classifyMarkdownHref, toLocalFileUrl } from '@/lib/localPathResolver';
+import { isRemoteFileOrigin, toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';
+import {
+ fetchChatFileWithToasts,
+ revealRemoteChatFile,
+ verifyRemotePathCached,
+} from '@/lib/remoteFileOpen';
+import { shouldOpenTextLightboxForOrigin } from '@/lib/filePreview';
+import { rewriteToRemoteMediaOrigin } from '../../../shared/remoteMediaUrl';
+import { useChatSessionFile } from './ChatSessionFileContext';
+import { useFileChipContextMenu } from './useFileChipContextMenu';
+import { ImageLightbox } from './ImageLightbox';
+import { TextLightbox } from './TextLightbox';
+import { ModelLightbox } from './ModelLightbox';
+
+function GeneratedFileChip({ file }: { file: GeneratedFileRef }) {
+ const fileCtx = useChatSessionFile();
+ const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;
+ const ctxMenu = useFileChipContextMenu({
+ getAbsPath: () => file.path,
+ // 生成物常是 .xlsx / .pdf / 图片等,"打开方式"对它们最有用;会话上下文
+ // (含侧边栏定位目标)由 useFileChipContextMenu 内部从 ChatSessionFileContext 取。
+ canOpenInBrowser: false,
+ });
+
+ const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
+ const [textLightboxOpen, setTextLightboxOpen] = useState(false);
+ const [modelLightboxPath, setModelLightboxPath] = useState<string | null>(null);
+
+ // 左键与正文文件链接同策(见文件头注释)。非文本兜底交给
+ // shouldOpenTextLightboxForOrigin:本地 openPath、远程取回缓存副本,均含失败 toast。
+ const open = async (): Promise<void> => {
+ const kind = classifyMarkdownHref(file.path);
+ if (kind === 'image-local') {
+ const localUrl = toLocalFileUrl(file.path);
+ if (!remoteOrigin) {
+ setLightboxSrc(localUrl);
+ return;
+ }
+ // 远程:xdt-file:// 经 origin 改写走 cindy-remote-media 管线;改写不了
+ // (ssh workdir 外)→ 取回缓存副本后按本机文件预览(与正文链接同策)。
+ const rewritten = rewriteToRemoteMediaOrigin(
+ localUrl,
+ toRemoteMediaOrigin(fileCtx.origin, fileCtx.workingDir),
+ );
+ if (rewritten !== localUrl) {
+ setLightboxSrc(rewritten);
+ return;
+ }
+ const cachePath = await fetchChatFileWithToasts(remoteOrigin, fileCtx.workingDir, file.path);
+ if (cachePath) setLightboxSrc(toLocalFileUrl(cachePath));
+ return;
+ }
+ if (kind === 'model-local') {
+ if (remoteOrigin) {
+ await revealRemoteChatFile(remoteOrigin, fileCtx.workingDir, file.path);
+ return;
+ }
+ // FBX 无应用内预览且 openPath 有误导弹窗风险(正文链接同款取舍)→ 定位。
+ if (/\.fbx$/i.test(file.path)) {
+ void window.electronAPI.showItemInFolder({ filePath: file.path });
+ return;
+ }
+ setModelLightboxPath(file.path);
+ return;
+ }
+ if (!(await shouldOpenTextLightboxForOrigin(fileCtx, file.path))) return;
+ setTextLightboxOpen(true);
+ };
+
+ return (
+ <>
+ <button
+ type="button"
+ title={file.path}
+ onClick={() => void open()}
+ onContextMenu={ctxMenu.onContextMenu}
+ className={cn(
+ 'inline-flex items-center gap-1.5',
+ 'h-7 px-2.5 py-1.5 max-w-[280px]',
+ 'rounded-[9999px]',
+ 'bg-[var(--msg-md-inline-code-bg)]',
+ 'text-[13px] font-medium text-[var(--msg-assistant-text)]',
+ 'hover:bg-[var(--cmd-palette-item-hover)]',
+ 'transition-colors cursor-pointer',
+ )}
+ >
+ <FileText size={14} className="shrink-0 opacity-70" />
+ <span className="truncate">{file.name}</span>
+ </button>
+ {ctxMenu.menu}
+ {lightboxSrc && <ImageLightbox src={lightboxSrc} onClose={() => setLightboxSrc(null)} />}
+ {textLightboxOpen && (
+ <TextLightbox
+ filePath={file.path}
+ fileName={file.name}
+ onClose={() => setTextLightboxOpen(false)}
+ />
+ )}
+ {modelLightboxPath && (
+ <ModelLightbox
+ source={{ kind: 'local', absPath: modelLightboxPath }}
+ onClose={() => setModelLightboxPath(null)}
+ />
+ )}
+ </>
+ );
+}
+
+/** command 候选 mtime 下界的时钟余量:消息落库时间与文件写盘时间的抖动缓冲。 */
+const TURN_START_SLACK_MS = 120_000;
+
+interface GeneratedFileStat {
+ kind: 'dir' | 'file' | 'missing';
+ birthtimeMs?: number;
+ mtimeMs?: number;
+}
+
+/**
+ * 本地文件是否有足够证据归属于该 turn。tool 来源必须有真实创建时间:
+ * Write 也可能覆盖既有文件,仅凭成功/mtime 不能把它当成“新建”;birthtime
+ * 不可用时宁可不出。command 来源为兼容不提供 birthtime 的 Linux FS,维持
+ * mtime 回退,但仍受完整 turn 时间窗约束。
+ */
+export function isLocalGeneratedFileInTurn(
+ file: GeneratedFileRef,
+ stat: GeneratedFileStat,
+ turnStartMs: number | null,
+ turnEndMs: number | null,
+): boolean {
+ if (stat.kind !== 'file' || turnStartMs === null) return false;
+ const birthtimeMs =
+ typeof stat.birthtimeMs === 'number' && stat.birthtimeMs > 0 ? stat.birthtimeMs : null;
+ const ts = file.source === 'tool' ? birthtimeMs : (birthtimeMs ?? stat.mtimeMs);
+ // tool 来源的 birthtime 是同机 FS 事实,不放宽下界:放 2 分钟 slack 会把本轮
+ // 覆盖的旧文件误当新建。command 来源保留消息落库/执行时序抖动余量。
+ const lowerBound =
+ file.source === 'tool' ? turnStartMs : turnStartMs - TURN_START_SLACK_MS;
+ return (
+ typeof ts === 'number' &&
+ ts >= lowerBound &&
+ (turnEndMs === null || ts < turnEndMs)
+ );
+}
+
+/** 折叠阈值:约两行 chip。超过则收起为「前 N 个 + 再显示 M 个文件」。 */
+const MAX_VISIBLE_FILES = 6;
+
+export function GeneratedFilesCard({
+ files,
+ turnStartMs,
+ turnEndMs,
+}: {
+ files: readonly GeneratedFileRef[];
+ turnStartMs: number | null;
+ turnEndMs: number | null;
+}) {
+ const { t } = useTranslation();
+ const fileCtx = useChatSessionFile();
+ const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;
+ // 本地会话:stat 过滤到真实存在的文件(null = 尚未算完,不渲染,避免闪现后
+ // 又被过滤掉);远程:tool 来源先乐观呈现、远端 stat 复核,command 候选无法
+ // 验证 mtime 一律不出(见文件头注释)。
+ const [existing, setExisting] = useState<GeneratedFileRef[] | null>(
+ remoteOrigin ? files.filter((f) => f.source === 'tool') : null,
+ );
+ const [expanded, setExpanded] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ if (remoteOrigin) {
+ const toolFiles = files.filter((f) => f.source === 'tool');
+ setExisting(toolFiles);
+ void (async () => {
+ const checks = await Promise.all(
+ toolFiles.map(async (f) => {
+ const verdict = await verifyRemotePathCached(remoteOrigin, fileCtx.workingDir, f.path);
+ // nonfile(不存在 / 非普通文件)/ directory 是远端确定结论 → 摘掉;
+ // unknown(断链 / 限流)保持乐观。
+ return verdict !== 'nonfile' && verdict !== 'directory';
+ }),
+ );
+ if (!cancelled) setExisting(toolFiles.filter((_, idx) => checks[idx]));
+ })();
+ 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]));
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [files, remoteOrigin, turnStartMs, turnEndMs, fileCtx.workingDir]);
+
+ if (!existing || existing.length === 0) return null;
+
+ // 折叠(对标 Codex 的可展开产物列表):超过 MAX_VISIBLE_FILES 时只显示前
+ // MAX_VISIBLE_FILES 个 + 「再显示 N 个文件」;展开后提供「收起」回折。
+ const visible = expanded ? existing : existing.slice(0, MAX_VISIBLE_FILES);
+ const hiddenCount = existing.length - visible.length;
+
+ return (
+ <div className="my-1 flex flex-col gap-1.5">
+ <span className="text-12 text-[var(--text-secondary)]">
+ {t('chat.generatedFiles.title')}
+ </span>
+ <div className="flex flex-wrap gap-1.5">
+ {visible.map((f) => (
+ <GeneratedFileChip key={f.path} file={f} />
+ ))}
+ {hiddenCount > 0 && (
+ <button
+ type="button"
+ onClick={() => setExpanded(true)}
+ className={cn(
+ 'inline-flex items-center gap-1 h-7 px-2.5 py-1.5 rounded-[9999px]',
+ 'text-[13px] text-[var(--text-secondary)]',
+ 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors cursor-pointer',
+ )}
+ >
+ {t('chat.generatedFiles.showMore', { count: hiddenCount })}
+ <ChevronDown size={14} className="shrink-0" />
+ </button>
+ )}
+ {expanded && existing.length > MAX_VISIBLE_FILES && (
+ <button
+ type="button"
+ onClick={() => setExpanded(false)}
+ className={cn(
+ 'inline-flex items-center gap-1 h-7 px-2.5 py-1.5 rounded-[9999px]',
+ 'text-[13px] text-[var(--text-secondary)]',
+ 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors cursor-pointer',
+ )}
+ >
+ {t('chat.generatedFiles.showLess')}
+ <ChevronUp size={14} className="shrink-0" />
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 3322450b45..dd8bdecdf2 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -47,7 +47,8 @@ import type {
import { Spinner } from '@/components/ui/spinner';
import { useMessageNavRailPreference } from '@/hooks/useMessageNavRailPreference';
import { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';
-import type { KnownLocalFileRef } from '@/lib/localPathResolver';
+import { resolveToolFilePath, type KnownLocalFileRef } from '@/lib/localPathResolver';
+import { collectGeneratedFiles, type GeneratedFileRef } from '@/lib/generatedFiles';
import {
isRemoteSessionSticky,
subscribeTurnChangeSetUpdated,
@@ -159,6 +160,7 @@ import { ThinkingCard } from './ThinkingCard';
import { AgentActionsBlock } from './AgentActionsBlock';
import { AgentTaskCard } from './AgentTaskCard';
import { TurnChangesCard } from './TurnChangesCard';
+import { GeneratedFilesCard } from './GeneratedFilesCard';
import { WorkGroupBlock, type WorkGroupChild } from './WorkGroupBlock';
import {
extractAnchorCardId,
@@ -328,6 +330,13 @@ type TurnChangesRenderItem = {
key: string;
changeSet: TurnChangeSetSummary;
};
+type GeneratedFilesRenderItem = {
+ type: 'generated_files';
+ key: string;
+ files: GeneratedFileRef[];
+ turnStartMs: number | null;
+ turnEndMs: number | null;
+};
/** 原子工作子项:tool / agent task / thinking / assistant 工作文字。 */
export type WorkChildItem = ToolSegmentRenderItem | AgentTaskRenderItem | MessageRenderItem;
@@ -358,6 +367,7 @@ export type RenderItem =
| AgentTaskRenderItem
| ForkOriginRenderItem
| TurnChangesRenderItem
+ | GeneratedFilesRenderItem
| {
/** tool-result-media: 把 tool_result 里的 xdt_image_url(s) / xdt_video_urls
* 提取出来作为独立视觉消息渲染,跳出 tool_segment 折叠卡片。统一容器,
@@ -906,6 +916,8 @@ export function buildRenderItems(
historyWindowIncomplete?: boolean;
/** Main-persisted exact patches, anchored to their visible user message. */
turnChangeSets?: readonly TurnChangeSetSummary[];
+ /** Session working directory for opaque generated-file fallback chips. */
+ workingDir?: string;
},
): {
items: RenderItem[];
@@ -1058,6 +1070,18 @@ export function buildRenderItems(
const changeSets = (opts?.turnChangeSets ?? []).filter(
(changeSet) => changeSet.anchorClientId === anchorClientId,
);
+ const exactPaths = new Set<string>();
+ const pathKey = (value: string): string => {
+ const normalized = value.replace(/\\/g, '/');
+ const windowsShape = /^[a-zA-Z]:[\\/]/.test(value) || value.includes('\\');
+ return windowsShape ? normalized.toLowerCase() : normalized;
+ };
+ for (const changeSet of changeSets) {
+ for (const file of changeSet.files) {
+ exactPaths.add(pathKey(resolveToolFilePath(file.path, changeSet.cwd)));
+ if (file.oldPath) exactPaths.add(pathKey(resolveToolFilePath(file.oldPath, changeSet.cwd)));
+ }
+ }
for (const changeSet of changeSets) {
items.push({
type: 'turn_changes',
@@ -1065,6 +1089,29 @@ export function buildRenderItems(
changeSet,
});
}
+ const workingDir = opts?.workingDir ?? '';
+ if (!workingDir || hi <= lo) return;
+ const slice = messages.slice(lo, hi);
+ const generatedFiles = collectGeneratedFiles(slice, workingDir).filter((file) => {
+ const normalized = pathKey(file.path);
+ return !exactPaths.has(normalized) || changeSets.length === 0;
+ });
+ if (generatedFiles.length === 0) return;
+ let turnStartMs: number | null = null;
+ for (const message of slice) {
+ const timestamp = Date.parse(message.createdAt ?? '');
+ if (Number.isFinite(timestamp) && (turnStartMs === null || timestamp < turnStartMs)) {
+ turnStartMs = timestamp;
+ }
+ }
+ const boundaryTimestamp = Date.parse(messages[hi]?.createdAt ?? '');
+ items.push({
+ type: 'generated_files',
+ key: `genfiles-${messages[lo].clientId}`,
+ files: generatedFiles,
+ turnStartMs,
+ turnEndMs: Number.isFinite(boundaryTimestamp) ? boundaryTimestamp : null,
+ });
};
let i = 0;
while (i < messages.length) {
@@ -2431,8 +2478,9 @@ export function MessageStream({
buildRenderItems(messages, taskUpdates, ghostCardSnapshot, {
historyWindowIncomplete: Boolean(hasMoreMessages),
turnChangeSets,
+ workingDir,
}),
- [messages, taskUpdates, ghostCardSnapshot, hasMoreMessages, turnChangeSets],
+ [messages, taskUpdates, ghostCardSnapshot, hasMoreMessages, turnChangeSets, workingDir],
);
const assistantsWithFollowingUserBoundary = useMemo(
() => collectAssistantsWithFollowingUserBoundary(messages),
@@ -3752,6 +3800,17 @@ export function MessageStream({
);
}
+ if (item.type === 'generated_files') {
+ return (
+ <GeneratedFilesCard
+ key={item.key}
+ files={item.files}
+ turnStartMs={item.turnStartMs}
+ turnEndMs={item.turnEndMs}
+ />
+ );
+ }
+
if (item.type === 'tool_segment') {
return (
<AgentActionsBlock
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 600ad9cb5a..84e86307e1 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6196,6 +6196,11 @@
"DEVICE_LINK_CONTROL_DISABLED": "Control for this device is off; the message was not sent.",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "Attachment transfer failed; the message was not sent. Please try again."
},
+ "generatedFiles": {
+ "title": "Files created this message",
+ "showMore": "Show {{count}} more",
+ "showLess": "Show less"
+ },
"turnChanges": {
"title": "Changed {{count}} files",
"partialTitle": "File changes were not fully captured",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 8a634e464e..8cc96cb68e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6194,6 +6194,11 @@
"DEVICE_LINK_CONTROL_DISABLED": "このデバイスの操作はオフです。メッセージは送信されていません。",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "添付ファイルの転送に失敗しました。メッセージは送信されていません。もう一度お試しください。"
},
+ "generatedFiles": {
+ "title": "このメッセージで作成されたファイル",
+ "showMore": "さらに {{count}} 件表示",
+ "showLess": "折りたたむ"
+ },
"turnChanges": {
"title": "{{count}} ファイルを変更",
"partialTitle": "このターンのファイル変更を完全には取得できませんでした",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 3cadadec56..dbd0238687 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6194,6 +6194,11 @@
"DEVICE_LINK_CONTROL_DISABLED": "이 기기의 제어가 꺼져 있어 메시지가 전송되지 않았습니다.",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "첨부 파일 전송에 실패했습니다. 메시지가 전송되지 않았습니다. 다시 시도하세요."
},
+ "generatedFiles": {
+ "title": "이 메시지에서 생성된 파일",
+ "showMore": "{{count}}개 더 보기",
+ "showLess": "간략히 보기"
+ },
"turnChanges": {
"title": "파일 {{count}}개 변경",
"partialTitle": "이번 턴의 파일 변경 사항이 완전히 캡처되지 않았습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index ccc6389e51..c0e3a41804 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6194,6 +6194,11 @@
"DEVICE_LINK_CONTROL_DISABLED": "已关闭对该设备的控制,消息未发送。",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "附件传输失败,消息未发送。请重试。"
},
+ "generatedFiles": {
+ "title": "本条消息生成的文件",
+ "showMore": "显示另外 {{count}} 个",
+ "showLess": "收起"
+ },
"turnChanges": {
"title": "已更改 {{count}} 个文件",
"partialTitle": "本轮文件变更未完整记录",
diff --git a/apps/desktop/src/renderer/lib/generatedFiles.ts b/apps/desktop/src/renderer/lib/generatedFiles.ts
new file mode 100644
index 0000000000..31369d5adc
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/generatedFiles.ts
@@ -0,0 +1,188 @@
+/**
+ * generatedFiles — 从一轮回复的 tool_use 消息里派生「本轮 agent 新建的文件」。
+ * ---------------------------------------------------------------------------
+ * 纯派生、不新增持久化:tool_use 消息本身已落库并原样回放,所以历史会话重开后
+ * 这张卡能稳定重建。跨 agent(claude-code / codex / pi)的工具名差异统一交给
+ * `describeToolUse` 归一化,不自己维护工具名表:
+ * - kind==='file' 且 action==='create' → Write / write(claude / pi 新建文件)
+ * - kind==='fileChange' 的 changes 里 action==='add' → codex file_change 新增文件
+ * - kind==='command' → 从命令文本启发式提取产物路径候选(source:'command')。
+ * Excel / Word / PDF 等二进制产物只能靠脚本(Bash/exec 跑 python、node)生成,
+ * 没有文件工具记录;不补这个盲区,卡在「帮我生成个表格」主场景直接失灵。
+ * 「修改已有文件」(edit / update)与读取不算产出(产品口径:只收新建,见
+ * AskUserQuestion 决策)。move / delete 同样排除。
+ *
+ * 误报防线(source:'command' 特有,由渲染方 GeneratedFilesCard 执行):
+ * 命令文本里出现路径 ≠ 命令创建了它(可能只是读输入)。所以 command 候选除
+ * 存在性外,还必须满足「文件 mtime 落在本轮时间窗内」才出 chip;窗口不可得
+ * (消息无 createdAt / 远程会话无法 stat)时宁可不出。tool 来源保持原判定。
+ */
+
+import { describeToolUse } from '@cindy/maker-shared';
+
+import { resolveToolFilePath } from './localPathResolver';
+import { basename } from './utils';
+
+export interface GeneratedFileRef {
+ /** 已按 workingDir 解析的绝对路径(用于存在性校验与 chip 打开)。 */
+ path: string;
+ /** 展示用文件名(basename)。 */
+ name: string;
+ /**
+ * 'tool' = 文件工具结构化新建记录,存在即列;
+ * 'command' = 命令文本启发式候选,渲染前还需 mtime 时间窗校验。
+ */
+ source: 'tool' | 'command';
+}
+
+interface ToolUseLike {
+ role: string;
+ toolName?: string;
+ toolInput?: unknown;
+}
+
+/**
+ * 去重 key。**只对 Windows 路径形态**(盘符前缀或含反斜杠)做大小写不敏感折叠——
+ * NTFS 上 `A.txt` 与 `a.txt` 是同一文件;POSIX 路径(Linux 本地会话 / 远程 Linux
+ * workdir)必须保留原大小写,否则会把两个真实不同的文件错误合并、丢掉一个
+ * (PR #1835 review)。macOS 虽默认大小写不敏感,但无法从纯 POSIX 路径形态区分
+ * macOS 与 Linux;两害相权取轻:宁可 macOS 偶尔多出一个重复 chip,也不能在 Linux
+ * 上丢文件。
+ */
+function dedupeKeyForPath(abs: string): string {
+ const isWindowsShape = /^[a-zA-Z]:[\\/]/.test(abs) || abs.includes('\\');
+ // 斜杠也归一:`C:/x/a.md`(命令文本常见形态)与 `C:\x\a.md`(Write 记录)是
+ // 同一文件,不折叠会重复出 chip。
+ return isWindowsShape ? abs.replace(/\//g, '\\').toLowerCase() : abs;
+}
+
+/**
+ * Windows 形态的绝对路径统一成反斜杠本机形态再往下传:Explorer `/select`
+ * (定位)对正斜杠路径静默无反应,`shell.openPath` 在仅用户层文件关联的机器上
+ * 对正斜杠也会解析失败(实测「本轮产出」卡 docx chip 打不开的根因)。POSIX
+ * 路径原样保留。
+ */
+function canonicalizeWindowsShape(abs: string): string {
+ return /^[a-zA-Z]:[\\/]/.test(abs) ? abs.replace(/\//g, '\\') : abs;
+}
+
+/** 单条 tool_use 消息 → 它新建的文件原始路径列表(可能为空)。 */
+function createdPathsFromToolUse(toolName: string, input: unknown): string[] {
+ const descriptor = describeToolUse(toolName, input);
+ if (descriptor.kind === 'file') {
+ return descriptor.action === 'create' && descriptor.filePath ? [descriptor.filePath] : [];
+ }
+ if (descriptor.kind === 'fileChange') {
+ return descriptor.changes
+ .filter((c) => c.action === 'add' && c.path)
+ .map((c) => c.path);
+ }
+ return [];
+}
+
+/** 带扩展名(1–8 位字母数字,不含纯数字)的路径才算候选;`a.b.c` 取末段。 */
+const EXT_RE = /\.[A-Za-z][A-Za-z0-9]{0,7}$/;
+
+/** 临时目录里的产物是脚本自身/中间文件的高发区,一律不算「本轮产出」。 */
+const TEMP_DIR_RE = /(^|[\\/])(tmp|temp)([\\/])|[\\/]AppData[\\/]Local[\\/]Temp[\\/]/i;
+
+function isPathCandidate(raw: string): boolean {
+ const s = raw.trim();
+ if (s.length < 3 || s.length > 512) return false;
+ if (!EXT_RE.test(s)) return false;
+ if (TEMP_DIR_RE.test(s)) return false;
+ // 绝对路径,或含分隔符的相对路径(交给 resolveToolFilePath 按 workingDir 解析)。
+ // 纯文件名(`输出.xlsx`)不收:随机带点 token 误报率太高。
+ const isAbs = /^[A-Za-z]:[\\/]/.test(s) || s.startsWith('/');
+ const hasSep = s.includes('/') || s.includes('\\');
+ return isAbs || hasSep;
+}
+
+/**
+ * 命令文本 → 产物路径候选。两个来源:
+ * 1. 引号字符串(`'...'` / `"..."`):脚本内路径的主形态,可含空格与 CJK,
+ * 如 python 的 `wb.save(r'C:\Users\x\表格.xlsx')`;
+ * 2. 裸 token:重定向 / CLI 参数里的无引号绝对路径(不含空格)。
+ * 只做形态过滤,不判断读写意图——读写区分交给渲染方的 mtime 时间窗。
+ */
+export function extractCommandPathCandidates(command: string): string[] {
+ if (!command) return [];
+ const out: string[] = [];
+ const seen = new Set<string>();
+ const push = (raw: string): void => {
+ const s = raw.trim();
+ if (!isPathCandidate(s)) return;
+ if (seen.has(s)) return;
+ seen.add(s);
+ out.push(s);
+ };
+ for (const m of command.matchAll(/'([^'\r\n]+)'|"([^"\r\n]+)"/g)) {
+ push(m[1] ?? m[2] ?? '');
+ }
+ // 裸 Windows 盘符路径与裸 POSIX 绝对路径(前面是行首/空白/常见分隔)。
+ // 盘符前不允许字母数字:排除 URL scheme 尾字母被当盘符(https://…)。
+ for (const m of command.matchAll(/(?<![A-Za-z0-9])[A-Za-z]:[\\/][^\s'"<>|?*]+/g)) push(m[0]);
+ for (const m of command.matchAll(/(?:^|[\s=(,>])(\/[^\s'"<>|?*:]+)/g)) push(m[1]);
+ return out;
+}
+
+/**
+ * 一组消息(通常是一个 turn 的切片,但对任意切片都成立)→ 新建文件的有序去重
+ * 列表。路径经 `resolveToolFilePath` 解析成绝对路径;`workingDir` 为空时按原样
+ * 保留(与其它 chip 解析同策)。存在性(及 command 候选的 mtime 时间窗)校验由
+ * 调用方在渲染前做(异步 IPC)。同一路径同时有 tool 与 command 来源时按 tool 计
+ * (tool 是结构化实锤,不该被降级成启发式候选)。
+ */
+export function collectGeneratedFiles(
+ messages: readonly ToolUseLike[],
+ workingDir: string,
+): GeneratedFileRef[] {
+ // 第一遍:收「本轮被文件工具**修改**过」的路径。它们是编辑不是新建,命令文本
+ // 里再出现也不算产物候选——否则跑测试 / 构建命令引用刚编辑过的源码文件
+ // (`vitest run src/x.test.ts`)会被 mtime 窗口放行,把编码会话的改动文件全
+ // 误收进卡。read 不排除:agent 生成后回读验证是常见动作,不该反杀真产物。
+ const editedKeys = new Set<string>();
+ for (const msg of messages) {
+ if (msg.role !== 'tool_use' || !msg.toolName) continue;
+ const d = describeToolUse(msg.toolName, msg.toolInput);
+ if (d.kind === 'file' && d.action === 'edit' && d.filePath) {
+ editedKeys.add(dedupeKeyForPath(resolveToolFilePath(d.filePath, workingDir)));
+ } else if (d.kind === 'fileChange') {
+ for (const c of d.changes) {
+ if (c.action !== 'add' && c.path) {
+ editedKeys.add(dedupeKeyForPath(resolveToolFilePath(c.path, workingDir)));
+ }
+ }
+ }
+ }
+
+ const byKey = new Map<string, GeneratedFileRef>();
+ for (const msg of messages) {
+ if (msg.role !== 'tool_use') continue;
+ const toolName = msg.toolName ?? '';
+ if (!toolName) continue;
+
+ const addPath = (rawPath: string, source: GeneratedFileRef['source']): void => {
+ 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';
+ return;
+ }
+ byKey.set(key, { path: abs, name: basename(abs), source });
+ };
+
+ for (const rawPath of createdPathsFromToolUse(toolName, msg.toolInput)) {
+ addPath(rawPath, 'tool');
+ }
+ const descriptor = describeToolUse(toolName, msg.toolInput);
+ if (descriptor.kind === 'command' && descriptor.command) {
+ for (const rawPath of extractCommandPathCandidates(descriptor.command)) {
+ addPath(rawPath, 'command');
+ }
+ }
+ }
+ return [...byKey.values()];
+}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 7b981b8588..bc3434cf18 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -19130,6 +19130,58 @@ describe('CodexAgent context window reporting', () => {
await handle.close();
});
+ it('forwards root and descendant Codex diffs into one merged turn capture event', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-descendant-diff',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.descendantThreadStarted || !handlers.descendantNotification) {
+ throw new Error('expected descendant handlers');
+ }
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-root-diff' } });
+ handlers.turnDiffUpdated?.({
+ threadId: 'start-thread-id',
+ turnId: 'turn-root-diff',
+ diff: 'diff --git a/root.txt b/root.txt\n--- a/root.txt\n+++ b/root.txt\n@@ -1 +1 @@\n-old\n+root\n',
+ });
+ handlers.descendantThreadStarted({
+ thread: { id: 'child-diff-thread', parentThreadId: 'start-thread-id' },
+ });
+ handlers.descendantThreadStarted({
+ thread: { id: 'grandchild-diff-thread', parentThreadId: 'child-diff-thread' },
+ });
+ handlers.descendantNotification('child-diff-thread', 'turn/diff/updated', {
+ threadId: 'child-diff-thread',
+ turnId: 'child-diff-turn',
+ diff: 'diff --git a/child.txt b/child.txt\n--- a/child.txt\n+++ b/child.txt\n@@ -1 +1 @@\n-old\n+child\n',
+ });
+ handlers.descendantNotification('grandchild-diff-thread', 'turn/diff/updated', {
+ threadId: 'grandchild-diff-thread',
+ turnId: 'grandchild-diff-turn',
+ diff: 'diff --git a/grandchild.txt b/grandchild.txt\n--- a/grandchild.txt\n+++ b/grandchild.txt\n@@ -1 +1 @@\n-old\n+grandchild\n',
+ });
+
+ await vi.waitFor(() => {
+ const diffs = events.filter((event) => event.type === 'turn_diff');
+ expect(diffs.length).toBeGreaterThanOrEqual(3);
+ });
+ const lastDiff = events.filter((event) => event.type === 'turn_diff').at(-1);
+ expect(lastDiff?.data).toMatchObject({ turnId: 'turn-root-diff', cwd: '/repo' });
+ expect((lastDiff?.data as { diff: string }).diff).toContain('root.txt');
+ expect((lastDiff?.data as { diff: string }).diff).toContain('child.txt');
+ expect((lastDiff?.data as { diff: string }).diff).toContain('grandchild.txt');
+
+ await handle.close();
+ });
+
it('completes the subagent card without any thread/started (codex 0.145 real behavior)', async () => {
// 生产实测(2026-08-04):0.145 只在显式 thread/start / fork RPC 时发
// thread/started,spawn 出的子线程从来不发。血缘必须在识别 spawn item 的那一刻
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 8db8dfd461..4903ee461e 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -2461,6 +2461,32 @@ export class CodexAgent extends BaseAgent {
let sdkSessionId: string | undefined;
let currentTurnId: string | null = null;
+ // app-server emits one cumulative diff per thread. Descendant threads use
+ // different turn ids, but their changes belong to the active root turn;
+ // retain each thread's latest snapshot and publish one merged diff.
+ const turnDiffSnapshots = new Map<string, string>();
+ const splitTurnDiffBlocks = (diff: string): string[] => diff
+ .split(/(?=^diff --git )/m)
+ .filter((block) => block.startsWith('diff --git '));
+ const mergeTurnDiffSnapshots = (): string => {
+ const blocks = new Map<string, string>();
+ for (const snapshot of turnDiffSnapshots.values()) {
+ for (const block of splitTurnDiffBlocks(snapshot)) {
+ const header = block.split('\n', 1)[0] ?? block;
+ blocks.set(header, block);
+ }
+ }
+ return [...blocks.values()].join('');
+ };
+ const publishTurnDiff = (threadKey: string, turnId: string, diff: string): void => {
+ if (!diff) return;
+ turnDiffSnapshots.set(threadKey, diff);
+ eventQueue.push({
+ type: 'turn_diff',
+ data: { turnId, diff: mergeTurnDiffSnapshots(), cwd: opts.workingDir },
+ source: 'codex',
+ });
+ };
let isTurnInFlight = false;
/**
* 本 handle 上「起过多少个 turn」的单调计数器,每次 isTurnInFlight 被置活 +1。
@@ -3532,6 +3558,17 @@ export class CodexAgent extends BaseAgent {
}
}
}
+ if (method === 'turn/diff/updated') {
+ const diffParams = params as { turnId?: unknown; diff?: unknown } | null;
+ if (
+ currentTurnId
+ && diffParams
+ && typeof diffParams.turnId === 'string'
+ && typeof diffParams.diff === 'string'
+ ) {
+ publishTurnDiff(childThreadId, currentTurnId, diffParams.diff);
+ }
+ }
const update = subagentLiveCards.handleDescendantNotification(childThreadId, method, params);
if (update) emitSubagentCardUpdate(update);
@@ -7734,6 +7771,7 @@ export class CodexAgent extends BaseAgent {
);
}
currentTurnId = params.turn.id;
+ if (!wasSameTurn) turnDiffSnapshots.clear();
isTurnInFlight = true;
turnStartGeneration += 1; // 见声明处:延迟善后靠它判断"期间起过新 turn"
if (!wasSameTurn) {
@@ -7851,15 +7889,7 @@ export class CodexAgent extends BaseAgent {
turnDiffUpdated: (params) => {
if (enqueueIfBufferedTurn(params.turnId, () => handlers.turnDiffUpdated?.(params))) return;
if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
- eventQueue.push({
- type: 'turn_diff',
- data: {
- turnId: params.turnId,
- diff: params.diff,
- cwd: opts.workingDir,
- },
- source: 'codex',
- });
+ publishTurnDiff(threadId, params.turnId, params.diff);
},
turnCompleted: (params) => {
// buffered turn 的终态同样进队列等对账 (greptile R11 P1 + codex R12 P1):