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): 修复审查生成文件误报与大文件卡顿

davidd8c1ea6bb4be
diff --git a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts b/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
index 4f7d50c56f..12504c5267 100644
--- a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
+++ b/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { collectGeneratedFiles, extractCommandPathCandidates } from '../lib/generatedFiles';
+import { collectGeneratedFiles, extractCommandOutputPathCandidates } from '../lib/generatedFiles';
const WORKDIR = '/work';
@@ -118,21 +118,23 @@ describe('collectGeneratedFiles', () => {
],
'C:\\work',
);
- expect(files.map((f) => f.path)).toEqual(['C:\\work\\report.docx', 'C:\\work\\输出\\表格.xlsx']);
+ expect(files.map((f) => f.path)).toEqual([
+ 'C:\\work\\report.docx',
+ 'C:\\work\\输出\\表格.xlsx',
+ ]);
expect(files[0].source).toBe('tool');
});
it('collapses doubled backslashes so escaped wrapper commands do not duplicate chips', () => {
- // 实测场景(pr-watch session):powershell 包一层 node -e,落库命令文本里的
- // 路径带转义残留(`C:\\Users\\...`);同轮另一条命令用正斜杠形态。fs 层它们
- // 是同一文件(Windows 归并重复分隔符),不折叠会出两个同名 chip。
+ // 包装脚本里的写出路径可能带转义残留(`C:\\Users\\...`);同轮另一条命令用
+ // 正斜杠形态。fs 层它们是同一文件(Windows 归并重复分隔符),不折叠会出两个同名 chip。
const files = collectGeneratedFiles(
[
toolUse('Bash', {
- command: "powershell -Command '$p = 'C:\\\\Users\\\\U\\\\pr-watch\\\\registry.json'; Get-Content $p'",
+ command: 'node -e "save(\'C:\\\\Users\\\\U\\\\pr-watch\\\\registry.json\')"',
}),
toolUse('Bash', {
- command: "node -e \"const p='C:/Users/U/pr-watch/registry.json'; console.log(p);\"",
+ command: 'node -e "save(\'C:/Users/U/pr-watch/registry.json\')"',
}),
],
'C:\\Users\\U\\pr-watch',
@@ -188,33 +190,82 @@ describe('collectGeneratedFiles', () => {
});
});
-describe('extractCommandPathCandidates', () => {
- it('extracts quoted paths (CJK, spaces) and bare absolute paths', () => {
+describe('extractCommandOutputPathCandidates', () => {
+ it('extracts paths from explicit save, redirection and copy destinations', () => {
expect(
- extractCommandPathCandidates("wb.save(r'C:\\Users\\A\\My Docs\\报表 v2.xlsx')"),
+ extractCommandOutputPathCandidates("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(
+ expect(extractCommandOutputPathCandidates('node gen.js > C:/out/result.json')).toContain(
'C:/out/result.json',
);
- expect(extractCommandPathCandidates('cp a "/home/u/输出/report.pdf"')).toContain(
+ expect(extractCommandOutputPathCandidates('cp a "/home/u/输出/report.pdf"')).toContain(
'/home/u/输出/report.pdf',
);
+ expect(
+ extractCommandOutputPathCandidates(
+ 'Get-Content "inputs/source.md" && copy "inputs/source.md" \'artifacts/report.md\'',
+ ),
+ ).toEqual(['artifacts/report.md']);
});
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([]);
+ expect(extractCommandOutputPathCandidates("save('/tmp/x.xlsx')")).toEqual([]);
+ expect(
+ extractCommandOutputPathCandidates("save('C:\\Users\\A\\AppData\\Local\\Temp\\x.xlsx')"),
+ ).toEqual([]);
+ expect(extractCommandOutputPathCandidates('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([]);
+ expect(extractCommandOutputPathCandidates("save('输出.xlsx')")).toEqual([]);
+ expect(extractCommandOutputPathCandidates("save('out/输出.xlsx')")).toEqual(['out/输出.xlsx']);
+ expect(extractCommandOutputPathCandidates('curl https://x.com/a.js')).toEqual([]);
+ expect(extractCommandOutputPathCandidates('')).toEqual([]);
});
- it('dedupes the same path appearing quoted and bare', () => {
+ it('dedupes the same output path', () => {
expect(
- extractCommandPathCandidates('python gen.py C:/out/a.csv && stat "C:/out/a.csv"'),
+ extractCommandOutputPathCandidates(
+ 'python gen.py > C:/out/a.csv && node gen.js --output "C:/out/a.csv"',
+ ),
).toEqual(['C:/out/a.csv']);
});
+
+ it('does not treat paths in PowerShell and shell read commands as outputs', () => {
+ const powershellRead =
+ 'powershell.exe -Command \'$p="docs/design-rules/DESIGN.md"; ' +
+ "$l=[System.IO.File]::ReadAllLines($p); $l[0..20]'";
+ expect(extractCommandOutputPathCandidates(powershellRead)).toEqual([]);
+ expect(
+ extractCommandOutputPathCandidates(
+ "Get-Content 'docs/dev-rules/repo-map.md'; rg foo 'apps/desktop/src/index.tsx'",
+ ),
+ ).toEqual([]);
+ });
+
+ it('keeps only the explicit output when a command also names input files', () => {
+ expect(
+ extractCommandOutputPathCandidates(
+ "python convert.py 'inputs/source.md' --output 'artifacts/report.pdf'",
+ ),
+ ).toEqual(['artifacts/report.pdf']);
+ expect(
+ extractCommandOutputPathCandidates(
+ "open('inputs/source.txt', 'r'); open('artifacts/result.txt', 'wb')",
+ ),
+ ).toEqual(['artifacts/result.txt']);
+ expect(
+ extractCommandOutputPathCandidates(
+ "Set-Content -Path 'artifacts/result.txt' -Value (Get-Content 'inputs/source.txt')",
+ ),
+ ).toEqual(['artifacts/result.txt']);
+ expect(
+ extractCommandOutputPathCandidates(
+ "Set-Content $output ([System.IO.File]::ReadAllText('inputs/source.txt'))",
+ ),
+ ).toEqual([]);
+ expect(
+ extractCommandOutputPathCandidates(
+ "node convert.js 'inputs/source.md' --output='artifacts/result.html'",
+ ),
+ ).toEqual(['artifacts/result.html']);
+ });
});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/PlainUnifiedDiff.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/PlainUnifiedDiff.test.ts
index df90693168..ce63589985 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/PlainUnifiedDiff.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/PlainUnifiedDiff.test.ts
@@ -16,6 +16,7 @@ import type { FileDiff, Hunk } from '@/lib/gitReview.types';
import { buildSplitRows, buildUnifiedRows, shouldVirtualizeDiffRows, shouldVirtualizeFileList } from '../diffRows';
import {
collectHighlightLines,
+ HIGHLIGHT_MAX_DIFF_LINES,
HIGHLIGHT_MAX_LINE_LENGTH,
highlightLineKey,
LruCache,
@@ -523,14 +524,19 @@ describe('PlainUnifiedDiff split rows', () => {
describe('PlainUnifiedDiff performance helpers', () => {
it('uses explicit thresholds for diff and file-list virtualization', () => {
- expect(shouldVirtualizeDiffRows(500)).toBe(false);
- expect(shouldVirtualizeDiffRows(501)).toBe(true);
+ expect(shouldVirtualizeDiffRows(200)).toBe(false);
+ expect(shouldVirtualizeDiffRows(201)).toBe(true);
expect(shouldVirtualizeFileList(100)).toBe(false);
expect(shouldVirtualizeFileList(101)).toBe(true);
});
- it('marks the virtualized diff branch for large diffs', () => {
- const manyLines = Array.from({ length: 510 }, (_, index) =>
+ it('virtualizes files shaped like the two-file whole-file rewrite regression', () => {
+ expect(shouldVirtualizeDiffRows(487)).toBe(true);
+ expect(shouldVirtualizeDiffRows(478)).toBe(true);
+ });
+
+ it('marks the virtualized diff branch for a file from the two-file regression', () => {
+ const manyLines = Array.from({ length: 487 }, (_, index) =>
line(index, 'context', `line ${index}`, index + 1, index + 1),
);
const diff: FileDiff = {
@@ -679,6 +685,19 @@ describe('PlainUnifiedDiff highlighting helpers', () => {
expect(shouldSkipHighlightDiff(rows)).toBe(false);
});
+ it('skips per-line worker highlighting for medium whole-file rewrites', () => {
+ const manyLines = Array.from({ length: HIGHLIGHT_MAX_DIFF_LINES + 1 }, (_, index) =>
+ line(index, 'add', `const value${index} = true;`, null, index + 1),
+ );
+ const rows = buildUnifiedRows([{
+ ...hunk(0, 1, manyLines.length),
+ lines: manyLines,
+ selectableLines: manyLines.map((_, index) => index),
+ }]);
+
+ expect(shouldSkipHighlightDiff(rows)).toBe(true);
+ });
+
it('keeps multi-hunk highlight keys from overwriting same local line indices', () => {
const firstHunk: Hunk = {
...hunk(0, 1, 2),
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts
index 145297065e..164a8b9a7e 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts
@@ -37,7 +37,9 @@ export interface HunkActionAnchor {
hunk: Hunk;
}
-export const DIFF_ROW_VIRTUAL_THRESHOLD = 500;
+// Keep medium-sized files off the eager DOM path. Two files just below the old
+// 500-row cutoff could otherwise mount roughly a thousand diff rows at once.
+export const DIFF_ROW_VIRTUAL_THRESHOLD = 200;
export const FILE_LIST_VIRTUAL_THRESHOLD = 100;
function oldEndLine(hunk: Hunk): number {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts
index ca35ea065f..c37aafae24 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts
@@ -2,7 +2,9 @@ import type { DiffRenderRow } from './diffRows';
export const HIGHLIGHT_MAX_LINE_LENGTH = 1000;
export const HIGHLIGHT_MAX_DIFF_CHARS = 200_000;
-export const HIGHLIGHT_MAX_DIFF_LINES = 1200;
+// The highlighter sends one worker request per line. Virtualized medium diffs
+// stay responsive by rendering plain text instead of queueing hundreds at once.
+export const HIGHLIGHT_MAX_DIFF_LINES = 400;
type HighlightRequest = { id: string; code: string; lang: string };
type HighlightResponse =
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts
index 7552dd5a8f..90dfb93c46 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts
@@ -22,9 +22,9 @@ interface InlineDiffOptions {
}
export const INLINE_DIFF_MIN_COMMON_RATIO = 0.3;
-// Guard the pre-virtualization hot path: 400 paired changed lines at 500 chars
-// each is already enough useful signal, while larger diffs can block rendering.
-export const INLINE_DIFF_MAX_PAIR_COUNT = 400;
+// Inline word diffing is synchronous. Keep it away from medium whole-file
+// rewrites even when an existing task has the legacy word-diff default enabled.
+export const INLINE_DIFF_MAX_PAIR_COUNT = 150;
export const INLINE_DIFF_MAX_TOTAL_CHARS = 200_000;
const inlineDiffCache = new LruCache<string, InlineDiffPair | null>(2000);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
index 8e7035f84e..1144b4ef44 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
@@ -564,7 +564,7 @@ function TurnChangeSetReviewBody({ state, ctx, setSource, setSelectedCommitOid }
onViewModeChange={(diffViewMode) => ctx.patchState({ diffViewMode })}
onRichMarkdownPreviewChange={(richMarkdownPreview) => ctx.patchState({ richMarkdownPreview })}
wordWrap={state.wordWrap ?? false}
- wordDiff={state.wordDiff ?? true}
+ wordDiff={state.wordDiff ?? false}
fileTreeVisible={state.fileTreeVisible ?? false}
jumpRequest={jumpRequest}
loadImagePreview={unavailablePreview}
@@ -612,7 +612,7 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
const diffViewMode: DiffViewMode = state.diffViewMode ?? 'unified';
const fileTreeVisible = state.fileTreeVisible ?? false;
const wordWrap = state.wordWrap ?? false;
- const wordDiff = state.wordDiff ?? true;
+ const wordDiff = state.wordDiff ?? false;
const richMarkdownPreview = state.richMarkdownPreview ?? true;
const collapsedSet = useMemo(() => new Set(state.collapsedPaths ?? []), [state.collapsedPaths]);
const rawUnstaged = data?.diffs.unstaged ?? [];
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/plugin.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/plugin.test.ts
index 651a6d5206..8587238bd2 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/plugin.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/plugin.test.ts
@@ -44,7 +44,7 @@ describe('review plugin', () => {
expect(a.diffViewMode).toBe('unified');
expect(a.fileTreeVisible).toBe(false);
expect(a.wordWrap).toBe(false);
- expect(a.wordDiff).toBe(true);
+ expect(a.wordDiff).toBe(false);
expect(a.hideWhitespace).toBe(false);
expect(a.richMarkdownPreview).toBe(true);
expect(a.branchBaseRef).toBeNull();
@@ -101,12 +101,12 @@ describe('review plugin', () => {
expect((p.hydrateState!({}) as { wordWrap: boolean }).wordWrap).toBe(false);
});
- it('hydrateState defaults word diff to enabled for invalid values', () => {
+ it('hydrateState defaults word diff to disabled for invalid values', () => {
const p = registry.getTabKind('review')!;
expect((p.hydrateState!({ wordDiff: false }) as { wordDiff: boolean }).wordDiff).toBe(false);
expect((p.hydrateState!({ wordDiff: true }) as { wordDiff: boolean }).wordDiff).toBe(true);
- expect((p.hydrateState!({ wordDiff: 'no' }) as { wordDiff: boolean }).wordDiff).toBe(true);
- expect((p.hydrateState!({}) as { wordDiff: boolean }).wordDiff).toBe(true);
+ expect((p.hydrateState!({ wordDiff: 'no' }) as { wordDiff: boolean }).wordDiff).toBe(false);
+ expect((p.hydrateState!({}) as { wordDiff: boolean }).wordDiff).toBe(false);
});
it('hydrateState falls back to visible whitespace changes for invalid values', () => {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
index a09ad0c623..2a663c6680 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
@@ -59,7 +59,7 @@ const DEFAULT_STATE: ReviewState = {
diffViewMode: 'unified',
fileTreeVisible: false,
wordWrap: false,
- wordDiff: true,
+ wordDiff: false,
hideWhitespace: false,
richMarkdownPreview: true,
branchBaseRef: null,
diff --git a/apps/desktop/src/renderer/lib/generatedFiles.ts b/apps/desktop/src/renderer/lib/generatedFiles.ts
index f7aebe1f9b..d33ed40667 100644
--- a/apps/desktop/src/renderer/lib/generatedFiles.ts
+++ b/apps/desktop/src/renderer/lib/generatedFiles.ts
@@ -6,15 +6,15 @@
* `describeToolUse` 归一化,不自己维护工具名表:
* - kind==='file' 且 action==='create' → Write / write(claude / pi 新建文件)
* - kind==='fileChange' 的 changes 里 action==='add' → codex file_change 新增文件
- * - kind==='command' → 从命令文本启发式提取产物路径候选(source:'command')。
+ * - kind==='command' → 从命令文本里带明确写出语义的位置提取产物路径候选(source:'command')。
* Excel / Word / PDF 等二进制产物只能靠脚本(Bash/exec 跑 python、node)生成,
* 没有文件工具记录;不补这个盲区,卡在「帮我生成个表格」主场景直接失灵。
* 「修改已有文件」(edit / update)与读取不算产出(产品口径:只收新建,见
* AskUserQuestion 决策)。move / delete 同样排除。
*
* 误报防线(source:'command' 特有,由渲染方 GeneratedFilesCard 执行):
- * 命令文本里出现路径 ≠ 命令创建了它(可能只是读输入)。所以 command 候选除
- * 存在性外,还必须满足「文件 mtime 落在本轮时间窗内」才出 chip;窗口不可得
+ * 命令文本里出现路径 ≠ 命令创建了它(可能只是读输入)。所以只认重定向、save / write
+ * API、输出参数等明确写出位置;候选除存在性外,还必须满足「文件 mtime 落在本轮时间窗内」才出 chip;窗口不可得
* (消息无 createdAt / 远程会话无法 stat)时宁可不出。tool 来源保持原判定。
*/
@@ -72,9 +72,7 @@ function dedupeKeyForPath(abs: string): string {
function canonicalizeWindowsShape(abs: string): string {
// 连续分隔符折叠进画布路径本身(不只 dedupe key):stat 虽能容忍 `C:\\x`,但
// Explorer `/select` 与 chip 展示不该带转义残留。盘符形态不存在 UNC 头,可整段折叠。
- return /^[a-zA-Z]:[\\/]/.test(abs)
- ? abs.replace(/\//g, '\\').replace(/\\{2,}/g, '\\')
- : abs;
+ return /^[a-zA-Z]:[\\/]/.test(abs) ? abs.replace(/\//g, '\\').replace(/\\{2,}/g, '\\') : abs;
}
/** 单条 tool_use 消息 → 它新建的文件原始路径列表(可能为空)。 */
@@ -84,9 +82,7 @@ function createdPathsFromToolUse(toolName: string, input: unknown): string[] {
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 descriptor.changes.filter((c) => c.action === 'add' && c.path).map((c) => c.path);
}
return [];
}
@@ -109,31 +105,139 @@ function isPathCandidate(raw: string): boolean {
return isAbs || hasSep;
}
-/**
- * 命令文本 → 产物路径候选。两个来源:
- * 1. 引号字符串(`'...'` / `"..."`):脚本内路径的主形态,可含空格与 CJK,
- * 如 python 的 `wb.save(r'C:\Users\x\表格.xlsx')`;
- * 2. 裸 token:重定向 / CLI 参数里的无引号绝对路径(不含空格)。
- * 只做形态过滤,不判断读写意图——读写区分交给渲染方的 mtime 时间窗。
- */
-export function extractCommandPathCandidates(command: string): string[] {
+interface CommandPathToken {
+ path: string;
+ start: number;
+ end: number;
+}
+
+/** 提取路径 token 及其在命令中的位置;写出语义需要靠相邻文本判断。 */
+function extractCommandPathTokens(command: string): CommandPathToken[] {
if (!command) return [];
- const out: string[] = [];
- const seen = new Set<string>();
- const push = (raw: string): void => {
+ const out: CommandPathToken[] = [];
+ const quotedRanges: Array<{ start: number; end: number }> = [];
+ const push = (raw: string, start: number, end: number): void => {
const s = raw.trim();
if (!isPathCandidate(s)) return;
- if (seen.has(s)) return;
- seen.add(s);
- out.push(s);
+ out.push({ path: s, start, end });
};
- for (const m of command.matchAll(/'([^'\r\n]+)'|"([^"\r\n]+)"/g)) {
- push(m[1] ?? m[2] ?? '');
- }
+ // 单、双引号分开扫描,才能识别 `node -e "save('C:\\out\\a.xlsx')"` 这类
+ // 外层 shell 引号包内层语言字符串的常见形态。合并成一个 alternation 会被外层先吞掉。
+ const scanQuoted = (re: RegExp): void => {
+ for (const m of command.matchAll(re)) {
+ const raw = m[1] ?? '';
+ const matchStart = m.index ?? 0;
+ quotedRanges.push({ start: matchStart, end: matchStart + m[0].length });
+ push(raw, matchStart + 1, matchStart + 1 + raw.length);
+ }
+ };
+ scanQuoted(/'([^'\r\n]+)'/g);
+ scanQuoted(/"([^"\r\n]+)"/g);
// 裸 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]);
+ const insideQuotedRange = (index: number): boolean =>
+ quotedRanges.some((range) => index >= range.start && index < range.end);
+ for (const m of command.matchAll(/(?<![A-Za-z0-9])[A-Za-z]:[\\/][^\s'"<>|?*]+/g)) {
+ const start = m.index ?? 0;
+ if (!insideQuotedRange(start)) push(m[0], start, start + m[0].length);
+ }
+ for (const m of command.matchAll(/(?:^|[\s=(,>])(\/[^\s'"<>|?*:]+)/g)) {
+ const start = (m.index ?? 0) + m[0].length - m[1].length;
+ if (!insideQuotedRange(start)) push(m[1], start, start + m[1].length);
+ }
+ return out.sort((a, b) => a.start - b.start || a.end - b.end);
+}
+
+const WRITE_CALL_PREFIX_RE =
+ /(?:\.|\b)(?:save|writeFileSync|writeFile|writeAllText|writeAllBytes|createWriteStream|write_text|write_bytes|to_csv|to_excel|to_json|to_parquet|imwrite|imsave|dump)\s*\(\s*(?:[rubf]{0,2})?['"]$/i;
+const POWERSHELL_CMDLET_RE = /\b[A-Za-z][A-Za-z0-9]*-[A-Za-z][A-Za-z0-9-]*\b/g;
+const POWERSHELL_WRITE_COMMANDS = new Set([
+ 'out-file',
+ 'set-content',
+ 'add-content',
+ 'export-csv',
+ 'export-clixml',
+ 'new-item',
+]);
+const OUTPUT_OPTION_PREFIX_RE = /(?:^|\s)(?:-o|--output(?:-file)?|--outfile)(?:\s+|=)['"]?$/i;
+const REDIRECT_PREFIX_RE = /(?:^|[^>])>{1,2}\s*['"]?$/;
+const SAVE_COMMAND_PREFIX_RE = /(?:^|[;&|]\s*|\s)save\s+['"]?$/i;
+
+function isPowerShellOutputPosition(before: string): boolean {
+ let lastCmdlet: RegExpMatchArray | null = null;
+ for (const match of before.matchAll(POWERSHELL_CMDLET_RE)) lastCmdlet = match;
+ if (!lastCmdlet || !POWERSHELL_WRITE_COMMANDS.has(lastCmdlet[0].toLowerCase())) return false;
+ const trailing = before.slice((lastCmdlet.index ?? 0) + lastCmdlet[0].length);
+ // Support the first positional path and the cmdlets' explicit path switches.
+ // Any nested/read cmdlet becomes the last cmdlet and therefore cannot leak its input path.
+ return /^\s*['"]?$/.test(trailing) || /-(?:FilePath|LiteralPath|Path)\s+['"]?$/i.test(trailing);
+}
+
+function isExplicitOutputPath(
+ command: string,
+ token: CommandPathToken,
+ tokens: readonly CommandPathToken[],
+): boolean {
+ const before = command.slice(Math.max(0, token.start - 240), token.start);
+ const after = command.slice(token.end, token.end + 80);
+ if (
+ WRITE_CALL_PREFIX_RE.test(before) ||
+ isPowerShellOutputPosition(before) ||
+ OUTPUT_OPTION_PREFIX_RE.test(before) ||
+ REDIRECT_PREFIX_RE.test(before) ||
+ SAVE_COMMAND_PREFIX_RE.test(before)
+ ) {
+ return true;
+ }
+ // Python / Ruby 等的 open(path, 'w'|'a'|'x'|'wb'...)。
+ if (
+ /\bopen\s*\(\s*(?:[rubf]{0,2})?['"]$/i.test(before) &&
+ /^['"]\s*,\s*['"][wax][bt+]*['"]/i.test(after)
+ ) {
+ return true;
+ }
+
+ // cp/copy 的最后一个路径参数是目标。只看当前命令段,避免把前一条读取命令的路径带进来。
+ const previousSeparators = [
+ { index: command.lastIndexOf(';', token.start - 1), length: 1 },
+ { index: command.lastIndexOf('\n', token.start - 1), length: 1 },
+ { index: command.lastIndexOf('&&', token.start - 1), length: 2 },
+ { index: command.lastIndexOf('||', token.start - 1), length: 2 },
+ ];
+ const previousSeparator = previousSeparators.reduce((latest, candidate) =>
+ candidate.index > latest.index ? candidate : latest,
+ );
+ const segmentStart = previousSeparator.index + previousSeparator.length;
+ const nextSeparators = [
+ command.indexOf(';', token.end),
+ command.indexOf('\n', token.end),
+ command.indexOf('&&', token.end),
+ command.indexOf('||', token.end),
+ ].filter((index) => index >= 0);
+ const segmentEnd = nextSeparators.length > 0 ? Math.min(...nextSeparators) : command.length;
+ const segment = command.slice(segmentStart, segmentEnd);
+ const lastPath = tokens
+ .filter((candidate) => candidate.start >= segmentStart && candidate.end <= segmentEnd)
+ .at(-1);
+ return lastPath === token && /(?:^|[|]\s*)\s*(?:cp|copy|Copy-Item)\b/i.test(segment);
+}
+
+/**
+ * 命令文本 → 明确写出位置里的产物路径候选。
+ *
+ * mtime 只能证明文件最近变过,不能证明是当前命令创建的(新 worktree 中所有文件尤其容易
+ * 同时命中时间窗)。因此普通参数、变量赋值、Get-Content / ReadAllLines 等读取位置一律不收;
+ * 只认重定向、常见 save/write API、输出参数及复制目标。后续仍由渲染方做时间窗复核。
+ */
+export function extractCommandOutputPathCandidates(command: string): string[] {
+ const tokens = extractCommandPathTokens(command);
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const token of tokens) {
+ if (!isExplicitOutputPath(command, token, tokens) || seen.has(token.path)) continue;
+ seen.add(token.path);
+ out.push(token.path);
+ }
return out;
}
@@ -190,7 +294,7 @@ export function collectGeneratedFiles(
}
const descriptor = describeToolUse(toolName, msg.toolInput);
if (descriptor.kind === 'command' && descriptor.command) {
- for (const rawPath of extractCommandPathCandidates(descriptor.command)) {
+ for (const rawPath of extractCommandOutputPathCandidates(descriptor.command)) {
addPath(rawPath, 'command');
}
}