The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 13:15 UTC
feat(web): open tool call diffs in the diff panel (#26304)
Yash Singh committed
Oct 28, 2026 at 02:42 UTC
441a4ebd65543fa414797253eb31cc02f8811e32
15 files changed
+520
-51
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+19
-1
@@ -111,7 +111,25 @@ const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test");
111
const decodeUnknownJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
112
113
describe("acpToolCallDiffPatch", () => {
114
- it("builds a patch per file from ACP v1 oldText/newText, with /dev/null for a new file", () => {
114
+ it("builds per-file patches from ACP hunks and recorded old/new text", () => {
115
+ for (const operation of ["add", "delete"]) {
116
+ const text = operation === "add" ? "@@ -0,0 +1 @@\n+content\n" : "@@ -1 +0,0 @@\n-content\n";
117
+ assert.equal(
118
+ acpToolCallDiffPatch([
119
+ {
120
+ type: "diff",
121
+ changes: [{ operation, path: "/repo/a.ts" }],
122
+ patch: { format: "git_patch", text },
123
+ },
124
+ ]),
125
+ [
126
+ 'diff --git "a//repo/a.ts" "b//repo/a.ts"',
127
+ operation === "add" ? "--- /dev/null" : '--- "a//repo/a.ts"',
128
+ operation === "delete" ? "+++ /dev/null" : '+++ "b//repo/a.ts"',
129
+ text,
130
+ ].join("\n"),
131
+ );
132
+ }
133
assert.equal(
134
acpToolCallDiffPatch([
135
{ type: "diff", path: "/repo/new.txt", oldText: null, newText: "hello\n" },
apps/server/src/orchestration-v2/WireProjection.test.ts
+9
@@ -275,6 +275,15 @@ describe("orchestration V2 wire projection", () => {
275
expect(projected).not.toHaveProperty("newStr");
276
expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 });
277
expect(item.diffStr).toBe("+new code");
278
+ expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" });
279
+ expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr");
280
+ expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr");
281
+ const { diffStr: _diff, ...contentOnly } = item;
282
+ expect(projectTurnItemForDetail(contentOnly)).toMatchObject({
283
+ oldStr: "old code",
284
+ newStr: "new code",
285
+ });
286
+ expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr");
287
const failed = projectTurnItemForWire({
288
...item,
289
status: "failed",
apps/server/src/orchestration-v2/WireProjection.ts
+13
-1
@@ -200,8 +200,20 @@ export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): Orchest
200
result:
201
item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null),
202
};
203
- case "handoff":
203
case "file_change":
204
+ return {
205
+ ...projectTurnItemForWire(item),
206
+ ...(item.diffStr === undefined
207
+ ? {}
208
+ : { diffStr: truncateDetail(item.diffStr, MAX_ON_DEMAND_BYTES) }),
209
+ ...(!item.diffStr?.trim() && item.oldStr !== undefined
210
+ ? { oldStr: truncateDetail(item.oldStr, MAX_ON_DEMAND_BYTES) }
211
+ : {}),
212
+ ...(!item.diffStr?.trim() && item.newStr !== undefined
213
+ ? { newStr: truncateDetail(item.newStr, MAX_ON_DEMAND_BYTES) }
214
+ : {}),
215
+ };
216
+ case "handoff":
217
return projectTurnItemForWire(item);
218
default:
219
return item;
apps/web/src/components/ChatView.tsx
+2
@@ -2323,6 +2323,7 @@ export default function ChatView(props: ChatViewProps) {
2323
createBrowserSurface,
2324
createBrowserSurfaceStable,
2325
moveRightPanelSurfaceStable,
2326
+ onOpenToolDiffStable,
2327
onOpenTurnDiffStable,
2328
openChangesFromThreadPanelStable,
2329
openFileSurfaceStable,
@@ -3309,6 +3310,7 @@ export default function ChatView(props: ChatViewProps) {
3310
routeThreadKey={displayedTimelineKey}
3311
displayThreadKey={displayedTimelineKey}
3312
announceTurnStatus={!isProviderSubagent}
3313
+ onOpenToolDiff={onOpenToolDiffStable}
3314
onOpenTurnDiff={onOpenTurnDiffStable}
3315
onOpenThread={onOpenRelatedThreadStable}
3316
parentThreadLink={parentThreadLink}
apps/web/src/components/DiffPanel.tsx
+116
-41
@@ -26,10 +26,12 @@ import { useOpenInPreferredEditor } from "../editorPreferences";
26
import { useFileContextMenuHandler } from "../fileContextMenu";
27
import { type DraftId } from "../composerDraftStore";
28
import { openDiffFilePrimaryAction } from "../diffFileActions";
29
-import { useCheckpointDiff } from "~/state/queries";
29
+import { toolCallDiff } from "../lib/toolCallDiff";
30
+import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries";
31
import { revisionedQuery } from "~/state/revisionedQuery";
32
import { cn } from "~/lib/utils";
33
import {
34
+ resolveToolCallDiffTarget,
35
selectThreadDiffPanelSelection,
36
useDiffPanelSessionStore,
37
useDiffPanelStore,
@@ -48,7 +50,12 @@ import {
50
import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
51
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
52
import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "../hooks/useLiveRefresh";
51
-import { useProject, useThreadCheckpointSummaries, useQuietThreadShell } from "../state/entities";
53
+import {
54
+ useProject,
55
+ useThreadCheckpointSummaries,
56
+ useQuietThreadShell,
57
+ useQuietThreadVisibleTurnItems,
58
+} from "../state/entities";
59
import { useClientSettings, updateClientSettings } from "../hooks/useSettings";
60
import { formatShortTimestamp } from "../timestampFormat";
61
import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
@@ -252,6 +259,18 @@ export default function DiffPanel({
259
const diffSelection = useDiffPanelStore((state) =>
260
selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef),
261
);
262
+ const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null;
263
+ const isGitSelection = diffSelection.kind === "branch" || diffSelection.kind === "unstaged";
264
+ const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null);
265
+ const toolCallDetail = useTurnItemDetail(
266
+ toolCallSelection && routeThreadRef
267
+ ? {
268
+ ...resolveToolCallDiffTarget(toolCallSelection, toolCallItems),
269
+ environmentId: routeThreadRef.environmentId,
270
+ }
271
+ : null,
272
+ );
273
+ const toolCallItem = toolCallDetail.data?.item;
274
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
275
const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef);
276
const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => {
@@ -283,24 +302,31 @@ export default function DiffPanel({
302
orderedTurnDiffSummaries[0]);
303
const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount;
304
const latestTurn = orderedTurnDiffSummaries[0];
286
- const selectedScopeLabel =
287
- selectedRunId === null
305
+ const selectedScopeLabel = toolCallSelection
306
+ ? "Tool call"
307
+ : selectedRunId === null
308
? selectedGitScope === "unstaged"
309
? "Uncommitted"
310
: "Changes"
311
: selectedTurn?.runId === latestTurn?.runId
312
? "Latest turn"
313
: `Turn ${selectedCheckpointTurnCount ?? "?"}`;
294
- const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope;
314
+ const reviewSectionId = toolCallSelection
315
+ ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}`
316
+ : selectedTurn
317
+ ? `turn:${selectedTurn.runId}`
318
+ : selectedGitScope;
319
const collapseScopeKey = routeThreadRef
320
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
321
: null;
322
const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
299
- const reviewSectionTitle = selectedTurn
300
- ? `Turn ${selectedCheckpointTurnCount ?? "?"}`
301
- : selectedGitScope === "unstaged"
302
- ? "Uncommitted"
303
- : "Changes";
323
+ const reviewSectionTitle = toolCallSelection
324
+ ? "Tool call"
325
+ : selectedTurn
326
+ ? `Turn ${selectedCheckpointTurnCount ?? "?"}`
327
+ : selectedGitScope === "unstaged"
328
+ ? "Uncommitted"
329
+ : "Changes";
330
const selectedCheckpointRange =
331
typeof selectedCheckpointTurnCount === "number"
332
? {
@@ -320,7 +346,7 @@ export default function DiffPanel({
346
{ enabled: isGitRepo && selectedTurn !== undefined },
347
);
348
const branchDiffPreviewInput =
323
- canReadFiles && selectedRunId === null && activeThread && activeCwd
349
+ canReadFiles && isGitSelection && activeThread && activeCwd
350
? {
351
cwd: activeCwd,
352
...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
@@ -328,7 +354,7 @@ export default function DiffPanel({
354
}
355
: undefined;
356
const canRefreshGitDiff =
331
- isGitRepo && selectedRunId === null && activeThread != null && activeCwd != null;
357
+ isGitRepo && isGitSelection && activeThread != null && activeCwd != null;
358
// Read under the workspace mutation id, so each mutation refetches the diff; the panel stays
359
// mounted while hidden, so a mutation made then is already reflected when it shows.
360
const branchDiffPreview = useEnvironmentQuery(
@@ -355,25 +381,52 @@ export default function DiffPanel({
381
const preview = branchDiffPreview.data;
382
const gitDiff = selectedGitSource?.diff;
383
358
- const selectedPatch = selectedTurn ? activeCheckpointDiff.data?.diff : gitDiff;
359
- const isSelectedPatchTruncated = !selectedTurn && selectedGitSource?.truncated === true;
360
- const selectedPatchQuery = selectedTurn ? activeCheckpointDiff : branchDiffPreview;
384
+ const toolCallPreview =
385
+ toolCallSelection && toolCallItem?.type === "file_change" ? toolCallDiff(toolCallItem) : null;
386
+ const selectedPatch = toolCallSelection
387
+ ? toolCallPreview?.patch
388
+ : selectedTurn
389
+ ? activeCheckpointDiff.data?.diff
390
+ : gitDiff;
391
+ const isSelectedPatchTruncated =
392
+ toolCallPreview?.truncated === true ||
393
+ (isGitSelection && selectedGitSource?.truncated === true);
394
+ const selectedPatchQuery = toolCallSelection
395
+ ? toolCallDetail
396
+ : selectedTurn
397
+ ? activeCheckpointDiff
398
+ : branchDiffPreview;
399
const isLoadingSelectedPatch = selectedPatchQuery.isPending && selectedPatchQuery.data === null;
362
- const selectedPatchError = selectedTurn ? activeCheckpointDiff.error : branchDiffPreview.error;
400
+ const selectedPatchError = toolCallSelection
401
+ ? toolCallDetail.error
402
+ : selectedTurn
403
+ ? activeCheckpointDiff.error
404
+ : branchDiffPreview.error;
405
const hasResolvedPatch = typeof selectedPatch === "string";
406
const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
407
const lazySource =
366
- !selectedTurn && selectedGitSource?.truncated && selectedGitSource.files
408
+ isGitSelection && selectedGitSource?.truncated && selectedGitSource.files
409
? selectedGitSource
410
: null;
411
const renderablePatch = getRenderablePatch(
412
lazySource ? undefined : selectedPatch,
413
`diff-panel:${resolvedTheme}`,
372
- { compactPartialHunkOffsets: selectedRunId === null },
414
+ {
415
+ compactPartialHunkOffsets: isGitSelection,
416
+ ...(toolCallSelection ? { ignoreWhitespace: diffIgnoreWhitespace } : {}),
417
+ },
418
);
419
+ const recordedToolCallFileCount =
420
+ toolCallSelection && toolCallItem?.type === "file_change"
421
+ ? (toolCallItem.changes?.length ?? 0)
422
+ : 0;
423
+ const omittedToolCallFiles =
424
+ renderablePatch?.kind === "files"
425
+ ? Math.max(0, recordedToolCallFileCount - renderablePatch.files.length)
426
+ : 0;
427
const fileStats = new Map(lazySource?.files?.map((file) => [file.path, file]));
428
const sourceLineStat =
376
- !selectedTurn && selectedGitSource?.files
429
+ isGitSelection && selectedGitSource?.files
430
? selectedGitSource.files.reduce(
431
(total, file) => ({
432
additions: total.additions + file.additions,
@@ -383,7 +436,7 @@ export default function DiffPanel({
436
)
437
: null;
438
const currentLoadDiffFiles =
386
- selectedRunId === null && activeThread && preview && selectedGitSource && canReadFiles
439
+ isGitSelection && activeThread && preview && selectedGitSource && canReadFiles
440
? createGitDiffFileContentsLoader(getDiffFileContents, {
441
environmentId: activeThread.environmentId,
442
cwd: preview.cwd,
@@ -400,10 +453,7 @@ export default function DiffPanel({
453
return currentLoadDiffFiles(fileDiff);
454
});
455
const localBranchRefs = useEnvironmentQuery(
403
- selectedRunId === null &&
404
- selectedGitScope === "branch" &&
405
- activeThread &&
406
- branchDiffPreview.data?.cwd
456
+ isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd
457
? vcsEnvironment.listRefs({
458
environmentId: activeThread.environmentId,
459
input: {
@@ -417,10 +467,7 @@ export default function DiffPanel({
467
: null,
468
);
469
const remoteBranchRefs = useEnvironmentQuery(
420
- selectedRunId === null &&
421
- selectedGitScope === "branch" &&
422
- activeThread &&
423
- branchDiffPreview.data?.cwd
470
+ isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd
471
? vcsEnvironment.listRefs({
472
environmentId: activeThread.environmentId,
473
input: {
@@ -630,8 +677,9 @@ export default function DiffPanel({
677
useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
678
};
679
const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : "";
633
- const selectedScopeValue =
634
- selectedRunId === null
680
+ const selectedScopeValue = toolCallSelection
681
+ ? ""
682
+ : selectedRunId === null
683
? selectedGitScope
684
: selectedTurn?.runId === latestTurn?.runId
685
? "latest"
@@ -698,7 +746,7 @@ export default function DiffPanel({
746
</DropdownMenuSub>
747
</DropdownMenuContent>
748
</DropdownMenu>
701
- {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
749
+ {isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
750
<div
751
className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
752
aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
@@ -831,7 +879,7 @@ export default function DiffPanel({
879
)}
880
</div>
881
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
834
- {codeViewFiles.length > 0 || (!selectedTurn && selectedGitSource?.files?.length) ? (
882
+ {codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? (
883
<DiffStatLabel
884
additions={diffLineStat.additions}
885
deletions={diffLineStat.deletions}
@@ -973,7 +1021,7 @@ export default function DiffPanel({
1021
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1022
Select a thread to inspect turn diffs.
1023
</div>
976
- ) : !isGitRepo ? (
1024
+ ) : !isGitRepo && !toolCallSelection ? (
1025
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1026
Turn diffs are unavailable because this project is not a git repository.
1027
</div>
@@ -981,7 +1029,7 @@ export default function DiffPanel({
1029
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1030
No completed turns yet.
1031
</div>
984
- ) : selectedRunId === null && !canReadFiles ? (
1032
+ ) : isGitSelection && !canReadFiles ? (
1033
fileAccess.isPending ? (
1034
<DiffPanelLoadingState label="Checking file access..." />
1035
) : (
@@ -995,7 +1043,13 @@ export default function DiffPanel({
1043
{isSelectedPatchTruncated && !lazySource && (
1044
<p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
1045
This preview exceeds the size limit. Changes shown are incomplete.
998
- {selectedGitSource?.files ? " Totals include all changes." : ""}
1046
+ {isGitSelection && selectedGitSource?.files ? " Totals include all changes." : ""}
1047
+ </p>
1048
+ )}
1049
+ {omittedToolCallFiles > 0 && (
1050
+ <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
1051
+ This tool call changed {recordedToolCallFileCount} files. The recorded patch omits{" "}
1052
+ {omittedToolCallFiles} of them.
1053
</p>
1054
)}
1055
{selectedPatchError && !renderablePatch && (
@@ -1003,15 +1057,36 @@ export default function DiffPanel({
1057
<p className="mb-2 text-2xs text-error/80">{selectedPatchError}</p>
1058
</div>
1059
)}
1006
- {!renderablePatch && !lazySource ? (
1060
+ {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? (
1061
+ <div className="min-h-0 flex-1 space-y-3 overflow-auto p-3 text-xs">
1062
+ <p className="text-muted-foreground">
1063
+ The provider recorded file content without a diff.
1064
+ </p>
1065
+ {toolCallPreview.content.map(({ label, text }) => (
1066
+ <div key={label} className="space-y-1">
1067
+ <p className="text-muted-foreground">{label}</p>
1068
+ <pre
1069
+ className={cn(
1070
+ "overflow-auto font-mono text-2xs",
1071
+ wordWrap && "whitespace-pre-wrap wrap-break-word",
1072
+ )}
1073
+ >
1074
+ {text === "" ? "Empty content." : text}
1075
+ </pre>
1076
+ </div>
1077
+ ))}
1078
+ </div>
1079
+ ) : !renderablePatch && !lazySource ? (
1080
isLoadingSelectedPatch ? (
1081
<DiffPanelLoadingState
1082
label={
1010
- selectedTurn
1011
- ? "Loading checkpoint diff..."
1012
- : selectedGitScope === "unstaged"
1013
- ? "Loading uncommitted changes..."
1014
- : "Loading changes..."
1083
+ toolCallSelection
1084
+ ? "Loading tool call diff..."
1085
+ : selectedTurn
1086
+ ? "Loading checkpoint diff..."
1087
+ : selectedGitScope === "unstaged"
1088
+ ? "Loading uncommitted changes..."
1089
+ : "Loading changes..."
1090
}
1091
/>
1092
) : (
apps/web/src/components/chat/MessagesTimeline.tsx
+4
@@ -1,3 +1,4 @@
1
+import type { ToolCallDiffTarget } from "../../diffPanelStore";
2
import { AudioPreviewUnmountContext } from "../files/AudioPreview";
3
import { ThreadFindTimelineContext } from "./ThreadFindProvider";
4
import { MarkdownFindContext } from "./markdownFindContext";
@@ -241,6 +242,7 @@ interface MessagesTimelineProps {
242
displayThreadKey?: string;
243
/** Off where another region already speaks the thread's status, like a subagent's bar. */
244
announceTurnStatus?: boolean;
245
+ onOpenToolDiff?: (target: ToolCallDiffTarget) => void;
246
onOpenTurnDiff?: (runId: RunId, filePath?: string) => void;
247
onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
248
renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];
@@ -350,6 +352,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
352
routeThreadKey,
353
displayThreadKey,
354
announceTurnStatus = true,
355
+ onOpenToolDiff,
356
onOpenTurnDiff,
357
onOpenThread,
358
renderHtmlRender,
@@ -1053,6 +1056,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1056
onAppFullscreenChange,
1057
onFileDownload,
1058
openPullRequest,
1059
+ onOpenToolDiff,
1060
onOpenTurnDiff,
1061
onOpenThread,
1062
renderHtmlRender,
apps/web/src/components/chat/TimelineWorkEntryRow.tsx
+1
-1
@@ -536,7 +536,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {
536
environmentId={ctx.activeThreadEnvironmentId}
537
cwd={ctx.markdownCwd}
538
workspaceRoot={workspaceRoot}
539
- onOpenTurnDiff={ctx.onOpenTurnDiff}
539
+ onOpenToolDiff={ctx.onOpenToolDiff}
540
onImageExpand={ctx.onImageExpand}
541
source={ctx.turnItemSource}
542
/>
apps/web/src/components/chat/V2ItemInspector.tsx
+11
-4
@@ -1,4 +1,5 @@
1
-import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, RunId } from "@t3tools/contracts";
1
+import type { ToolCallDiffTarget } from "../../diffPanelStore";
2
+import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";
3
import {
4
toolCallLines,
5
turnItemDetailRevision,
@@ -32,7 +33,7 @@ interface V2ItemInspectorProps {
33
readonly environmentId: EnvironmentId;
34
readonly cwd?: string | undefined;
35
readonly workspaceRoot?: string | undefined;
35
- readonly onOpenTurnDiff?: ((runId: RunId, filePath?: string) => void) | undefined;
36
+ readonly onOpenToolDiff?: ((target: ToolCallDiffTarget) => void) | undefined;
37
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
38
readonly source?: TurnItemSource | undefined;
39
}
@@ -289,11 +290,17 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec
290
<span className="text-diff-deletion">-{formatDiffCount(item.deletions ?? 0)}</span>
291
</span>
292
) : null}
292
- {item.runId !== null && props.onOpenTurnDiff ? (
293
+ {props.onOpenToolDiff ? (
294
<Button
295
size="xs"
296
variant="outline"
296
- onClick={() => props.onOpenTurnDiff?.(item.runId!, item.fileName)}
297
+ onClick={() =>
298
+ props.onOpenToolDiff?.({
299
+ threadId: props.projectedItem.sourceThreadId,
300
+ itemId: props.projectedItem.sourceItemId,
301
+ revision: turnItemDetailRevision(item),
302
+ })
303
+ }
304
>
305
Open diff
306
</Button>
apps/web/src/components/chat/timelineRowContext.ts
+2
@@ -1,3 +1,4 @@
1
+import type { ToolCallDiffTarget } from "../../diffPanelStore";
2
import type {
3
ProviderApprovalDecision,
4
RuntimeRequestId,
@@ -67,6 +68,7 @@ export interface TimelineRowSharedState {
68
findActive: boolean;
69
onImageExpand: (preview: ExpandedImagePreview) => void;
70
displayThreadKey?: string;
71
+ onOpenToolDiff: ((target: ToolCallDiffTarget) => void) | undefined;
72
/** Unset where there is no diff to open, so the timeline shows no "Open diff" button. */
73
onOpenTurnDiff: ((runId: RunId, filePath?: string) => void) | undefined;
74
/**
apps/web/src/components/chat/useRightPanelActions.ts
+11
@@ -1,3 +1,4 @@
1
+import type { ToolCallDiffTarget } from "../../diffPanelStore";
2
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
3
import type { ThreadPreviewState } from "../../previewStateStore";
4
import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
@@ -302,6 +303,15 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
303
useRightPanelStore.getState().open(activeThreadRef, "diff");
304
onDiffPanelOpen?.();
305
};
306
+ const onOpenToolDiffStable = useStableCallback((target: ToolCallDiffTarget) => {
307
+ if (!isServerThread || !activeThreadRef) return;
308
+ const diffOpen =
309
+ selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === "diff";
310
+ explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef;
311
+ useDiffPanelStore.getState().selectToolCall(activeThreadRef, target);
312
+ useRightPanelStore.getState().open(activeThreadRef, "diff");
313
+ onDiffPanelOpen?.();
314
+ });
315
const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff);
316
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the preview action bus to toggle the preview panel
317
useEffect(
@@ -338,6 +348,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
348
createBrowserSurface,
349
createBrowserSurfaceStable,
350
moveRightPanelSurfaceStable,
351
+ onOpenToolDiffStable,
352
onOpenTurnDiffStable,
353
onToggleDiffStable,
354
openChangesFromThreadPanelStable,
apps/web/src/diffPanelStore.test.ts
+75
-1
@@ -1,6 +1,13 @@
1
+import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2
+import * as DateTime from "effect/DateTime";
3
+import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4
import { beforeEach, describe, expect, it } from "vite-plus/test";
5
3
-import { useDiffPanelSessionStore, useDiffPanelStore } from "./diffPanelStore";
6
+import {
7
+ resolveToolCallDiffTarget,
8
+ useDiffPanelSessionStore,
9
+ useDiffPanelStore,
10
+} from "./diffPanelStore";
11
12
describe("diffPanelStore", () => {
13
beforeEach(() => {
@@ -11,6 +18,73 @@ describe("diffPanelStore", () => {
18
useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });
19
});
20
21
+ it("keeps a tool call selection independent of checkpoints and allows returning to Git changes", () => {
22
+ const ref = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
23
+ const target = {
24
+ threadId: ThreadId.make("child"),
25
+ itemId: TurnItemId.make("edit"),
26
+ revision: "1",
27
+ };
28
+ const store = useDiffPanelStore.getState();
29
+ store.selectToolCall(ref, target);
30
+ store.reconcileTurnSelection(ref, []);
31
+ expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(ref)]).toEqual({
32
+ kind: "tool-call",
33
+ ...target,
34
+ });
35
+ store.selectGitScope(ref, "branch");
36
+ expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(ref)]).toEqual({
37
+ kind: "branch",
38
+ baseRef: null,
39
+ });
40
+ });
41
+
42
+ it("refreshes a live tool-call target when its source item completes", () => {
43
+ const target = {
44
+ threadId: ThreadId.make("child"),
45
+ itemId: TurnItemId.make("edit"),
46
+ revision: "live",
47
+ };
48
+ const now = DateTime.makeUnsafe("2026-10-28T00:00:00Z");
49
+ const row = {
50
+ position: 0,
51
+ visibility: "local" as const,
52
+ sourceThreadId: target.threadId,
53
+ sourceItemId: target.itemId,
54
+ item: {
55
+ id: target.itemId,
56
+ threadId: target.threadId,
57
+ runId: null,
58
+ nodeId: null,
59
+ providerThreadId: null,
60
+ providerTurnId: null,
61
+ nativeItemRef: null,
62
+ parentItemId: null,
63
+ ordinal: 1,
64
+ status: "running" as const,
65
+ title: null,
66
+ startedAt: now,
67
+ completedAt: null,
68
+ updatedAt: now,
69
+ type: "file_change" as const,
70
+ fileName: "a.ts",
71
+ },
72
+ };
73
+ expect(resolveToolCallDiffTarget(target, [row])).toBe(target);
74
+ const completed = {
75
+ ...row,
76
+ item: { ...row.item, status: "completed" as const, completedAt: now },
77
+ };
78
+ expect(resolveToolCallDiffTarget(target, [completed])).toEqual({
79
+ ...target,
80
+ revision: DateTime.formatIso(now),
81
+ });
82
+ expect(
83
+ resolveToolCallDiffTarget(target, [{ ...completed, sourceThreadId: ThreadId.make("other") }]),
84
+ ).toBe(target);
85
+ expect(resolveToolCallDiffTarget(target, [])).toBe(target);
86
+ });
87
+
88
it("retains fold choices when a panel consumer returns with fresh defaults", () => {
89
const scopeKey = "environment-1:thread-1:branch";
90
const defaults = new Set(["src/app.ts", "src/index.ts"]);
apps/web/src/diffPanelStore.ts
+30
-1
@@ -1,11 +1,20 @@
1
+import type { ThreadStructureVisibleTurnItem } from "@t3tools/client-runtime/state/shell";
2
+import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
3
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2
-import type { RunId, ScopedThreadRef } from "@t3tools/contracts";
4
+import type { RunId, ScopedThreadRef, ThreadId, TurnItemId } from "@t3tools/contracts";
5
import { create } from "zustand";
6
import { createJSONStorage, persist } from "zustand/middleware";
7
8
import { resolveStorage } from "./lib/storage";
9
10
+export interface ToolCallDiffTarget {
11
+ readonly threadId: ThreadId;
12
+ readonly itemId: TurnItemId;
13
+ readonly revision: string;
14
+}
15
+
16
export type DiffPanelSelection =
17
+ | ({ kind: "tool-call" } & ToolCallDiffTarget)
18
| { kind: "branch"; baseRef: string | null }
19
| { kind: "unstaged" }
20
| { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number };
@@ -17,6 +26,7 @@ interface DiffPanelStoreState {
26
branchBaseRefByThreadKey: Record<string, string | null>;
27
selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void;
28
selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void;
29
+ selectToolCall: (ref: ScopedThreadRef, target: ToolCallDiffTarget) => void;
30
selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void;
31
reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<RunId>) => void;
32
removeThread: (ref: ScopedThreadRef) => void;
@@ -69,6 +79,13 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()(
79
},
80
};
81
}),
82
+ selectToolCall: (ref, target) =>
83
+ set((state) => ({
84
+ byThreadKey: {
85
+ ...state.byThreadKey,
86
+ [scopedThreadKey(ref)]: { kind: "tool-call", ...target },
87
+ },
88
+ })),
89
selectTurn: (ref, turnId, filePath) =>
90
set((state) => {
91
const threadKey = scopedThreadKey(ref);
@@ -160,3 +177,15 @@ export function selectThreadDiffPanelSelection(
177
if (!ref) return DEFAULT_SELECTION;
178
return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_SELECTION;
179
}
180
+
181
+export function resolveToolCallDiffTarget(
182
+ target: ToolCallDiffTarget,
183
+ items: ReadonlyArray<ThreadStructureVisibleTurnItem>,
184
+): ToolCallDiffTarget {
185
+ const row = items.find(
186
+ (row) => row.sourceThreadId === target.threadId && row.sourceItemId === target.itemId,
187
+ );
188
+ if (row?.item.type !== "file_change") return target;
189
+ const revision = turnItemDetailRevision(row.item);
190
+ return revision === target.revision ? target : { ...target, revision };
191
+}
apps/web/src/lib/toolCallDiff.test.ts
new
+132
@@ -0,0 +1,132 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering";
3
+import { toolCallDiff } from "./toolCallDiff";
4
+
5
+describe("toolCallDiff", () => {
6
+ it("renders recorded hunks without reading a repository, including renamed paths", () => {
7
+ for (const changes of [
8
+ undefined,
9
+ [{ operation: "update", oldPath: "old.ts", path: "new.ts" }],
10
+ ]) {
11
+ const { patch } = toolCallDiff({
12
+ fileName: "old.ts",
13
+ diffStr: "@@ -1 +1 @@\n-before\n+after\n",
14
+ ...(changes ? { changes } : {}),
15
+ });
16
+ const rendered = getRenderablePatch(patch);
17
+ expect(rendered?.kind).toBe("files");
18
+ if (rendered?.kind !== "files") throw new Error("Expected a file diff");
19
+ expect(rendered.files).toHaveLength(1);
20
+ expect(resolveFileDiffPath(rendered.files[0]!)).toBe(changes ? "new.ts" : "old.ts");
21
+ expect(rendered.files[0]!.additionLines.join("")).toContain("after");
22
+ expect(rendered.files[0]!.deletionLines.join("")).toContain("before");
23
+ }
24
+ });
25
+
26
+ it("renders added and deleted file contents as a file diff", () => {
27
+ for (const operation of ["add", "delete"]) {
28
+ for (const [content, ending] of [
29
+ ["first\nsecond", ""],
30
+ ["@@ -0,0 +1 @@\n+content", "\n"],
31
+ ["@@ -1 +0,0 @@\n-content", "\n"],
32
+ ["first\nsecond", "\n"],
33
+ ["--- notes\nsecond", "\n"],
34
+ ["diff --git notes\nsecond", "\n"],
35
+ ["--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after", "\n"],
36
+ [
37
+ "diff --git a/embedded.ts b/embedded.ts\n--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after",
38
+ "\n",
39
+ ],
40
+ ] as const) {
41
+ const recordedContent = `${content}${ending}`;
42
+ const rendered = getRenderablePatch(
43
+ toolCallDiff({
44
+ fileName: "file with spaces.ts",
45
+ diffStr: recordedContent,
46
+ changes: [{ operation, path: "file with spaces.ts" }],
47
+ }).patch,
48
+ );
49
+ expect(rendered?.kind).toBe("files");
50
+ if (rendered?.kind !== "files") throw new Error("Expected a file diff");
51
+ expect(resolveFileDiffPath(rendered.files[0]!)).toBe("file with spaces.ts");
52
+ const file = rendered.files[0]!;
53
+ const lines = content.split("\n").length;
54
+ expect(file.additionLines).toHaveLength(operation === "add" ? lines : 0);
55
+ expect(file.deletionLines).toHaveLength(operation === "delete" ? lines : 0);
56
+ expect((operation === "add" ? file.additionLines : file.deletionLines).join("")).toBe(
57
+ recordedContent.replace(/\n$/, ""),
58
+ );
59
+ }
60
+ }
61
+ });
62
+
63
+ it("keeps content-only writes out of the patch and preserves empty recorded content", () => {
64
+ for (const operation of ["add", "delete"]) {
65
+ expect(
66
+ toolCallDiff({
67
+ fileName: "empty.ts",
68
+ diffStr: "",
69
+ changes: [{ operation, path: "empty.ts" }],
70
+ }).content,
71
+ ).toEqual([
72
+ {
73
+ label: operation === "add" ? "Recorded content after" : "Recorded content before",
74
+ text: "",
75
+ },
76
+ ]);
77
+ }
78
+ expect(toolCallDiff({ fileName: "a.ts", oldStr: "before", newStr: "" })).toEqual({
79
+ patch: undefined,
80
+ content: [
81
+ { label: "Recorded content before", text: "before" },
82
+ { label: "Recorded content after", text: "" },
83
+ ],
84
+ truncated: false,
85
+ });
86
+ expect(toolCallDiff({ fileName: "a.ts", newStr: "after" }).content).toEqual([
87
+ { label: "Recorded content after", text: "after" },
88
+ ]);
89
+ });
90
+
91
+ it("removes transport truncation markers before converting file contents", () => {
92
+ const suffix = "\n… output truncated for transport";
93
+ const diff = toolCallDiff({
94
+ fileName: "a.ts",
95
+ diffStr: `first\nsecond${suffix}`,
96
+ changes: [{ operation: "add", path: "a.ts" }],
97
+ });
98
+ expect(diff.truncated).toBe(true);
99
+ expect(diff.patch).not.toContain("output truncated");
100
+ expect(getRenderablePatch(diff.patch)?.kind).toBe("files");
101
+ expect(toolCallDiff({ fileName: "a.ts", newStr: `content${suffix}` })).toMatchObject({
102
+ content: [{ label: "Recorded content after", text: "content" }],
103
+ truncated: true,
104
+ });
105
+ });
106
+
107
+ it("preserves complete patches and unsupported provider output", () => {
108
+ for (const operation of ["add", "delete"]) {
109
+ const diffStr = [
110
+ "diff --git a/a.ts b/a.ts",
111
+ `--- ${operation === "add" ? "/dev/null" : "a/a.ts"}`,
112
+ `+++ ${operation === "add" ? "b/a.ts" : "/dev/null"}`,
113
+ operation === "add" ? "@@ -0,0 +1 @@" : "@@ -1 +0,0 @@",
114
+ operation === "add" ? "+content" : "-content",
115
+ "",
116
+ ].join("\n");
117
+ expect(
118
+ toolCallDiff({ fileName: "a.ts", diffStr, changes: [{ operation, path: "a.ts" }] }).patch,
119
+ ).toBe(diffStr);
120
+ }
121
+ for (const diffStr of [
122
+ undefined,
123
+ "",
124
+ "provider output",
125
+ "--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n",
126
+ ]) {
127
+ expect(
128
+ toolCallDiff({ fileName: "a.ts", ...(diffStr === undefined ? {} : { diffStr }) }).patch,
129
+ ).toBe(diffStr);
130
+ }
131
+ });
132
+});
apps/web/src/lib/toolCallDiff.ts
new
+77
@@ -0,0 +1,77 @@
1
+import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
2
+import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering";
3
+
4
+type FileChange = Extract<OrchestrationV2TurnItem, { type: "file_change" }>;
5
+
6
+function toolCallPatch(item: Pick<FileChange, "diffStr" | "fileName" | "changes">) {
7
+ let patch = item.diffStr;
8
+ if (!patch) return patch;
9
+ const change = item.changes?.[0];
10
+ const rawFileOperation = change?.operation === "add" || change?.operation === "delete";
11
+ if (patch.startsWith("diff --git ") || patch.startsWith("--- ")) {
12
+ if (!rawFileOperation) return patch;
13
+ const parsed = getRenderablePatch(patch, "tool-call-format");
14
+ if (
15
+ parsed?.kind === "files" &&
16
+ parsed.files.every((file) => {
17
+ const path = resolveFileDiffPath(file).replaceAll("\\", "/");
18
+ return (
19
+ file.hunks.length > 0 &&
20
+ item.changes?.some((recorded) => {
21
+ const recordedPath = recorded.path.replaceAll("\\", "/");
22
+ return (
23
+ (recorded.operation === "add"
24
+ ? file.deletionLines.length === 0
25
+ : recorded.operation === "delete"
26
+ ? file.additionLines.length === 0
27
+ : true) &&
28
+ (recordedPath === path || recordedPath.endsWith(`/${path}`))
29
+ );
30
+ })
31
+ );
32
+ })
33
+ )
34
+ return patch;
35
+ }
36
+ // Codex can record added/deleted file contents or bare hunks instead of a complete patch.
37
+ if (rawFileOperation || !patch.trimStart().startsWith("@@ ")) {
38
+ if (!rawFileOperation) return patch;
39
+ const lines = patch.split("\n");
40
+ const hasFinalNewline = patch.endsWith("\n");
41
+ if (hasFinalNewline) lines.pop();
42
+ const added = change.operation === "add";
43
+ const range = `1,${lines.length}`;
44
+ patch = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`;
45
+ }
46
+ const oldPath = change?.oldPath ?? item.fileName;
47
+ const newPath = change?.path ?? item.fileName;
48
+ const before = change?.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`);
49
+ const after = change?.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`);
50
+ return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n--- ${before}\n+++ ${after}\n${patch.trimStart()}`;
51
+}
52
+
53
+function recordedText(value: string | undefined) {
54
+ const suffix = "\n… output truncated for transport";
55
+ const truncated = value !== undefined && value.endsWith(suffix);
56
+ return { text: truncated ? value.slice(0, -suffix.length) : value, truncated };
57
+}
58
+
59
+export function toolCallDiff(
60
+ item: Pick<FileChange, "diffStr" | "fileName" | "changes" | "oldStr" | "newStr">,
61
+) {
62
+ const diff = recordedText(item.diffStr);
63
+ const operation = item.changes?.[0]?.operation;
64
+ const emptyContent = diff.text === "" ? "" : undefined;
65
+ const before = recordedText(item.oldStr ?? (operation === "delete" ? emptyContent : undefined));
66
+ const after = recordedText(item.newStr ?? (operation === "add" ? emptyContent : undefined));
67
+ return {
68
+ patch: toolCallPatch({ ...item, ...(diff.text === undefined ? {} : { diffStr: diff.text }) }),
69
+ content: diff.text?.trim()
70
+ ? []
71
+ : [
72
+ { label: "Recorded content before", text: before.text },
73
+ { label: "Recorded content after", text: after.text },
74
+ ].filter((entry): entry is { label: string; text: string } => entry.text !== undefined),
75
+ truncated: diff.truncated || before.truncated || after.truncated,
76
+ };
77
+}
packages/provider-acp/src/server/adapter.ts
+18
-1
@@ -838,7 +838,24 @@ export function acpToolCallDiffPatch(content: unknown): string | undefined {
838
});
839
for (const diff of diffs) {
840
const patch = unknownRecord(diff.patch);
841
- if (typeof patch?.text === "string") return patch.text;
841
+ if (typeof patch?.text === "string") {
842
+ const change =
843
+ Array.isArray(diff.changes) && diff.changes.length === 1
844
+ ? unknownRecord(diff.changes[0])
845
+ : undefined;
846
+ if (
847
+ patch.format === "git_patch" &&
848
+ patch.text.trimStart().startsWith("@@ ") &&
849
+ typeof change?.path === "string"
850
+ ) {
851
+ const oldPath = typeof change.oldPath === "string" ? change.oldPath : change.path;
852
+ const before = change.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`);
853
+ const after =
854
+ change.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${change.path}`);
855
+ return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${change.path}`)}\n--- ${before}\n+++ ${after}\n${patch.text.trimStart()}`;
856
+ }
857
+ return patch.text;
858
+ }
859
}
860
const v1Patches = diffs.flatMap((diff) => {
861
if (typeof diff.path !== "string" || typeof diff.newText !== "string") return [];