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。

perf(desktop): move large diffs off renderer thread

DavidShen3d1e3329b17e
diff --git a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
index b450b5caba..e986a8e209 100644
--- a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
+++ b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
@@ -39,7 +39,13 @@
* attachment chip.
*/
-import { useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
+import {
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type KeyboardEvent as ReactKeyboardEvent,
+} from 'react';
import { Check, ChevronDown, ChevronRight, File as FileIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import {
@@ -58,7 +64,16 @@ import {
verbLabelKeyForIntent,
verbLabelKeyForRow,
} from '@/lib/agent-actions/verbAggregator';
-import { statsForToolCall } from '@/lib/agent-actions/diffStats';
+import {
+ DIFF_MAIN_THREAD_MAX_CHARS,
+ DIFF_MAX_SEGMENTS,
+ diffSourcesForToolCall,
+ getDiffDetailsSync,
+ requestToolDiffDetails,
+ statsForToolCall,
+ type DiffDetails,
+ type ToolDiffDetails,
+} from '@/lib/agent-actions/diffStats';
import { extractDisplayParam } from '@/lib/agent-actions/actionPresentation';
import { SUPPORTED_IMAGE_EXTS, extractExt } from '@/lib/fileTypes';
import { toLocalFileUrl, resolveToolFilePath } from '@/lib/localPathResolver';
@@ -556,7 +571,9 @@ type FileChangeDescriptor = Extract<ToolUseDescriptor, { kind: 'fileChange' }>;
function buildDiffPayload(
descriptor: ToolUseDescriptor,
inp: Record<string, unknown> | null,
+ analysis?: ToolDiffDetails | null,
): ToolPayloadMode | null {
+ const detailByKey = new Map(analysis?.segments.map((segment) => [segment.key, segment.details]));
if (descriptor.kind === 'fileChange') {
return {
kind: 'diff',
@@ -579,7 +596,9 @@ function buildDiffPayload(
{
key: filePath,
filePath,
- diffs: [{ key: 'edit:0', oldString: o, newString: n }],
+ diffs: [
+ { key: 'edit:0', oldString: o, newString: n, analysis: detailByKey.get('edit:0') },
+ ],
},
],
};
@@ -592,7 +611,9 @@ function buildDiffPayload(
{
key: filePath,
filePath,
- diffs: [{ key: 'write:0', oldString: '', newString: c }],
+ diffs: [
+ { key: 'write:0', oldString: '', newString: c, analysis: detailByKey.get('write:0') },
+ ],
},
],
};
@@ -600,23 +621,37 @@ function buildDiffPayload(
// pi edit:声明 schema 的 edits[] 与 legacy 顶层 {oldText,newText} 两种形态,
// 由共享的 piEditReplacements 归一化(只认一种会让另一种退化成空 diff)。
if (toolName === 'edit') {
+ const allEdits = piEditReplacements(inp);
+ const visibleEdits = allEdits.slice(0, DIFF_MAX_SEGMENTS);
return {
kind: 'diff',
files: [
{
key: filePath,
filePath,
- diffs: piEditReplacements(inp).map((edit, index) => ({
+ diffs: visibleEdits.map((edit, index) => ({
key: `edit:${index}`,
oldString: edit.oldText,
newString: edit.newText,
+ analysis: detailByKey.get(`edit:${index}`),
})),
+ ...(allEdits.length > visibleEdits.length
+ ? {
+ copyDiffs: allEdits.map((edit, index) => ({
+ key: `edit:${index}`,
+ oldString: edit.oldText,
+ newString: edit.newText,
+ })),
+ omittedDiffCount: allEdits.length - visibleEdits.length,
+ }
+ : {}),
},
],
};
}
if (toolName === 'MultiEdit') {
- const edits = Array.isArray(inp.edits) ? inp.edits : [];
+ const allEdits = Array.isArray(inp.edits) ? inp.edits : [];
+ const edits = allEdits.slice(0, DIFF_MAX_SEGMENTS);
return {
kind: 'diff',
files: [
@@ -627,8 +662,24 @@ function buildDiffPayload(
const er = e as Record<string, unknown> | null;
const o = er && typeof er.old_string === 'string' ? er.old_string : '';
const n = er && typeof er.new_string === 'string' ? er.new_string : '';
- return { key: `edit:${index}`, oldString: String(o), newString: String(n) };
+ return {
+ key: `edit:${index}`,
+ oldString: String(o),
+ newString: String(n),
+ analysis: detailByKey.get(`edit:${index}`),
+ };
}),
+ ...(allEdits.length > edits.length
+ ? {
+ copyDiffs: allEdits.map((e, index) => {
+ const er = e as Record<string, unknown> | null;
+ const o = er && typeof er.old_string === 'string' ? er.old_string : '';
+ const n = er && typeof er.new_string === 'string' ? er.new_string : '';
+ return { key: `edit:${index}`, oldString: String(o), newString: String(n) };
+ }),
+ omittedDiffCount: allEdits.length - edits.length,
+ }
+ : {}),
},
],
};
@@ -763,7 +814,59 @@ export function AgentActionRow({
const userFacingToolResult = displayedToolResult
? (humanizeDocumentToolResult(toolName, displayedToolResult) ?? displayedToolResult)
: null;
- const stats = useMemo(() => statsForToolCall(toolName, inp), [toolName, inp]);
+ const diffSources = useMemo(() => diffSourcesForToolCall(toolName, inp), [toolName, inp]);
+ const syncDiff = useMemo<ToolDiffDetails | null>(() => {
+ if (!diffSources || diffSources.truncated) return null;
+ // Apply the budget to the complete tool call, not each segment. A
+ // MultiEdit with many individually-small replacements must still stay off
+ // the renderer thread.
+ const totalChars = diffSources.segments.reduce(
+ (total, segment) => total + segment.oldString.length + segment.newString.length,
+ 0,
+ );
+ if (totalChars > DIFF_MAIN_THREAD_MAX_CHARS) return null;
+ const segments = diffSources.segments.map((segment) => ({
+ key: segment.key,
+ details: getDiffDetailsSync(segment.oldString, segment.newString),
+ }));
+ if (segments.some((segment) => !segment.details)) return null;
+ const resolvedSegments = segments as Array<{ key: string; details: DiffDetails }>;
+ return {
+ stats: segments.reduce(
+ (total, segment) => ({
+ add: total.add + (segment.details?.stats.add ?? 0),
+ del: total.del + (segment.details?.stats.del ?? 0),
+ }),
+ { add: 0, del: 0 },
+ ),
+ segments: resolvedSegments,
+ truncated: false,
+ };
+ }, [diffSources]);
+ const initialStats = useMemo(
+ () => syncDiff?.stats ?? statsForToolCall(toolName, inp),
+ [inp, syncDiff, toolName],
+ );
+ const [asyncDiff, setAsyncDiff] = useState<ToolDiffDetails | null>(null);
+
+ // Small edits stay synchronous for a stable first paint. Larger edits are
+ // analysed off-thread; the same result is passed to the lightbox on click.
+ useEffect(() => {
+ let active = true;
+ if (!diffSources || syncDiff || initialStats !== null) {
+ setAsyncDiff(null);
+ return () => {
+ active = false;
+ };
+ }
+ void requestToolDiffDetails(toolName, inp).then((result) => {
+ if (active) setAsyncDiff(result);
+ });
+ return () => {
+ active = false;
+ };
+ }, [diffSources, initialStats, inp, syncDiff, toolName]);
+ const stats = asyncDiff?.truncated ? null : (asyncDiff?.stats ?? initialStats);
const isFilePathTool = FILE_PATH_TOOLS.has(toolName);
const filePath = descriptor.kind === 'file' ? descriptor.filePath : '';
const singleFileChange =
@@ -784,7 +887,7 @@ export function AgentActionRow({
* - Read → 文稿/图片 lightbox
*/
const onActivate = async (anchor: HTMLElement) => {
- const diffPayload = buildDiffPayload(descriptor, inp);
+ const diffPayload = buildDiffPayload(descriptor, inp, asyncDiff ?? syncDiff);
if (diffPayload) {
triggerRef.current = anchor;
setLightbox({ kind: 'payload', payload: diffPayload });
diff --git a/apps/desktop/src/renderer/components/chat/DiffView.tsx b/apps/desktop/src/renderer/components/chat/DiffView.tsx
index e1e880f71c..ff8e2f7dbd 100644
--- a/apps/desktop/src/renderer/components/chat/DiffView.tsx
+++ b/apps/desktop/src/renderer/components/chat/DiffView.tsx
@@ -3,24 +3,31 @@
* ---------------------------------------------------------------------------
* F-MSG-6: Edit tool diff rendering, GitHub-standard red/green full-row fill.
*
- * Uses the `diff` package for real line-level diffing.
- * - Deleted lines: GitHub red foreground + light red background (full row)
- * - Added lines: GitHub green foreground + light green background (full row)
- * - Unchanged lines: context
- * - Line numbers in Stone gray, JetBrains Mono
- *
- * Background tokens (--diff-del-bg / --diff-add-bg) are shared with
- * MarkdownDiffBlock and the TextLightbox hljs override so all three diff
- * surfaces look identical. Switched from grayscale → red/green on 2026-04-21.
+ * Diff analysis is shared with AgentActionRow and runs in a module Worker for
+ * large payloads. This component only applies the existing context folding
+ * rule and paints the returned rows. Large row sets use @tanstack/react-virtual
+ * so the lightbox never mounts thousands of DOM nodes at once.
*/
-import { useMemo } from 'react';
-import { diffLines } from 'diff';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useVirtualizer } from '@tanstack/react-virtual';
+import { useTranslation } from 'react-i18next';
+
import { cn } from '@/lib/utils';
+import {
+ DIFF_MAIN_THREAD_MAX_CHARS,
+ DIFF_VIRTUALIZE_THRESHOLD,
+ getDiffDetailsSync,
+ requestDiffDetails,
+ type DiffDetails,
+ type DiffLine,
+} from '@/lib/agent-actions/diffStats';
interface DiffViewProps {
oldString: string;
newString: string;
+ /** Pair analysis already produced by AgentActionRow, avoiding a second diff. */
+ analysis?: DiffDetails;
/**
* 只在每个变化前后保留 N 行 context,中间未变化的部分用 "···" 分隔行折叠。
* 类似 git diff -U{N}。不传 = 不折叠(展示全部 context),保留原行为给 Edit tool
@@ -30,49 +37,17 @@ interface DiffViewProps {
contextLines?: number;
}
-interface DiffLine {
- type: 'del' | 'add' | 'ctx';
- text: string;
- lineNum: number;
-}
-
interface SkipMarker {
type: 'skip';
/** 折叠的行数,用于 "··· skipped N lines ···" 提示 */
count: number;
/** 用作 React key 的稳定标识 */
anchorIdx: number;
+ truncated?: boolean;
}
type RenderRow = DiffLine | SkipMarker;
-/**
- * Real line-level diff using the `diff` package.
- */
-function computeDiff(oldStr: string, newStr: string): DiffLine[] {
- const changes = diffLines(oldStr, newStr);
- const result: DiffLine[] = [];
- let lineNum = 1;
-
- for (const change of changes) {
- // diffLines includes trailing newline in value; split and filter empty trailing
- const lines = change.value.replace(/\n$/, '').split('\n');
-
- for (const line of lines) {
- if (change.added) {
- result.push({ type: 'add', text: line, lineNum });
- } else if (change.removed) {
- result.push({ type: 'del', text: line, lineNum });
- } else {
- result.push({ type: 'ctx', text: line, lineNum });
- }
- lineNum++;
- }
- }
-
- return result;
-}
-
/**
* 把超出 ±contextLines 范围的连续 ctx 行折叠成一个 SkipMarker。
*
@@ -82,16 +57,16 @@ function computeDiff(oldStr: string, newStr: string): DiffLine[] {
function applyContextLimit(lines: DiffLine[], contextLines: number): RenderRow[] {
if (lines.length === 0) return [];
const keep = new Array(lines.length).fill(false);
- for (let i = 0; i < lines.length; i++) {
+ for (let i = 0; i < lines.length; i += 1) {
if (lines[i].type !== 'ctx') {
const lo = Math.max(0, i - contextLines);
const hi = Math.min(lines.length - 1, i + contextLines);
- for (let j = lo; j <= hi; j++) keep[j] = true;
+ for (let j = lo; j <= hi; j += 1) keep[j] = true;
}
}
const result: RenderRow[] = [];
let skipStart = -1;
- for (let i = 0; i < lines.length; i++) {
+ for (let i = 0; i < lines.length; i += 1) {
if (keep[i]) {
if (skipStart >= 0) {
result.push({ type: 'skip', count: i - skipStart, anchorIdx: skipStart });
@@ -108,21 +83,161 @@ function applyContextLimit(lines: DiffLine[], contextLines: number): RenderRow[]
return result;
}
-export function DiffView({ oldString, newString, contextLines }: DiffViewProps) {
- const rows = useMemo<RenderRow[]>(() => {
- const all = computeDiff(oldString, newString);
- return contextLines !== undefined ? applyContextLimit(all, contextLines) : all;
- }, [oldString, newString, contextLines]);
+function DiffLineRow({ row, gutterWidth }: { row: DiffLine; gutterWidth: number }) {
+ return (
+ <div
+ className={cn(
+ 'flex min-h-[20px]',
+ row.type === 'del' && 'bg-[var(--diff-del-bg)]',
+ row.type === 'add' && 'bg-[var(--diff-add-bg)]',
+ )}
+ >
+ {/* Gutter: line number + prefix */}
+ <span
+ className="shrink-0 select-none px-2 text-right text-[var(--diff-line-num)]"
+ style={{ minWidth: `${gutterWidth + 3}ch` }}
+ >
+ {row.lineNum}
+ </span>
+ <span
+ className={cn(
+ 'shrink-0 w-4 select-none text-center',
+ row.type === 'del' && 'text-[var(--diff-del-fg)]',
+ row.type === 'add' && 'text-[var(--diff-add-fg)]',
+ )}
+ >
+ {row.type === 'del' ? '-' : row.type === 'add' ? '+' : ' '}
+ </span>
+ {/* Content */}
+ <span
+ className={cn(
+ 'flex-1 whitespace-pre pr-3',
+ row.type === 'del' && 'text-[var(--diff-del-fg)]',
+ row.type === 'add' && 'text-[var(--diff-add-fg)]',
+ )}
+ >
+ {row.text}
+ </span>
+ </div>
+ );
+}
+function SkipRow({
+ row,
+ gutterWidth,
+ truncatedLabel,
+}: {
+ row: SkipMarker;
+ gutterWidth: number;
+ truncatedLabel: string;
+}) {
+ return (
+ <div
+ className="flex min-h-[20px] select-none text-[var(--diff-line-num)]"
+ data-diff-skip-count={row.count}
+ >
+ <span className="shrink-0 px-2 text-right" style={{ minWidth: `${gutterWidth + 3}ch` }} />
+ <span className="shrink-0 w-4 text-center">⋯</span>
+ <span className="flex-1 whitespace-pre pr-3 italic">
+ {row.truncated ? truncatedLabel : `${row.count} 行未变`}
+ </span>
+ </div>
+ );
+}
+
+function renderRow(row: RenderRow, gutterWidth: number, truncatedLabel: string) {
+ return row.type === 'skip' ? (
+ <SkipRow row={row} gutterWidth={gutterWidth} truncatedLabel={truncatedLabel} />
+ ) : (
+ <DiffLineRow row={row} gutterWidth={gutterWidth} />
+ );
+}
+
+export function DiffView({ oldString, newString, analysis, contextLines }: DiffViewProps) {
+ const { t } = useTranslation();
+ const parentRef = useRef<HTMLDivElement | null>(null);
+ const syncAnalysis = useMemo(() => {
+ if (analysis) return analysis;
+ // Keep the existing synchronous first paint for small edits. Large edits
+ // intentionally return no value here and are resolved by the Worker below.
+ if (oldString.length + newString.length > DIFF_MAIN_THREAD_MAX_CHARS) return null;
+ return getDiffDetailsSync(oldString, newString);
+ }, [analysis, oldString, newString]);
+ const [resolvedAnalysis, setResolvedAnalysis] = useState<DiffDetails | null>(syncAnalysis);
+
+ useEffect(() => {
+ let active = true;
+ if (analysis) {
+ setResolvedAnalysis(analysis);
+ return () => {
+ active = false;
+ };
+ }
+ setResolvedAnalysis(syncAnalysis);
+ void requestDiffDetails(oldString, newString).then((details) => {
+ if (active) setResolvedAnalysis(details);
+ });
+ return () => {
+ active = false;
+ };
+ }, [analysis, newString, oldString, syncAnalysis]);
+
+ const rows = useMemo<RenderRow[]>(() => {
+ const all = resolvedAnalysis?.rows ?? [];
+ const rendered = contextLines !== undefined ? applyContextLimit(all, contextLines) : all;
+ if (!resolvedAnalysis?.truncated && !resolvedAnalysis?.rowsTruncated) return rendered;
+ const omitted = Math.max(1, resolvedAnalysis.omittedRows ?? 1);
+ return [
+ ...rendered,
+ {
+ type: 'skip',
+ count: omitted,
+ anchorIdx: all.length,
+ truncated: true,
+ },
+ ];
+ }, [contextLines, resolvedAnalysis]);
// 算 gutter 宽度:取最大 lineNum,跳过 skip marker
const maxLineNum = useMemo(() => {
let max = 0;
- for (const r of rows) {
- if (r.type !== 'skip' && r.lineNum > max) max = r.lineNum;
+ for (const row of rows) {
+ if (row.type !== 'skip' && row.lineNum > max) max = row.lineNum;
}
return max;
}, [rows]);
const gutterWidth = String(maxLineNum).length || 1;
+ const minWidthCh = useMemo(() => {
+ let longest = 0;
+ for (const row of rows) {
+ if (row.type !== 'skip' && row.text.length > longest) longest = row.text.length;
+ }
+ // Virtual rows are absolutely positioned and therefore do not contribute
+ // to the pre's intrinsic width; reserve the longest row explicitly so
+ // horizontal scrolling and full-row backgrounds remain intact.
+ return Math.max(1, longest + gutterWidth + 7);
+ }, [gutterWidth, rows]);
+ const virtualized = rows.length > DIFF_VIRTUALIZE_THRESHOLD;
+ const truncatedLabel = t('chat.lightbox.diffPreviewTruncated');
+ const virtualizer = useVirtualizer({
+ count: rows.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => 20,
+ overscan: 24,
+ getItemKey: (index) => {
+ const row = rows[index];
+ return row.type === 'skip' ? `skip-${row.anchorIdx}` : `${row.type}-${row.lineNum}-${index}`;
+ },
+ });
+
+ if (!resolvedAnalysis) {
+ return (
+ <div className="diff-hscroll overflow-x-auto rounded-[12px] border border-[var(--msg-tool-card-border)]">
+ <div className="px-3 py-3 text-13 text-[var(--msg-tool-card-chevron)]">
+ {t('chat.lightbox.diffPreviewLoading')}
+ </div>
+ </div>
+ );
+ }
// select-text:globals.css 全局禁用了文本选中(Electron 原生 app 风格),
// diff 内容必须可读可复制,所以这里显式开。gutter / 符号列已通过 select-none
@@ -131,67 +246,45 @@ export function DiffView({ oldString, newString, contextLines }: DiffViewProps)
// diff-hscroll:横向滚动条常显(globals.css),否则长行只能靠 trackpad 盲滚。
// pre 的 `w-max min-w-full`:行是 flex 容器,pre 宽度若锁在 100% 容器宽,
// 长行内容会溢出到行的边界之外 —— 滚过去以后行背景(红/绿)在一屏宽处就断了。
- // 让 pre 取 max-content(至少铺满容器),行宽 = 最长行宽,底色跟着滚动区一起延伸。
- return (
- <div className="diff-hscroll select-text overflow-x-auto rounded-[12px] border border-[var(--msg-tool-card-border)]">
- <pre className="m-0 w-max min-w-full p-0 text-[length:calc(var(--app-code-font-size)_-_1px)] leading-[1.5] font-mono">
- {rows.map((row, i) => {
- if (row.type === 'skip') {
- // 折叠占位行 — 不带行号,只显示 "··· N lines unchanged ···"
- return (
- <div
- key={`skip-${row.anchorIdx}`}
- className="flex min-h-[20px] select-none text-[var(--diff-line-num)]"
- >
- <span
- className="shrink-0 px-2 text-right"
- style={{ minWidth: `${gutterWidth + 3}ch` }}
- />
- <span className="shrink-0 w-4 text-center">⋯</span>
- <span className="flex-1 whitespace-pre pr-3 italic">
- {row.count} 行未变
- </span>
- </div>
- );
- }
- return (
+ if (virtualized) {
+ return (
+ <div
+ ref={parentRef}
+ data-diff-virtualized="true"
+ className="diff-hscroll select-text overflow-x-auto overflow-y-auto max-h-[60vh] rounded-[12px] border border-[var(--msg-tool-card-border)]"
+ >
+ <pre
+ className="relative m-0 w-max min-w-full p-0 text-[length:calc(var(--app-code-font-size)_-_1px)] leading-[1.5] font-mono"
+ style={{ height: virtualizer.getTotalSize(), minWidth: `${minWidthCh}ch` }}
+ >
+ {virtualizer.getVirtualItems().map((item) => (
<div
- key={`${row.type}-${row.lineNum}-${i}`}
- className={cn(
- 'flex min-h-[20px]',
- row.type === 'del' && 'bg-[var(--diff-del-bg)]',
- row.type === 'add' && 'bg-[var(--diff-add-bg)]',
- )}
+ key={item.key}
+ data-index={item.index}
+ ref={virtualizer.measureElement}
+ className="absolute left-0 top-0 w-full overflow-visible"
+ style={{ transform: `translateY(${item.start}px)` }}
>
- {/* Gutter: line number + prefix */}
- <span
- className="shrink-0 select-none px-2 text-right text-[var(--diff-line-num)]"
- style={{ minWidth: `${gutterWidth + 3}ch` }}
- >
- {row.lineNum}
- </span>
- <span
- className={cn(
- 'shrink-0 w-4 select-none text-center',
- row.type === 'del' && 'text-[var(--diff-del-fg)]',
- row.type === 'add' && 'text-[var(--diff-add-fg)]',
- )}
- >
- {row.type === 'del' ? '-' : row.type === 'add' ? '+' : ' '}
- </span>
- {/* Content */}
- <span
- className={cn(
- 'flex-1 whitespace-pre pr-3',
- row.type === 'del' && 'text-[var(--diff-del-fg)]',
- row.type === 'add' && 'text-[var(--diff-add-fg)]',
- )}
- >
- {row.text}
- </span>
+ {renderRow(rows[item.index], gutterWidth, truncatedLabel)}
</div>
- );
- })}
+ ))}
+ </pre>
+ </div>
+ );
+ }
+
+ return (
+ <div className="diff-hscroll select-text overflow-x-auto rounded-[12px] border border-[var(--msg-tool-card-border)]">
+ <pre className="m-0 w-max min-w-full p-0 text-[length:calc(var(--app-code-font-size)_-_1px)] leading-[1.5] font-mono">
+ {rows.map((row, index) => (
+ <div
+ key={
+ row.type === 'skip' ? `skip-${row.anchorIdx}` : `${row.type}-${row.lineNum}-${index}`
+ }
+ >
+ {renderRow(row, gutterWidth, truncatedLabel)}
+ </div>
+ ))}
</pre>
</div>
);
diff --git a/apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx b/apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx
index 166f8f620e..7f3351fc0f 100644
--- a/apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx
+++ b/apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx
@@ -31,6 +31,7 @@ import { Tooltip } from '@/components/ui/tooltip';
import { DiffView } from './DiffView';
import { MarkdownDiffBlock } from './MarkdownDiffBlock';
+import type { DiffDetails } from '@/lib/agent-actions/diffStats';
import { isRemoteFileOrigin } from '@/lib/sessionFileOrigin';
import { resolveToolFilePath } from '@/lib/localPathResolver';
import { revealRemoteChatFile } from '@/lib/remoteFileOpen';
@@ -42,6 +43,8 @@ export type ToolDiffSegment =
oldString: string;
newString: string;
label?: string;
+ /** Pair-level analysis shared with the compact row when available. */
+ analysis?: DiffDetails;
}
| {
key: string;
@@ -53,6 +56,9 @@ export interface ToolDiffFile {
key: string;
filePath: string;
diffs: ToolDiffSegment[];
+ /** Full source segments used by Copy; rendering may be bounded separately. */
+ copyDiffs?: ToolDiffSegment[];
+ omittedDiffCount?: number;
}
export type ToolPayloadMode =
@@ -215,11 +221,12 @@ export function ToolPayloadLightbox({
text = payload.files
.map((file) => {
const fileHead = payload.files.length > 1 ? `--- ${file.filePath} ---\n` : '';
- const body = file.diffs
+ const copiedDiffs = file.copyDiffs ?? file.diffs;
+ const body = copiedDiffs
.map((diff, index) => {
const diffHead =
- file.diffs.length > 1
- ? `--- ${diff.label ?? `Edit ${index + 1}/${file.diffs.length}`} ---\n`
+ copiedDiffs.length > 1
+ ? `--- ${diff.label ?? `Edit ${index + 1}/${copiedDiffs.length}`} ---\n`
: '';
if ('rawDiff' in diff) return `${diffHead}${diff.rawDiff}`;
return `${diffHead}--- old\n${diff.oldString}\n+++ new\n${diff.newString}`;
@@ -440,11 +447,28 @@ export function ToolPayloadLightbox({
{'rawDiff' in diff ? (
<MarkdownDiffBlock raw={diff.rawDiff} />
) : (
- <DiffView oldString={diff.oldString} newString={diff.newString} />
+ <DiffView
+ oldString={diff.oldString}
+ newString={diff.newString}
+ analysis={diff.analysis}
+ />
)}
</div>
))
)}
+ {file.omittedDiffCount ? (
+ <span
+ data-diff-omitted-count={file.omittedDiffCount}
+ className="text-12 text-[var(--msg-tool-card-chevron)]"
+ aria-label={t('chat.lightbox.omittedDiffSegments', {
+ count: file.omittedDiffCount,
+ })}
+ >
+ {t('chat.lightbox.omittedDiffSegments', {
+ count: file.omittedDiffCount,
+ })}
+ </span>
+ ) : null}
</div>
))}
</div>
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fb7844aefa..69ef0d612e 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8477,7 +8477,10 @@
"copyContent": "Copy content",
"openInExplorer": "Open in file manager",
"close": "Close",
- "editIndex": "Edit {{index}}/{{total}}"
+ "editIndex": "Edit {{index}}/{{total}}",
+ "omittedDiffSegments": "{{count}} additional diff segments omitted from preview",
+ "diffPreviewTruncated": "Some diff lines are hidden in this preview",
+ "diffPreviewLoading": "Preparing diff preview…"
},
"textLightbox": {
"unreadable": "Unable to read this file",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index aadb1fbfa5..1a300664be 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8471,7 +8471,10 @@
"copyContent": "内容をコピー",
"openInExplorer": "ファイルマネージャーで開く",
"close": "閉じる",
- "editIndex": "編集 {{index}}/{{total}}"
+ "editIndex": "編集 {{index}}/{{total}}",
+ "omittedDiffSegments": "プレビューでは追加の差分 {{count}} 件を省略しています",
+ "diffPreviewTruncated": "プレビューでは一部の差分行を非表示にしています",
+ "diffPreviewLoading": "差分プレビューを準備しています…"
},
"textLightbox": {
"unreadable": "このファイルを読み取れません",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 4d1072d790..1588a647d3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8471,7 +8471,10 @@
"copyContent": "내용 복사",
"openInExplorer": "파일 관리자에서 열기",
"close": "닫기",
- "editIndex": "편집 {{index}}/{{total}}"
+ "editIndex": "편집 {{index}}/{{total}}",
+ "omittedDiffSegments": "미리보기에서 추가 diff 세그먼트 {{count}}개를 생략했습니다",
+ "diffPreviewTruncated": "미리보기에서 일부 diff 줄을 숨겼습니다",
+ "diffPreviewLoading": "diff 미리보기를 준비하는 중입니다…"
},
"textLightbox": {
"unreadable": "이 파일을 읽을 수 없습니다",
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 641b41f0ab..ecdf3cfb99 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8471,7 +8471,10 @@
"copyContent": "复制内容",
"openInExplorer": "在文件管理器中打开",
"close": "关闭",
- "editIndex": "编辑 {{index}}/{{total}}"
+ "editIndex": "编辑 {{index}}/{{total}}",
+ "omittedDiffSegments": "预览中省略了 {{count}} 个额外差异片段",
+ "diffPreviewTruncated": "预览中隐藏了部分差异行",
+ "diffPreviewLoading": "正在准备差异预览…"
},
"textLightbox": {
"unreadable": "无法读取该文件",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 52288d91c5..17e0a594ec 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8470,7 +8470,10 @@
"copyContent": "複製內容",
"openInExplorer": "在檔案管理器中開啟",
"close": "關閉",
- "editIndex": "編輯 {{index}}/{{total}}"
+ "editIndex": "編輯 {{index}}/{{total}}",
+ "omittedDiffSegments": "預覽中省略了 {{count}} 個額外差異片段",
+ "diffPreviewTruncated": "預覽中隱藏了部分差異行",
+ "diffPreviewLoading": "正在準備差異預覽…"
},
"textLightbox": {
"unreadable": "無法讀取該檔案",
diff --git a/apps/desktop/src/renderer/lib/agent-actions/diff.worker.ts b/apps/desktop/src/renderer/lib/agent-actions/diff.worker.ts
new file mode 100644
index 0000000000..9bd1d7be6e
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/agent-actions/diff.worker.ts
@@ -0,0 +1,40 @@
+/**
+ * Worker-side line diffing for large Edit/MultiEdit payloads.
+ * The worker imports only the pure analysis function; it has no Electron,
+ * filesystem, or renderer privileges.
+ */
+
+import { computeDiffDetails, type ToolDiffDetails, type ToolDiffSegmentInput } from './diffStats';
+
+type DiffWorkerRequest = { id: string; segments: ToolDiffSegmentInput[] };
+
+self.addEventListener('message', (event: MessageEvent<DiffWorkerRequest>) => {
+ const request = event.data;
+ if (!request?.id || !Array.isArray(request.segments)) return;
+ try {
+ const segments = request.segments.map((segment) => ({
+ key: segment.key,
+ details: computeDiffDetails(segment.oldString, segment.newString),
+ }));
+ const result: ToolDiffDetails = {
+ stats: segments.reduce(
+ (total, segment) => ({
+ add: total.add + segment.details.stats.add,
+ del: total.del + segment.details.stats.del,
+ }),
+ { add: 0, del: 0 },
+ ),
+ segments,
+ truncated: segments.some((segment) => segment.details.truncated === true),
+ };
+ (self as unknown as Worker).postMessage({ id: request.id, ok: true, result });
+ } catch (error) {
+ (self as unknown as Worker).postMessage({
+ id: request.id,
+ ok: false,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+});
+
+export {};
diff --git a/apps/desktop/src/renderer/lib/agent-actions/diffStats.ts b/apps/desktop/src/renderer/lib/agent-actions/diffStats.ts
index 3e42bf5912..678b4b2113 100644
--- a/apps/desktop/src/renderer/lib/agent-actions/diffStats.ts
+++ b/apps/desktop/src/renderer/lib/agent-actions/diffStats.ts
@@ -1,48 +1,263 @@
/**
- * diffStats
- * ---------------------------------------------------------------------------
- * F2 — compute "+N -N" line counts for Edit / Write / MultiEdit per ADR-5.
+ * Diff analysis shared by compact tool rows and the diff lightbox.
*
- * Why three tools (D1 / ADR-5):
- * - Edit → diff old_string vs new_string → real +N -N
- * - Write → diff "" vs content → +N -0 (every line is new)
- * - MultiEdit → sum of diffs across edits[] → single combined +N -N
- * - other tools → null → row hides the number cluster
- *
- * Backed by the same `diff` package that DiffView already uses, so the
- * counts here line up exactly with the diff body the user can expand.
+ * The expensive part of an Edit/MultiEdit preview is line diffing, not the
+ * React markup. This module keeps the pure implementation available for
+ * small inputs and tests, while larger inputs are sent to a module Worker.
+ * Both callers use the same bounded cache, so a row's `+N/-N` summary and the
+ * opened detail view never calculate the same pair twice.
*/
import { diffLines } from 'diff';
-import { piEditReplacements } from '@cindy/maker-shared';
export interface DiffStat {
add: number;
del: number;
}
+export interface DiffLine {
+ type: 'del' | 'add' | 'ctx';
+ text: string;
+ lineNum: number;
+}
+
+export interface DiffDetails {
+ rows: DiffLine[];
+ stats: DiffStat;
+ /** True when the input guard intentionally used a preview fallback. */
+ truncated?: boolean;
+ /** True when the row payload was capped, while stats remain exact. */
+ rowsTruncated?: boolean;
+ /** Number of rows omitted from the returned row payload, when known. */
+ omittedRows?: number;
+}
+
+export interface ToolDiffSegmentInput {
+ key: string;
+ oldString: string;
+ newString: string;
+}
+
+export interface ToolDiffSources {
+ segments: ToolDiffSegmentInput[];
+ truncated: boolean;
+}
+
+export interface ToolDiffDetails {
+ stats: DiffStat;
+ segments: Array<{ key: string; details: DiffDetails }>;
+ truncated: boolean;
+}
+
+/** Keep the fast path small enough that a chat render cannot monopolize a frame. */
+export const DIFF_MAIN_THREAD_MAX_CHARS = 32_000;
+/** Hard input guard for the worker and its structured-clone payload. */
+export const DIFF_MAX_INPUT_CHARS = 1_000_000;
+/** MultiEdit/pi edit can contain arbitrary model-provided segment counts. */
+export const DIFF_MAX_SEGMENTS = 200;
+/** Bound the number of rows returned by a fallback preview. */
+export const DIFF_MAX_PREVIEW_ROWS = 600;
+/** Bound a single unbroken line in a fallback preview as well. */
+export const DIFF_MAX_PREVIEW_LINE_CHARS = 16_384;
+/** Keep worker responses and the virtualizer's row index bounded. */
+export const DIFF_MAX_RENDER_ROWS = 20_000;
+/** Virtualize before React creates a large row subtree. */
+export const DIFF_VIRTUALIZE_THRESHOLD = 200;
+const DIFF_CACHE_LIMIT = 96;
+
+type WorkerRequest = {
+ id: string;
+ segments: ToolDiffSegmentInput[];
+};
+
+type WorkerResponse =
+ { id: string; ok: true; result: ToolDiffDetails } | { id: string; ok: false; error: string };
+
+interface CacheEntry {
+ key: string;
+ oldString: string;
+ newString: string;
+ details: DiffDetails;
+ weight: number;
+}
+
+// An array-based LRU avoids concatenating whole source files into cache keys.
+// Entries keep references to the message strings instead of making another
+// potentially multi-megabyte copy.
+const detailsCache: CacheEntry[] = [];
+let detailsCacheWeight = 0;
+const pendingDetails: Array<{
+ oldString: string;
+ newString: string;
+ promise: Promise<DiffDetails>;
+ resolve: (details: DiffDetails) => void;
+}> = [];
+let diffWorker: Worker | null = null;
+let nextWorkerRequestId = 0;
+const pendingToolRequests: Array<{
+ toolName: string;
+ sources: ToolDiffSources;
+ promise: Promise<ToolDiffDetails>;
+}> = [];
+const pendingBatches: Array<{
+ segments: ToolDiffSegmentInput[];
+ promise: Promise<ToolDiffDetails>;
+ resolve: (result: ToolDiffDetails) => void;
+}> = [];
+const DIFF_WORKER_TIMEOUT_MS = 5_000;
+const DIFF_CACHE_WEIGHT_LIMIT = 2_000_000;
+
+function cacheKey(oldString: string, newString: string): string {
+ return `${oldString.length}:${newString.length}:${oldString.slice(0, 32)}:${newString.slice(0, 32)}`;
+}
+
+function getCachedDetails(oldString: string, newString: string): DiffDetails | undefined {
+ const key = cacheKey(oldString, newString);
+ const index = detailsCache.findIndex(
+ (entry) => entry.key === key && entry.oldString === oldString && entry.newString === newString,
+ );
+ if (index < 0) return undefined;
+ const [entry] = detailsCache.splice(index, 1);
+ detailsCache.push(entry);
+ return entry.details;
+}
+
+function setCachedDetails(oldString: string, newString: string, details: DiffDetails): void {
+ const weight = details.rows.reduce((total, row) => total + row.text.length + 1, 0);
+ // A cache hit must not retain many megabytes of rendered row objects. Large
+ // results are still shared directly from AgentActionRow to the lightbox;
+ // skipping the pair cache for them keeps unrelated messages bounded.
+ if (weight > DIFF_CACHE_WEIGHT_LIMIT) return;
+ const key = cacheKey(oldString, newString);
+ const existing = detailsCache.findIndex(
+ (entry) => entry.key === key && entry.oldString === oldString && entry.newString === newString,
+ );
+ if (existing >= 0) {
+ detailsCacheWeight -= detailsCache[existing].weight;
+ detailsCache.splice(existing, 1);
+ }
+ detailsCache.push({ key, oldString, newString, details, weight });
+ detailsCacheWeight += weight;
+ while (detailsCache.length > DIFF_CACHE_LIMIT || detailsCacheWeight > DIFF_CACHE_WEIGHT_LIMIT) {
+ const evicted = detailsCache.shift();
+ if (!evicted) break;
+ detailsCacheWeight -= evicted.weight;
+ }
+}
+
+function boundedDetailsForRequest(oldString: string, newString: string): DiffDetails {
+ return oldString.length + newString.length > DIFF_MAIN_THREAD_MAX_CHARS
+ ? computeBoundedDetails(oldString, newString)
+ : computeDiffDetails(oldString, newString);
+}
+
+function previewLines(text: string): string[] {
+ const end = text.endsWith('\n') ? text.length - 1 : text.length;
+ if (end === 0) return [];
+ const previewLine = (start: number, stop: number) =>
+ stop - start > DIFF_MAX_PREVIEW_LINE_CHARS
+ ? `${text.slice(start, start + DIFF_MAX_PREVIEW_LINE_CHARS)}…`
+ : text.slice(start, stop);
+ const collectAllLines = (): string[] => {
+ const lines: string[] = [];
+ let start = 0;
+ while (start <= end && lines.length < DIFF_MAX_PREVIEW_ROWS) {
+ const newline = text.indexOf('\n', start);
+ if (newline < 0 || newline >= end) {
+ lines.push(previewLine(start, end));
+ break;
+ }
+ lines.push(previewLine(start, newline));
+ start = newline + 1;
+ }
+ return lines;
+ };
+ const head = Math.floor(DIFF_MAX_PREVIEW_ROWS / 2);
+ const tail = DIFF_MAX_PREVIEW_ROWS - head;
+ const headLines: string[] = [];
+ let headStart = 0;
+ for (let index = 0; index < head; index += 1) {
+ const newline = text.indexOf('\n', headStart);
+ if (newline < 0 || newline >= end) return [...headLines, previewLine(headStart, end)];
+ headLines.push(previewLine(headStart, newline));
+ headStart = newline + 1;
+ }
+
+ const tailLines: string[] = [];
+ let tailEnd = end;
+ for (let index = 0; index < tail; index += 1) {
+ const newline = text.lastIndexOf('\n', tailEnd - 1);
+ if (newline < headStart) {
+ // The head/tail windows overlap, so the full text has at most the
+ // preview limit of lines and can be materialized without duplication.
+ return collectAllLines();
+ }
+ tailLines.unshift(previewLine(newline + 1, tailEnd));
+ tailEnd = newline;
+ }
+ return [...headLines, ...tailLines];
+}
+
/**
- * Count line-level additions and deletions between two strings.
- * Trailing newline on a chunk is stripped before counting so a file ending
- * in `\n` doesn't get billed an extra phantom line.
+ * For an input that is too large for `diffLines`, retain a bounded head/tail
+ * replacement preview. The full source remains in the payload for copy; only
+ * the expensive analysis is bounded.
*/
-export function computeDiffStats(oldStr: string, newStr: string): DiffStat {
+function computeBoundedDetails(oldString: string, newString: string): DiffDetails {
+ const oldLines = previewLines(oldString);
+ const newLines = previewLines(newString);
+ const rows: DiffLine[] = [];
+ let lineNum = 1;
+ for (const text of oldLines) rows.push({ type: 'del', text, lineNum: lineNum++ });
+ for (const text of newLines) rows.push({ type: 'add', text, lineNum: lineNum++ });
+ return {
+ rows,
+ // Truncated previews must stay bounded even if the original text is huge.
+ // Callers suppress summary stats while `truncated` is true.
+ stats: { add: newLines.length, del: oldLines.length },
+ truncated: true,
+ };
+}
+
+/** Count line-level additions and deletions using the historical DiffView semantics. */
+export function computeDiffDetails(oldString: string, newString: string): DiffDetails {
+ if (oldString.length + newString.length > DIFF_MAX_INPUT_CHARS) {
+ return computeBoundedDetails(oldString, newString);
+ }
+
let add = 0;
let del = 0;
- const changes = diffLines(oldStr, newStr);
- for (const c of changes) {
- if (!c.added && !c.removed) continue;
- const trimmed = c.value.replace(/\n$/, '');
- // Empty chunk shouldn't count any lines (trimmed === '' → split → ['']).
- const lineCount = trimmed === '' ? 0 : trimmed.split('\n').length;
- if (c.added) add += lineCount;
- else if (c.removed) del += lineCount;
+ let rowsTruncated = false;
+ const rows: DiffLine[] = [];
+ let lineNum = 1;
+ for (const change of diffLines(oldString, newString)) {
+ const lines = change.value.replace(/\n$/, '').split('\n');
+ for (const text of lines) {
+ const type: DiffLine['type'] = change.added ? 'add' : change.removed ? 'del' : 'ctx';
+ if (rows.length < DIFF_MAX_RENDER_ROWS) rows.push({ type, text, lineNum });
+ else rowsTruncated = true;
+ lineNum += 1;
+ if (type === 'add') add += 1;
+ if (type === 'del') del += 1;
+ }
}
- return { add, del };
+ return {
+ rows,
+ stats: { add, del },
+ ...(rowsTruncated
+ ? { rowsTruncated: true, omittedRows: Math.max(0, lineNum - 1 - rows.length) }
+ : {}),
+ };
+}
+
+/** Compatibility API used by existing non-chat diff panels. */
+export function computeDiffStats(oldStr: string, newStr: string): DiffStat {
+ return computeDiffDetails(oldStr, newStr).stats;
}
/** Count additions/deletions in an already-materialized unified diff. */
export function computeUnifiedDiffStats(raw: string): DiffStat | null {
+ if (raw.length > DIFF_MAX_INPUT_CHARS) return null;
let add = 0;
let del = 0;
for (const rawLine of raw.split('\n')) {
@@ -54,76 +269,387 @@ export function computeUnifiedDiffStats(raw: string): DiffStat | null {
return add > 0 || del > 0 ? { add, del } : null;
}
-/**
- * Resolve diff stats from a tool-call (toolName + toolInput).
- * Returns null for tools without a meaningful diff (everything except
- * Edit / Write / MultiEdit), letting AgentActionRow skip the number block.
- */
-export function statsForToolCall(
+function readRecord(value: unknown): Record<string, unknown> | null {
+ return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null;
+}
+
+function boundedPiEditSources(inp: Record<string, unknown>): ToolDiffSources {
+ const segments: ToolDiffSegmentInput[] = [];
+ let truncated = false;
+ const rawEdits = Array.isArray(inp.edits) ? inp.edits : [];
+ if (rawEdits.length > DIFF_MAX_SEGMENTS) truncated = true;
+ for (let index = 0; index < Math.min(rawEdits.length, DIFF_MAX_SEGMENTS); index += 1) {
+ const edit = readRecord(rawEdits[index]);
+ const oldText = typeof edit?.oldText === 'string' ? edit.oldText : undefined;
+ const newText = typeof edit?.newText === 'string' ? edit.newText : undefined;
+ if (oldText === undefined && newText === undefined) continue;
+ segments.push({
+ key: `edit:${segments.length}`,
+ oldString: oldText ?? '',
+ newString: newText ?? '',
+ });
+ }
+ if (typeof inp.oldText === 'string' && typeof inp.newText === 'string') {
+ if (segments.length >= DIFF_MAX_SEGMENTS) truncated = true;
+ else
+ segments.push({
+ key: `edit:${segments.length}`,
+ oldString: inp.oldText,
+ newString: inp.newText,
+ });
+ }
+ return { segments, truncated };
+}
+
+/** Normalize Edit/Write/MultiEdit/pi edit input once for stats and details. */
+export function diffSourcesForToolCall(
toolName: string,
toolInput: unknown,
-): DiffStat | null {
- const inp = toolInput as Record<string, unknown> | null;
+): ToolDiffSources | null {
+ const inp = readRecord(toolInput);
if (!inp) return null;
-
if (toolName === 'Edit') {
- const o = typeof inp.old_string === 'string' ? inp.old_string : '';
- const n = typeof inp.new_string === 'string' ? inp.new_string : '';
- return computeDiffStats(o, n);
+ return {
+ segments: [
+ {
+ key: 'edit:0',
+ oldString: typeof inp.old_string === 'string' ? inp.old_string : '',
+ newString: typeof inp.new_string === 'string' ? inp.new_string : '',
+ },
+ ],
+ truncated: false,
+ };
}
-
if (toolName === 'Write' || toolName === 'write') {
- const c = typeof inp.content === 'string' ? inp.content : '';
- // All-add: oldStr = ''. Surface as `+N -0` per ADR-5.
- return computeDiffStats('', c);
+ return {
+ segments: [
+ {
+ key: 'write:0',
+ oldString: '',
+ newString: typeof inp.content === 'string' ? inp.content : '',
+ },
+ ],
+ truncated: false,
+ };
}
-
- // pi edit:两种入参形态(edits[] + legacy 顶层单段)由共享归一化器抹平后逐段求和。
- if (toolName === 'edit') {
- let add = 0;
- let del = 0;
- for (const edit of piEditReplacements(inp)) {
- const s = computeDiffStats(edit.oldText, edit.newText);
- add += s.add;
- del += s.del;
+ if (toolName === 'edit') return boundedPiEditSources(inp);
+ if (toolName === 'MultiEdit') {
+ const rawEdits = Array.isArray(inp.edits) ? inp.edits : [];
+ const truncated = rawEdits.length > DIFF_MAX_SEGMENTS;
+ const segments: ToolDiffSegmentInput[] = [];
+ for (let index = 0; index < Math.min(rawEdits.length, DIFF_MAX_SEGMENTS); index += 1) {
+ const edit = readRecord(rawEdits[index]);
+ segments.push({
+ key: `edit:${index}`,
+ oldString: typeof edit?.old_string === 'string' ? edit.old_string : '',
+ newString: typeof edit?.new_string === 'string' ? edit.new_string : '',
+ });
}
- return { add, del };
+ return { segments, truncated };
}
+ return null;
+}
- if (toolName === 'MultiEdit') {
- const edits = Array.isArray(inp.edits) ? inp.edits : [];
- let add = 0;
- let del = 0;
- for (const e of edits) {
- const er = e as Record<string, unknown> | null;
- const o =
- er && typeof er.old_string === 'string' ? (er.old_string as string) : '';
- const n =
- er && typeof er.new_string === 'string' ? (er.new_string as string) : '';
- const s = computeDiffStats(o, n);
- add += s.add;
- del += s.del;
+function getDiffWorker(): Worker | null {
+ if (typeof Worker === 'undefined') return null;
+ if (diffWorker) return diffWorker;
+ let worker: Worker;
+ try {
+ worker = new Worker(new URL('./diff.worker.ts', import.meta.url), { type: 'module' });
+ } catch {
+ return null;
+ }
+ diffWorker = worker;
+ worker.addEventListener('error', () => {
+ failDiffWorker(worker);
+ if (diffWorker === worker) diffWorker = null;
+ });
+ return worker;
+}
+
+function failDiffWorker(worker: Worker): void {
+ for (const pending of [...pendingDetails]) {
+ pending.resolve(boundedDetailsForRequest(pending.oldString, pending.newString));
+ }
+ for (const pending of [...pendingBatches]) {
+ const segments = pending.segments.map((segment) => ({
+ key: segment.key,
+ details: boundedDetailsForRequest(segment.oldString, segment.newString),
+ }));
+ pending.resolve({ stats: aggregateStats(segments), segments, truncated: true });
+ }
+ worker.terminate();
+ if (diffWorker === worker) diffWorker = null;
+}
+
+function aggregateStats(segments: Array<{ key: string; details: DiffDetails }>): DiffStat {
+ return segments.reduce(
+ (total, segment) => ({
+ add: total.add + segment.details.stats.add,
+ del: total.del + segment.details.stats.del,
+ }),
+ { add: 0, del: 0 },
+ );
+}
+
+function sameSegments(a: ToolDiffSegmentInput[], b: ToolDiffSegmentInput[]): boolean {
+ return (
+ a.length === b.length &&
+ a.every(
+ (segment, index) =>
+ segment.key === b[index].key &&
+ segment.oldString === b[index].oldString &&
+ segment.newString === b[index].newString,
+ )
+ );
+}
+
+function requestWorkerBatchDetails(segments: ToolDiffSegmentInput[]): Promise<ToolDiffDetails> {
+ const existing = pendingBatches.find((pending) => sameSegments(pending.segments, segments));
+ if (existing) return existing.promise;
+ const worker = getDiffWorker();
+ if (!worker) {
+ const values = segments.map((segment) => ({
+ key: segment.key,
+ details: boundedDetailsForRequest(segment.oldString, segment.newString),
+ }));
+ return Promise.resolve({ stats: aggregateStats(values), segments: values, truncated: true });
+ }
+ const id = `diff-batch-${Date.now()}-${nextWorkerRequestId++}`;
+ let resolveResult!: (result: ToolDiffDetails) => void;
+ const promise = new Promise<ToolDiffDetails>((resolve) => {
+ resolveResult = resolve;
+ const onMessage = (event: MessageEvent<WorkerResponse>) => {
+ if (event.data.id !== id) return;
+ worker.removeEventListener('message', onMessage);
+ if (!event.data.ok) {
+ const values = segments.map((segment) => ({
+ key: segment.key,
+ details: boundedDetailsForRequest(segment.oldString, segment.newString),
+ }));
+ resolve({ stats: aggregateStats(values), segments: values, truncated: true });
+ return;
+ }
+ for (const segment of event.data.result.segments) {
+ const source = segments.find((candidate) => candidate.key === segment.key);
+ if (source) setCachedDetails(source.oldString, source.newString, segment.details);
+ }
+ resolve(event.data.result);
+ };
+ worker.addEventListener('message', onMessage);
+ globalThis.setTimeout(() => {
+ if (!pendingBatches.some((pending) => pending.promise === promise)) return;
+ worker.removeEventListener('message', onMessage);
+ failDiffWorker(worker);
+ }, DIFF_WORKER_TIMEOUT_MS);
+ try {
+ worker.postMessage({ id, segments } satisfies WorkerRequest);
+ } catch {
+ worker.removeEventListener('message', onMessage);
+ const values = segments.map((segment) => ({
+ key: segment.key,
+ details: boundedDetailsForRequest(segment.oldString, segment.newString),
+ }));
+ resolve({ stats: aggregateStats(values), segments: values, truncated: true });
+ }
+ }).finally(() => {
+ const index = pendingBatches.findIndex((pending) => pending.promise === promise);
+ if (index >= 0) pendingBatches.splice(index, 1);
+ });
+ pendingBatches.push({ segments, promise, resolve: resolveResult });
+ return promise;
+}
+
+function requestWorkerDetails(segment: ToolDiffSegmentInput): Promise<DiffDetails> {
+ const worker = getDiffWorker();
+ if (!worker)
+ return Promise.resolve(boundedDetailsForRequest(segment.oldString, segment.newString));
+ const existing = pendingDetails.find(
+ (pending) => pending.oldString === segment.oldString && pending.newString === segment.newString,
+ );
+ if (existing) return existing.promise;
+ const id = `diff-${Date.now()}-${nextWorkerRequestId++}`;
+ let resolveResult!: (details: DiffDetails) => void;
+ const promise = new Promise<DiffDetails>((resolve) => {
+ resolveResult = resolve;
+ const onMessage = (event: MessageEvent<WorkerResponse>) => {
+ if (event.data.id !== id) return;
+ worker.removeEventListener('message', onMessage);
+ if (!event.data.ok) {
+ resolve(boundedDetailsForRequest(segment.oldString, segment.newString));
+ return;
+ }
+ const details =
+ event.data.result.segments[0]?.details ??
+ boundedDetailsForRequest(segment.oldString, segment.newString);
+ setCachedDetails(segment.oldString, segment.newString, details);
+ resolve(details);
+ };
+ worker.addEventListener('message', onMessage);
+ globalThis.setTimeout(() => {
+ if (!pendingDetails.some((pending) => pending.promise === promise)) return;
+ worker.removeEventListener('message', onMessage);
+ failDiffWorker(worker);
+ }, DIFF_WORKER_TIMEOUT_MS);
+ try {
+ worker.postMessage({ id, segments: [segment] } satisfies WorkerRequest);
+ } catch {
+ worker.removeEventListener('message', onMessage);
+ resolve(boundedDetailsForRequest(segment.oldString, segment.newString));
}
- return { add, del };
+ }).finally(() => {
+ const index = pendingDetails.findIndex((pending) => pending.promise === promise);
+ if (index >= 0) pendingDetails.splice(index, 1);
+ });
+ pendingDetails.push({
+ oldString: segment.oldString,
+ newString: segment.newString,
+ promise,
+ resolve: resolveResult,
+ });
+ return promise;
+}
+
+/** Request or retrieve the same pair-level analysis used by tool rows. */
+export function getDiffDetailsSync(oldString: string, newString: string): DiffDetails | null {
+ const cached = getCachedDetails(oldString, newString);
+ if (cached) return cached;
+ if (oldString.length + newString.length > DIFF_MAIN_THREAD_MAX_CHARS) return null;
+ const details = computeDiffDetails(oldString, newString);
+ setCachedDetails(oldString, newString, details);
+ return details;
+}
+
+export function requestDiffDetails(oldString: string, newString: string): Promise<DiffDetails> {
+ const sync = getDiffDetailsSync(oldString, newString);
+ if (sync) return Promise.resolve(sync);
+ if (oldString.length + newString.length > DIFF_MAX_INPUT_CHARS) {
+ return Promise.resolve(computeBoundedDetails(oldString, newString));
}
+ const pendingBatch = pendingBatches.find((pending) =>
+ pending.segments.some(
+ (segment) => segment.oldString === oldString && segment.newString === newString,
+ ),
+ );
+ if (pendingBatch) {
+ return pendingBatch.promise.then((result) => {
+ const source = pendingBatch.segments.find(
+ (candidate) => candidate.oldString === oldString && candidate.newString === newString,
+ );
+ const hit = source
+ ? result.segments.find((segment) => segment.key === source.key)
+ : undefined;
+ return hit?.details ?? boundedDetailsForRequest(oldString, newString);
+ });
+ }
+ return requestWorkerDetails({ key: 'diff:0', oldString, newString });
+}
+
+/** Request one shared analysis for all segments in an Edit/MultiEdit call. */
+export function requestToolDiffDetails(
+ toolName: string,
+ toolInput: unknown,
+): Promise<ToolDiffDetails | null> {
+ const sources = diffSourcesForToolCall(toolName, toolInput);
+ if (!sources) return Promise.resolve(null);
+ const existing = pendingToolRequests.find(
+ (pending) =>
+ pending.toolName === toolName &&
+ pending.sources.truncated === sources.truncated &&
+ sameSegments(pending.sources.segments, sources.segments),
+ );
+ if (existing) return existing.promise;
+ const totalChars = sources.segments.reduce(
+ (total, segment) => total + segment.oldString.length + segment.newString.length,
+ 0,
+ );
+ const allSmall = totalChars <= DIFF_MAIN_THREAD_MAX_CHARS;
+ // Segment-count truncation limits what we analyse, but it does not require
+ // falling back to renderer-thread work. The capped batch can still be sent
+ // to the worker whenever its aggregate text budget is safe.
+ const canDiffInWorker = totalChars <= DIFF_MAX_INPUT_CHARS;
+ const cached = allSmall
+ ? sources.segments.map((segment) => getCachedDetails(segment.oldString, segment.newString))
+ : [];
+ const promise = (async (): Promise<ToolDiffDetails> => {
+ const details = [] as Array<{ key: string; details: DiffDetails }>;
+ const missing = sources.segments.filter(
+ (segment) => !getCachedDetails(segment.oldString, segment.newString),
+ );
+ const workerValues =
+ canDiffInWorker && !allSmall && missing.length > 0
+ ? await requestWorkerBatchDetails(missing)
+ : null;
+ for (let index = 0; index < sources.segments.length; index += 1) {
+ const segment = sources.segments[index];
+ const hit = cached[index] ?? getCachedDetails(segment.oldString, segment.newString);
+ const value =
+ hit ??
+ workerValues?.segments.find((candidate) => candidate.key === segment.key)?.details ??
+ (allSmall
+ ? computeDiffDetails(segment.oldString, segment.newString)
+ : computeBoundedDetails(segment.oldString, segment.newString));
+ if (!hit) setCachedDetails(segment.oldString, segment.newString, value);
+ details.push({ key: segment.key, details: value });
+ }
+ return {
+ stats: aggregateStats(details),
+ segments: details,
+ truncated:
+ sources.truncated ||
+ !canDiffInWorker ||
+ details.some((segment) => segment.details.truncated === true),
+ };
+ })().finally(() => {
+ const index = pendingToolRequests.findIndex((pending) => pending.promise === promise);
+ if (index >= 0) pendingToolRequests.splice(index, 1);
+ });
+ pendingToolRequests.push({ toolName, sources, promise });
+ return promise;
+}
+
+/** Synchronous compatibility path; large inputs return null until the worker resolves. */
+export function statsForToolCall(toolName: string, toolInput: unknown): DiffStat | null {
+ const inp = readRecord(toolInput);
+ if (!inp) return null;
if (toolName === 'file_change') {
const changes = Array.isArray(inp.changes) ? inp.changes : [];
+ let truncated = changes.length > DIFF_MAX_SEGMENTS;
let add = 0;
let del = 0;
let hasDiff = false;
- for (const change of changes) {
- if (!change || typeof change !== 'object') continue;
- const diff = (change as Record<string, unknown>).diff;
+ for (let index = 0; index < Math.min(changes.length, DIFF_MAX_SEGMENTS); index += 1) {
+ const change = changes[index];
+ const diff = readRecord(change)?.diff;
if (typeof diff !== 'string') continue;
+ if (diff.length > DIFF_MAX_INPUT_CHARS) {
+ truncated = true;
+ continue;
+ }
const stats = computeUnifiedDiffStats(diff);
if (!stats) continue;
hasDiff = true;
add += stats.add;
del += stats.del;
}
- return hasDiff ? { add, del } : null;
+ return hasDiff && !truncated ? { add, del } : null;
}
-
- return null;
+ const sources = diffSourcesForToolCall(toolName, inp);
+ if (!sources || sources.truncated) return null;
+ const totalChars = sources.segments.reduce(
+ (total, segment) => total + segment.oldString.length + segment.newString.length,
+ 0,
+ );
+ if (totalChars > DIFF_MAIN_THREAD_MAX_CHARS) return null;
+ return sources.segments.reduce(
+ (total, segment) => {
+ const details =
+ getCachedDetails(segment.oldString, segment.newString) ??
+ computeDiffDetails(segment.oldString, segment.newString);
+ setCachedDetails(segment.oldString, segment.newString, details);
+ return { add: total.add + details.stats.add, del: total.del + details.stats.del };
+ },
+ { add: 0, del: 0 },
+ );
}