TypeScript
feat(web): open tool call diffs in the diff panel (#26304)
Yash Singh441a4ebd6554
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.tsindex 92eb5b1047f..f05ace7ff75 100644--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts@@ -111,7 +111,25 @@ const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test");const decodeUnknownJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));describe("acpToolCallDiffPatch", () => {- it("builds a patch per file from ACP v1 oldText/newText, with /dev/null for a new file", () => {+ it("builds per-file patches from ACP hunks and recorded old/new text", () => {+ for (const operation of ["add", "delete"]) {+ const text = operation === "add" ? "@@ -0,0 +1 @@\n+content\n" : "@@ -1 +0,0 @@\n-content\n";+ assert.equal(+ acpToolCallDiffPatch([+ {+ type: "diff",+ changes: [{ operation, path: "/repo/a.ts" }],+ patch: { format: "git_patch", text },+ },+ ]),+ [+ 'diff --git "a//repo/a.ts" "b//repo/a.ts"',+ operation === "add" ? "--- /dev/null" : '--- "a//repo/a.ts"',+ operation === "delete" ? "+++ /dev/null" : '+++ "b//repo/a.ts"',+ text,+ ].join("\n"),+ );+ }assert.equal(acpToolCallDiffPatch([{ type: "diff", path: "/repo/new.txt", oldText: null, newText: "hello\n" },diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.tsindex baf1ea0a3cb..d449aeb933d 100644--- a/apps/server/src/orchestration-v2/WireProjection.test.ts+++ b/apps/server/src/orchestration-v2/WireProjection.test.ts@@ -275,6 +275,15 @@ describe("orchestration V2 wire projection", () => {expect(projected).not.toHaveProperty("newStr");expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 });expect(item.diffStr).toBe("+new code");+ expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" });+ expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr");+ expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr");+ const { diffStr: _diff, ...contentOnly } = item;+ expect(projectTurnItemForDetail(contentOnly)).toMatchObject({+ oldStr: "old code",+ newStr: "new code",+ });+ expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr");const failed = projectTurnItemForWire({...item,status: "failed",diff --git a/apps/server/src/orchestration-v2/WireProjection.ts b/apps/server/src/orchestration-v2/WireProjection.tsindex a84f8cd4668..6b66f1b91f2 100644--- a/apps/server/src/orchestration-v2/WireProjection.ts+++ b/apps/server/src/orchestration-v2/WireProjection.ts@@ -200,8 +200,20 @@ export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): Orchestresult:item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null),};- case "handoff":case "file_change":+ return {+ ...projectTurnItemForWire(item),+ ...(item.diffStr === undefined+ ? {}+ : { diffStr: truncateDetail(item.diffStr, MAX_ON_DEMAND_BYTES) }),+ ...(!item.diffStr?.trim() && item.oldStr !== undefined+ ? { oldStr: truncateDetail(item.oldStr, MAX_ON_DEMAND_BYTES) }+ : {}),+ ...(!item.diffStr?.trim() && item.newStr !== undefined+ ? { newStr: truncateDetail(item.newStr, MAX_ON_DEMAND_BYTES) }+ : {}),+ };+ case "handoff":return projectTurnItemForWire(item);default:return item;diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 4796a8465e2..c6d9cfd534b 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -2323,6 +2323,7 @@ export default function ChatView(props: ChatViewProps) {createBrowserSurface,createBrowserSurfaceStable,moveRightPanelSurfaceStable,+ onOpenToolDiffStable,onOpenTurnDiffStable,openChangesFromThreadPanelStable,openFileSurfaceStable,@@ -3309,6 +3310,7 @@ export default function ChatView(props: ChatViewProps) {routeThreadKey={displayedTimelineKey}displayThreadKey={displayedTimelineKey}announceTurnStatus={!isProviderSubagent}+ onOpenToolDiff={onOpenToolDiffStable}onOpenTurnDiff={onOpenTurnDiffStable}onOpenThread={onOpenRelatedThreadStable}parentThreadLink={parentThreadLink}diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex 53af7b6e92e..c257d0ea52d 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -26,10 +26,12 @@ import { useOpenInPreferredEditor } from "../editorPreferences";import { useFileContextMenuHandler } from "../fileContextMenu";import { type DraftId } from "../composerDraftStore";import { openDiffFilePrimaryAction } from "../diffFileActions";-import { useCheckpointDiff } from "~/state/queries";+import { toolCallDiff } from "../lib/toolCallDiff";+import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries";import { revisionedQuery } from "~/state/revisionedQuery";import { cn } from "~/lib/utils";import {+ resolveToolCallDiffTarget,selectThreadDiffPanelSelection,useDiffPanelSessionStore,useDiffPanelStore,@@ -48,7 +50,12 @@ import {import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "../hooks/useLiveRefresh";-import { useProject, useThreadCheckpointSummaries, useQuietThreadShell } from "../state/entities";+import {+ useProject,+ useThreadCheckpointSummaries,+ useQuietThreadShell,+ useQuietThreadVisibleTurnItems,+} from "../state/entities";import { useClientSettings, updateClientSettings } from "../hooks/useSettings";import { formatShortTimestamp } from "../timestampFormat";import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";@@ -252,6 +259,18 @@ export default function DiffPanel({const diffSelection = useDiffPanelStore((state) =>selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef),);+ const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null;+ const isGitSelection = diffSelection.kind === "branch" || diffSelection.kind === "unstaged";+ const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null);+ const toolCallDetail = useTurnItemDetail(+ toolCallSelection && routeThreadRef+ ? {+ ...resolveToolCallDiffTarget(toolCallSelection, toolCallItems),+ environmentId: routeThreadRef.environmentId,+ }+ : null,+ );+ const toolCallItem = toolCallDetail.data?.item;const isGitRepo = gitStatusQuery.data?.isRepo ?? true;const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef);const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => {@@ -283,24 +302,31 @@ export default function DiffPanel({orderedTurnDiffSummaries[0]);const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount;const latestTurn = orderedTurnDiffSummaries[0];- const selectedScopeLabel =- selectedRunId === null+ const selectedScopeLabel = toolCallSelection+ ? "Tool call"+ : selectedRunId === null? selectedGitScope === "unstaged"? "Uncommitted": "Changes": selectedTurn?.runId === latestTurn?.runId? "Latest turn": `Turn ${selectedCheckpointTurnCount ?? "?"}`;- const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope;+ const reviewSectionId = toolCallSelection+ ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}`+ : selectedTurn+ ? `turn:${selectedTurn.runId}`+ : selectedGitScope;const collapseScopeKey = routeThreadRef? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`: null;const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;- const reviewSectionTitle = selectedTurn- ? `Turn ${selectedCheckpointTurnCount ?? "?"}`- : selectedGitScope === "unstaged"- ? "Uncommitted"- : "Changes";+ const reviewSectionTitle = toolCallSelection+ ? "Tool call"+ : selectedTurn+ ? `Turn ${selectedCheckpointTurnCount ?? "?"}`+ : selectedGitScope === "unstaged"+ ? "Uncommitted"+ : "Changes";const selectedCheckpointRange =typeof selectedCheckpointTurnCount === "number"? {@@ -320,7 +346,7 @@ export default function DiffPanel({{ enabled: isGitRepo && selectedTurn !== undefined },);const branchDiffPreviewInput =- canReadFiles && selectedRunId === null && activeThread && activeCwd+ canReadFiles && isGitSelection && activeThread && activeCwd? {cwd: activeCwd,...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),@@ -328,7 +354,7 @@ export default function DiffPanel({}: undefined;const canRefreshGitDiff =- isGitRepo && selectedRunId === null && activeThread != null && activeCwd != null;+ isGitRepo && isGitSelection && activeThread != null && activeCwd != null;// Read under the workspace mutation id, so each mutation refetches the diff; the panel stays// mounted while hidden, so a mutation made then is already reflected when it shows.const branchDiffPreview = useEnvironmentQuery(@@ -355,25 +381,52 @@ export default function DiffPanel({const preview = branchDiffPreview.data;const gitDiff = selectedGitSource?.diff;- const selectedPatch = selectedTurn ? activeCheckpointDiff.data?.diff : gitDiff;- const isSelectedPatchTruncated = !selectedTurn && selectedGitSource?.truncated === true;- const selectedPatchQuery = selectedTurn ? activeCheckpointDiff : branchDiffPreview;+ const toolCallPreview =+ toolCallSelection && toolCallItem?.type === "file_change" ? toolCallDiff(toolCallItem) : null;+ const selectedPatch = toolCallSelection+ ? toolCallPreview?.patch+ : selectedTurn+ ? activeCheckpointDiff.data?.diff+ : gitDiff;+ const isSelectedPatchTruncated =+ toolCallPreview?.truncated === true ||+ (isGitSelection && selectedGitSource?.truncated === true);+ const selectedPatchQuery = toolCallSelection+ ? toolCallDetail+ : selectedTurn+ ? activeCheckpointDiff+ : branchDiffPreview;const isLoadingSelectedPatch = selectedPatchQuery.isPending && selectedPatchQuery.data === null;- const selectedPatchError = selectedTurn ? activeCheckpointDiff.error : branchDiffPreview.error;+ const selectedPatchError = toolCallSelection+ ? toolCallDetail.error+ : selectedTurn+ ? activeCheckpointDiff.error+ : branchDiffPreview.error;const hasResolvedPatch = typeof selectedPatch === "string";const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;const lazySource =- !selectedTurn && selectedGitSource?.truncated && selectedGitSource.files+ isGitSelection && selectedGitSource?.truncated && selectedGitSource.files? selectedGitSource: null;const renderablePatch = getRenderablePatch(lazySource ? undefined : selectedPatch,`diff-panel:${resolvedTheme}`,- { compactPartialHunkOffsets: selectedRunId === null },+ {+ compactPartialHunkOffsets: isGitSelection,+ ...(toolCallSelection ? { ignoreWhitespace: diffIgnoreWhitespace } : {}),+ },);+ const recordedToolCallFileCount =+ toolCallSelection && toolCallItem?.type === "file_change"+ ? (toolCallItem.changes?.length ?? 0)+ : 0;+ const omittedToolCallFiles =+ renderablePatch?.kind === "files"+ ? Math.max(0, recordedToolCallFileCount - renderablePatch.files.length)+ : 0;const fileStats = new Map(lazySource?.files?.map((file) => [file.path, file]));const sourceLineStat =- !selectedTurn && selectedGitSource?.files+ isGitSelection && selectedGitSource?.files? selectedGitSource.files.reduce((total, file) => ({additions: total.additions + file.additions,@@ -383,7 +436,7 @@ export default function DiffPanel({): null;const currentLoadDiffFiles =- selectedRunId === null && activeThread && preview && selectedGitSource && canReadFiles+ isGitSelection && activeThread && preview && selectedGitSource && canReadFiles? createGitDiffFileContentsLoader(getDiffFileContents, {environmentId: activeThread.environmentId,cwd: preview.cwd,@@ -400,10 +453,7 @@ export default function DiffPanel({return currentLoadDiffFiles(fileDiff);});const localBranchRefs = useEnvironmentQuery(- selectedRunId === null &&- selectedGitScope === "branch" &&- activeThread &&- branchDiffPreview.data?.cwd+ isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd? vcsEnvironment.listRefs({environmentId: activeThread.environmentId,input: {@@ -417,10 +467,7 @@ export default function DiffPanel({: null,);const remoteBranchRefs = useEnvironmentQuery(- selectedRunId === null &&- selectedGitScope === "branch" &&- activeThread &&- branchDiffPreview.data?.cwd+ isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd? vcsEnvironment.listRefs({environmentId: activeThread.environmentId,input: {@@ -630,8 +677,9 @@ export default function DiffPanel({useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);};const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : "";- const selectedScopeValue =- selectedRunId === null+ const selectedScopeValue = toolCallSelection+ ? ""+ : selectedRunId === null? selectedGitScope: selectedTurn?.runId === latestTurn?.runId? "latest"@@ -698,7 +746,7 @@ export default function DiffPanel({</DropdownMenuSub></DropdownMenuContent></DropdownMenu>- {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (+ {isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && (<divclassName="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}@@ -831,7 +879,7 @@ export default function DiffPanel({)}</div><div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">- {codeViewFiles.length > 0 || (!selectedTurn && selectedGitSource?.files?.length) ? (+ {codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? (<DiffStatLabeladditions={diffLineStat.additions}deletions={diffLineStat.deletions}@@ -973,7 +1021,7 @@ export default function DiffPanel({<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">Select a thread to inspect turn diffs.</div>- ) : !isGitRepo ? (+ ) : !isGitRepo && !toolCallSelection ? (<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">Turn diffs are unavailable because this project is not a git repository.</div>@@ -981,7 +1029,7 @@ export default function DiffPanel({<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">No completed turns yet.</div>- ) : selectedRunId === null && !canReadFiles ? (+ ) : isGitSelection && !canReadFiles ? (fileAccess.isPending ? (<DiffPanelLoadingState label="Checking file access..." />) : (@@ -995,7 +1043,13 @@ export default function DiffPanel({{isSelectedPatchTruncated && !lazySource && (<p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">This preview exceeds the size limit. Changes shown are incomplete.- {selectedGitSource?.files ? " Totals include all changes." : ""}+ {isGitSelection && selectedGitSource?.files ? " Totals include all changes." : ""}+ </p>+ )}+ {omittedToolCallFiles > 0 && (+ <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">+ This tool call changed {recordedToolCallFileCount} files. The recorded patch omits{" "}+ {omittedToolCallFiles} of them.</p>)}{selectedPatchError && !renderablePatch && (@@ -1003,15 +1057,36 @@ export default function DiffPanel({<p className="mb-2 text-2xs text-error/80">{selectedPatchError}</p></div>)}- {!renderablePatch && !lazySource ? (+ {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? (+ <div className="min-h-0 flex-1 space-y-3 overflow-auto p-3 text-xs">+ <p className="text-muted-foreground">+ The provider recorded file content without a diff.+ </p>+ {toolCallPreview.content.map(({ label, text }) => (+ <div key={label} className="space-y-1">+ <p className="text-muted-foreground">{label}</p>+ <pre+ className={cn(+ "overflow-auto font-mono text-2xs",+ wordWrap && "whitespace-pre-wrap wrap-break-word",+ )}+ >+ {text === "" ? "Empty content." : text}+ </pre>+ </div>+ ))}+ </div>+ ) : !renderablePatch && !lazySource ? (isLoadingSelectedPatch ? (<DiffPanelLoadingStatelabel={- selectedTurn- ? "Loading checkpoint diff..."- : selectedGitScope === "unstaged"- ? "Loading uncommitted changes..."- : "Loading changes..."+ toolCallSelection+ ? "Loading tool call diff..."+ : selectedTurn+ ? "Loading checkpoint diff..."+ : selectedGitScope === "unstaged"+ ? "Loading uncommitted changes..."+ : "Loading changes..."}/>) : (diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex a166a25e477..c7a38de8fbe 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -1,3 +1,4 @@+import type { ToolCallDiffTarget } from "../../diffPanelStore";import { AudioPreviewUnmountContext } from "../files/AudioPreview";import { ThreadFindTimelineContext } from "./ThreadFindProvider";import { MarkdownFindContext } from "./markdownFindContext";@@ -241,6 +242,7 @@ interface MessagesTimelineProps {displayThreadKey?: string;/** Off where another region already speaks the thread's status, like a subagent's bar. */announceTurnStatus?: boolean;+ onOpenToolDiff?: (target: ToolCallDiffTarget) => void;onOpenTurnDiff?: (runId: RunId, filePath?: string) => void;onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];@@ -350,6 +352,7 @@ const ConversationTimeline = memo(function ConversationTimeline({routeThreadKey,displayThreadKey,announceTurnStatus = true,+ onOpenToolDiff,onOpenTurnDiff,onOpenThread,renderHtmlRender,@@ -1053,6 +1056,7 @@ const ConversationTimeline = memo(function ConversationTimeline({onAppFullscreenChange,onFileDownload,openPullRequest,+ onOpenToolDiff,onOpenTurnDiff,onOpenThread,renderHtmlRender,diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsxindex 94d001be7e5..a8d5e3e68de 100644--- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx+++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx@@ -536,7 +536,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {environmentId={ctx.activeThreadEnvironmentId}cwd={ctx.markdownCwd}workspaceRoot={workspaceRoot}- onOpenTurnDiff={ctx.onOpenTurnDiff}+ onOpenToolDiff={ctx.onOpenToolDiff}onImageExpand={ctx.onImageExpand}source={ctx.turnItemSource}/>diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsxindex 958a56077e5..ee6072b926b 100644--- a/apps/web/src/components/chat/V2ItemInspector.tsx+++ b/apps/web/src/components/chat/V2ItemInspector.tsx@@ -1,4 +1,5 @@-import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, RunId } from "@t3tools/contracts";+import type { ToolCallDiffTarget } from "../../diffPanelStore";+import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";import {toolCallLines,turnItemDetailRevision,@@ -32,7 +33,7 @@ interface V2ItemInspectorProps {readonly environmentId: EnvironmentId;readonly cwd?: string | undefined;readonly workspaceRoot?: string | undefined;- readonly onOpenTurnDiff?: ((runId: RunId, filePath?: string) => void) | undefined;+ readonly onOpenToolDiff?: ((target: ToolCallDiffTarget) => void) | undefined;readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;readonly source?: TurnItemSource | undefined;}@@ -289,11 +290,17 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec<span className="text-diff-deletion">-{formatDiffCount(item.deletions ?? 0)}</span></span>) : null}- {item.runId !== null && props.onOpenTurnDiff ? (+ {props.onOpenToolDiff ? (<Buttonsize="xs"variant="outline"- onClick={() => props.onOpenTurnDiff?.(item.runId!, item.fileName)}+ onClick={() =>+ props.onOpenToolDiff?.({+ threadId: props.projectedItem.sourceThreadId,+ itemId: props.projectedItem.sourceItemId,+ revision: turnItemDetailRevision(item),+ })+ }>Open diff</Button>diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.tsindex b3677b33de7..6334ef53bd0 100644--- a/apps/web/src/components/chat/timelineRowContext.ts+++ b/apps/web/src/components/chat/timelineRowContext.ts@@ -1,3 +1,4 @@+import type { ToolCallDiffTarget } from "../../diffPanelStore";import type {ProviderApprovalDecision,RuntimeRequestId,@@ -67,6 +68,7 @@ export interface TimelineRowSharedState {findActive: boolean;onImageExpand: (preview: ExpandedImagePreview) => void;displayThreadKey?: string;+ onOpenToolDiff: ((target: ToolCallDiffTarget) => void) | undefined;/** Unset where there is no diff to open, so the timeline shows no "Open diff" button. */onOpenTurnDiff: ((runId: RunId, filePath?: string) => void) | undefined;/**diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.tsindex ac79b0853bf..3919df03b6a 100644--- a/apps/web/src/components/chat/useRightPanelActions.ts+++ b/apps/web/src/components/chat/useRightPanelActions.ts@@ -1,3 +1,4 @@+import type { ToolCallDiffTarget } from "../../diffPanelStore";import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import type { ThreadPreviewState } from "../../previewStateStore";import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";@@ -302,6 +303,15 @@ export function useRightPanelActions(input: RightPanelActionsInput) {useRightPanelStore.getState().open(activeThreadRef, "diff");onDiffPanelOpen?.();};+ const onOpenToolDiffStable = useStableCallback((target: ToolCallDiffTarget) => {+ if (!isServerThread || !activeThreadRef) return;+ const diffOpen =+ selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === "diff";+ explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef;+ useDiffPanelStore.getState().selectToolCall(activeThreadRef, target);+ useRightPanelStore.getState().open(activeThreadRef, "diff");+ onDiffPanelOpen?.();+ });const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff);// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the preview action bus to toggle the preview paneluseEffect(@@ -338,6 +348,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {createBrowserSurface,createBrowserSurfaceStable,moveRightPanelSurfaceStable,+ onOpenToolDiffStable,onOpenTurnDiffStable,onToggleDiffStable,openChangesFromThreadPanelStable,diff --git a/apps/web/src/diffPanelStore.test.ts b/apps/web/src/diffPanelStore.test.tsindex b7238e8edf9..82065c86fe3 100644--- a/apps/web/src/diffPanelStore.test.ts+++ b/apps/web/src/diffPanelStore.test.ts@@ -1,6 +1,13 @@+import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import { scopedThreadKey } from "@t3tools/client-runtime/environment";import { beforeEach, describe, expect, it } from "vite-plus/test";-import { useDiffPanelSessionStore, useDiffPanelStore } from "./diffPanelStore";+import {+ resolveToolCallDiffTarget,+ useDiffPanelSessionStore,+ useDiffPanelStore,+} from "./diffPanelStore";describe("diffPanelStore", () => {beforeEach(() => {@@ -11,6 +18,73 @@ describe("diffPanelStore", () => {useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });});+ it("keeps a tool call selection independent of checkpoints and allows returning to Git changes", () => {+ const ref = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };+ const target = {+ threadId: ThreadId.make("child"),+ itemId: TurnItemId.make("edit"),+ revision: "1",+ };+ const store = useDiffPanelStore.getState();+ store.selectToolCall(ref, target);+ store.reconcileTurnSelection(ref, []);+ expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(ref)]).toEqual({+ kind: "tool-call",+ ...target,+ });+ store.selectGitScope(ref, "branch");+ expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(ref)]).toEqual({+ kind: "branch",+ baseRef: null,+ });+ });++ it("refreshes a live tool-call target when its source item completes", () => {+ const target = {+ threadId: ThreadId.make("child"),+ itemId: TurnItemId.make("edit"),+ revision: "live",+ };+ const now = DateTime.makeUnsafe("2026-10-28T00:00:00Z");+ const row = {+ position: 0,+ visibility: "local" as const,+ sourceThreadId: target.threadId,+ sourceItemId: target.itemId,+ item: {+ id: target.itemId,+ threadId: target.threadId,+ runId: null,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ status: "running" as const,+ title: null,+ startedAt: now,+ completedAt: null,+ updatedAt: now,+ type: "file_change" as const,+ fileName: "a.ts",+ },+ };+ expect(resolveToolCallDiffTarget(target, [row])).toBe(target);+ const completed = {+ ...row,+ item: { ...row.item, status: "completed" as const, completedAt: now },+ };+ expect(resolveToolCallDiffTarget(target, [completed])).toEqual({+ ...target,+ revision: DateTime.formatIso(now),+ });+ expect(+ resolveToolCallDiffTarget(target, [{ ...completed, sourceThreadId: ThreadId.make("other") }]),+ ).toBe(target);+ expect(resolveToolCallDiffTarget(target, [])).toBe(target);+ });+it("retains fold choices when a panel consumer returns with fresh defaults", () => {const scopeKey = "environment-1:thread-1:branch";const defaults = new Set(["src/app.ts", "src/index.ts"]);diff --git a/apps/web/src/diffPanelStore.ts b/apps/web/src/diffPanelStore.tsindex eb6f0e9d455..11d96a3909c 100644--- a/apps/web/src/diffPanelStore.ts+++ b/apps/web/src/diffPanelStore.ts@@ -1,11 +1,20 @@+import type { ThreadStructureVisibleTurnItem } from "@t3tools/client-runtime/state/shell";+import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";import { scopedThreadKey } from "@t3tools/client-runtime/environment";-import type { RunId, ScopedThreadRef } from "@t3tools/contracts";+import type { RunId, ScopedThreadRef, ThreadId, TurnItemId } from "@t3tools/contracts";import { create } from "zustand";import { createJSONStorage, persist } from "zustand/middleware";import { resolveStorage } from "./lib/storage";+export interface ToolCallDiffTarget {+ readonly threadId: ThreadId;+ readonly itemId: TurnItemId;+ readonly revision: string;+}+export type DiffPanelSelection =+ | ({ kind: "tool-call" } & ToolCallDiffTarget)| { kind: "branch"; baseRef: string | null }| { kind: "unstaged" }| { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number };@@ -17,6 +26,7 @@ interface DiffPanelStoreState {branchBaseRefByThreadKey: Record<string, string | null>;selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void;selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void;+ selectToolCall: (ref: ScopedThreadRef, target: ToolCallDiffTarget) => void;selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void;reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<RunId>) => void;removeThread: (ref: ScopedThreadRef) => void;@@ -69,6 +79,13 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()(},};}),+ selectToolCall: (ref, target) =>+ set((state) => ({+ byThreadKey: {+ ...state.byThreadKey,+ [scopedThreadKey(ref)]: { kind: "tool-call", ...target },+ },+ })),selectTurn: (ref, turnId, filePath) =>set((state) => {const threadKey = scopedThreadKey(ref);@@ -160,3 +177,15 @@ export function selectThreadDiffPanelSelection(if (!ref) return DEFAULT_SELECTION;return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_SELECTION;}++export function resolveToolCallDiffTarget(+ target: ToolCallDiffTarget,+ items: ReadonlyArray<ThreadStructureVisibleTurnItem>,+): ToolCallDiffTarget {+ const row = items.find(+ (row) => row.sourceThreadId === target.threadId && row.sourceItemId === target.itemId,+ );+ if (row?.item.type !== "file_change") return target;+ const revision = turnItemDetailRevision(row.item);+ return revision === target.revision ? target : { ...target, revision };+}diff --git a/apps/web/src/lib/toolCallDiff.test.ts b/apps/web/src/lib/toolCallDiff.test.tsnew file mode 100644index 00000000000..cb33dd45cfb--- /dev/null+++ b/apps/web/src/lib/toolCallDiff.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vite-plus/test";+import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering";+import { toolCallDiff } from "./toolCallDiff";++describe("toolCallDiff", () => {+ it("renders recorded hunks without reading a repository, including renamed paths", () => {+ for (const changes of [+ undefined,+ [{ operation: "update", oldPath: "old.ts", path: "new.ts" }],+ ]) {+ const { patch } = toolCallDiff({+ fileName: "old.ts",+ diffStr: "@@ -1 +1 @@\n-before\n+after\n",+ ...(changes ? { changes } : {}),+ });+ const rendered = getRenderablePatch(patch);+ expect(rendered?.kind).toBe("files");+ if (rendered?.kind !== "files") throw new Error("Expected a file diff");+ expect(rendered.files).toHaveLength(1);+ expect(resolveFileDiffPath(rendered.files[0]!)).toBe(changes ? "new.ts" : "old.ts");+ expect(rendered.files[0]!.additionLines.join("")).toContain("after");+ expect(rendered.files[0]!.deletionLines.join("")).toContain("before");+ }+ });++ it("renders added and deleted file contents as a file diff", () => {+ for (const operation of ["add", "delete"]) {+ for (const [content, ending] of [+ ["first\nsecond", ""],+ ["@@ -0,0 +1 @@\n+content", "\n"],+ ["@@ -1 +0,0 @@\n-content", "\n"],+ ["first\nsecond", "\n"],+ ["--- notes\nsecond", "\n"],+ ["diff --git notes\nsecond", "\n"],+ ["--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after", "\n"],+ [+ "diff --git a/embedded.ts b/embedded.ts\n--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after",+ "\n",+ ],+ ] as const) {+ const recordedContent = `${content}${ending}`;+ const rendered = getRenderablePatch(+ toolCallDiff({+ fileName: "file with spaces.ts",+ diffStr: recordedContent,+ changes: [{ operation, path: "file with spaces.ts" }],+ }).patch,+ );+ expect(rendered?.kind).toBe("files");+ if (rendered?.kind !== "files") throw new Error("Expected a file diff");+ expect(resolveFileDiffPath(rendered.files[0]!)).toBe("file with spaces.ts");+ const file = rendered.files[0]!;+ const lines = content.split("\n").length;+ expect(file.additionLines).toHaveLength(operation === "add" ? lines : 0);+ expect(file.deletionLines).toHaveLength(operation === "delete" ? lines : 0);+ expect((operation === "add" ? file.additionLines : file.deletionLines).join("")).toBe(+ recordedContent.replace(/\n$/, ""),+ );+ }+ }+ });++ it("keeps content-only writes out of the patch and preserves empty recorded content", () => {+ for (const operation of ["add", "delete"]) {+ expect(+ toolCallDiff({+ fileName: "empty.ts",+ diffStr: "",+ changes: [{ operation, path: "empty.ts" }],+ }).content,+ ).toEqual([+ {+ label: operation === "add" ? "Recorded content after" : "Recorded content before",+ text: "",+ },+ ]);+ }+ expect(toolCallDiff({ fileName: "a.ts", oldStr: "before", newStr: "" })).toEqual({+ patch: undefined,+ content: [+ { label: "Recorded content before", text: "before" },+ { label: "Recorded content after", text: "" },+ ],+ truncated: false,+ });+ expect(toolCallDiff({ fileName: "a.ts", newStr: "after" }).content).toEqual([+ { label: "Recorded content after", text: "after" },+ ]);+ });++ it("removes transport truncation markers before converting file contents", () => {+ const suffix = "\n… output truncated for transport";+ const diff = toolCallDiff({+ fileName: "a.ts",+ diffStr: `first\nsecond${suffix}`,+ changes: [{ operation: "add", path: "a.ts" }],+ });+ expect(diff.truncated).toBe(true);+ expect(diff.patch).not.toContain("output truncated");+ expect(getRenderablePatch(diff.patch)?.kind).toBe("files");+ expect(toolCallDiff({ fileName: "a.ts", newStr: `content${suffix}` })).toMatchObject({+ content: [{ label: "Recorded content after", text: "content" }],+ truncated: true,+ });+ });++ it("preserves complete patches and unsupported provider output", () => {+ for (const operation of ["add", "delete"]) {+ const diffStr = [+ "diff --git a/a.ts b/a.ts",+ `--- ${operation === "add" ? "/dev/null" : "a/a.ts"}`,+ `+++ ${operation === "add" ? "b/a.ts" : "/dev/null"}`,+ operation === "add" ? "@@ -0,0 +1 @@" : "@@ -1 +0,0 @@",+ operation === "add" ? "+content" : "-content",+ "",+ ].join("\n");+ expect(+ toolCallDiff({ fileName: "a.ts", diffStr, changes: [{ operation, path: "a.ts" }] }).patch,+ ).toBe(diffStr);+ }+ for (const diffStr of [+ undefined,+ "",+ "provider output",+ "--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n",+ ]) {+ expect(+ toolCallDiff({ fileName: "a.ts", ...(diffStr === undefined ? {} : { diffStr }) }).patch,+ ).toBe(diffStr);+ }+ });+});diff --git a/apps/web/src/lib/toolCallDiff.ts b/apps/web/src/lib/toolCallDiff.tsnew file mode 100644index 00000000000..2224702601d--- /dev/null+++ b/apps/web/src/lib/toolCallDiff.ts@@ -0,0 +1,77 @@+import type { OrchestrationV2TurnItem } from "@t3tools/contracts";+import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering";++type FileChange = Extract<OrchestrationV2TurnItem, { type: "file_change" }>;++function toolCallPatch(item: Pick<FileChange, "diffStr" | "fileName" | "changes">) {+ let patch = item.diffStr;+ if (!patch) return patch;+ const change = item.changes?.[0];+ const rawFileOperation = change?.operation === "add" || change?.operation === "delete";+ if (patch.startsWith("diff --git ") || patch.startsWith("--- ")) {+ if (!rawFileOperation) return patch;+ const parsed = getRenderablePatch(patch, "tool-call-format");+ if (+ parsed?.kind === "files" &&+ parsed.files.every((file) => {+ const path = resolveFileDiffPath(file).replaceAll("\\", "/");+ return (+ file.hunks.length > 0 &&+ item.changes?.some((recorded) => {+ const recordedPath = recorded.path.replaceAll("\\", "/");+ return (+ (recorded.operation === "add"+ ? file.deletionLines.length === 0+ : recorded.operation === "delete"+ ? file.additionLines.length === 0+ : true) &&+ (recordedPath === path || recordedPath.endsWith(`/${path}`))+ );+ })+ );+ })+ )+ return patch;+ }+ // Codex can record added/deleted file contents or bare hunks instead of a complete patch.+ if (rawFileOperation || !patch.trimStart().startsWith("@@ ")) {+ if (!rawFileOperation) return patch;+ const lines = patch.split("\n");+ const hasFinalNewline = patch.endsWith("\n");+ if (hasFinalNewline) lines.pop();+ const added = change.operation === "add";+ const range = `1,${lines.length}`;+ 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"}`;+ }+ const oldPath = change?.oldPath ?? item.fileName;+ const newPath = change?.path ?? item.fileName;+ const before = change?.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`);+ const after = change?.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`);+ return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n--- ${before}\n+++ ${after}\n${patch.trimStart()}`;+}++function recordedText(value: string | undefined) {+ const suffix = "\n… output truncated for transport";+ const truncated = value !== undefined && value.endsWith(suffix);+ return { text: truncated ? value.slice(0, -suffix.length) : value, truncated };+}++export function toolCallDiff(+ item: Pick<FileChange, "diffStr" | "fileName" | "changes" | "oldStr" | "newStr">,+) {+ const diff = recordedText(item.diffStr);+ const operation = item.changes?.[0]?.operation;+ const emptyContent = diff.text === "" ? "" : undefined;+ const before = recordedText(item.oldStr ?? (operation === "delete" ? emptyContent : undefined));+ const after = recordedText(item.newStr ?? (operation === "add" ? emptyContent : undefined));+ return {+ patch: toolCallPatch({ ...item, ...(diff.text === undefined ? {} : { diffStr: diff.text }) }),+ content: diff.text?.trim()+ ? []+ : [+ { label: "Recorded content before", text: before.text },+ { label: "Recorded content after", text: after.text },+ ].filter((entry): entry is { label: string; text: string } => entry.text !== undefined),+ truncated: diff.truncated || before.truncated || after.truncated,+ };+}diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.tsindex ead4f553fc4..7e7f43fa632 100644--- a/packages/provider-acp/src/server/adapter.ts+++ b/packages/provider-acp/src/server/adapter.ts@@ -838,7 +838,24 @@ export function acpToolCallDiffPatch(content: unknown): string | undefined {});for (const diff of diffs) {const patch = unknownRecord(diff.patch);- if (typeof patch?.text === "string") return patch.text;+ if (typeof patch?.text === "string") {+ const change =+ Array.isArray(diff.changes) && diff.changes.length === 1+ ? unknownRecord(diff.changes[0])+ : undefined;+ if (+ patch.format === "git_patch" &&+ patch.text.trimStart().startsWith("@@ ") &&+ typeof change?.path === "string"+ ) {+ const oldPath = typeof change.oldPath === "string" ? change.oldPath : change.path;+ const before = change.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`);+ const after =+ change.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${change.path}`);+ return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${change.path}`)}\n--- ${before}\n+++ ${after}\n${patch.text.trimStart()}`;+ }+ return patch.text;+ }}const v1Patches = diffs.flatMap((diff) => {if (typeof diff.path !== "string" || typeof diff.newText !== "string") return [];