mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-09 07:10:34 +01:00
feat(task-chat): show an inline diff for every file edit (#19269)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The task chat shows what an agent did during a run, including each tool call > - Codex and Claude both report the patch for every file edit, but Paperclip dropped it. Claude's ACP `diff` content was never read. The Codex `fileChange` item became a generic item with no patch. Codex `turn/diff/updated` had no native-runner mapping > - A reviewer could not see what an agent changed without opening the workspace > - This pull request carries a bounded patch on each edit call and shows it in the edit row. Each turn that changed files ends with a "Changed in this turn" card > - The benefit is that a reviewer can check every change in the conversation, with the same view for Codex and Claude ## Linked Issues or Issue Description Refs #19252 (precedent: canonical `plan.updated` events as a docked plan card). **Subsystem affected** Paperclip runner (Rust and TypeScript canonical event mapping), PRP provider-event schema, and the task-chat UI. **Problem or motivation** Edit rows say "Edited a file" with no content. Claude Edit/Write `diff` content is lost after the ACPX sidecar. The Codex native runner drops `fileChange.changes` and `turn/diff/updated`. The existing workspace-changes card showed a raw text patch in a dialog, and only on the in-process Codex path. **Proposed solution** Add an optional, bounded `fileChanges` list to `paperclip.tool.execution.v1`. Fill it from Codex `fileChange` items and Claude ACP `diff` content. Map Codex `turn/diff/updated` to `workspace.change.updated` on the native runner. In the UI, show `+N −M` on each edit row, open a compact colored diff, and end the turn with the change set. **Alternatives considered** A runner-side git diff at turn end. It needs workspace access and extra cost on every turn. The harness patches are already available. For Claude, the UI builds the turn card from the edit rows instead of new per-turn runner state. ## What Changed - Protocol: optional `fileChanges[]` on `toolExecution` in `provider-event.schema.json`, with the regenerated schema bundle, validators and manifest. Paths are workspace-relative. A patch is at most 32 KiB, and a call has at most 32 files. - Runner (Rust): new `tool_file_changes.rs`. A Codex `fileChange` item now also emits `tool.execution.*` with `fileChanges`; the native item event stays for the recovery and progress projections. `turn/diff/updated` becomes `workspace.change.updated`. `normalize_acpx_tool_call` re-validates the sidecar's `fileChanges`. `normalize_codex_notification_in` resolves absolute paths against the session cwd. - Runner (Rust): `has_bounded_rich_display_shape` accepts schema-valid workspace diffs. Without this change, durable storage cut each patch string to a 4 KiB preview. Patches use the uncapped secret redactor. - Runner (TS): new `tool-file-changes.ts`. The ACPX sidecar computes `fileChanges` from ACP `diff` content with the working directory. The in-process Codex and ACPX mappers do the same, with an optional `context` argument. - UI: new `TaskChatDiffView` (colored rows, hunk labels, a height cap, "Show N more lines"). Edit rows show counts and the diff. Collapsed activity groups show edit totals. The workspace card is now "Changed in this turn", with in-place per-file diffs, and it sits at the end of the turn. When a harness sends no whole-turn diff (Claude), the card is built from the edit rows. A change set is marked complete when its run ends. - UI: `native-run-events.ts` maps `workspace.change.updated` and attaches each edit's latest patch to its row (the `diff` transcript entries now carry `toolUseId`). - Design tokens: `--diff-add-*`, `--diff-remove-*` and `--sz-edit-diff-max-h` come from the status icon hues. - Storybook: `Tasks/Edit diffs` story. Docs: `doc/run-log-events.md`. ## Verification - Real runs on a local instance (`test-drive`, native runner): - Codex (`gpt-5.6-sol`): the "Applied a patch" rows show `+9` and `+35 −2` with their diffs. The turn ends with "Changed in this turn", 2 files, `+42`, from `turn/diff/updated`. - Claude (`claude-opus-5-5` via ACPX): the Write and Edit rows show `+5`, `+14 −1` and `+9` with correct hunks. The turn card is built from the edit rows. - Codex model note: with `gpt-5.4`, pinned Codex 0.160 reports "model metadata not found". The model then wrote files through the shell, so no `fileChange` items occurred. - `pnpm check:token-gates`: all gates clean. - `pnpm --filter @paperclipai/ui exec vitest run src/components/task-chat src/components/transcript src/adapters`: 1073 passed. - `packages/paperclip-runner`: `vitest run src/provider-events.test.ts src/tool-file-changes.test.ts src/cli/acpx-runtime-sidecar.test.ts` passed. `check:protocol-types` and `check:protocol-manifest` match. - `cargo test -p paperclip-runner-core --lib provider_events tool_file_changes`: passed. `cargo fmt --check`: clean. - Storybook: open `Tasks and conversations/…/Tasks/Edit diffs`. ## Risks - Larger payloads: an edit call can carry up to 96 KiB of patch in Rust, and the sidecar keeps 48 KiB under its 128 KiB frame. Above the budget, a file keeps its counts and drops its patch (`diffTruncated`). - Redaction: each patch goes through the shared secret redactor. Before this change, a 4 KiB preview cap also applied. - Claude turn card: it joins each edit's patch in order. It is not a net diff. For a file the turn created, the counts are net and exact. For an existing file, the counts are summed over its edits. - The workspace card moves to the end of the turn. One adapter test changed to match. - Local only: four Linux cgroup `task_memory` Rust tests fail on macOS. They do not touch these modules. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, browser and file editing) and a long context window. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3fca8a1500
commit
c6996799c4
38 files changed
+2486
-195
No files matched your search
@@ -0,0 +1,129 @@
|
||||
import { useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { hunkLabel } from "./diff-lines";
|
||||
import type { TaskChatDiffLine } from "./task-chat-model";
|
||||
|
||||
/** `+12 −3` in the diff hues. Unknown counts are omitted, not shown as zero. */
|
||||
export function TaskChatDiffCounts({
|
||||
added,
|
||||
removed,
|
||||
className,
|
||||
}: {
|
||||
added: number | null | undefined;
|
||||
removed: number | null | undefined;
|
||||
className?: string;
|
||||
}) {
|
||||
if (added == null && removed == null) return null;
|
||||
// A pure addition or deletion reads cleaner without the empty side.
|
||||
const showAdded = added != null && (added > 0 || !removed);
|
||||
const showRemoved = removed != null && (removed > 0 || !added);
|
||||
return (
|
||||
<span
|
||||
className={cn("inline-flex shrink-0 items-center gap-1 font-mono tabular-nums", className)}
|
||||
data-testid="task-chat-diff-counts"
|
||||
>
|
||||
{showAdded ? <span className="text-(--diff-add-fg)">+{added}</span> : null}
|
||||
{showRemoved ? <span className="text-(--diff-remove-fg)">−{removed}</span> : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const MARKER: Record<TaskChatDiffLine["kind"], string> = {
|
||||
add: "+",
|
||||
remove: "−",
|
||||
context: " ",
|
||||
hunk: "",
|
||||
file: "",
|
||||
};
|
||||
|
||||
/**
|
||||
* Compact unified diff for one file. Long diffs show the first `previewLines`
|
||||
* lines with a control to reveal the rest; the block scrolls inside a fixed
|
||||
* maximum height so a large edit never pushes the conversation away.
|
||||
*/
|
||||
export function TaskChatDiffView({
|
||||
lines,
|
||||
truncated = false,
|
||||
previewLines = 24,
|
||||
className,
|
||||
}: {
|
||||
lines: readonly TaskChatDiffLine[];
|
||||
truncated?: boolean;
|
||||
previewLines?: number;
|
||||
className?: string;
|
||||
}) {
|
||||
const [showAll, setShowAll] = useState(false);
|
||||
const visible = showAll ? lines : lines.slice(0, previewLines);
|
||||
const hidden = lines.length - visible.length;
|
||||
return (
|
||||
<div
|
||||
className={cn("min-w-0 overflow-hidden rounded-sm border border-border bg-muted/30", className)}
|
||||
data-testid="task-chat-diff-view"
|
||||
>
|
||||
<div className="max-h-(--sz-edit-diff-max-h) overflow-auto">
|
||||
<table className="w-full border-collapse font-mono text-(length:--text-micro) leading-relaxed">
|
||||
<tbody>
|
||||
{visible.map((line, index) =>
|
||||
line.kind === "file" ? (
|
||||
<tr key={index} className="border-t border-border">
|
||||
<td colSpan={2} className="truncate px-2 py-1 font-medium text-foreground">
|
||||
{line.text}
|
||||
</td>
|
||||
</tr>
|
||||
) : line.kind === "hunk" ? (
|
||||
<tr key={index} className="bg-muted/60 text-muted-foreground">
|
||||
<td colSpan={2} className="whitespace-pre px-2 py-0.5">
|
||||
{hunkLabel(line.text)}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
<tr
|
||||
key={index}
|
||||
className={cn(
|
||||
line.kind === "add" && "bg-(--diff-add-bg)",
|
||||
line.kind === "remove" && "bg-(--diff-remove-bg)",
|
||||
)}
|
||||
>
|
||||
<td
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"w-4 select-none pl-2 align-top",
|
||||
line.kind === "add" && "text-(--diff-add-fg)",
|
||||
line.kind === "remove" && "text-(--diff-remove-fg)",
|
||||
line.kind === "context" && "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{MARKER[line.kind]}
|
||||
</td>
|
||||
<td
|
||||
className={cn(
|
||||
"whitespace-pre pr-3 align-top",
|
||||
line.kind === "context" ? "text-muted-foreground" : "text-foreground",
|
||||
)}
|
||||
>
|
||||
<span className="sr-only">{line.kind === "add" ? "Added: " : line.kind === "remove" ? "Removed: " : ""}</span>
|
||||
{line.text || " "}
|
||||
</td>
|
||||
</tr>
|
||||
),
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{hidden > 0 || truncated ? (
|
||||
<div className="flex items-center gap-2 border-t border-border px-2 py-1 text-(length:--text-micro) text-muted-foreground">
|
||||
{hidden > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="text-foreground underline-offset-2 hover:underline"
|
||||
onClick={() => setShowAll(true)}
|
||||
>
|
||||
Show {hidden} more {hidden === 1 ? "line" : "lines"}
|
||||
</button>
|
||||
) : null}
|
||||
{truncated && hidden === 0 ? <span>Diff shortened for display.</span> : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -73,7 +73,7 @@ describe("TaskChatLiveTail", () => {
|
||||
expect(container.querySelector('[data-testid="task-chat-phase-child-rail"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps tool diff bodies out of the activity feed", () => {
|
||||
it("shows an edit's diff only when its row is opened", () => {
|
||||
const items = parse([
|
||||
{ kind: "tool_call", ts: TS, name: "Edit", toolUseId: "t1", input: { file_path: "a.ts" } },
|
||||
{ kind: "diff", ts: TS, changeType: "add", text: "const x = 1;" },
|
||||
@@ -83,12 +83,11 @@ describe("TaskChatLiveTail", () => {
|
||||
|
||||
expect(toggle().getAttribute("aria-expanded")).toBe("false");
|
||||
expect(container.textContent).not.toContain("const x = 1;");
|
||||
expect(container.textContent).not.toContain("+1 −1");
|
||||
|
||||
expandFirstDetail();
|
||||
|
||||
expect(container.textContent).toContain("+1 −1");
|
||||
expect(container.textContent).not.toContain("const x = 1;");
|
||||
expect(container.querySelector('[data-testid="task-chat-diff-counts"]')?.textContent).toBe("+1−1");
|
||||
expect(container.querySelector('[data-testid="task-chat-diff-view"]')?.textContent).toContain("const x = 1;");
|
||||
expect(container.querySelector('[data-testid="task-chat-runner-activity-detail"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -422,7 +422,26 @@ describe("TaskChatProtocolCard", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens a workspace diff review dialog", async () => {
|
||||
it("says when a change set counts more files than it lists", () => {
|
||||
renderCard(root, {
|
||||
id: "workspace-large",
|
||||
kind: "protocol",
|
||||
surface: "workspace_change",
|
||||
changeSetId: "changes-large",
|
||||
revision: 1,
|
||||
source: "harness_reported",
|
||||
complete: true,
|
||||
files: [
|
||||
{ path: "a.ts", operation: "modify", previousPath: null, additions: 1, deletions: 0, binary: false, diff: null, diffTruncated: true },
|
||||
],
|
||||
totals: { files: 40, additions: 120, deletions: 3 },
|
||||
patchArtifactRef: null,
|
||||
});
|
||||
expect(container.textContent).toContain("40 files changed");
|
||||
expect(container.querySelector('[data-testid="task-chat-workspace-change-omitted"]')?.textContent).toContain("39 more files changed.");
|
||||
});
|
||||
|
||||
it("lists the turn's changed files and opens each diff in place", async () => {
|
||||
renderCard(root, {
|
||||
id: "workspace",
|
||||
kind: "protocol",
|
||||
@@ -439,24 +458,22 @@ describe("TaskChatProtocolCard", () => {
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
binary: false,
|
||||
diff: "-old\n+new",
|
||||
diff: "@@ -1 +1 @@\n-old\n+new\n",
|
||||
},
|
||||
],
|
||||
totals: { files: 1, additions: 1, deletions: 1 },
|
||||
patchArtifactRef: null,
|
||||
});
|
||||
const button = Array.from(container.querySelectorAll("button")).find(
|
||||
(candidate) => candidate.textContent === "Review diff",
|
||||
);
|
||||
expect(button).not.toBeUndefined();
|
||||
expect(container.textContent).toContain("1 file changed · +1 −1");
|
||||
await act(async () => button?.click());
|
||||
expect(document.querySelector('[role="dialog"]')?.textContent).toContain(
|
||||
"ui/src/App.tsx",
|
||||
);
|
||||
expect(document.querySelector('[role="dialog"]')?.textContent).toContain(
|
||||
"old",
|
||||
);
|
||||
expect(container.textContent).toContain("Changed in this turn");
|
||||
expect(container.textContent).toContain("1 file changed");
|
||||
expect(container.querySelector('[data-testid="task-chat-diff-view"]')).toBeNull();
|
||||
const row = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-workspace-change-file"] button');
|
||||
expect(row?.textContent).toContain("ui/src/App.tsx");
|
||||
await act(async () => row?.click());
|
||||
const diff = container.querySelector('[data-testid="task-chat-diff-view"]');
|
||||
expect(diff?.textContent).toContain("Line 1");
|
||||
expect(diff?.textContent).toContain("old");
|
||||
expect(diff?.textContent).toContain("new");
|
||||
});
|
||||
|
||||
it("opens a bounded file preview", async () => {
|
||||
|
||||
@@ -48,6 +48,8 @@ import type {
|
||||
import { QuestionForm, QuestionResponseSummary } from "./QuestionForm";
|
||||
import { TaskChatComposerTakeoverHeader, TaskChatRequestHistoryContext } from "./TaskChatComposerTakeoverContext";
|
||||
import { RichWorkProductCard } from "./RichWorkProductCard";
|
||||
import { TaskChatDiffCounts, TaskChatDiffView } from "./TaskChatDiffView";
|
||||
import { parseUnifiedDiffLines } from "./diff-lines";
|
||||
import { useArtifactsV1Enabled } from "@/hooks/useArtifactsV1Enabled";
|
||||
import { ArtifactFileRow, ArtifactRow, fileRowSourceFromAttachment, fileRowSourceFromWorkProduct, subjectFromAttachment, subjectFromDocumentSummary, subjectFromWorkProduct, workProductStateBadge } from "@/components/artifacts/v1";
|
||||
|
||||
@@ -379,134 +381,143 @@ function ProviderActivityCard({
|
||||
);
|
||||
}
|
||||
|
||||
function diffStats(file: TaskChatWorkspaceChangeItem["files"][number]) {
|
||||
function WorkspaceChangeFileRow({
|
||||
file,
|
||||
open,
|
||||
onToggle,
|
||||
}: {
|
||||
file: TaskChatWorkspaceChangeItem["files"][number];
|
||||
open: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const parsed = useMemo(
|
||||
() => (file.diff ? parseUnifiedDiffLines(file.diff) : null),
|
||||
[file.diff],
|
||||
);
|
||||
const expandable = file.binary || Boolean(parsed?.lines.length) || file.diffTruncated === true;
|
||||
return (
|
||||
<span className="shrink-0 font-mono text-xs text-muted-foreground">
|
||||
{file.additions == null ? "" : `+${file.additions}`}
|
||||
{file.additions != null && file.deletions != null ? " " : ""}
|
||||
{file.deletions == null ? "" : `−${file.deletions}`}
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-col" data-testid="task-chat-workspace-change-file">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expandable ? open : undefined}
|
||||
disabled={!expandable}
|
||||
className={cn(
|
||||
"group/file flex min-w-0 items-center gap-2 rounded-sm px-2 py-1 text-left text-xs",
|
||||
expandable ? "hover:bg-muted/60" : "cursor-default",
|
||||
)}
|
||||
onClick={expandable ? onToggle : undefined}
|
||||
>
|
||||
<ChevronRight
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"h-3 w-3 shrink-0 text-muted-foreground transition-transform",
|
||||
open && "rotate-90",
|
||||
!expandable && "invisible",
|
||||
)}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-foreground">
|
||||
{file.previousPath ? `${file.previousPath} → ${file.path}` : file.path}
|
||||
</span>
|
||||
{file.operation !== "modify" ? (
|
||||
<span className="shrink-0 text-(length:--text-micro) capitalize text-muted-foreground">
|
||||
{file.binary ? "binary · " : ""}
|
||||
{OPERATION_LABEL[file.operation] ?? file.operation.replaceAll("_", " ")}
|
||||
</span>
|
||||
) : file.binary ? (
|
||||
<span className="shrink-0 text-(length:--text-micro) text-muted-foreground">binary</span>
|
||||
) : null}
|
||||
<TaskChatDiffCounts added={file.additions} removed={file.deletions} />
|
||||
</button>
|
||||
{open ? (
|
||||
file.binary ? (
|
||||
<p className="ml-7 mt-1 text-xs text-muted-foreground">Binary file; text diff is unavailable.</p>
|
||||
) : parsed?.lines.length ? (
|
||||
<TaskChatDiffView
|
||||
className="ml-7 mt-1"
|
||||
lines={parsed.lines}
|
||||
truncated={parsed.truncated || file.diffTruncated === true}
|
||||
/>
|
||||
) : (
|
||||
<p className="ml-7 mt-1 text-xs text-muted-foreground">This patch is too large to show here.</p>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const OPERATION_LABEL: Record<string, string> = {
|
||||
create: "new",
|
||||
delete: "deleted",
|
||||
rename: "renamed",
|
||||
mode_change: "mode change",
|
||||
};
|
||||
|
||||
function WorkspaceChangeCard({ item }: { item: TaskChatWorkspaceChangeItem }) {
|
||||
const [selectedPath, setSelectedPath] = useState<string | null>(null);
|
||||
const [openPaths, setOpenPaths] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const selected =
|
||||
item.files.find((file) => file.path === selectedPath) ?? null;
|
||||
const visibleFiles = expanded ? item.files : item.files.slice(0, 3);
|
||||
const visibleFiles = expanded ? item.files : item.files.slice(0, 5);
|
||||
const fileCount = item.totals.files || item.files.length;
|
||||
const fileLabel = `${fileCount} ${fileCount === 1 ? "file" : "files"}`;
|
||||
const stats = [
|
||||
item.totals.additions == null ? null : `+${item.totals.additions}`,
|
||||
item.totals.deletions == null ? null : `−${item.totals.deletions}`,
|
||||
].filter(Boolean).join(" ");
|
||||
const summary = item.complete
|
||||
? `${fileLabel} changed${stats ? ` · ${stats}` : ""}`
|
||||
: "Workspace changes in progress";
|
||||
const summary = item.complete ? `${fileLabel} changed` : `${fileLabel} so far`;
|
||||
const toggle = (path: string) =>
|
||||
setOpenPaths((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(path)) next.delete(path);
|
||||
else next.add(path);
|
||||
return next;
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<CardShell
|
||||
icon={GitBranch}
|
||||
title="Workspace changes"
|
||||
status={item.complete ? "completed" : "running"}
|
||||
summary={summary}
|
||||
testId="task-chat-workspace-change"
|
||||
>
|
||||
<div className="flex flex-col gap-1">
|
||||
{visibleFiles.map((file) => (
|
||||
<button
|
||||
key={`${file.operation}:${file.path}`}
|
||||
type="button"
|
||||
className="flex min-w-0 items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-muted/60"
|
||||
onClick={() => setSelectedPath(file.path)}
|
||||
>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-mono">
|
||||
{file.previousPath
|
||||
? `${file.previousPath} → ${file.path}`
|
||||
: file.path}
|
||||
</span>
|
||||
<span className="text-xs capitalize text-muted-foreground">
|
||||
{file.binary ? "binary · " : ""}
|
||||
{file.operation.replaceAll("_", " ")}
|
||||
</span>
|
||||
</span>
|
||||
{diffStats(file)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
{item.files.length > 3 ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded
|
||||
? "Show fewer files"
|
||||
: `Show ${item.files.length - 3} more files`}
|
||||
</Button>
|
||||
) : null}
|
||||
{item.files.length > 0 ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setSelectedPath(item.files[0].path)}
|
||||
>
|
||||
Review diff
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</CardShell>
|
||||
<Dialog
|
||||
open={selected !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setSelectedPath(null);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="w-full max-w-(--pct-90) overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="font-mono text-sm">
|
||||
{selected?.path ?? "Workspace diff"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
{item.files.length > 1 ? (
|
||||
<div
|
||||
className="flex max-w-full gap-1 overflow-x-auto pb-1"
|
||||
aria-label="Changed files"
|
||||
>
|
||||
{item.files.map((file) => (
|
||||
<Button
|
||||
key={file.path}
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={file.path === selected?.path ? "secondary" : "ghost"}
|
||||
onClick={() => setSelectedPath(file.path)}
|
||||
>
|
||||
{file.path}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{selected?.binary ? (
|
||||
<p className="rounded-sm bg-muted/50 p-3 text-sm text-muted-foreground">
|
||||
Binary file; text diff is unavailable.
|
||||
</p>
|
||||
) : selected?.diff ? (
|
||||
<pre className="max-h-(--sz-70vh) overflow-auto whitespace-pre rounded-sm bg-muted/50 p-3 font-mono text-xs">
|
||||
{selected.diff}
|
||||
</pre>
|
||||
) : (
|
||||
<p className="rounded-sm bg-muted/50 p-3 text-sm text-muted-foreground">
|
||||
No inline patch was recorded for this file.
|
||||
</p>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
<CardShell
|
||||
icon={GitBranch}
|
||||
title={item.complete ? "Changed in this turn" : "Changing files"}
|
||||
status={item.complete ? null : "running"}
|
||||
testId="task-chat-workspace-change"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2 px-2 pb-1 text-xs text-muted-foreground">
|
||||
<span>{summary}</span>
|
||||
<TaskChatDiffCounts added={item.totals.additions} removed={item.totals.deletions} />
|
||||
{item.files.length > 1 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="ml-auto text-foreground underline-offset-2 hover:underline"
|
||||
onClick={() =>
|
||||
setOpenPaths((current) =>
|
||||
current.size > 0 ? new Set() : new Set(item.files.map((file) => file.path)),
|
||||
)
|
||||
}
|
||||
>
|
||||
{openPaths.size > 0 ? "Collapse all" : "Expand all"}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
{visibleFiles.map((file) => (
|
||||
<WorkspaceChangeFileRow
|
||||
key={`${file.operation}:${file.path}`}
|
||||
file={file}
|
||||
open={openPaths.has(file.path)}
|
||||
onToggle={() => toggle(file.path)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{item.files.length > 5 ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="mt-1"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded ? "Show fewer files" : `Show ${item.files.length - 5} more files`}
|
||||
</Button>
|
||||
) : null}
|
||||
{fileCount > item.files.length ? (
|
||||
<p className="mt-1 px-2 text-xs text-muted-foreground" data-testid="task-chat-workspace-change-omitted">
|
||||
{fileCount - item.files.length} more {fileCount - item.files.length === 1 ? "file" : "files"} changed.
|
||||
This change set is too large to list them here.
|
||||
</p>
|
||||
) : null}
|
||||
</CardShell>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import { TaskChatReasoningSummary } from "./TaskChatReasoningSummary";
|
||||
import { latestReasoningHeadline } from "./reasoning-summary";
|
||||
import { toolActivityPresentation, type ToolIcon } from "./tool-taxonomy";
|
||||
import { useTaskChatShimmer } from "./TaskChatShimmer";
|
||||
import { TaskChatDiffCounts, TaskChatDiffView } from "./TaskChatDiffView";
|
||||
|
||||
type Activity = TaskChatActivityPhaseItem["items"][number];
|
||||
|
||||
@@ -194,6 +195,13 @@ function ActivityContent({
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
{item.kind === "tool" && item.diff && (item.diff.added > 0 || item.diff.removed > 0) ? (
|
||||
<TaskChatDiffCounts
|
||||
added={item.diff.added}
|
||||
removed={item.diff.removed}
|
||||
className="text-xs"
|
||||
/>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -262,6 +270,10 @@ function ActivityDetails({ item }: { item: Activity }) {
|
||||
{item.detail ?? item.label}
|
||||
</p>
|
||||
);
|
||||
if (item.diff?.lines?.length)
|
||||
return (
|
||||
<TaskChatDiffView lines={item.diff.lines} truncated={item.diff.truncated} />
|
||||
);
|
||||
return (
|
||||
<>
|
||||
{item.target ? (
|
||||
@@ -370,6 +382,13 @@ export function TaskChatRunnerActivityGroup({
|
||||
const summary = completedActivitySummary(activities);
|
||||
const SummaryIcon = summary.icon;
|
||||
const countLabel = `${activities.length} ${activities.length === 1 ? "activity" : "activities"}`;
|
||||
const editTotals = activities.reduce(
|
||||
(sum, activity) =>
|
||||
activity.kind === "tool" && activity.diff
|
||||
? { added: sum.added + activity.diff.added, removed: sum.removed + activity.diff.removed }
|
||||
: sum,
|
||||
{ added: 0, removed: 0 },
|
||||
);
|
||||
return (
|
||||
<section
|
||||
className="flex min-w-0 flex-col gap-2"
|
||||
@@ -422,6 +441,13 @@ export function TaskChatRunnerActivityGroup({
|
||||
<RollingActivity item={latest} active={item.active} />
|
||||
)}
|
||||
<span className="flex shrink-0 items-center gap-1 text-xs">
|
||||
{!item.active && (editTotals.added > 0 || editTotals.removed > 0) ? (
|
||||
<TaskChatDiffCounts
|
||||
added={editTotals.added}
|
||||
removed={editTotals.removed}
|
||||
className="mr-1"
|
||||
/>
|
||||
) : null}
|
||||
{expanded ? countLabel : item.active ? activities.length : null}
|
||||
<ChevronRight
|
||||
className={cn("size-3.5", expanded && "rotate-90")}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import type { TaskChatToolItem } from "./task-chat-model";
|
||||
import { toolTaxonomy } from "./tool-taxonomy";
|
||||
import { useTaskChatShimmer } from "./TaskChatShimmer";
|
||||
import { TaskChatDiffCounts, TaskChatDiffView } from "./TaskChatDiffView";
|
||||
|
||||
const STATUS_ICON = {
|
||||
pending: { Icon: Loader2, spin: false, tone: "text-muted-foreground" },
|
||||
@@ -28,7 +29,8 @@ const STATUS_ICON = {
|
||||
* Tool invocation as a flat activity row (v7): [glyph] [name] [mono target] …
|
||||
* [hover chevron] [status]. No card chrome — activity is metadata, not
|
||||
* content. Clicking toggles a compact result/change summary (left-rail
|
||||
* inset). Full diff bodies stay out of the activity feed.
|
||||
* inset). An edit row carries its `+N −M` counts and opens to a compact,
|
||||
* height-capped diff of that one edit.
|
||||
*/
|
||||
export function TaskChatToolCard({ item }: { item: TaskChatToolItem }) {
|
||||
const { Icon, spin, tone } = STATUS_ICON[item.status];
|
||||
@@ -66,6 +68,13 @@ export function TaskChatToolCard({ item }: { item: TaskChatToolItem }) {
|
||||
) : null}
|
||||
</span>
|
||||
<span className="ml-auto flex shrink-0 items-center gap-2">
|
||||
{item.diff && (item.diff.added > 0 || item.diff.removed > 0) ? (
|
||||
<TaskChatDiffCounts
|
||||
added={item.diff.added}
|
||||
removed={item.diff.removed}
|
||||
className="text-(length:--text-micro)"
|
||||
/>
|
||||
) : null}
|
||||
{item.decision ? (
|
||||
<span
|
||||
className={cn(
|
||||
@@ -103,7 +112,7 @@ export function TaskChatToolCard({ item }: { item: TaskChatToolItem }) {
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
{item.target && showDetail ? (
|
||||
{item.target && showDetail && !item.diff?.lines?.length ? (
|
||||
<div
|
||||
className="task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground"
|
||||
data-testid="task-chat-tool-target-detail"
|
||||
@@ -117,22 +126,26 @@ export function TaskChatToolCard({ item }: { item: TaskChatToolItem }) {
|
||||
</pre>
|
||||
) : null}
|
||||
{item.diff && showDetail ? (
|
||||
<div
|
||||
className="ml-1.5 mt-0.5 border-l-2 border-border py-1 pl-2.5"
|
||||
data-testid="task-chat-tool-change-summary"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2 text-(length:--text-micro) text-muted-foreground">
|
||||
<span className="shrink-0">Changed</span>
|
||||
{item.diff.path ? (
|
||||
<span className="min-w-0 truncate font-mono text-foreground">
|
||||
{item.diff.path}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="ml-auto shrink-0 font-mono">
|
||||
+{item.diff.added} −{item.diff.removed}
|
||||
</span>
|
||||
item.diff.lines && item.diff.lines.length > 0 ? (
|
||||
<div className="ml-1.5 mt-1 min-w-0 max-w-full" data-testid="task-chat-tool-diff">
|
||||
<TaskChatDiffView lines={item.diff.lines} truncated={item.diff.truncated} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="ml-1.5 mt-0.5 border-l-2 border-border py-1 pl-2.5"
|
||||
data-testid="task-chat-tool-change-summary"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2 text-(length:--text-micro) text-muted-foreground">
|
||||
<span className="shrink-0">Changed</span>
|
||||
{item.diff.path ? (
|
||||
<span className="min-w-0 truncate font-mono text-foreground">
|
||||
{item.diff.path}
|
||||
</span>
|
||||
) : null}
|
||||
<TaskChatDiffCounts added={item.diff.added} removed={item.diff.removed} className="ml-auto" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseUnifiedDiffLines } from "./diff-lines";
|
||||
|
||||
describe("parseUnifiedDiffLines", () => {
|
||||
it("skips file headers but keeps header-like changed lines inside a hunk", () => {
|
||||
const parsed = parseUnifiedDiffLines(
|
||||
"diff --git a/q.sql b/q.sql\n--- a/q.sql\n+++ b/q.sql\n@@ -1,2 +1,2 @@\n--- old comment\n+++ new comment\n keep\n",
|
||||
);
|
||||
expect(parsed).toMatchObject({ added: 1, removed: 1 });
|
||||
expect(parsed.lines).toEqual([
|
||||
{ kind: "hunk", text: "@@ -1,2 +1,2 @@" },
|
||||
{ kind: "remove", text: "-- old comment" },
|
||||
{ kind: "add", text: "++ new comment" },
|
||||
{ kind: "context", text: "keep" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { TaskChatDiffLine } from "./task-chat-model";
|
||||
|
||||
/** Display cap for one diff in the task chat. */
|
||||
export const TASK_CHAT_DIFF_LINE_LIMIT = 400;
|
||||
|
||||
export type UnifiedDiffLineKind = TaskChatDiffLine["kind"] | "skip";
|
||||
|
||||
/**
|
||||
* Classify unified diff lines. File headers (`diff --git`, `index`, `---`,
|
||||
* `+++`, mode and rename lines) are skipped only before a file's first hunk;
|
||||
* inside a hunk, `--- x` is a removed `-- x` line and `+++ x` an added `++ x`.
|
||||
*/
|
||||
export function createUnifiedDiffClassifier(): (raw: string) => { kind: UnifiedDiffLineKind; text: string } {
|
||||
let inHunk = false;
|
||||
return (raw) => {
|
||||
if (raw.startsWith("diff --git ")) {
|
||||
inHunk = false;
|
||||
return { kind: "skip", text: raw };
|
||||
}
|
||||
if (raw.startsWith("@@")) {
|
||||
inHunk = true;
|
||||
return { kind: "hunk", text: raw };
|
||||
}
|
||||
if (raw === "\\ No newline at end of file") return { kind: "skip", text: raw };
|
||||
if (!inHunk && (
|
||||
raw.startsWith("+++ ") || raw.startsWith("--- ") || raw.startsWith("index ") ||
|
||||
raw.startsWith("new file mode") || raw.startsWith("deleted file mode") ||
|
||||
raw.startsWith("similarity index") || raw.startsWith("rename from") || raw.startsWith("rename to")
|
||||
)) return { kind: "skip", text: raw };
|
||||
if (raw.startsWith("+")) return { kind: "add", text: raw.slice(1) };
|
||||
if (raw.startsWith("-")) return { kind: "remove", text: raw.slice(1) };
|
||||
return { kind: "context", text: raw.startsWith(" ") ? raw.slice(1) : raw };
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a unified diff body into display lines. File headers (`---`, `+++`,
|
||||
* `diff --git`, `index`) are dropped because the row or card already names the
|
||||
* file. Lines past the display cap are omitted and reported as truncated.
|
||||
*/
|
||||
export function parseUnifiedDiffLines(
|
||||
patch: string,
|
||||
limit = TASK_CHAT_DIFF_LINE_LIMIT,
|
||||
): { lines: TaskChatDiffLine[]; added: number; removed: number; truncated: boolean } {
|
||||
const lines: TaskChatDiffLine[] = [];
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
let truncated = false;
|
||||
const classify = createUnifiedDiffClassifier();
|
||||
const source = patch.endsWith("\n") ? patch.slice(0, -1) : patch;
|
||||
for (const raw of source.split("\n")) {
|
||||
const { kind, text } = classify(raw);
|
||||
if (kind === "skip") continue;
|
||||
if (kind === "add") added += 1;
|
||||
if (kind === "remove") removed += 1;
|
||||
if (lines.length < limit) lines.push({ kind, text });
|
||||
else truncated = true;
|
||||
}
|
||||
return { lines, added, removed, truncated };
|
||||
}
|
||||
|
||||
/** Readable hunk label: `@@ -41,9 +41,18 @@ fn()` becomes `Line 41 · fn()`. */
|
||||
export function hunkLabel(text: string): string {
|
||||
const match = text.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$/);
|
||||
if (!match) return text;
|
||||
const context = match[2]?.trim();
|
||||
return context ? `Line ${match[1]} · ${context}` : `Line ${match[1]}`;
|
||||
}
|
||||
@@ -60,6 +60,8 @@ export interface TaskChatWorkspaceChangeFile {
|
||||
deletions: number | null;
|
||||
binary: boolean;
|
||||
diff: string | null;
|
||||
/** The patch was shortened by its producer; counts still cover all of it. */
|
||||
diffTruncated?: boolean;
|
||||
}
|
||||
import type { IssueThreadInteraction } from "@/lib/issue-thread-interactions";
|
||||
|
||||
@@ -91,7 +93,20 @@ export interface TaskChatDiff {
|
||||
added: number;
|
||||
removed: number;
|
||||
/** Optional unified-diff-ish lines for display only. */
|
||||
lines?: Array<{ kind: "add" | "remove" | "context"; text: string }>;
|
||||
lines?: TaskChatDiffLine[];
|
||||
/** True when the producer bounded the patch and lines were omitted. */
|
||||
truncated?: boolean;
|
||||
/**
|
||||
* Per-file counts reported by the producer for the whole patch. When present
|
||||
* they are authoritative; `added`/`removed` are their sums, not line counts.
|
||||
*/
|
||||
files?: Array<{ path: string; additions: number; deletions: number; truncated: boolean }>;
|
||||
}
|
||||
|
||||
export interface TaskChatDiffLine {
|
||||
/** `file` starts the next file when one edit call changed several files. */
|
||||
kind: "add" | "remove" | "context" | "hunk" | "file";
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface TaskChatTokenUsage {
|
||||
|
||||
@@ -720,13 +720,14 @@ describe("transcriptToTaskChatItems protocol surfaces", () => {
|
||||
opts,
|
||||
);
|
||||
expect(items).toHaveLength(2);
|
||||
expect(items[0]).toMatchObject({
|
||||
// The turn's changed files close the turn, after its other activity.
|
||||
expect(items[1]).toMatchObject({
|
||||
kind: "protocol",
|
||||
surface: "workspace_change",
|
||||
revision: 2,
|
||||
complete: true,
|
||||
});
|
||||
expect(items[1]).toMatchObject({
|
||||
expect(items[0]).toMatchObject({
|
||||
kind: "protocol",
|
||||
surface: "runtime_request",
|
||||
runId: "run-protocol",
|
||||
@@ -2865,3 +2866,76 @@ describe("prependIssueBrief (PAP-375)", () => {
|
||||
expect(prependIssueBrief(items, false)).toBe(items);
|
||||
});
|
||||
});
|
||||
|
||||
describe("turn changes assembled from edit rows", () => {
|
||||
it("lists each edited file when the harness reports only per-edit patches", () => {
|
||||
const items = transcriptToTaskChatItems(
|
||||
[
|
||||
{ kind: "tool_call", ts: TS, name: "Write", toolUseId: "w1", input: { path: "price.js" } },
|
||||
{ kind: "diff", ts: TS, changeType: "file_header", text: "price.js", toolUseId: "w1" },
|
||||
{ kind: "diff", ts: TS, changeType: "hunk", text: "@@ -0,0 +1,2 @@", toolUseId: "w1" },
|
||||
{ kind: "diff", ts: TS, changeType: "add", text: "a", toolUseId: "w1" },
|
||||
{ kind: "diff", ts: TS, changeType: "add", text: "b", toolUseId: "w1" },
|
||||
{ kind: "tool_call", ts: TS, name: "Edit", toolUseId: "e1", input: { path: "price.js" } },
|
||||
{ kind: "tool_call", ts: TS, name: "Edit", toolUseId: "e2", input: { path: "other.js" } },
|
||||
{ kind: "diff", ts: TS, changeType: "file_header", text: "other.js", toolUseId: "e2" },
|
||||
{ kind: "diff", ts: TS, changeType: "hunk", text: "@@ -4,2 +4,2 @@", toolUseId: "e2" },
|
||||
{ kind: "diff", ts: TS, changeType: "context", text: "keep", toolUseId: "e2" },
|
||||
{ kind: "diff", ts: TS, changeType: "remove", text: "old", toolUseId: "e2" },
|
||||
{ kind: "diff", ts: TS, changeType: "add", text: "new", toolUseId: "e2" },
|
||||
// An addressed line reaches its own row even after another call started.
|
||||
{ kind: "diff", ts: TS, changeType: "file_header", text: "price.js", toolUseId: "e1" },
|
||||
{ kind: "diff", ts: TS, changeType: "hunk", text: "@@ -1,2 +1,2 @@", toolUseId: "e1" },
|
||||
{ kind: "diff", ts: TS, changeType: "remove", text: "b", toolUseId: "e1" },
|
||||
{ kind: "diff", ts: TS, changeType: "add", text: "c", toolUseId: "e1" },
|
||||
{ kind: "diff", ts: TS, changeType: "truncation", text: "Diff shortened for display.", toolUseId: "e1" },
|
||||
{ kind: "tool_result", ts: TS, toolUseId: "w1", content: "", isError: false },
|
||||
{ kind: "tool_result", ts: TS, toolUseId: "e1", content: "", isError: false },
|
||||
{ kind: "tool_result", ts: TS, toolUseId: "e2", content: "", isError: false },
|
||||
],
|
||||
{ runId: "run-edits", running: false },
|
||||
);
|
||||
const edit = items.find((item) => item.kind === "tool" && item.id.endsWith("e1"));
|
||||
expect(edit).toMatchObject({ diff: { path: "price.js", added: 1, removed: 1, truncated: true } });
|
||||
const changes = items.at(-1);
|
||||
expect(changes).toMatchObject({
|
||||
kind: "protocol",
|
||||
surface: "workspace_change",
|
||||
complete: true,
|
||||
totals: { files: 2, additions: 3, deletions: 1 },
|
||||
});
|
||||
if (changes?.kind !== "protocol" || changes.surface !== "workspace_change") throw new Error("expected changes");
|
||||
// A file created this turn reports its net size.
|
||||
expect(changes.files[0]).toMatchObject({ path: "price.js", operation: "create", additions: 2, deletions: 0 });
|
||||
expect(changes.files[1]).toMatchObject({ path: "other.js", operation: "modify", additions: 1, deletions: 1 });
|
||||
expect(changes.files[1].diff).toBe("@@ -4,2 +4,2 @@\n keep\n-old\n+new\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("edit diff review fixes", () => {
|
||||
it("leaves failed edits out of the turn card and keeps producer counts for shortened patches", () => {
|
||||
const items = transcriptToTaskChatItems(
|
||||
[
|
||||
{ kind: "tool_call", ts: TS, name: "Edit", toolUseId: "ok", input: { path: "big.js" } },
|
||||
{ kind: "diff", ts: TS, changeType: "file_header", text: "big.js", toolUseId: "ok", additions: 900, deletions: 40 },
|
||||
{ kind: "diff", ts: TS, changeType: "hunk", text: "@@ -1,1 +1,1 @@", toolUseId: "ok" },
|
||||
{ kind: "diff", ts: TS, changeType: "remove", text: "a", toolUseId: "ok" },
|
||||
{ kind: "diff", ts: TS, changeType: "add", text: "b", toolUseId: "ok" },
|
||||
{ kind: "diff", ts: TS, changeType: "truncation", text: "Diff shortened for display.", toolUseId: "ok" },
|
||||
{ kind: "tool_result", ts: TS, toolUseId: "ok", content: "", isError: false },
|
||||
{ kind: "tool_call", ts: TS, name: "Edit", toolUseId: "bad", input: { path: "never.js" } },
|
||||
{ kind: "diff", ts: TS, changeType: "file_header", text: "never.js", toolUseId: "bad", additions: 3, deletions: 0 },
|
||||
{ kind: "diff", ts: TS, changeType: "add", text: "x", toolUseId: "bad" },
|
||||
{ kind: "tool_result", ts: TS, toolUseId: "bad", content: "rejected", isError: true },
|
||||
],
|
||||
{ runId: "run-review", running: false },
|
||||
);
|
||||
expect(items.find((item) => item.kind === "tool" && item.id.endsWith(":ok"))).toMatchObject({
|
||||
diff: { added: 900, removed: 40, truncated: true },
|
||||
});
|
||||
const card = items.at(-1);
|
||||
if (card?.kind !== "protocol" || card.surface !== "workspace_change") throw new Error("expected changes");
|
||||
expect(card.files.map((file) => file.path)).toEqual(["big.js"]);
|
||||
expect(card.files[0]).toMatchObject({ additions: 900, deletions: 40, diffTruncated: true });
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@
|
||||
* only showing a response after the turn settles.
|
||||
*/
|
||||
import type { TranscriptEntry } from "@/adapters";
|
||||
import { turnChangesFromEditRows } from "./turn-file-changes";
|
||||
import type {
|
||||
TaskChatDiff,
|
||||
TaskChatActivityPhaseItem,
|
||||
@@ -128,9 +129,10 @@ export function flattenSelfTalk(text: string): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
function diffKind(changeType: string): "add" | "remove" | "context" {
|
||||
function diffKind(changeType: string): "add" | "remove" | "context" | "hunk" {
|
||||
if (changeType === "add") return "add";
|
||||
if (changeType === "remove") return "remove";
|
||||
if (changeType === "hunk") return "hunk";
|
||||
return "context";
|
||||
}
|
||||
|
||||
@@ -832,16 +834,39 @@ export function transcriptToTaskChatItems(
|
||||
break;
|
||||
}
|
||||
case "diff": {
|
||||
// Diff lines addressed to a tool call attach to that row; legacy
|
||||
// unaddressed lines attach to the most recent tool.
|
||||
const addressedIndex = entry.toolUseId ? toolIndexById.get(entry.toolUseId) : undefined;
|
||||
const targetIndex = addressedIndex ?? lastToolIndex;
|
||||
const target =
|
||||
targetIndex >= 0 && items[targetIndex]?.kind === "tool"
|
||||
? (items[targetIndex] as TaskChatToolItem)
|
||||
: null;
|
||||
if (entry.changeType === "file_header") {
|
||||
if (lastToolIndex >= 0 && items[lastToolIndex].kind === "tool") {
|
||||
const tool = items[lastToolIndex] as TaskChatToolItem;
|
||||
tool.diff = tool.diff ?? {
|
||||
path: entry.text,
|
||||
added: 0,
|
||||
removed: 0,
|
||||
lines: [],
|
||||
};
|
||||
tool.diff.path = entry.text;
|
||||
if (target) {
|
||||
if (target.diff?.lines?.length || target.diff?.files?.length) {
|
||||
target.diff.lines = target.diff.lines ?? [];
|
||||
target.diff.lines.push({ kind: "file", text: entry.text });
|
||||
} else {
|
||||
target.diff = target.diff ?? { added: 0, removed: 0, lines: [] };
|
||||
target.diff.path = entry.text;
|
||||
}
|
||||
if (entry.additions != null && entry.deletions != null) {
|
||||
const diff = target.diff!;
|
||||
diff.files = diff.files ?? [];
|
||||
diff.files.push({ path: entry.text, additions: entry.additions, deletions: entry.deletions, truncated: false });
|
||||
diff.added = diff.files.reduce((sum, file) => sum + file.additions, 0);
|
||||
diff.removed = diff.files.reduce((sum, file) => sum + file.deletions, 0);
|
||||
}
|
||||
}
|
||||
resetInline();
|
||||
break;
|
||||
}
|
||||
if (entry.changeType === "truncation") {
|
||||
if (target?.diff) {
|
||||
target.diff.truncated = true;
|
||||
const file = target.diff.files?.at(-1);
|
||||
if (file) file.truncated = true;
|
||||
}
|
||||
resetInline();
|
||||
break;
|
||||
@@ -850,18 +875,20 @@ export function transcriptToTaskChatItems(
|
||||
kind: diffKind(entry.changeType),
|
||||
text: entry.text ?? "",
|
||||
};
|
||||
if (lastToolIndex >= 0 && items[lastToolIndex].kind === "tool") {
|
||||
const tool = items[lastToolIndex] as TaskChatToolItem;
|
||||
const diff: TaskChatDiff = tool.diff ?? {
|
||||
if (target) {
|
||||
const diff: TaskChatDiff = target.diff ?? {
|
||||
added: 0,
|
||||
removed: 0,
|
||||
lines: [],
|
||||
};
|
||||
diff.lines = diff.lines ?? [];
|
||||
diff.lines.push(line);
|
||||
if (line.kind === "add") diff.added += 1;
|
||||
if (line.kind === "remove") diff.removed += 1;
|
||||
tool.diff = diff;
|
||||
// Producer counts cover the whole patch; count lines only without them.
|
||||
if (!diff.files?.length) {
|
||||
if (line.kind === "add") diff.added += 1;
|
||||
if (line.kind === "remove") diff.removed += 1;
|
||||
}
|
||||
target.diff = diff;
|
||||
} else {
|
||||
items.push({
|
||||
id: `${runId}:diff:${i}`,
|
||||
@@ -913,13 +940,12 @@ export function transcriptToTaskChatItems(
|
||||
revision: entry.revision,
|
||||
source: entry.source,
|
||||
complete: entry.complete,
|
||||
files: entry.files.map((file) => ({
|
||||
...file,
|
||||
diff:
|
||||
file.diff == null
|
||||
? null
|
||||
: file.diff.slice(0, PROTOCOL_OUTPUT_MAX),
|
||||
})),
|
||||
files: entry.files.map((file) => {
|
||||
if (file.diff == null || file.diff.length <= PROTOCOL_OUTPUT_MAX) return { ...file };
|
||||
// Keep whole lines so the preview still parses as a patch.
|
||||
const cut = file.diff.lastIndexOf("\n", PROTOCOL_OUTPUT_MAX);
|
||||
return { ...file, diff: file.diff.slice(0, cut > 0 ? cut + 1 : PROTOCOL_OUTPUT_MAX), diffTruncated: true };
|
||||
}),
|
||||
totals: entry.totals,
|
||||
patchArtifactRef: entry.patchArtifactRef,
|
||||
};
|
||||
@@ -1107,10 +1133,26 @@ export function transcriptToTaskChatItems(
|
||||
item.status === "pending"
|
||||
) {
|
||||
item.status = "cancelled";
|
||||
} else if (item.kind === "protocol" && item.surface === "workspace_change") {
|
||||
// A harness-reported change set is final once its run has ended.
|
||||
item.complete = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every turn that edited files ends with its changed files, just before its
|
||||
// final answer. A harness that reports only per-edit patches gets the card
|
||||
// assembled from its edit rows.
|
||||
const changeIndex = items.findIndex((item) => item.kind === "protocol" && item.surface === "workspace_change");
|
||||
const changes = changeIndex >= 0
|
||||
? items.splice(changeIndex, 1)[0]
|
||||
: turnChangesFromEditRows(items, runId ?? "run", !running);
|
||||
if (changes) {
|
||||
const last = items.at(-1);
|
||||
const beforeFinal = last?.kind === "message" && last.channel === "final";
|
||||
items.splice(beforeFinal ? items.length - 1 : items.length, 0, changes);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import type {
|
||||
TaskChatDiffLine,
|
||||
TaskChatItem,
|
||||
TaskChatToolItem,
|
||||
TaskChatWorkspaceChangeItem,
|
||||
} from "./task-chat-model";
|
||||
|
||||
type ChangeFile = TaskChatWorkspaceChangeItem["files"][number];
|
||||
|
||||
function patchLine(line: TaskChatDiffLine): string {
|
||||
if (line.kind === "hunk") return line.text;
|
||||
if (line.kind === "add") return `+${line.text}`;
|
||||
if (line.kind === "remove") return `-${line.text}`;
|
||||
return ` ${line.text}`;
|
||||
}
|
||||
|
||||
interface EditFile {
|
||||
path: string;
|
||||
lines: TaskChatDiffLine[];
|
||||
additions: number;
|
||||
deletions: number;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split one edit row's diff into per-file patches (`file` lines start the next
|
||||
* file). Producer counts, when present, cover patches that were shortened.
|
||||
*/
|
||||
function editFiles(tool: TaskChatToolItem): EditFile[] {
|
||||
const diff = tool.diff;
|
||||
if (!diff?.lines?.length && !diff?.files?.length) return [];
|
||||
const chunks: Array<{ path: string; lines: TaskChatDiffLine[] }> = [];
|
||||
let current = { path: diff.path ?? tool.target ?? "", lines: [] as TaskChatDiffLine[] };
|
||||
for (const line of diff.lines ?? []) {
|
||||
if (line.kind === "file") {
|
||||
if (current.path) chunks.push(current);
|
||||
current = { path: line.text, lines: [] };
|
||||
} else {
|
||||
current.lines.push(line);
|
||||
}
|
||||
}
|
||||
if (current.path) chunks.push(current);
|
||||
return chunks.map((chunk, index) => {
|
||||
const reported = diff.files?.[index];
|
||||
const counted = {
|
||||
additions: chunk.lines.filter((line) => line.kind === "add").length,
|
||||
deletions: chunk.lines.filter((line) => line.kind === "remove").length,
|
||||
};
|
||||
return {
|
||||
...chunk,
|
||||
additions: reported?.additions ?? counted.additions,
|
||||
deletions: reported?.deletions ?? counted.deletions,
|
||||
truncated: reported?.truncated ?? (diff.truncated === true && index === chunks.length - 1),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The turn's changed files, assembled from its edit rows. Used when the
|
||||
* harness reports only per-edit patches (Claude) and no whole-turn diff, so
|
||||
* every turn that edited files ends with the same card.
|
||||
*/
|
||||
export function turnChangesFromEditRows(
|
||||
items: readonly TaskChatItem[],
|
||||
runId: string,
|
||||
complete: boolean,
|
||||
): TaskChatWorkspaceChangeItem | null {
|
||||
const byPath = new Map<string, { patches: string[]; additions: number; deletions: number; created: boolean; truncated: boolean }>();
|
||||
for (const item of items) {
|
||||
// A failed or interrupted call may carry the patch it proposed before it
|
||||
// ran; only edits that ran (or are still running) count as changes.
|
||||
if (item.kind !== "tool" || item.status === "failed" || item.status === "interrupted") continue;
|
||||
for (const file of editFiles(item)) {
|
||||
const entry = byPath.get(file.path) ?? { patches: [], additions: 0, deletions: 0, created: true, truncated: false };
|
||||
if (file.lines.length) entry.patches.push(file.lines.map(patchLine).join("\n"));
|
||||
entry.additions += file.additions;
|
||||
entry.deletions += file.deletions;
|
||||
entry.truncated ||= file.truncated;
|
||||
// A file is new only when its first edit added lines to nothing.
|
||||
if (byPath.has(file.path) === false) {
|
||||
const hunks = file.lines.filter((line) => line.kind === "hunk");
|
||||
entry.created = hunks.length > 0
|
||||
&& hunks.every((line) => /^@@ -0,0 /.test(line.text))
|
||||
&& file.lines.every((line) => line.kind === "add" || line.kind === "hunk");
|
||||
}
|
||||
byPath.set(file.path, entry);
|
||||
}
|
||||
}
|
||||
if (byPath.size === 0) return null;
|
||||
const files: ChangeFile[] = [...byPath.entries()].map(([path, entry]) => ({
|
||||
path,
|
||||
operation: entry.created ? "create" : "modify",
|
||||
previousPath: null,
|
||||
// Every line removed from a file this turn created was added earlier in
|
||||
// the turn, so its net size is exact; edits to existing files are summed.
|
||||
additions: entry.created ? Math.max(entry.additions - entry.deletions, 0) : entry.additions,
|
||||
deletions: entry.created ? 0 : entry.deletions,
|
||||
binary: false,
|
||||
diff: entry.patches.length ? `${entry.patches.join("\n")}\n` : null,
|
||||
diffTruncated: entry.truncated,
|
||||
}));
|
||||
return {
|
||||
id: `${runId}:workspace:edits`,
|
||||
kind: "protocol",
|
||||
surface: "workspace_change",
|
||||
changeSetId: `${runId}:edits`,
|
||||
revision: 1,
|
||||
source: "harness_reported",
|
||||
complete,
|
||||
files,
|
||||
totals: {
|
||||
files: files.length,
|
||||
additions: files.reduce((sum, file) => sum + (file.additions ?? 0), 0),
|
||||
deletions: files.reduce((sum, file) => sum + (file.deletions ?? 0), 0),
|
||||
},
|
||||
patchArtifactRef: null,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user