Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(runs): show captured file changes for each agent run (#10459)
SUBARUAWA48698c53df049b6
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex 1628421102..cc10456474 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -22,6 +22,8 @@ The AI coding tools a local runtime invokes, those tools' own login credentials,So the team can collaborate, the server stores issues, comments, agent configuration, run context, run records, and the results agents write back. That content can include code snippets or other project context an agent chose to read and include in its replies.+[Run changes](/tasks#run-changes) also automatically uploads captured file paths and patches from registered repositories, including captured uncommitted changes. The daemon masks credential patterns it recognizes before sending. This masking cannot guarantee removal of every secret; the records are visible to people who can access the run.+<Callout type="warning">"Local execution" does not mean every secret exists only on this machine. An agent's custom environment variables and MCP configuration are stored on the server, and their display is limited by the sensitive-value rules; custom environment variables are sent to the runtime at execution time.</Callout>diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 13710effbd..30d72b9ac9 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -22,6 +22,8 @@ Multica 记录和协调工作,连接上来的电脑负责执行:电脑上的为了让团队能够协作,服务器会保存任务、评论、智能体配置、运行上下文、执行记录和智能体写回的结果。这些内容可能包含智能体主动读取并写入回复的代码片段或其他项目上下文。+[本轮文件变化](/tasks#本轮文件变化)还会自动上传登记仓库中采集到的文件路径和补丁,其中可能包含未提交修改。守护进程发送前会遮蔽可识别的凭据格式;这种脱敏无法保证清除所有秘密。能够访问运行的成员也能够查看这些记录。+<Callout type="warning">"本地执行"不等于所有 secret 都只存在本机。智能体的自定义环境变量和 MCP 配置保存在服务器侧,展示时受敏感信息规则限制;自定义环境变量会在执行时发送给运行时。</Callout>diff --git a/apps/docs/content/docs/tasks.mdx b/apps/docs/content/docs/tasks.mdxindex 562c170b3f..c307083985 100644--- a/apps/docs/content/docs/tasks.mdx+++ b/apps/docs/content/docs/tasks.mdx@@ -188,3 +188,23 @@ All other failure reasons (auth, quota, configuration, model, and so on) never r- [Daemon and runtimes](/daemon-runtimes) — which computer a run executes on.- [Assigning issues to agents](/assigning-issues) — trigger a run from an issue.- [Mentioning agents](/mentioning-agents) — add requirements in comments or bring in other agents.++## Run changes++Open **Run changes** below an agent's reply or in the run's transcript dialog. Select a file to see its additions and deletions.++A repository can have several comparisons:++- **Working tree, start to end** compares the files before and after the run, including uncommitted edits and new files Git does not ignore. Existing edits form the baseline. In an in-place run, concurrent edits to the same directory can also appear in this comparison.+- **Commits** compares the run's start and end commits. For a delivered worktree, this is the range delivered to the issue branch.+- **Saved draft** shows changes that worktree finalization saved separately from the delivered commits, compared with the delivered tip.++The runtime covers configured local repositories and repositories registered through `multica repo checkout`. Each run has its own records, including any partial results successfully captured after a failure. The viewer distinguishes an empty comparison, a failed capture, and a truncated record. Older runs may have no recorded diff. Records follow task-message access and retention.++For an in-place run bound to a subdirectory, both working-tree snapshots and commit comparisons are restricted to that configured directory. Sibling directories are excluded. File paths in the viewer remain relative to the repository root. Concurrent edits inside the configured directory can still appear in the comparison.++If worktree finalization fails and preserves the checkout, the working-tree comparison is unavailable because its starting commit may use a different representation from the files on disk, such as Git LFS or clean/smudge filters. Valid commit ranges remain reviewable. Inspect uncommitted changes in the preserved checkout.++The daemon automatically sends the captured file paths and textual patches to the Multica server, including captured uncommitted changes. It masks credentials recognized by the existing redaction rules before sending; these rules cannot detect every secret. Review who can access the run before using it with sensitive repositories.++Capture is limited to eight repositories, 50 files per comparison, 64 KiB per patch, and 256 KiB of patch bodies per run. Repository registrations survive environment reuse, including repositories omitted by the capture limit. The temporary working-tree snapshots can use more disk space than the uploaded patches; capture timeouts do not impose a disk quota. The daemon sends the final records once with a three-second deadline. If reporting fails or the daemon exits before delivery, the records may be missing from history.diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdxindex 803d6f1da1..8ce2c720c7 100644--- a/apps/docs/content/docs/tasks.zh.mdx+++ b/apps/docs/content/docs/tasks.zh.mdx@@ -188,3 +188,23 @@ multica issue rerun-task <run-id>- [守护进程与运行时](/daemon-runtimes) — 了解运行在哪台电脑上执行。- [分配任务给智能体](/assigning-issues) — 从任务发起一次运行。- [提及智能体](/mentioning-agents) — 在评论中补充要求或邀请其他智能体参与。++## 本轮文件变化++点击智能体回复下或运行日志弹窗中的**本轮文件变化**,选择文件查看增删内容。++同一个仓库可以有多种对比:++- **工作树:运行前后**。比较本轮开始和结束时的文件状态,包括未提交修改和 Git 未忽略的新文件。开始时已有的内容是本轮基线。就地运行期间,其他人在同一目录里的修改也可能出现在差异中。+- **提交范围**。比较本轮的起止提交。隔离工作树完成交付后,这里显示交付到任务分支的内容。+- **已保存草稿**。如果隔离工作树交付了提交,同时把未提交内容另外保存,这里显示草稿相对交付提交的差异。++运行时记录配置的本地仓库和通过 `multica repo checkout` 登记的仓库。各轮独立记录。运行失败后,仍能查看已成功采集的部分成果。查看器会区分无净变化、采集失败和达到记录上限。较早的运行可能没有差异记录。记录沿用任务消息的访问权限和保留期限。++就地运行绑定仓库子目录时,工作树快照和提交范围都限制在配置的目录内。查看器中的文件路径仍相对于仓库根目录。配置目录内的并发修改也可能出现在差异中。++如果工作树收尾失败并保留了检出目录,工作树对比会标记为不可用,因为起始提交与磁盘文件可能使用不同的内容表示,例如 Git LFS 或 clean/smudge 过滤器。有效的提交范围仍可查看;未提交修改请在保留的工作树中检查。++守护进程会自动向 Multica 服务器发送采集到的文件路径和文本补丁,其中可能包含未提交修改。发送前会按现有脱敏规则遮蔽可识别的凭据,这些规则无法识别所有秘密。在敏感仓库中使用前,请确认哪些成员可以查看运行记录。++每轮最多采集 8 个仓库,每个对比最多记录 50 个文件,单个补丁上限为 64 KiB,整轮补丁正文上限为 256 KiB。仓库登记会随环境复用保留,包括因采集上限而省略的仓库。临时工作树快照的磁盘占用可能超过上传补丁大小;采集超时并不构成磁盘配额。最终记录仅发送一次,请求时限为 3 秒。如果上报失败或守护进程在交付前退出,历史记录中可能缺少这些差异。diff --git a/apps/mobile/components/chat/chat-timeline.tsx b/apps/mobile/components/chat/chat-timeline.tsxindex bf24d7822e..8ab6d2fbf3 100644--- a/apps/mobile/components/chat/chat-timeline.tsx+++ b/apps/mobile/components/chat/chat-timeline.tsx@@ -30,6 +30,7 @@ import {CollapsibleTrigger,} from "@/components/ui/collapsible";import { useT } from "@/lib/i18n";+import { isInternalRunMessage } from "@/lib/run-transcript";interface Props {items: TaskMessagePayload[];@@ -39,7 +40,7 @@ interface Props {}export function ChatTimeline({ items, isStreaming = false }: Props) {- const processSteps = items.filter((i) => i.type !== "text");+ const processSteps = items.filter((i) => i.type !== "text" && !isInternalRunMessage(i));const { t } = useT("chat");if (processSteps.length === 0) return null;diff --git a/apps/mobile/lib/run-transcript.test.ts b/apps/mobile/lib/run-transcript.test.tsindex 6162bddf83..d844daf413 100644--- a/apps/mobile/lib/run-transcript.test.ts+++ b/apps/mobile/lib/run-transcript.test.ts@@ -8,6 +8,7 @@ import {getRunDiagnostics,isCancellableRunStatus,isRunTranscriptTaskId,+ isInternalRunMessage,RUN_TRANSCRIPT_PATHNAME,runTranscriptRoute,runToolContext,@@ -40,6 +41,20 @@ function message(seq: number, type: TaskMessagePayload["type"], content?: string}describe("historical run transcript", () => {+ it("hides captured diffs from transcript entries and chat process steps", () => {+ const call = { ...message(1, "tool_use"), tool: "Bash", call_id: "A" };+ const internal = { ...message(2, "tool_use"), tool: "multica_commit_diff", input: { repository: "private-repository" } };+ const result = { ...message(3, "tool_result"), tool: "multica_commit_diff" };+ const source = [call, internal, result];++ expect(source.filter((item) => !isInternalRunMessage(item))).toEqual([call]);+ expect(buildRunTranscript(source)).toEqual([call]);+ expect(buildRunTranscriptEntries(source)).toEqual([+ { kind: "tool", task_id: "task-1", seq: 1, call },+ ]);+ expect(source).toHaveLength(3);+ });+it("pairs parallel same-name calls by ID when results finish in reverse order", () => {const callA = { ...message(1, "tool_use"), tool: "Bash", call_id: "A", input: { command: "test A" } };const callB = { ...message(2, "tool_use"), tool: "Bash", call_id: "B", input: { command: "test B" } };diff --git a/apps/mobile/lib/run-transcript.ts b/apps/mobile/lib/run-transcript.tsindex 2092f23f58..bbc4ca7ded 100644--- a/apps/mobile/lib/run-transcript.ts+++ b/apps/mobile/lib/run-transcript.ts@@ -1,5 +1,6 @@import type { AgentTask, TaskMessagePayload } from "@multica/core/types";import { redactSecrets } from "@multica/core/security/redact-secrets";+import { COMMIT_DIFF_TOOL } from "@multica/core/chat/commit-diff";import { failureReasonKey } from "./failure-reason-label";const UUID_PATTERN =@@ -33,12 +34,20 @@ export function isCancellableRunStatus(status: AgentTask["status"]): boolean {);}+export function isInternalRunMessage(message: TaskMessagePayload): boolean {+ return (+ (message.type === "tool_use" || message.type === "tool_result") &&+ message.tool === COMMIT_DIFF_TOOL+ );+}+/** Match web transcript semantics without importing its UI or query layer. */export function buildRunTranscript(messages: readonly TaskMessagePayload[],): TaskMessagePayload[] {const items: TaskMessagePayload[] = [];for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {+ if (isInternalRunMessage(message)) continue;const previous = items[items.length - 1];if (previous &&diff --git a/packages/core/chat/commit-diff.test.ts b/packages/core/chat/commit-diff.test.tsnew file mode 100644index 0000000000..2aa01b4e45--- /dev/null+++ b/packages/core/chat/commit-diff.test.ts@@ -0,0 +1,74 @@+// @vitest-environment node+import { describe, expect, it, vi } from "vitest";+import { getCommitDiffs, COMMIT_DIFF_TOOL } from "./commit-diff";+import { noopLogger } from "../logger";+import { setSchemaLogger } from "../api/schema";+import type { TaskMessagePayload } from "../types";+const payload = {+ repository: "app",+ repository_id: "repo-1",+ base: "a".repeat(40),+ head: "b".repeat(40),+ changes: [{ path: "a.ts", kind: "modify", diff: "@@ -1 +1 @@\n-old\n+new" }],+};+const message = (input: unknown, seq = 1): TaskMessagePayload => ({+ task_id: "task",+ issue_id: "issue",+ type: "tool_use",+ tool: COMMIT_DIFF_TOOL,+ seq,+ input: input as Record<string, unknown>,+ created_at: "2026-11-11T00:00:00Z",+});+describe("getCommitDiffs", () => {+ it("keeps repository identities separate and selects the newest report", () => {+ const diffs = getCommitDiffs([+ message({ ...payload, head: "c".repeat(40) }, 3),+ message(payload, 1),+ message({ ...payload, repository_id: "repo-2" }, 2),+ ]);+ expect(diffs).toHaveLength(2);+ expect(diffs[0]?.head).toBe("c".repeat(40));+ expect(diffs[0]?.repositories_omitted).toBe(false);+ });+ it("retains the run-level repository limit status", () => {+ const diffs = getCommitDiffs([message({ ...payload, repositories_omitted: true })]);+ expect(diffs[0]?.repositories_omitted).toBe(true);+ });+ it("retains empty and unavailable comparisons alongside the same repository's commits", () => {+ const diffs = getCommitDiffs([+ message(payload),+ message({ ...payload, kind: "worktree", changes: [] }, 2),+ message({ ...payload, kind: "draft", unavailable: true, base: undefined, head: undefined, changes: [] }, 3),+ ]);+ expect(diffs.map(({ kind, unavailable }) => [kind, unavailable])).toEqual([+ ["commits", false],+ ["worktree", false],+ ["draft", true],+ ]);+ });+ it("ignores provider edits and invalid input without logging source code", () => {+ const warn = vi.fn();+ setSchemaLogger({ debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() });+ expect(+ getCommitDiffs([+ message({ ...payload, base: "invalid", source: "secret source" }),+ message({ ...payload, base: undefined }),+ { ...message(payload), tool: "patch_apply" },+ ]),+ ).toEqual([]);+ expect(warn).not.toHaveBeenCalled();+ setSchemaLogger(noopLogger);+ });+ it("retains truncated and binary files even without text", () => {+ const diff = getCommitDiffs([+ message({+ ...payload,+ truncated: true,+ changes: [{ path: "asset.png", kind: "add", binary: true }],+ }),+ ])[0];+ expect(diff?.truncated).toBe(true);+ expect(diff?.changes[0]?.binary).toBe(true);+ });+});diff --git a/packages/core/chat/commit-diff.ts b/packages/core/chat/commit-diff.tsnew file mode 100644index 0000000000..a37376d490--- /dev/null+++ b/packages/core/chat/commit-diff.ts@@ -0,0 +1,54 @@+import { z } from "zod";+import { parseWithFallback } from "../api/schema";+import type { TaskMessagePayload } from "../types";++export const COMMIT_DIFF_TOOL = "multica_commit_diff";+const commit = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/);+const commitDiffSchema = z.object({+ repository: z.string().min(1),+ repository_id: z.string().min(1),+ base: commit.optional(),+ head: commit.optional(),+ kind: z.enum(["commits", "worktree", "draft"]).optional(),+ unavailable: z.boolean().default(false),+ repositories_omitted: z.boolean().default(false),+ worktree: z.boolean().default(false),+ changes: z.array(+ z.object({+ path: z.string().min(1),+ kind: z.string(),+ diff: z.string().optional(),+ binary: z.boolean().optional(),+ truncated: z.boolean().optional(),+ unavailable: z.boolean().optional(),+ }),+ ),+ truncated: z.boolean().default(false),+})+ .refine((value) => value.unavailable || (value.base !== undefined && value.head !== undefined))+ .transform(({ kind, worktree, ...value }) => ({+ ...value,+ kind: kind ?? (worktree ? "worktree" : "commits"),+ }));+export type CommitDiff = z.infer<typeof commitDiffSchema>;++export function getCommitDiffs(+ messages: readonly TaskMessagePayload[],+): CommitDiff[] {+ const comparisons = new Map<string, CommitDiff>();+ for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {+ if (message.type !== "tool_use" || message.tool !== COMMIT_DIFF_TOOL)+ continue;+ // Diff bodies contain source code: malformed payloads must not be copied+ // into schema diagnostics. The catch also keeps older clients rendering.+ const diff = parseWithFallback<CommitDiff | null>(+ message.input,+ commitDiffSchema.nullable().catch(null),+ null,+ { endpoint: "task/commit-diff" },+ );+ if (diff)+ comparisons.set(JSON.stringify([diff.repository_id, diff.kind]), diff);+ }+ return [...comparisons.values()];+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex a4a1a9c6b3..2398f58fe2 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -79,6 +79,7 @@"./notification-preferences/patch": "./notification-preferences/patch.ts","./chat": "./chat/index.ts","./chat/queries": "./chat/queries.ts",+ "./chat/commit-diff": "./chat/commit-diff.ts","./chat/mutations": "./chat/mutations.ts","./chat/pending": "./chat/pending.ts","./chat/session-list": "./chat/session-list.ts",diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsxindex a972470c7f..34766b535f 100644--- a/packages/views/chat/components/chat-message-list.test.tsx+++ b/packages/views/chat/components/chat-message-list.test.tsx@@ -1043,3 +1043,31 @@ describe("ChatMessageList onboarding starter cards", () => {expect(screen.getByRole("button", { name: "Later chip" })).toBeEnabled();});});++describe("ChatMessageList failed-run commit changes", () => {+ it("opens recorded partial results from a failed chat reply", async () => {+ const qc = new QueryClient();+ qc.setQueryData(chatKeys.taskMessages(TASK_ID), [taskMsg(1, "tool_use", {+ tool: "multica_commit_diff",+ input: {+ repository: "demo", repository_id: "repo-1", base: "a".repeat(40), head: "b".repeat(40),+ changes: [{ path: "partial.ts", kind: "add", diff: "@@ -0,0 +1 @@\n+partial result" }],+ },+ })]);+ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={qc}>+ <ChatMessageList messages={[{+ id: "failed-message", chat_session_id: "session-1", role: "assistant",+ content: "network failed after committing partial results", task_id: TASK_ID,+ created_at: new Date(0).toISOString(), failure_reason: "skill_bundle_unavailable",+ }]} pendingTask={null} availability="online" />+ </QueryClientProvider>+ </I18nProvider>,+ );+ expect(await screen.findByText(enChat.message_list.failure.skill_bundle_unavailable)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Run changes · 1 file" }));+ expect(await screen.findByRole("dialog")).toHaveTextContent("aaaaaaaa → bbbbbbbb");+ expect(screen.getByRole("button", { name: "partial.ts" })).toBeInTheDocument();+ });+});diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex da0dd5e911..beeb73bc43 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -51,6 +51,7 @@ import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";import { FOLLOW_EDGE_THRESHOLD } from "../../common/task-transcript/transcript-follow";import { LIVE_END_ROW_ATTR, useStickToBottom } from "./stick-to-bottom";import { JumpToLiveEndButton, useJumpToLiveEnd } from "./jump-to-live-end";+import { CommitChanges } from "../../common/commit-changes/commit-changes";import { formatElapsedMs } from "../lib/format";import {canonicalAnswerText,@@ -657,12 +658,15 @@ function AssistantMessage({// so the user can see exactly where the run broke.if (message?.failure_reason) {return (- <FailureBubble- reason={message.failure_reason}- rawError={message.content}- timeline={timeline}- elapsedMs={message.elapsed_ms}- />+ <div className="w-full space-y-1.5">+ <FailureBubble+ reason={message.failure_reason}+ rawError={message.content}+ timeline={timeline}+ elapsedMs={message.elapsed_ms}+ />+ <CommitChanges messages={taskMessages ?? []} />+ </div>);}@@ -704,6 +708,7 @@ function AssistantMessage({/></div>) : null}+ <CommitChanges messages={taskMessages ?? []} />{message && (<><AttachmentListdiff --git a/packages/views/common/commit-changes/commit-changes.test.tsx b/packages/views/common/commit-changes/commit-changes.test.tsxnew file mode 100644index 0000000000..136670d58d--- /dev/null+++ b/packages/views/common/commit-changes/commit-changes.test.tsx@@ -0,0 +1,203 @@+import { fireEvent, screen, waitFor } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import type { TaskMessagePayload } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { CommitChanges, TaskCommitChanges } from "./commit-changes";++vi.mock("@multica/core/api", () => ({ api: { listTaskMessages: vi.fn() } }));+const message: TaskMessagePayload = {+ task_id: "33333333-3333-4333-8333-333333333333",+ issue_id: "issue",+ seq: 1,+ type: "tool_use",+ tool: "multica_commit_diff",+ created_at: "2026-11-11T00:00:00Z",+ input: {+ repository: "demo",+ repository_id: "repo-1",+ base: "a".repeat(40),+ head: "b".repeat(40),+ changes: [+ {+ path: "src/main.ts",+ kind: "modify",+ diff: "@@ -1 +1 @@\n-old value\n+new value",+ },+ { path: "image.png", kind: "add", binary: true },+ ],+ },+};+describe("CommitChanges", () => {+ it("opens a read-only commit range and switches between text and binary files", async () => {+ renderWithI18n(<CommitChanges messages={[message]} />);+ fireEvent.click(screen.getByRole("button", { name: "Run changes · 2 files" }));+ expect(await screen.findByRole("dialog", { name: "Run changes" })).toBeInTheDocument();+ expect(screen.getByText("demo")).toBeInTheDocument();+ expect(screen.getByText("Commits")).toBeInTheDocument();+ expect(screen.getByText("aaaaaaaa → bbbbbbbb")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Commits" })).not.toBeInTheDocument();+ expect(screen.getByRole("dialog")).toHaveTextContent("new value");+ fireEvent.click(screen.getByRole("button", { name: "image.png" }));+ expect(+ screen.getByText("No textual diff is available."),+ ).toBeInTheDocument();+ });+ it("shows file changes when the run ends on the same commit", async () => {+ renderWithI18n(+ <CommitChanges messages={[{+ ...message,+ input: { ...message.input, worktree: true, head: "a".repeat(40) },+ }]} />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Run changes · 2 files" }));+ expect(await screen.findByText("Working tree, start to end")).toBeInTheDocument();+ expect(screen.getByRole("dialog")).toHaveTextContent("new value");+ });+ it("shows the incomplete status in place of a truncated file count", () => {+ renderWithI18n(+ <CommitChanges messages={[{ ...message, input: { ...message.input, truncated: true } }]} />,+ { locale: "zh-Hans" },+ );+ expect(screen.getByRole("button", { name: "本轮文件变化 · 记录不完整" })).toBeInTheDocument();+ });+ it("shows omitted repositories before the file viewer even when recorded repositories have no changes", async () => {+ renderWithI18n(+ <CommitChanges messages={[{+ ...message,+ input: { ...message.input, changes: [], repositories_omitted: true },+ }]} />,+ { locale: "zh-Hans" },+ );+ fireEvent.click(screen.getByRole("button", { name: "本轮文件变化 · 记录不完整" }));+ expect(await screen.findByText("达到仓库记录上限,部分仓库未采集。")).toBeInTheDocument();+ });+ it("shows the incomplete status when a file's diff could not be read", async () => {+ renderWithI18n(<CommitChanges messages={[{+ ...message,+ input: {+ ...message.input,+ changes: [{ path: "src/main.ts", kind: "modify", unavailable: true }],+ },+ }]} />);+ fireEvent.click(screen.getByRole("button", { name: "Run changes · Incomplete record" }));+ expect(await screen.findByRole("button", { name: "src/main.ts" })).toBeInTheDocument();+ expect(screen.getByText("This file’s diff could not be recorded in full. Review it in the repository.")).toBeInTheDocument();+ });+ it("opens commits before an empty working tree and keeps all comparisons selectable", async () => {+ const worktree = {+ ...message,+ seq: 2,+ input: { ...message.input, kind: "worktree", changes: [] },+ };+ const draft = {+ ...message,+ seq: 3,+ input: { ...message.input, kind: "draft", changes: [{ path: "draft.txt", kind: "add" }] },+ };+ renderWithI18n(<CommitChanges messages={[message, worktree, draft]} />);+ expect(screen.getByText("src/main.ts, image.png")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Run changes · 3 files" }));+ expect(await screen.findByRole("button", { name: "Commits", pressed: true })).toBeInTheDocument();+ expect(screen.getByRole("dialog")).toHaveTextContent("new value");+ fireEvent.click(screen.getByRole("button", { name: "Working tree, start to end" }));+ expect(screen.getByText("No net working tree changes.")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Working tree changes could not be recorded." })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Saved draft" }));+ expect(screen.getByRole("button", { name: "draft.txt" })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "src/main.ts" })).not.toBeInTheDocument();+ });+ it("shows a capture failure even without any recorded changes", async () => {+ renderWithI18n(+ <CommitChanges messages={[{+ ...message,+ input: { ...message.input, kind: "worktree", unavailable: true, base: undefined, changes: [] },+ }]} />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Run changes · Incomplete record" }));+ expect(await screen.findByText("Working tree changes could not be recorded.")).toBeInTheDocument();+ expect(screen.queryByText("No net working tree changes.")).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Working tree changes could not be recorded." })).not.toBeInTheDocument();+ });+ it("shows partial capture failure on the default comparison for the affected repository", async () => {+ const unavailableWorktree = {+ ...message,+ seq: 2,+ input: { ...message.input, kind: "worktree", unavailable: true, changes: [] },+ };+ const otherRepository = {+ ...message,+ seq: 3,+ input: { ...message.input, repository: "other", repository_id: "repo-2" },+ };+ renderWithI18n(<CommitChanges messages={[message, unavailableWorktree, otherRepository]} />);+ fireEvent.click(screen.getByRole("button", { name: "Run changes · Incomplete record" }));+ expect(await screen.findByRole("button", { name: "Commits", pressed: true })).toBeInTheDocument();+ const failure = "Working tree changes could not be recorded.";+ fireEvent.click(screen.getByRole("button", { name: failure }));+ expect(screen.getByRole("button", { name: "Working tree, start to end", pressed: true })).toHaveFocus();+ expect(screen.getByRole("status")).toHaveTextContent(failure);+ expect(screen.queryByRole("button", { name: failure })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "other" }));+ expect(screen.queryByText(failure)).not.toBeInTheDocument();+ });+ it("does not turn ordinary tool events into commit comparisons", () => {+ const { container } = renderWithI18n(+ <CommitChanges messages={[{ ...message, tool: "patch_apply" }]} />,+ );+ expect(container).toBeEmptyDOMElement();+ });+ it("loads the file summary only after opening an uncached run", async () => {+ // Simulate a visible reply even though jsdom does not lay out the page.+ vi.stubGlobal("IntersectionObserver", class {+ constructor(private callback: IntersectionObserverCallback) {}+ observe() {+ this.callback(+ [{ isIntersecting: true } as IntersectionObserverEntry],+ this as unknown as IntersectionObserver,+ );+ }+ disconnect() {}+ });+ try {+ vi.mocked(api.listTaskMessages).mockClear().mockResolvedValue([message]);+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ renderWithI18n(+ <QueryClientProvider client={client}>+ <TaskCommitChanges taskId={message.task_id} />+ </QueryClientProvider>,+ );+ expect(screen.queryByText("Run changes · 2 files")).not.toBeInTheDocument();+ expect(api.listTaskMessages).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Run changes" }));+ expect(await screen.findByText("Run changes · 2 files")).toBeInTheDocument();+ expect(screen.getByText("src/main.ts, image.png")).toBeInTheDocument();+ expect(api.listTaskMessages).toHaveBeenCalledTimes(1);+ } finally {+ vi.unstubAllGlobals();+ }+ });+ it("shows an empty state when the run has no records", async () => {+ vi.mocked(api.listTaskMessages).mockClear();+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ renderWithI18n(+ <QueryClientProvider client={client}>+ <TaskCommitChanges taskId={message.task_id} />+ </QueryClientProvider>,+ );+ expect(api.listTaskMessages).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Run changes" }));+ await waitFor(() =>+ expect(+ screen.getByText("No changes were recorded for this run."),+ ).toBeInTheDocument(),+ );+ expect(api.listTaskMessages).toHaveBeenCalledWith(message.task_id);+ });+});diff --git a/packages/views/common/commit-changes/commit-changes.tsx b/packages/views/common/commit-changes/commit-changes.tsxnew file mode 100644index 0000000000..7870c0f397--- /dev/null+++ b/packages/views/common/commit-changes/commit-changes.tsx@@ -0,0 +1,327 @@+"use client";++import { useMemo, useRef, useState } from "react";+import {+ getCommitDiffs,+ type CommitDiff,+} from "@multica/core/chat/commit-diff";+import { useTaskMessages } from "@multica/core/chat/queries";+import type { TaskMessagePayload } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@multica/ui/components/ui/dialog";+import { FilePen } from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../../i18n";+import { DiffDetailSurface } from "../task-transcript/detail-surfaces";+import { parseUnifiedDiff } from "../task-transcript/trace-event-presenter";++export function TaskCommitChanges({ taskId }: { taskId: string }) {+ const [open, setOpen] = useState(false);+ const { data, isPending, isError, refetch } = useTaskMessages(+ taskId,+ false,+ open,+ );+ const diffs = useMemo(() => getCommitDiffs(data ?? []), [data]);+ return (+ <ChangesDialog+ open={open}+ onOpenChange={setOpen}+ diffs={diffs}+ pending={isPending}+ error={isError}+ retry={() => void refetch()}+ />+ );+}++export function CommitChanges({+ messages,+}: {+ messages: readonly TaskMessagePayload[];+}) {+ const [open, setOpen] = useState(false);+ const diffs = useMemo(() => getCommitDiffs(messages), [messages]);+ if (diffs.length === 0) return null;+ return <ChangesDialog open={open} onOpenChange={setOpen} diffs={diffs} />;+}++function ChangesDialog({+ open,+ onOpenChange,+ diffs,+ pending = false,+ error = false,+ retry,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ diffs: CommitDiff[];+ pending?: boolean;+ error?: boolean;+ retry?: () => void;+}) {+ const { t } = useT("chat");+ const files = useMemo(() => {+ const paths = new Map<string, string>();+ const multipleRepos = new Set(diffs.map((diff) => diff.repository_id)).size > 1;+ for (const diff of diffs) {+ for (const change of diff.changes) {+ paths.set(+ JSON.stringify([diff.repository_id, change.path]),+ multipleRepos ? `${diff.repository}/${change.path}` : change.path,+ );+ }+ }+ return [...paths.values()];+ }, [diffs]);+ const filePreview = files.slice(0, 2).join(", ");+ const repositoriesOmitted = diffs.some((diff) => diff.repositories_omitted);+ const summary = diffs.some((diff) =>+ diff.repositories_omitted || diff.truncated || diff.unavailable ||+ diff.changes.some((change) => change.truncated || change.unavailable),+ )+ ? t(($) => $.commit_changes.incomplete_record)+ : files.length > 0+ ? t(($) => $.commit_changes.recorded_files, { count: files.length })+ : "";+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <div className="my-2 flex min-w-0 items-center gap-2">+ <DialogTrigger render={<Button variant="outline" size="sm" className="max-w-full" />}>+ <FilePen />+ <span className="min-w-0 truncate">+ {t(($) => $.commit_changes.heading)}+ {summary && ` · ${summary}`}+ </span>+ </DialogTrigger>+ {filePreview && (+ <span className="hidden min-w-0 truncate font-mono text-caption text-muted-foreground sm:block" title={filePreview}>+ {filePreview}+ </span>+ )}+ </div>+ <DialogContent className="flex h-[85vh] w-[94vw] max-w-[1100px] flex-col gap-0 overflow-hidden p-0 sm:max-w-[1100px]">+ <DialogHeader className="shrink-0 border-b px-5 py-3 pr-12">+ <DialogTitle>{t(($) => $.commit_changes.heading)}</DialogTitle>+ </DialogHeader>+ {repositoriesOmitted && (+ <p role="status" className="shrink-0 border-b px-5 py-2 text-caption text-muted-foreground">+ {t(($) => $.commit_changes.repositories_omitted)}+ </p>+ )}+ {pending ? (+ <p role="status" className="p-5 text-body text-muted-foreground">+ {t(($) => $.commit_changes.loading)}+ </p>+ ) : error ? (+ <div role="alert" className="p-5">+ <Button variant="outline" onClick={retry}>+ {t(($) => $.commit_changes.retry)}+ </Button>+ </div>+ ) : diffs.length === 0 ? (+ <p className="p-5 text-body text-muted-foreground">+ {t(($) => $.commit_changes.empty)}+ </p>+ ) : (+ <ChangesViewer diffs={diffs} />+ )}+ </DialogContent>+ </Dialog>+ );+}++const comparisonOrder = { worktree: 0, commits: 1, draft: 2 };++function hasRecordedFiles(diff: CommitDiff) {+ return !diff.unavailable && diff.changes.length > 0;+}++function ChangesViewer({ diffs }: { diffs: CommitDiff[] }) {+ const { t } = useT("chat");+ const [selection, setSelection] = useState<{+ repository?: string;+ kind?: CommitDiff["kind"];+ path?: string;+ }>({});+ const comparisonButtons = useRef<Partial<Record<CommitDiff["kind"], HTMLButtonElement | null>>>({});+ const repositories = [+ ...new Map(diffs.map((diff) => [diff.repository_id, diff.repository])).entries(),+ ];+ const repositoryId =+ repositories.find(([id]) => id === selection.repository)?.[0] ??+ diffs.find(hasRecordedFiles)?.repository_id ??+ diffs[0]!.repository_id;+ const comparisons = diffs+ .filter((diff) => diff.repository_id === repositoryId)+ .sort((a, b) => comparisonOrder[a.kind] - comparisonOrder[b.kind]);+ const diff =+ comparisons.find((candidate) => candidate.kind === selection.kind) ??+ comparisons.find(hasRecordedFiles) ??+ comparisons[0]!;+ const unavailableComparisons = diff.unavailable+ ? []+ : comparisons.filter((comparison) => comparison.unavailable);+ const file =+ diff.changes.find((change) => change.path === selection.path) ?? diff.changes[0];+ const lines = useMemo(+ () => (file?.diff ? parseUnifiedDiff(file.diff) : []),+ [file?.diff],+ );+ const label = {+ worktree: t(($) => $.commit_changes.worktree),+ commits: t(($) => $.commit_changes.commits),+ draft: t(($) => $.commit_changes.draft),+ };+ const unavailableLabel = {+ worktree: t(($) => $.commit_changes.worktree_unavailable),+ commits: t(($) => $.commit_changes.commits_unavailable),+ draft: t(($) => $.commit_changes.draft_unavailable),+ };+ const commitRange = diff.kind === "commits" && diff.base && diff.head+ ? `${diff.base.slice(0, 8)} → ${diff.head.slice(0, 8)}`+ : null;++ return (+ <>+ <div className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-1 border-b px-5 py-2 text-caption">+ {repositories.length > 1 ? (+ <div className="flex min-w-0 flex-wrap gap-1">+ {repositories.map(([id, name]) => (+ <Button+ key={id}+ size="xs"+ variant={id === repositoryId ? "secondary" : "ghost"}+ aria-pressed={id === repositoryId}+ onClick={() => setSelection({ repository: id })}+ className="max-w-full"+ title={name}+ >+ <span className="truncate">{name}</span>+ </Button>+ ))}+ </div>+ ) : (+ <span className="font-mono break-all">{diff.repository}</span>+ )}+ {comparisons.length > 1 ? (+ <div className="flex flex-wrap gap-1">+ {comparisons.map((comparison) => (+ <Button+ key={comparison.kind}+ ref={(button) => {+ comparisonButtons.current[comparison.kind] = button;+ }}+ size="xs"+ variant={comparison.kind === diff.kind ? "secondary" : "ghost"}+ aria-pressed={comparison.kind === diff.kind}+ onClick={() => setSelection({ repository: repositoryId, kind: comparison.kind })}+ >+ {label[comparison.kind]}+ </Button>+ ))}+ </div>+ ) : (+ <span>{label[diff.kind]}</span>+ )}+ {commitRange && <span className="font-mono text-muted-foreground">{commitRange}</span>}+ </div>+ {unavailableComparisons.length > 0 && (+ <div className="flex shrink-0 flex-wrap gap-x-4 border-b px-5 py-1">+ {unavailableComparisons.map((comparison) => (+ <Button+ key={comparison.kind}+ size="xs"+ variant="link"+ className="h-auto min-w-0 px-0 py-1 whitespace-normal text-left underline underline-offset-2"+ onClick={() => {+ comparisonButtons.current[comparison.kind]?.focus();+ setSelection({ repository: repositoryId, kind: comparison.kind });+ }}+ >+ {unavailableLabel[comparison.kind]}+ </Button>+ ))}+ </div>+ )}+ {diff.unavailable ? (+ <p role="status" className="p-5 text-body text-muted-foreground">+ {unavailableLabel[diff.kind]}+ </p>+ ) : (+ <>+ {diff.truncated && (+ <p role="status" className="border-b px-5 py-2 text-caption text-muted-foreground">+ {t(($) => $.commit_changes.incomplete)}+ </p>+ )}+ {diff.changes.length === 0 && !diff.truncated && (+ <p className="p-5 text-body text-muted-foreground">+ {diff.kind === "worktree"+ ? t(($) => $.commit_changes.worktree_unchanged)+ : t(($) => $.commit_changes.comparison_unchanged)}+ </p>+ )}+ {file && (+ <div className="flex min-h-0 flex-1 flex-col sm:flex-row">+ <nav+ aria-label={t(($) => $.commit_changes.files)}+ className="max-h-40 shrink-0 overflow-auto border-b sm:max-h-none sm:w-64 sm:border-r sm:border-b-0"+ >+ {diff.changes.map((change) => (+ <button+ key={change.path}+ aria-label={change.path}+ type="button"+ onClick={() =>+ setSelection({ repository: repositoryId, kind: diff.kind, path: change.path })+ }+ aria-current={change.path === file.path ? "true" : undefined}+ className={cn(+ "flex w-full gap-2 px-4 py-3 text-left text-caption hover:bg-muted",+ change.path === file.path && "bg-muted font-medium",+ )}+ >+ <span+ className={+ change.kind === "add"+ ? "text-success"+ : change.kind === "delete"+ ? "text-destructive"+ : "text-muted-foreground"+ }+ >+ {change.kind === "add" ? "A" : change.kind === "delete" ? "D" : "M"}+ </span>+ <span className="break-all">{change.path}</span>+ </button>+ ))}+ </nav>+ <div className="min-w-0 flex-1 overflow-auto">+ <div className="border-b px-4 py-3 font-mono text-caption break-all">{file.path}</div>+ {file.truncated || file.unavailable ? (+ <p className="p-4 text-body text-muted-foreground">+ {t(($) => $.commit_changes.unavailable)}+ </p>+ ) : lines.length > 0 ? (+ <DiffDetailSurface path={file.path} lines={lines} />+ ) : (+ <p className="p-4 text-body text-muted-foreground">+ {t(($) => $.commit_changes.no_text)}+ </p>+ )}+ </div>+ </div>+ )}+ </>+ )}+ </>+ );+}diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsxindex e8a3071ae0..207b0c83cf 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx@@ -12,6 +12,11 @@ import { renderWithI18n } from "../../test/i18n";import { AgentTranscriptDialog } from "./agent-transcript-dialog";import type { TimelineItem } from "./build-timeline";+vi.mock("../commit-changes/commit-changes", () => ({+ TaskCommitChanges: ({ taskId }: { taskId: string }) => (+ <button type="button" data-task-id={taskId}>Run changes</button>+ ),+}));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace" }));vi.mock("./use-trace-issue-labels", () => ({useTraceIssueLabels: () => (text: string) => text.replaceAll("01a07eca-8e82-775e-be06-e4a97ccfa299", "DEV-17"),@@ -260,6 +265,10 @@ function codeBlock(text: string) {}describe("AgentTranscriptDialog", () => {+ it("offers run changes for runs without an associated issue", () => {+ renderDialog([], { task: { ...baseTask, issue_id: "" } });+ expect(screen.getByRole("button", { name: "Run changes" })).toHaveAttribute("data-task-id", baseTask.id);+ });it.each([{ type: "text", label: "Agent", icon: ".icon-bot" },{ type: "thinking", label: "Thinking", icon: ".icon-brain" },diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsxindex 8ba2693bf4..78fdf7ddb7 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx@@ -2,6 +2,7 @@import { useState, useRef, useCallback, useEffect, useLayoutEffect, useMemo, forwardRef } from "react";import { useWorkspaceId } from "@multica/core/hooks";+import { TaskCommitChanges } from "../commit-changes/commit-changes";import { useTraceIssueLabels } from "./use-trace-issue-labels";import { Virtuoso, type VirtuosoHandle, type Components } from "react-virtuoso";import {@@ -1104,6 +1105,9 @@ export function AgentTranscriptDialog({{/* ── What the run produced ──────────────────────────────────── */}<RunOutcomeRow outcome={outcome} branch={task.branch_name} />+ <div className="shrink-0 px-4">+ <TaskCommitChanges taskId={task.id} />+ </div>{/* ── Where the time went ────────────────────────────────────── */}{lanes && (diff --git a/packages/views/common/task-transcript/build-timeline.ts b/packages/views/common/task-transcript/build-timeline.tsindex 9f70158720..d892c98e5f 100644--- a/packages/views/common/task-transcript/build-timeline.ts+++ b/packages/views/common/task-transcript/build-timeline.ts@@ -1,3 +1,4 @@+import { COMMIT_DIFF_TOOL } from "@multica/core/chat/commit-diff";import type { TaskMessagePayload } from "@multica/core/types/events";import { redactSecrets } from "./redact";@@ -138,6 +139,8 @@ export function buildTimeline(msgs: TaskMessagePayload[]): TimelineItem[] {let run: TaskMessagePayload[] = [];for (const msg of sorted) {+ // Diff records are rendered by the run changes viewer.+ if (msg.type === "tool_use" && msg.tool === COMMIT_DIFF_TOOL) continue;const previous = run[run.length - 1];// Same rule as `canMergeStreamingText`, read off the messages: a run's type// is its first message's, and every member shares it.diff --git a/packages/views/common/task-transcript/transcript-button.test.tsx b/packages/views/common/task-transcript/transcript-button.test.tsxindex 54feff0f86..90c74982a8 100644--- a/packages/views/common/task-transcript/transcript-button.test.tsx+++ b/packages/views/common/task-transcript/transcript-button.test.tsx@@ -102,6 +102,23 @@ afterEach(() => {});describe("TranscriptButton", () => {+ it("keeps raw diff messages available when opening a completed unlinked run", async () => {+ const diff: TaskMessagePayload = {+ ...msg(1, "multica_commit_diff"),+ input: {+ repository: "demo", repository_id: "repo-1", base: "a".repeat(40), head: "b".repeat(40),+ changes: [{ path: "result.ts", kind: "add", diff: "@@ -0,0 +1 @@\n+result" }],+ },+ };+ listTaskMessages.mockResolvedValue([diff]);+ const qc = newClient();+ renderWith(qc, <TranscriptButton task={{ ...baseTask, issue_id: "", status: "completed" }} agentName="Codex" />);+ fireEvent.click(screen.getByRole("button", { name: "View transcript" }));+ await screen.findByRole("dialog");+ expect(qc.getQueryData(chatKeys.taskMessages(baseTask.id))).toEqual([diff]);+ expect(screen.queryByTestId("event")).not.toBeInTheDocument();+ expect(listTaskMessages).toHaveBeenCalledTimes(1);+ });it("closes the transcript dialog when desktop navigation starts", async () => {const items: TimelineItem[] = [{ seq: 1, type: "text", content: "hello" }];const qc = newClient();diff --git a/packages/views/common/task-transcript/transcript-button.tsx b/packages/views/common/task-transcript/transcript-button.tsxindex b82684abce..1dac782545 100644--- a/packages/views/common/task-transcript/transcript-button.tsx+++ b/packages/views/common/task-transcript/transcript-button.tsx@@ -95,6 +95,7 @@ export function TranscriptButton({const returnFocus = finalFocus ?? fromKeyboard;const [loading, setLoading] = useState(false);const [loadedItems, setLoadedItems] = useState<TimelineItem[] | null>(null);+ const queryClient = useQueryClient();const open = controlledOpen ?? uncontrolledOpen;const setOpen = controlledOnOpenChange ?? setUncontrolledOpen;@@ -145,6 +146,7 @@ export function TranscriptButton({api.listTaskMessages(task.id).then((msgs) => {+ queryClient.setQueryData<TaskMessagePayload[]>(chatKeys.taskMessages(task.id), msgs);const timeline = buildTimeline(msgs);setLoadedItems(timeline);openTerminal(timeline);@@ -156,7 +158,7 @@ export function TranscriptButton({}).finally(() => setLoading(false));},- [liveCacheMode, providedItems, loadedItems, setOpen, task.id, onOpenTranscript],+ [liveCacheMode, providedItems, loadedItems, setOpen, task.id, onOpenTranscript, queryClient],);useEffect(() => {diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex 8f4872824b..cb4fadeb1c 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -1,5 +1,6 @@"use client";+import { TaskCommitChanges } from "../../common/commit-changes/commit-changes";import { Fragment, memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";import { CheckCircle2, ChevronRight, CornerUpLeft, ListChevronsDownUp, Copy, Link2, Loader2, MessageSquare, MessageSquarePlus, MoreHorizontal, Pencil, Plus, RotateCcw, SmilePlus, Trash2 } from "@multica/ui/icons";import { toast } from "sonner";@@ -1023,7 +1024,7 @@ function CommentRow({<div className="pl-12 pr-4 max-md:pl-3 max-md:pr-3"><SteerReceipts issueId={issueId} entry={entry} />{entry.actor_type === "agent" && entry.source_task_id && (- <AppCallChips issueId={issueId} taskId={entry.source_task_id} />+ <><AppCallChips issueId={issueId} taskId={entry.source_task_id} /><TaskCommitChanges taskId={entry.source_task_id} /></>)}</div>{retryableAgentFailureComment(entry) && (@@ -1605,7 +1606,7 @@ function CommentCardImpl({<div className="pl-8 max-md:pl-0"><SteerReceipts issueId={issueId} entry={entry} />{entry.actor_type === "agent" && entry.source_task_id && (- <AppCallChips issueId={issueId} taskId={entry.source_task_id} />+ <><AppCallChips issueId={issueId} taskId={entry.source_task_id} /><TaskCommitChanges taskId={entry.source_task_id} /></>)}</div>{retryableAgentFailureComment(entry) && (diff --git a/packages/views/issues/components/inline-comment-run.test.tsx b/packages/views/issues/components/inline-comment-run.test.tsxindex 9b67dc41cf..8158c499c3 100644--- a/packages/views/issues/components/inline-comment-run.test.tsx+++ b/packages/views/issues/components/inline-comment-run.test.tsx@@ -482,7 +482,9 @@ describe("InlineCommentRun", () => {vi.spyOn(window, "getComputedStyle").mockImplementation((el, pseudo) => {const style = originalComputedStyle(el, pseudo);if (!clipped(el)) return style;- return { overflowX: "hidden", overflowY: "hidden" } as CSSStyleDeclaration;+ style.overflowX = "hidden";+ style.overflowY = "hidden";+ return style;});});afterEach(() => {diff --git a/packages/views/issues/components/inline-comment-run.tsx b/packages/views/issues/components/inline-comment-run.tsxindex 1a650225fb..7a73869fb7 100644--- a/packages/views/issues/components/inline-comment-run.tsx+++ b/packages/views/issues/components/inline-comment-run.tsx@@ -33,6 +33,7 @@ import { TaskStatusIcon } from "./task-status-icon";import { useStatusLabel } from "./task-run-labels";import { commentRunOutput, isActiveCommentRun, showCommentRunInHeader, type CommentRun } from "./comment-runs";+import { TaskCommitChanges } from "../../common/commit-changes/commit-changes";import { useRunAnimationVisibility, useRunDisclosureMotion } from "./use-run-comment-motion";function thinkingPreview(content: string | undefined, formatText: (text: string) => string): string {@@ -240,6 +241,7 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal{rawError}</p></TruncatedTooltip>}+ {!hasReply && <TaskCommitChanges taskId={task.id} />}{expanded && <div id={regionId} className="mt-2 min-w-0 space-y-1">{isPending && <p className="text-caption text-muted-foreground">{t(($) => $.inline_run.loading)}</p>}{isError && <div role="alert" className="text-caption text-destructive">{t(($) => $.inline_run.load_failed)}diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 2fa8258c67..7d341b91d2 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -269,5 +269,27 @@"archive": "Archive chat","unarchive": "Unarchive chat","delete": "Delete chat"+ },+ "commit_changes": {+ "heading": "Run changes",+ "files": "Changed files",+ "incomplete": "Some changes were omitted because of recording limits.",+ "unavailable": "This file’s diff could not be recorded in full. Review it in the repository.",+ "no_text": "No textual diff is available.",+ "loading": "Loading changes…",+ "retry": "Retry loading changes",+ "empty": "No changes were recorded for this run.",+ "worktree": "Working tree, start to end",+ "commits": "Commits",+ "draft": "Saved draft",+ "recorded_files_one": "{{count}} file",+ "recorded_files_other": "{{count}} files",+ "incomplete_record": "Incomplete record",+ "repositories_omitted": "Some repositories were not recorded because the repository limit was reached.",+ "worktree_unavailable": "Working tree changes could not be recorded.",+ "commits_unavailable": "Commit changes could not be recorded.",+ "draft_unavailable": "Saved draft changes could not be recorded.",+ "worktree_unchanged": "No net working tree changes.",+ "comparison_unchanged": "No file changes in this comparison."}}diff --git a/packages/views/locales/es/chat.json b/packages/views/locales/es/chat.jsonindex dabfec9fca..1fb86202f6 100644--- a/packages/views/locales/es/chat.json+++ b/packages/views/locales/es/chat.json@@ -269,5 +269,27 @@"unarchive": "Desarchivar chat","delete": "Eliminar chat","agent_settings": "Ajustes del agente"+ },+ "commit_changes": {+ "heading": "Cambios de archivos de esta ejecución",+ "files": "Archivos modificados",+ "incomplete": "Se omitieron algunos cambios por los límites de registro.",+ "unavailable": "No se pudo registrar el diff completo de este archivo. Revísalo en el repositorio.",+ "no_text": "No hay un diff de texto disponible.",+ "loading": "Cargando cambios…",+ "retry": "Volver a cargar los cambios",+ "empty": "No se registraron cambios para esta ejecución.",+ "worktree": "Árbol de trabajo: inicio y fin",+ "commits": "Commits",+ "draft": "Borrador guardado",+ "recorded_files_one": "{{count}} archivo",+ "recorded_files_other": "{{count}} archivos",+ "incomplete_record": "Registro incompleto",+ "repositories_omitted": "Algunos repositorios no se registraron porque se alcanzó el límite de repositorios.",+ "worktree_unavailable": "No se pudieron registrar los cambios del árbol de trabajo.",+ "commits_unavailable": "No se pudieron registrar los cambios de los commits.",+ "draft_unavailable": "No se pudieron registrar los cambios del borrador guardado.",+ "worktree_unchanged": "No hay cambios netos en el árbol de trabajo.",+ "comparison_unchanged": "No hay cambios de archivos en esta comparación."}}diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.jsonindex b7f79e1563..0a7982a927 100644--- a/packages/views/locales/fr/chat.json+++ b/packages/views/locales/fr/chat.json@@ -269,5 +269,27 @@"archive": "Archiver la discussion","unarchive": "Désarchiver la discussion","delete": "Supprimer la discussion"+ },+ "commit_changes": {+ "heading": "Fichiers modifiés pendant cette exécution",+ "files": "Fichiers modifiés",+ "incomplete": "Certaines modifications ont été omises en raison des limites d’enregistrement.",+ "unavailable": "Le diff de ce fichier n’a pas pu être enregistré en entier. Consultez-le dans le dépôt.",+ "no_text": "Aucun diff textuel disponible.",+ "loading": "Chargement des modifications…",+ "retry": "Recharger les modifications",+ "empty": "Aucune modification n’a été enregistrée pour cette exécution.",+ "worktree": "Arbre de travail : début et fin",+ "commits": "Commits",+ "draft": "Brouillon enregistré",+ "recorded_files_one": "{{count}} fichier",+ "recorded_files_other": "{{count}} fichiers",+ "incomplete_record": "Enregistrement incomplet",+ "repositories_omitted": "Certains dépôts n’ont pas été enregistrés car la limite de dépôts a été atteinte.",+ "worktree_unavailable": "Impossible d’enregistrer les modifications de l’arbre de travail.",+ "commits_unavailable": "Impossible d’enregistrer les différences entre les commits.",+ "draft_unavailable": "Impossible d’enregistrer les modifications du brouillon.",+ "worktree_unchanged": "Aucune modification nette de l’arbre de travail.",+ "comparison_unchanged": "Aucun fichier modifié dans cette comparaison."}}diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex 442feb605f..a60d676b27 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -264,5 +264,26 @@"delete": "チャットを削除","archive": "チャットをアーカイブ","unarchive": "アーカイブを解除"+ },+ "commit_changes": {+ "heading": "この実行のファイル変更",+ "files": "変更されたファイル",+ "incomplete": "記録の上限により、一部の変更は省略されています。",+ "unavailable": "このファイルの差分を完全に記録できませんでした。リポジトリで確認してください。",+ "no_text": "表示できるテキスト差分はありません。",+ "loading": "ファイルの変更を読み込み中…",+ "retry": "変更を再読み込み",+ "empty": "この実行で記録された変更はありません。",+ "worktree": "作業ツリー:実行の前後",+ "commits": "コミット範囲",+ "draft": "保存した下書き",+ "recorded_files_other": "{{count}} ファイル",+ "incomplete_record": "記録が不完全",+ "repositories_omitted": "リポジトリの記録上限に達したため、一部のリポジトリを記録できませんでした。",+ "worktree_unavailable": "作業ツリーの変更を記録できませんでした。",+ "commits_unavailable": "コミット範囲の差分を記録できませんでした。",+ "draft_unavailable": "保存した下書きの差分を記録できませんでした。",+ "worktree_unchanged": "実行前後の作業ツリーに差分はありません。",+ "comparison_unchanged": "この比較範囲にファイルの変更はありません。"}}diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex ab173202e9..3132204795 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -264,5 +264,26 @@"delete": "채팅 삭제","archive": "채팅 보관","unarchive": "채팅 보관 해제"+ },+ "commit_changes": {+ "heading": "이 실행의 파일 변경 사항",+ "files": "변경된 파일",+ "incomplete": "기록 한도로 인해 일부 변경 사항이 생략되었습니다.",+ "unavailable": "이 파일의 차이를 완전히 기록하지 못했습니다. 저장소에서 확인하세요.",+ "no_text": "표시할 텍스트 차이가 없습니다.",+ "loading": "파일 변경 사항을 불러오는 중…",+ "retry": "변경 사항 다시 불러오기",+ "empty": "이 실행에서 기록된 파일 변경 사항이 없습니다.",+ "worktree": "작업 트리: 실행 전후",+ "commits": "커밋 범위",+ "draft": "저장된 초안",+ "recorded_files_other": "파일 {{count}}개",+ "incomplete_record": "기록 불완전",+ "repositories_omitted": "저장소 기록 한도에 도달하여 일부 저장소를 기록하지 못했습니다.",+ "worktree_unavailable": "작업 트리 변경 사항을 기록하지 못했습니다.",+ "commits_unavailable": "커밋 범위의 변경 사항을 기록하지 못했습니다.",+ "draft_unavailable": "저장된 초안의 변경 사항을 기록하지 못했습니다.",+ "worktree_unchanged": "실행 전후 작업 트리에 차이가 없습니다.",+ "comparison_unchanged": "이 비교 범위에 파일 변경 사항이 없습니다."}}diff --git a/packages/views/locales/ru/chat.json b/packages/views/locales/ru/chat.jsonindex 22ad9f8f1a..0a2ece38a1 100644--- a/packages/views/locales/ru/chat.json+++ b/packages/views/locales/ru/chat.json@@ -279,5 +279,29 @@"archive": "Архивировать чат","unarchive": "Разархивировать чат","delete": "Удалить чат"+ },+ "commit_changes": {+ "heading": "Изменения файлов за этот запуск",+ "files": "Изменённые файлы",+ "incomplete": "Некоторые изменения пропущены из-за ограничения записи.",+ "unavailable": "Не удалось полностью записать diff этого файла. Проверьте его в репозитории.",+ "no_text": "Текстовый diff недоступен.",+ "loading": "Загрузка изменений…",+ "retry": "Загрузить изменения повторно",+ "empty": "За этот запуск изменения не записаны.",+ "worktree": "Рабочее дерево: до и после запуска",+ "commits": "Коммиты",+ "draft": "Сохранённый черновик",+ "recorded_files_one": "{{count}} файл",+ "recorded_files_few": "{{count}} файла",+ "recorded_files_many": "{{count}} файлов",+ "recorded_files_other": "{{count}} файла",+ "incomplete_record": "Неполная запись",+ "repositories_omitted": "Достигнут лимит репозиториев. Некоторые репозитории не записаны.",+ "worktree_unavailable": "Не удалось записать изменения рабочего дерева.",+ "commits_unavailable": "Не удалось записать изменения между коммитами.",+ "draft_unavailable": "Не удалось записать изменения сохранённого черновика.",+ "worktree_unchanged": "Итоговых изменений в рабочем дереве нет.",+ "comparison_unchanged": "В этом сравнении нет изменений файлов."}}diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex f7dc5536f3..32cdb49ec7 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -264,5 +264,26 @@"delete": "删除会话","archive": "归档会话","unarchive": "取消归档"+ },+ "commit_changes": {+ "heading": "本轮文件变化",+ "files": "变化文件",+ "incomplete": "受记录上限限制,仅显示部分差异。",+ "unavailable": "此文件的差异未能完整记录,请在仓库中查看。",+ "no_text": "没有可显示的文本差异。",+ "loading": "正在加载文件变化...",+ "retry": "重新加载差异",+ "empty": "此轮没有记录到文件变化。",+ "worktree": "工作树:运行前后",+ "commits": "提交范围",+ "draft": "已保存草稿",+ "recorded_files_other": "{{count}} 个文件",+ "incomplete_record": "记录不完整",+ "repositories_omitted": "达到仓库记录上限,部分仓库未采集。",+ "worktree_unavailable": "未能采集工作树差异。",+ "commits_unavailable": "未能采集提交范围的差异。",+ "draft_unavailable": "未能采集已保存草稿的差异。",+ "worktree_unchanged": "本轮工作树无净变化。",+ "comparison_unchanged": "此对比范围内没有文件变化。"}}diff --git a/packages/views/locales/zh-Hant/chat.json b/packages/views/locales/zh-Hant/chat.jsonindex 5a85e46c46..17e36b9110 100644--- a/packages/views/locales/zh-Hant/chat.json+++ b/packages/views/locales/zh-Hant/chat.json@@ -264,5 +264,26 @@"delete": "刪除會話","archive": "歸檔會話","unarchive": "取消歸檔"+ },+ "commit_changes": {+ "heading": "本輪檔案變更",+ "files": "變更檔案",+ "incomplete": "受記錄上限限制,僅顯示部分差異。",+ "unavailable": "此檔案的差異未能完整記錄,請在儲存庫中檢視。",+ "no_text": "沒有可顯示的文字差異。",+ "loading": "正在載入檔案變更...",+ "retry": "重新載入差異",+ "empty": "此輪沒有記錄到檔案變更。",+ "worktree": "工作樹:執行前後",+ "commits": "提交範圍",+ "draft": "已儲存草稿",+ "recorded_files_other": "{{count}} 個檔案",+ "incomplete_record": "記錄不完整",+ "repositories_omitted": "已達儲存庫記錄上限,部分儲存庫未擷取。",+ "worktree_unavailable": "無法擷取工作樹差異。",+ "commits_unavailable": "無法擷取提交範圍的差異。",+ "draft_unavailable": "無法擷取已儲存草稿的差異。",+ "worktree_unchanged": "本輪工作樹無淨變更。",+ "comparison_unchanged": "此比較範圍內沒有檔案變更。"}}diff --git a/server/internal/daemon/commit_diff.go b/server/internal/daemon/commit_diff.gonew file mode 100644index 0000000000..5d43d713c2--- /dev/null+++ b/server/internal/daemon/commit_diff.go@@ -0,0 +1,520 @@+package daemon++import (+ "bytes"+ "context"+ "crypto/sha256"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "sort"+ "strconv"+ "strings"+ "sync"+ "sync/atomic"+ "time"++ "github.com/multica-ai/multica/server/pkg/redact"+ "github.com/multica-ai/multica/server/pkg/taskfailure"+)++const commitDiffTool = "multica_commit_diff"+const commitDiffMaxFiles = 50+const commitDiffMaxBytes = 256 << 10+const commitDiffMaxRepos = 8++type commitRepo struct {+ root, base, head, leftoverRef string+ snapshotDir, baseTree, objects string+ scope string+}++// commitDiffRecorder observes only configured directories and authenticated+// checkout results. It never discovers repositories from prompts or tool text.+type commitDiffRecorder struct {+ mu sync.Mutex+ repos map[string]commitRepo+ registeredRepos map[string]struct{}+ registryPath string+ workDir string+ repositoriesOmitted bool+}++func newCommitDiffRecorder() *commitDiffRecorder {+ return &commitDiffRecorder{+ repos: make(map[string]commitRepo),+ registeredRepos: make(map[string]struct{}),+ }+}++// restoreCheckouts retains checkout locations across environment reuse, but+// captures a fresh HEAD for each run rather than carrying the previous baseline.+func (r *commitDiffRecorder) restoreCheckouts(rootDir, workDir string) {+ if rootDir == "" || workDir == "" {+ return+ }+ canonical, err := filepath.EvalSymlinks(workDir)+ if err != nil {+ return+ }+ r.workDir = canonical+ r.registryPath = filepath.Join(rootDir, "commit-repositories.json")+ data, err := os.ReadFile(r.registryPath)+ if err != nil {+ return+ }+ var paths []string+ if json.Unmarshal(data, &paths) != nil {+ return+ }+ var restored []string+ for _, relative := range paths {+ if filepath.IsLocal(relative) {+ path := filepath.Join(canonical, relative)+ r.registeredRepos[path] = struct{}{}+ restored = append(restored, path)+ }+ }+ for index, path := range restored {+ r.record(path)+ if len(r.repos) == commitDiffMaxRepos {+ if index+1 < len(restored) {+ r.mu.Lock()+ r.repositoriesOmitted = true+ r.mu.Unlock()+ }+ break+ }+ }+}++func (r *commitDiffRecorder) persistCheckoutsLocked() error {+ if r.registryPath == "" {+ return nil+ }+ paths := make([]string, 0, len(r.registeredRepos))+ for root := range r.registeredRepos {+ relative, err := filepath.Rel(r.workDir, root)+ if err == nil && filepath.IsLocal(relative) {+ paths = append(paths, relative)+ }+ }+ sort.Strings(paths)+ data, err := json.Marshal(paths)+ if err != nil {+ return err+ }+ file, err := os.CreateTemp(filepath.Dir(r.registryPath), ".commit-repositories-*")+ if err != nil {+ return err+ }+ defer os.Remove(file.Name())+ if _, err = file.Write(data); err != nil {+ file.Close()+ return err+ }+ if err = file.Close(); err != nil {+ return err+ }+ return os.Rename(file.Name(), r.registryPath)+}++func (r *commitDiffRecorder) record(dir string) {+ r.recordBaseline(dir, false)+}++// Replace a restored baseline only after checkout actually recreated or reset+// the directory. A kept checkout may already contain this run's agent work.+func (r *commitDiffRecorder) recordBaseline(dir string, replace bool) {+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ root, err, _ := commitGit(ctx, dir, 4096, "rev-parse", "--show-toplevel")+ if err != nil {+ return+ }+ path := strings.TrimSpace(string(root))+ canonicalDir, err := filepath.EvalSymlinks(dir)+ if err != nil {+ return+ }+ canonicalDir, err = filepath.Abs(canonicalDir)+ if err != nil {+ return+ }+ scope, err := filepath.Rel(path, canonicalDir)+ if err != nil || !filepath.IsLocal(scope) {+ return+ }+ if r.workDir != "" {+ relative, err := filepath.Rel(r.workDir, path)+ if err != nil || !filepath.IsLocal(relative) {+ return+ }+ }+ r.mu.Lock()+ defer r.mu.Unlock()+ previous, exists := r.repos[path]+ if r.repos == nil || (exists && !replace) {+ return+ }+ if _, registered := r.registeredRepos[path]; !registered {+ r.registeredRepos[path] = struct{}{}+ if err := r.persistCheckoutsLocked(); err != nil {+ slog.Warn("persist commit diff checkout registry failed", "error", err)+ }+ }+ if !exists && len(r.repos) >= commitDiffMaxRepos {+ r.repositoriesOmitted = true+ return+ }+ repo := commitRepo{root: path, scope: filepath.ToSlash(scope)}+ head, err, _ := commitGit(ctx, path, 128, "rev-parse", "--verify", "HEAD^{commit}")+ // Keep confirmed repositories even when HEAD cannot supply a baseline.+ if err == nil {+ repo.base = strings.TrimSpace(string(head))+ if repo.openSnapshot(ctx) {+ if tree, err := repo.snapshot(ctx, repo.base); err == nil {+ repo.baseTree = tree+ }+ }+ }+ r.repos[path] = repo+ if previous.snapshotDir != "" {+ _ = os.RemoveAll(previous.snapshotDir)+ }+}+func (r *commitDiffRecorder) close() {+ r.mu.Lock()+ defer r.mu.Unlock()+ for _, repo := range r.repos {+ if repo.snapshotDir != "" {+ _ = os.RemoveAll(repo.snapshotDir)+ }+ }+ r.repos = nil+}++// Snapshots use a disposable index and object database. The repository's+// object database supplies existing objects through an alternate.+func (repo *commitRepo) openSnapshot(ctx context.Context) bool {+ out, err, _ := commitGit(ctx, repo.root, 4096, "rev-parse", "--path-format=absolute", "--git-path", "objects")+ if err != nil {+ return false+ }+ dir, err := os.MkdirTemp("", "multica-run-diff-")+ if err != nil {+ return false+ }+ if err := os.Mkdir(filepath.Join(dir, "objects"), 0700); err != nil {+ _ = os.RemoveAll(dir)+ return false+ }+ repo.objects = strings.TrimSuffix(strings.TrimSuffix(string(out), "\n"), "\r")+ repo.snapshotDir = dir+ return true+}++func (repo commitRepo) snapshotEnv() []string {+ return []string{+ "GIT_INDEX_FILE=" + filepath.Join(repo.snapshotDir, "index"),+ "GIT_OBJECT_DIRECTORY=" + filepath.Join(repo.snapshotDir, "objects"),+ "GIT_ALTERNATE_OBJECT_DIRECTORIES=" + strconv.Quote(repo.objects),+ "GIT_OPTIONAL_LOCKS=0",+ }+}++func (repo commitRepo) snapshot(ctx context.Context, head string) (string, error) {+ env := repo.snapshotEnv()+ if _, err, _ := runDiffGit(ctx, repo.root, env, false, 128, "read-tree", "--reset", head); err != nil {+ return "", err+ }+ // Capture working copies without running repository clean filters such as+ // Git LFS, which can write to their own caches outside the scratch store.+ keys, err, _ := runDiffGit(ctx, repo.root, env, false, 16<<10, "config", "--null", "--name-only", "--get-regexp", `^filter\..*\.(clean|process|required)$`)+ var exitErr *exec.ExitError+ if err != nil && !(errors.As(err, &exitErr) && exitErr.ExitCode() == 1 && len(keys) == 0) {+ return "", err+ }+ var args []string+ for _, key := range strings.Split(strings.TrimSuffix(string(keys), "\x00"), "\x00") {+ if key == "" {+ continue+ }+ value := ""+ if strings.HasSuffix(key, ".required") {+ value = "false"+ }+ args = append(args, "-c", key+"="+value)+ }+ scope := "."+ if repo.scope != "" && repo.scope != "." {+ scope = ":(top,literal)" + repo.scope+ }+ args = append(args, "add", "-A", "--", scope, ":(exclude,glob)**/.agent_context/**", ":(exclude,glob)**/.multica/**")+ if _, err, _ := runDiffGit(ctx, repo.root, env, false, 128, args...); err != nil {+ return "", err+ }+ out, err, _ := runDiffGit(ctx, repo.root, env, false, 128, "write-tree")+ return strings.TrimSpace(string(out)), err+}++func (r *commitDiffRecorder) preserved(root, base string) {+ if base == "" {+ return+ }+ repo := commitRepo{root: root, base: base}+ // Only the starting commit is available here. It may contain clean-filtered+ // blobs, whereas snapshots disable clean/process filters. Without an actual+ // starting snapshot these representations cannot safely be compared.+ r.mu.Lock()+ defer r.mu.Unlock()+ r.repos[root] = repo+}++func (r *commitDiffRecorder) finalized(root, base, head, leftoverRef string) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.repos[root] = commitRepo{root: root, base: base, head: head, leftoverRef: leftoverRef}+}++type commitOutput struct {+ buffer bytes.Buffer+ limit int+ truncated bool+ cancel context.CancelFunc+}++func (b *commitOutput) Write(p []byte) (int, error) {+ n := len(p)+ remaining := b.limit - b.buffer.Len()+ if n > remaining {+ b.buffer.Write(p[:remaining])+ b.truncated = true+ b.cancel()+ } else {+ b.buffer.Write(p)+ }+ return n, nil+}++// Cancel the process when its output exceeds the budget, rather than reading+// an unbounded patch into memory and clipping it afterwards.+func commitGit(parent context.Context, dir string, limit int, args ...string) ([]byte, error, bool) {+ return runDiffGit(parent, dir, nil, true, limit, args...)+}++func runDiffGit(parent context.Context, dir string, env []string, literal bool, limit int, args ...string) ([]byte, error, bool) {+ ctx, cancel := context.WithCancel(parent)+ defer cancel()+ argv := []string{"-C", dir, "-c", "core.quotePath=false", "-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false"}+ if literal {+ argv = append(argv, "--literal-pathspecs")+ }+ if env != nil {+ argv = append(argv, "-c", "core.fsmonitor=false", "-c", "core.splitIndex=false", "-c", "core.untrackedCache=false", "-c", "core.hooksPath="+os.DevNull)+ }+ cmd := exec.CommandContext(ctx, "git", append(argv, args...)...)+ cmd.Env = append(os.Environ(), env...)+ out := &commitOutput{limit: limit, cancel: cancel}+ cmd.Stdout = out+ cmd.Stderr = io.Discard+ err := cmd.Run()+ return out.buffer.Bytes(), err, out.truncated+}++// Git's binary marker is an unprefixed metadata line. Hunk contents always+// have a space, + or - prefix, even when their text mentions "Binary files".+func isBinaryCommitPatch(patch []byte) bool {+ for _, line := range bytes.Split(patch, []byte{'\n'}) {+ if bytes.HasPrefix(line, []byte("Binary files ")) && bytes.HasSuffix(line, []byte(" differ")) {+ return true+ }+ }+ return false+}++const (+ diffCommits = "commits"+ diffWorktree = "worktree"+ diffDraft = "draft"+)++func repositoryDiff(repo commitRepo, kind string) map[string]any {+ identity := sha256.Sum256([]byte(repo.root))+ result := map[string]any{+ "repository": filepath.Base(repo.root), "repository_id": fmt.Sprintf("%x", identity[:8]),+ "kind": kind, "worktree": kind == diffWorktree, "changes": []map[string]any{},+ }+ if repo.base != "" {+ result["base"] = repo.base+ }+ if repo.head != "" {+ result["head"] = repo.head+ }+ return result+}++func unavailableDiff(repo commitRepo, kind string) map[string]any {+ result := repositoryDiff(repo, kind)+ result["unavailable"] = true+ return result+}++// A successful comparison can legitimately have zero changed files. Keep+// that result separate from an unavailable comparison and from other kinds.+func collectDiff(ctx context.Context, repo commitRepo, kind, from, to string, env []string, budget *int) map[string]any {+ if from == to {+ return repositoryDiff(repo, kind)+ }++ scope := repo.scope+ if scope == "" {+ scope = "."+ }+ raw, err, overflow := runDiffGit(ctx, repo.root, env, true, 64<<10, "diff", "--name-status", "-z", "--no-renames", from, to, "--", scope)+ if err != nil && !overflow {+ return unavailableDiff(repo, kind)+ }+ changes := make([]map[string]any, 0)+ // Exclude a final partial path if Git was stopped by the output limit.+ complete := bytes.LastIndexByte(raw, 0) + 1+ fields := bytes.Split(raw[:complete], []byte{0})+ truncated := overflow+ for i := 0; i+1 < len(fields) && len(fields[i]) > 0; i += 2 {+ if len(changes) == commitDiffMaxFiles {+ truncated = true+ break+ }+ status, path := string(fields[i]), string(fields[i+1])+ if path == "" {+ break+ }+ kind := "modify"+ if status == "A" {+ kind = "add"+ } else if status == "D" {+ kind = "delete"+ }+ change := map[string]any{"path": path, "kind": kind}+ limit := min(*budget, 64<<10)+ if limit <= 0 {+ change["truncated"] = true+ truncated = true+ } else {+ patch, patchErr, cut := runDiffGit(ctx, repo.root, env, true, limit, "diff", "--no-ext-diff", "--no-textconv", "--no-color", "--no-renames", "--unified=3", from, to, "--", path)+ *budget -= len(patch)+ switch {+ case cut:+ change["truncated"] = true+ truncated = true+ case patchErr != nil:+ change["unavailable"] = true+ case isBinaryCommitPatch(patch):+ change["binary"] = true+ default:+ // Oversized patches are discarded above. Scrub complete patch+ // bodies here so older servers never receive raw credentials.+ change["diff"] = redact.Text(string(patch))+ }+ }+ changes = append(changes, change)+ }+ result := repositoryDiff(repo, kind)+ result["changes"] = changes+ result["truncated"] = truncated+ return result+}++func collectDraftDiff(ctx context.Context, repo commitRepo, budget *int) map[string]any {+ delivered := repo.head+ repo.base = delivered+ repo.head = ""+ out, err, _ := commitGit(ctx, repo.root, 128, "rev-parse", "--verify", "--end-of-options", repo.leftoverRef+"^{commit}")+ if err != nil {+ return unavailableDiff(repo, diffDraft)+ }+ repo.head = strings.TrimSpace(string(out))+ return collectDiff(ctx, repo, diffDraft, delivered, repo.head, nil, budget)+}++func collectWorktreeDiff(ctx context.Context, repo commitRepo, budget *int) map[string]any {+ if repo.baseTree == "" || repo.head == "" {+ return unavailableDiff(repo, diffWorktree)+ }+ snapshotCtx, cancel := context.WithTimeout(ctx, 2*time.Second)+ tree, err := repo.snapshot(snapshotCtx, repo.head)+ cancel()+ if err != nil || tree == "" {+ return unavailableDiff(repo, diffWorktree)+ }+ return collectDiff(ctx, repo, diffWorktree, repo.baseTree, tree, repo.snapshotEnv(), budget)+}++func collectRunDiffs(ctx context.Context, repos []commitRepo, includeWorktree bool) []map[string]any {+ budget := commitDiffMaxBytes+ var results []map[string]any+ var worktrees []commitRepo+ for _, repo := range repos {+ finalized := repo.head != ""+ if !finalized {+ out, err, _ := commitGit(ctx, repo.root, 128, "rev-parse", "--verify", "HEAD^{commit}")+ if err == nil {+ repo.head = strings.TrimSpace(string(out))+ }+ worktrees = append(worktrees, repo)+ }+ if repo.base == "" || repo.head == "" {+ results = append(results, unavailableDiff(repo, diffCommits))+ } else if repo.base != repo.head {+ results = append(results, collectDiff(ctx, repo, diffCommits, repo.base, repo.head, nil, &budget))+ }+ if repo.leftoverRef != "" {+ results = append(results, collectDraftDiff(ctx, repo, &budget))+ }+ }+ // Preserve the commit/draft records within the shared budget even when+ // capturing working trees takes the rest of the collection deadline.+ for _, repo := range worktrees {+ if !includeWorktree {+ repo.baseTree = ""+ }+ results = append(results, collectWorktreeDiff(ctx, repo, &budget))+ }+ return results+}++func (d *Daemon) reportCommitDiff(taskID string, r *commitDiffRecorder, seq *atomic.Int32, logger *slog.Logger, includeWorktree bool, failureReason string) {+ r.mu.Lock()+ repos := make([]commitRepo, 0, len(r.repos))+ for _, repo := range r.repos {+ repos = append(repos, repo)+ }+ repositoriesOmitted := r.repositoriesOmitted+ r.mu.Unlock()+ sort.Slice(repos, func(i, j int) bool { return repos[i].root < repos[j].root })+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ // A provider may still be writing to a checkout after unconfirmed cleanup.+ inputs := collectRunDiffs(ctx, repos, includeWorktree && failureReason != taskfailure.ReasonProcessCleanupUnconfirmed.String())+ if len(inputs) == 0 {+ return+ }+ messages := make([]TaskMessageData, 0, len(inputs))+ for _, input := range inputs {+ if repositoriesOmitted {+ input["repositories_omitted"] = true+ }+ messages = append(messages, TaskMessageData{Seq: int(seq.Add(1)), Type: "tool_use", Tool: commitDiffTool, Input: input, CreatedAt: time.Now().UTC()})+ }+ // The collector can exhaust its deadline and still have status records to send.+ reportCtx, stopReport := context.WithTimeout(context.Background(), 3*time.Second)+ defer stopReport()+ if err := d.client.ReportTaskMessages(reportCtx, taskID, messages); err != nil {+ logger.Warn("report run diff failed", "error", err)+ }+}diff --git a/server/internal/daemon/commit_diff_acceptance_test.go b/server/internal/daemon/commit_diff_acceptance_test.gonew file mode 100644index 0000000000..176da24374--- /dev/null+++ b/server/internal/daemon/commit_diff_acceptance_test.go@@ -0,0 +1,292 @@+package daemon++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "testing"+ "time"+)++// Drive actual task preparation, the provider adapter, Git finalization and+// message reporting. The CLI is a fixture: no installed agent or account runs.+func TestCommitDiffAcceptanceTwoTurnsAndFailure(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell CLI fixture is POSIX-only")+ }+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ repo := commitTestRepo(t)+ fakeBin := filepath.Join(t.TempDir(), "claude")+ writeTestExecutable(t, fakeBin, []byte(`#!/bin/sh+if [ "$1" = "--version" ]; then echo 'fixture 1.0.0'; exit 0; fi+IFS= read -r _+if [ "$FIXTURE_TURN" = 1 ]; then printf 'version one\n' > feature.txt; fi+if [ "$FIXTURE_TURN" = 2 ]; then printf 'version two\n' > feature.txt; fi+if [ "$FIXTURE_TURN" = 4 ]; then printf 'updated draft\n' > file.txt; printf 'new draft\n' > scratch.txt; printf 'ignored draft\n' > ignored-draft.txt; fi+if [ "$FIXTURE_TURN" = 7 ]; then+ printf 'inside change\n' > inside.txt+ printf 'outside change\n' > ../outside.txt+ git config commit.gpgsign true+ git config gpg.program "$FIXTURE_MISSING_GPG"+fi+if [ "$FIXTURE_TURN" = 5 ] || [ "$FIXTURE_TURN" = 6 ]; then+ if [ "$FIXTURE_TURN" = 5 ]; then+ printf 'committed version\n' > file.txt+ git add -- file.txt || exit 2+ else+ printf 'delivered result\n' > delivered.txt+ git add -- delivered.txt || exit 2+ fi+ git -c core.hooksPath=/dev/null -c commit.gpgsign=false -c user.name=Fixture -c [email protected] commit -m 'fixture delivery' >/dev/null || exit 2+ if [ "$FIXTURE_TURN" = 5 ]; then+ printf 'updated draft\n' > file.txt+ else+ printf 'saved draft\n' > draft.txt+ fi+fi+if [ "$FIXTURE_TURN" = 3 ]; then+ printf 'partial result\n' > partial.txt+ git add -- partial.txt+ git -c core.hooksPath=/dev/null -c commit.gpgsign=false -c user.name=Fixture -c [email protected] commit -m 'partial work' >/dev/null || exit 2+fi+printf '%s\n' '{"type":"system","session_id":"session-commit-fixture"}'+if [ "$FIXTURE_TURN" = 3 ]; then+ printf '%s\n' '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"fixture failure after commit","errors":["fixture failure after commit"]}'+ exit 1+fi+printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"session-commit-fixture","result":"done"}'+`))+ var mu sync.Mutex+ reports := make(map[string][]TaskMessageData)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if strings.HasSuffix(r.URL.Path, "/messages") {+ var body struct {+ Messages []TaskMessageData `json:"messages"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ parts := strings.Split(r.URL.Path, "/")+ taskID := parts[len(parts)-2]+ mu.Lock()+ for _, m := range body.Messages {+ if m.Tool == commitDiffTool {+ reports[taskID] = append(reports[taskID], m)+ }+ }+ mu.Unlock()+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{}`))+ }))+ defer srv.Close()+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ d := &Daemon{client: NewClient(srv.URL), logger: logger, localPathLocks: NewLocalPathLocker(), workspaces: make(map[string]*workspaceState), activeEnvRoots: make(map[string]int), cfg: Config{DaemonID: "commit-fixture", WorkspacesRoot: t.TempDir(), AgentTimeout: 5 * time.Second, ServerBaseURL: srv.URL, Agents: map[string]AgentEntry{"claude": {Path: fakeBin}}}}+ ref, _ := json.Marshal(localDirectoryRef{LocalPath: repo, DaemonID: d.cfg.DaemonID, ExecutionMode: localDirectoryModeWorktree})+ task := Task{WorkspaceID: "ws-commit", IssueID: "issue-commit", IssueIdentifier: "DEMO-42", RuntimeID: "runtime-commit", AgentID: "agent-commit", AuthToken: "mat_fixture_token", ProjectResources: []ProjectResourceData{{ID: "repo-commit", ResourceType: localDirectoryResourceType, ResourceRef: ref}}}+ type acceptanceRun struct {+ Turn int `json:"turn"`+ Status string `json:"status"`+ Messages []TaskMessageData `json:"messages"`+ }+ runs := make([]acceptanceRun, 0, 3)+ for i := 1; i <= 3; i++ {+ task.ID = map[int]string{1: "commit-turn-1", 2: "commit-turn-2", 3: "commit-turn-3"}[i]+ task.Agent = &AgentData{ID: task.AgentID, Name: "Fixture", CustomEnv: map[string]string{"HOME": home, "FIXTURE_TURN": string(rune('0' + i))}}+ result, err := d.runTask(context.Background(), task, "claude", 0, logger)+ if i < 3 && (err != nil || result.Status != "completed") {+ t.Fatalf("turn %d: status=%s err=%v", i, result.Status, err)+ }+ if i == 3 && err == nil && result.Status == "completed" {+ t.Fatal("failure fixture was reported as completed")+ }+ mu.Lock()+ messages := append([]TaskMessageData(nil), reports[task.ID]...)+ mu.Unlock()+ if len(messages) != 1 {+ t.Fatalf("turn %d recorded %d ranges; status=%s err=%v", i, len(messages), result.Status, err)+ }+ status := "completed"+ if i == 3 {+ status = "failed"+ }+ runs = append(runs, acceptanceRun{Turn: i, Status: status, Messages: messages})+ task.PriorWorkDir = result.WorkDir+ task.PriorSessionID = result.SessionID+ }+ for i, run := range runs {+ raw, _ := json.Marshal(run.Messages[0].Input)+ expected := []string{"+version one", "-version one", "+partial result"}[i]+ if !strings.Contains(string(raw), expected) {+ t.Fatalf("turn %d missing its change %s", i+1, expected)+ }+ if i == 1 && (!strings.Contains(string(raw), "+version two") || strings.Contains(string(raw), "+version one")) {+ t.Fatal("second turn repeated first turn's patch")+ }+ if i > 0 && run.Messages[0].Input["base"] != runs[i-1].Messages[0].Input["head"] {+ t.Fatalf("turn %d is not based on previous delivery", i+1)+ }+ }+ t.Run("in place without a commit", func(t *testing.T) {+ repo := commitTestRepo(t)+ commitTestWrite(t, repo, "file.txt", "preexisting draft\n")+ commitTestGit(t, repo, "add", "--", "file.txt")+ commitTestWrite(t, repo, "old-draft.txt", "untouched draft\n")+ commitTestWrite(t, repo, ".git/info/exclude", "ignored-draft.txt\n")+ head := commitTestGit(t, repo, "rev-parse", "HEAD")+ index := commitTestGit(t, repo, "diff", "--cached")+ ref, err := json.Marshal(localDirectoryRef{LocalPath: repo, DaemonID: d.cfg.DaemonID, ExecutionMode: localDirectoryModeInPlace})+ if err != nil {+ t.Fatal(err)+ }+ task.ID = "file-changes-in-place"+ task.PriorWorkDir, task.PriorSessionID = "", ""+ task.ProjectResources[0].ResourceRef = ref+ task.Agent.CustomEnv["FIXTURE_TURN"] = "4"+ result, err := d.runTask(context.Background(), task, "claude", 0, logger)+ if err != nil || result.Status != "completed" {+ t.Fatalf("in place: status=%s err=%v", result.Status, err)+ }+ mu.Lock()+ messages := append([]TaskMessageData(nil), reports[task.ID]...)+ mu.Unlock()+ if len(messages) != 1 {+ t.Fatalf("expected one worktree diff, got %d", len(messages))+ }+ input := messages[0].Input+ if input["kind"] != diffWorktree || input["base"] != head || input["head"] != head {+ t.Fatalf("expected worktree diff without a commit, got %v", input)+ }+ raw, err := json.Marshal(input["changes"])+ if err != nil {+ t.Fatal(err)+ }+ for _, want := range []string{"-preexisting draft", "+updated draft", "scratch.txt", "+new draft"} {+ if !strings.Contains(string(raw), want) {+ t.Fatalf("missing %q in %s", want, raw)+ }+ }+ for _, excluded := range []string{"old-draft.txt", "ignored-draft.txt", "-original", "CLAUDE.md", ".multica"} {+ if strings.Contains(string(raw), excluded) {+ t.Fatalf("unexpected %q in %s", excluded, raw)+ }+ }+ if commitTestGit(t, repo, "rev-parse", "HEAD") != head || commitTestGit(t, repo, "diff", "--cached") != index {+ t.Fatal("recording changed the repository HEAD or staged files")+ }+ task.ID = "commit-then-restore-file"+ task.Agent.CustomEnv["FIXTURE_TURN"] = "5"+ result, err = d.runTask(context.Background(), task, "claude", 0, logger)+ if err != nil || result.Status != "completed" {+ t.Fatalf("commit then restore: status=%s err=%v", result.Status, err)+ }+ mu.Lock()+ messages = append([]TaskMessageData(nil), reports[task.ID]...)+ mu.Unlock()+ if len(messages) != 2 || messages[0].Input["kind"] != diffCommits || messages[1].Input["kind"] != diffWorktree {+ t.Fatalf("expected both comparisons, got %v", messages)+ }+ commits, _ := json.Marshal(messages[0].Input["changes"])+ if !strings.Contains(string(commits), "+committed version") {+ t.Fatalf("working-tree comparison hid committed content: %s", commits)+ }+ if messages[1].Input["unavailable"] == true || len(messages[1].Input["changes"].([]any)) != 0 {+ t.Fatalf("expected an empty net working-tree diff, got %v", messages[1].Input)+ }+ })+ t.Run("delivered commit and saved draft", func(t *testing.T) {+ repo := commitTestRepo(t)+ ref, err := json.Marshal(localDirectoryRef{LocalPath: repo, DaemonID: d.cfg.DaemonID, ExecutionMode: localDirectoryModeWorktree})+ if err != nil {+ t.Fatal(err)+ }+ task.ID, task.IssueID = "commit-with-saved-draft", "issue-with-draft"+ task.PriorWorkDir, task.PriorSessionID = "", ""+ task.ProjectResources[0].ResourceRef = ref+ task.Agent.CustomEnv["FIXTURE_TURN"] = "6"+ result, err := d.runTask(context.Background(), task, "claude", 0, logger)+ if err != nil || result.Status != "completed" {+ t.Fatalf("worktree delivery: status=%s err=%v", result.Status, err)+ }+ mu.Lock()+ messages := append([]TaskMessageData(nil), reports[task.ID]...)+ mu.Unlock()+ if len(messages) != 2 || messages[0].Input["kind"] != diffCommits || messages[1].Input["kind"] != diffDraft {+ t.Fatalf("expected separate commit and draft, got %v", messages)+ }+ delivered, draft := messages[0].Input, messages[1].Input+ deliveredChanges, _ := json.Marshal(delivered["changes"])+ draftChanges, _ := json.Marshal(draft["changes"])+ if delivered["head"] != draft["base"] || !strings.Contains(string(deliveredChanges), "+delivered result") ||+ strings.Contains(string(deliveredChanges), "draft.txt") || !strings.Contains(string(draftChanges), "+saved draft") ||+ strings.Contains(string(draftChanges), "delivered.txt") {+ t.Fatalf("incorrect delivery or draft range: %s / %s", deliveredChanges, draftChanges)+ }++ })+ t.Run("preserved worktree with a subdirectory resource", func(t *testing.T) {+ repo := commitTestRepo(t)+ subdir := filepath.Join(repo, "sub")+ if err := os.Mkdir(subdir, 0700); err != nil {+ t.Fatal(err)+ }+ commitTestWrite(t, repo, "sub/inside.txt", "inside before\n")+ commitTestWrite(t, repo, "outside.txt", "outside before\n")+ commitTestCommit(t, repo)+ ref, err := json.Marshal(localDirectoryRef{LocalPath: subdir, DaemonID: d.cfg.DaemonID, ExecutionMode: localDirectoryModeWorktree})+ if err != nil {+ t.Fatal(err)+ }+ task.ID, task.IssueID = "preserved-subdirectory", "issue-subdirectory"+ task.PriorWorkDir, task.PriorSessionID = "", ""+ task.ProjectResources[0].ResourceRef = ref+ task.Agent.CustomEnv["FIXTURE_TURN"] = "7"+ task.Agent.CustomEnv["FIXTURE_MISSING_GPG"] = filepath.Join(t.TempDir(), "missing-gpg")+ result, err := d.runTask(context.Background(), task, "claude", 0, logger)+ if err == nil {+ t.Fatal("expected finalization to fail when signing is unavailable")+ }+ if _, statErr := os.Stat(filepath.Join(result.WorkDir, "inside.txt")); statErr != nil {+ t.Fatalf("worktree was not preserved: %v", statErr)+ }+ mu.Lock()+ messages := append([]TaskMessageData(nil), reports[task.ID]...)+ mu.Unlock()+ if len(messages) != 1 || messages[0].Input["kind"] != diffWorktree || messages[0].Input["unavailable"] != true {+ t.Fatalf("expected an unavailable preserved worktree comparison, got %v", messages)+ }+ if len(messages[0].Input["changes"].([]any)) != 0 {+ t.Fatal("preserved worktree was compared without a starting snapshot")+ }+ for path, expected := range map[string]string{+ filepath.Join(result.WorkDir, "inside.txt"): "inside change\n",+ filepath.Join(result.WorkDir, "..", "outside.txt"): "outside change\n",+ } {+ content, err := os.ReadFile(path)+ if err != nil || string(content) != expected {+ t.Fatalf("worktree file was not preserved at %s: %v", path, err)+ }+ }+ })+ // Optional local review artifact contains only the public-shaped commit+ // payloads, not prompts, credentials, absolute workdirs or provider logs.+ if output := os.Getenv("MULTICA_COMMIT_ACCEPTANCE_OUTPUT"); output != "" {+ data, err := json.MarshalIndent(map[string]any{"runs": runs}, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(output, data, 0600); err != nil {+ t.Fatal(err)+ }+ }+}diff --git a/server/internal/daemon/commit_diff_checkout_test.go b/server/internal/daemon/commit_diff_checkout_test.gonew file mode 100644index 0000000000..dcd37d42df--- /dev/null+++ b/server/internal/daemon/commit_diff_checkout_test.go@@ -0,0 +1,128 @@+package daemon++import (+ "context"+ "encoding/json"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/daemon/repocache"+)++func TestCommitDiffCheckoutBaseline(t *testing.T) {+ for _, isolated := range []bool{false, true} {+ t.Run(map[bool]string{false: "linked", true: "isolated"}[isolated], func(t *testing.T) {+ source := commitTestRepo(t)+ cache := repocache.New(t.TempDir(), slog.Default())+ const workspace = "ws-diff-checkout"+ if err := cache.Sync(workspace, []repocache.RepoInfo{{URL: source}}); err != nil {+ t.Fatal(err)+ }+ root := t.TempDir()+ workDir := filepath.Join(root, "workdir")+ if err := os.Mkdir(workDir, 0700); err != nil {+ t.Fatal(err)+ }+ initial, err := cache.CreateWorktree(repocache.WorktreeParams{+ WorkspaceID: workspace, RepoURL: source, WorkDir: workDir,+ AgentName: "Test Agent", TaskID: "previous-task", IsolatedGitMetadata: isolated,+ })+ if err != nil {+ t.Fatal(err)+ }+ first := newCommitDiffRecorder()+ first.restoreCheckouts(root, workDir)+ first.record(initial.Path)+ first.close()+ recorder := newCommitDiffRecorder()+ t.Cleanup(recorder.close)+ recorder.restoreCheckouts(root, workDir)+ oldHead := commitTestGit(t, initial.Path, "rev-parse", "HEAD")+ commitTestWrite(t, source, "upstream.txt", "upstream change\n")+ newHead := commitTestCommit(t, source)+ if err := cache.Sync(workspace, []repocache.RepoInfo{{URL: source}}); err != nil {+ t.Fatal(err)+ }+ d := newRepoCheckoutTestDaemon(t, workspace, source, workDir, cache)+ d.registerActiveRepoCheckoutTask("mat_repo_checkout_test", activeRepoCheckoutTask{+ WorkspaceID: workspace, TaskID: "task-1", AgentID: "agent-1",+ AgentName: "Test Agent", WorkDir: workDir, CommitDiff: recorder,+ })+ checkout := func() repocache.WorktreeResult {+ t.Helper()+ mode := ""+ if isolated {+ mode = repoCheckoutModeIsolated+ }+ body, err := json.Marshal(repoCheckoutRequest{+ URL: source, WorkspaceID: workspace, TaskID: "task-1",+ WorkDir: workDir, CheckoutMode: mode,+ })+ if err != nil {+ t.Fatal(err)+ }+ response := httptest.NewRecorder()+ d.repoCheckoutHandler().ServeHTTP(response, authorizedRepoCheckoutRequest(strings.NewReader(string(body))))+ if response.Code != http.StatusOK {+ t.Fatalf("checkout: status=%d body=%s", response.Code, response.Body.String())+ }+ var result repocache.WorktreeResult+ if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {+ t.Fatal(err)+ }+ return result+ }+ collect := func() []map[string]any {+ t.Helper()+ var repos []commitRepo+ for _, repo := range recorder.repos {+ repos = append(repos, repo)+ }+ return collectRunDiffs(context.Background(), repos, true)+ }+ switched := checkout()+ if switched.Kept != "" || oldHead == newHead || commitTestGit(t, switched.Path, "rev-parse", "HEAD") != newHead {+ t.Fatal("fixture did not switch a clean checkout to the updated upstream")+ }+ diffs := collect()+ if len(diffs) != 1 || diffs[0]["kind"] != diffWorktree || diffs[0]["unavailable"] == true ||+ len(diffs[0]["changes"].([]map[string]any)) != 0 {+ t.Fatalf("checkout-only upstream changes were attributed to this run: %v", diffs)+ }+ commitTestWrite(t, switched.Path, "agent.txt", "agent commit\n")+ commitTestGit(t, switched.Path, "add", "-A")+ commitTestGit(t, switched.Path, "-c", "user.name=Test", "-c", "[email protected]", "-c", "commit.gpgsign=false", "commit", "-m", "agent work")+ commitTestWrite(t, switched.Path, "draft.txt", "agent draft\n")+ kept := checkout()+ if kept.Kept != repocache.KeptTaskBranch {+ t.Fatalf("expected same-task checkout to be kept, got %q", kept.Kept)+ }+ diffs = collect()+ if len(diffs) != 2 || diffs[0]["base"] != newHead {+ t.Fatalf("repeated checkout lost the commit baseline: %v", diffs)+ }+ raw, _ := json.Marshal(diffs)+ if !strings.Contains(string(raw), "+agent commit") || !strings.Contains(string(raw), "+agent draft") ||+ strings.Contains(string(raw), "upstream.txt") {+ t.Fatal("kept checkout lost agent work or included upstream work")+ }+ // A different task must also preserve the baseline when local work is kept.+ d.registerActiveRepoCheckoutTask("mat_repo_checkout_test", activeRepoCheckoutTask{+ WorkspaceID: workspace, TaskID: "task-1", AgentName: "Other Agent",+ WorkDir: workDir, CommitDiff: recorder,+ })+ if kept = checkout(); kept.Kept != repocache.KeptLocalWork {+ t.Fatalf("expected local work to be kept, got %q", kept.Kept)+ }+ after, _ := json.Marshal(collect())+ if string(after) != string(raw) {+ t.Fatal("kept local work changed the run comparisons")+ }+ })+ }+}diff --git a/server/internal/daemon/commit_diff_test.go b/server/internal/daemon/commit_diff_test.gonew file mode 100644index 0000000000..dffafbd885--- /dev/null+++ b/server/internal/daemon/commit_diff_test.go@@ -0,0 +1,626 @@+package daemon++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "sync/atomic"+ "testing"++ "github.com/multica-ai/multica/server/pkg/taskfailure"+)++func commitTestGit(t *testing.T, dir string, args ...string) string {+ t.Helper()+ cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)+ cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_COUNT=0")+ out, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("git %v: %v: %s", args, err, out)+ }+ return strings.TrimSpace(string(out))+}+func commitTestRepo(t *testing.T) string {+ t.Helper()+ dir := t.TempDir()+ commitTestGit(t, dir, "init", "-b", "main")+ for k, v := range map[string]string{"user.name": "Test", "user.email": "[email protected]", "commit.gpgsign": "false", "gc.auto": "0", "maintenance.auto": "false"} {+ commitTestGit(t, dir, "config", k, v)+ }+ commitTestWrite(t, dir, "file.txt", "original\n")+ commitTestCommit(t, dir)+ return dir+}+func commitTestWrite(t *testing.T, dir, path, content string) {+ t.Helper()+ if err := os.WriteFile(filepath.Join(dir, path), []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+}+func commitTestCommit(t *testing.T, dir string) string {+ t.Helper()+ commitTestGit(t, dir, "add", "-A")+ commitTestGit(t, dir, "commit", "-m", "test")+ return commitTestGit(t, dir, "rev-parse", "HEAD")+}+func TestCommitDiffCapturesOnlyThisRunsFileChanges(t *testing.T) {+ dir := commitTestRepo(t)+ r := newCommitDiffRecorder()+ t.Cleanup(r.close)+ r.record(dir)+ commitTestWrite(t, dir, "committed.txt", "committed change\n")+ head := commitTestCommit(t, dir)+ commitTestWrite(t, dir, "file.txt", "uncommitted change\n")+ commitTestWrite(t, dir, "not-committed.txt", "new file\n")+ before := commitTestGit(t, dir, "status", "--porcelain")+ var repo commitRepo+ for _, v := range r.repos {+ repo = v+ }+ diffs := collectRunDiffs(context.Background(), []commitRepo{repo}, true)+ if len(diffs) != 2 || diffs[0]["kind"] != diffCommits || diffs[1]["kind"] != diffWorktree {+ t.Fatalf("expected independent commit and working-tree comparisons, got %v", diffs)+ }+ commits, _ := json.Marshal(diffs[0])+ worktree, _ := json.Marshal(diffs[1])+ if diffs[0]["head"] != head || strings.Contains(string(commits), "not-committed.txt") ||+ !strings.Contains(string(worktree), "+uncommitted change") || !strings.Contains(string(worktree), "not-committed.txt") ||+ !strings.Contains(string(worktree), "+committed change") {+ t.Fatalf("unexpected comparisons: %s / %s", commits, worktree)+ }+ if after := commitTestGit(t, dir, "status", "--porcelain"); after != before {+ t.Fatalf("collector mutated repository: %q -> %q", before, after)+ }+ next := newCommitDiffRecorder()+ t.Cleanup(next.close)+ next.record(dir)+ for _, v := range next.repos {+ diffs := collectRunDiffs(context.Background(), []commitRepo{v}, true)+ if len(diffs) != 1 || diffs[0]["kind"] != diffWorktree || diffs[0]["unavailable"] == true ||+ len(diffs[0]["changes"].([]map[string]any)) != 0 {+ t.Fatalf("unchanged drafts must not reappear in a later run: %v", diffs)+ }+ }+}+func TestCommitDiffScopesInPlaceCaptureToConfiguredDirectory(t *testing.T) {+ for _, scope := range []string{"apps/web", "apps/[web]*"} {+ t.Run(scope, func(t *testing.T) {+ dir := commitTestRepo(t)+ if err := os.MkdirAll(filepath.Join(dir, scope), 0700); err != nil {+ t.Fatal(err)+ }+ inside := scope + "/file.txt"+ commitTestWrite(t, dir, inside, "initial\n")+ commitTestCommit(t, dir)+ commitTestWrite(t, dir, "outside-new.txt", "outside baseline secret\n")+ commitTestWrite(t, dir, "file.txt", "outside existing secret\n")+ r := newCommitDiffRecorder()+ t.Cleanup(r.close)+ r.record(filepath.Join(dir, scope))+ var repo commitRepo+ for _, value := range r.repos {+ repo = value+ }+ if repo.baseTree == "" {+ t.Fatal("missing scoped baseline")+ }+ baseline, err, _ := runDiffGit(context.Background(), repo.root, repo.snapshotEnv(), true, 4096, "ls-tree", "-r", "--name-only", repo.baseTree)+ if err != nil || strings.Contains(string(baseline), "outside-new.txt") {+ t.Fatalf("snapshot captured outside untracked file: %s, %v", baseline, err)+ }+ outside, err, _ := runDiffGit(context.Background(), repo.root, repo.snapshotEnv(), true, 4096, "show", repo.baseTree+":file.txt")+ if err != nil || string(outside) != "original\n" {+ t.Fatalf("snapshot captured outside working content: %s, %v", outside, err)+ }+ commitTestWrite(t, dir, inside, "inside committed\n")+ commitTestCommit(t, dir)+ commitTestWrite(t, dir, inside, "inside working\n")+ commitTestWrite(t, dir, scope+"/new.txt", "inside new\n")+ commitTestWrite(t, dir, "file.txt", "outside working secret\n")+ commitTestWrite(t, dir, "another-outside.txt", "outside new secret\n")+ before := commitTestGit(t, dir, "status", "--porcelain")+ diffs := collectRunDiffs(context.Background(), []commitRepo{repo}, true)+ if len(diffs) != 2 {+ t.Fatalf("expected commit and working-tree comparisons, got %v", diffs)+ }+ commits, _ := json.Marshal(diffs[0])+ worktree, _ := json.Marshal(diffs[1])+ if !strings.Contains(string(commits), "+inside committed") ||+ !strings.Contains(string(worktree), "+inside working") || !strings.Contains(string(worktree), "+inside new") {+ t.Fatalf("missing in-scope patches: %s / %s", commits, worktree)+ }+ for _, diff := range diffs {+ changes, ok := diff["changes"].([]map[string]any)+ if !ok || len(changes) == 0 || diff["unavailable"] == true {+ t.Fatalf("missing in-scope changes: %v", diff)+ }+ for _, change := range changes {+ if !strings.HasPrefix(change["path"].(string), scope+"/") || strings.Contains(fmt.Sprint(change["diff"]), "outside") {+ t.Fatalf("out-of-scope content captured: %v", change)+ }+ }+ }+ if after := commitTestGit(t, dir, "status", "--porcelain"); after != before {+ t.Fatalf("collector mutated repository: %q -> %q", before, after)+ }+ })+ }+}++func TestCommitDiffUsesFinalizationReceiptAfterWorktreeRemoval(t *testing.T) {+ dir := commitTestRepo(t)+ base := commitTestGit(t, dir, "rev-parse", "HEAD")+ commitTestWrite(t, dir, "file.txt", "first turn\n")+ head := commitTestCommit(t, dir)+ commitTestWrite(t, dir, "file.txt", "later turn\n")+ commitTestCommit(t, dir)+ diffs := collectRunDiffs(context.Background(), []commitRepo{{root: dir, base: base, head: head}}, true)+ if len(diffs) != 1 || diffs[0]["kind"] != diffCommits {+ t.Fatalf("expected the exact delivered range: %v", diffs)+ }+ got := diffs[0]+ raw, _ := json.Marshal(got)+ if strings.Contains(string(raw), "later turn") || !strings.Contains(string(raw), "first turn") {+ t.Fatalf("read mutable HEAD instead of receipt: %s", raw)+ }+}+func TestCommitDiffHandlesPathsAndBinaryFiles(t *testing.T) {+ dir := commitTestRepo(t)+ base := commitTestGit(t, dir, "rev-parse", "HEAD")+ name := "中文 name[1].txt"+ commitTestWrite(t, dir, name, "hello\n")+ commitTestWrite(t, dir, "binary.dat", "\x00\x01\x02")+ commitTestCommit(t, dir)+ budget := commitDiffMaxBytes+ got := collectDiff(context.Background(), commitRepo{root: dir, base: base}, diffCommits, base, "HEAD", nil, &budget)+ files := got["changes"].([]map[string]any)+ found, binary := false, false+ for _, file := range files {+ if file["path"] == name {+ found = strings.Contains(file["diff"].(string), "hello")+ }+ if file["path"] == "binary.dat" {+ binary = file["binary"] == true+ }+ }+ if !found || !binary {+ t.Fatalf("lost paths or binary state: %v", files)+ }+}+func TestCommitDiffStopsOversizedPatches(t *testing.T) {+ dir := commitTestRepo(t)+ base := commitTestGit(t, dir, "rev-parse", "HEAD")+ commitTestWrite(t, dir, "file.txt", strings.Repeat("changed line\n", 20000))+ commitTestCommit(t, dir)+ budget := 2048+ got := collectDiff(context.Background(), commitRepo{root: dir, base: base}, diffCommits, base, "HEAD", nil, &budget)+ file := got["changes"].([]map[string]any)[0]+ if got["truncated"] != true || file["truncated"] != true || file["diff"] != nil || budget < 0 {+ t.Fatalf("unbounded/partial patch: truncated=%v file-truncated=%v patch-bytes=%d budget=%d", got["truncated"], file["truncated"], len(fmt.Sprint(file["diff"])), budget)+ }+}++func TestCommitDiffReportsThroughTaskMessages(t *testing.T) {+ dir := commitTestRepo(t)+ r := newCommitDiffRecorder()+ t.Cleanup(r.close)+ r.record(dir)+ commitTestWrite(t, dir, "added.txt", "new\n")+ if err := os.Remove(filepath.Join(dir, "file.txt")); err != nil {+ t.Fatal(err)+ }+ commitTestCommit(t, dir)+ reports := make(chan []TaskMessageData, 2)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {+ if req.URL.Path != "/api/daemon/tasks/task-1/messages" {+ t.Errorf("unexpected endpoint: %s", req.URL.Path)+ }+ var body struct {+ Messages []TaskMessageData `json:"messages"`+ }+ if err := json.NewDecoder(req.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ reports <- body.Messages+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"status":"ok"}`))+ }))+ defer srv.Close()+ d := &Daemon{client: NewClient(srv.URL)}+ var seq atomic.Int32+ seq.Store(7)+ report := func(failureReason string) []TaskMessageData {+ t.Helper()+ d.reportCommitDiff("task-1", r, &seq, slog.Default(), true, failureReason)+ select {+ case messages := <-reports:+ return messages+ default:+ t.Fatal("no diff messages reported")+ return nil+ }+ }+ received := report("")+ if len(received) != 2 {+ t.Fatalf("messages=%d", len(received))+ }+ msg := received[0]+ if msg.Input["kind"] != diffCommits || received[1].Input["kind"] != diffWorktree || received[1].Input["unavailable"] == true {+ t.Fatalf("expected both comparisons to be available: %+v", received)+ }+ if msg.Tool != commitDiffTool || msg.Seq != 8 || msg.Type != "tool_use" {+ t.Fatalf("wrong report identity: %+v", msg)+ }+ raw, _ := json.Marshal(msg.Input)+ if strings.Contains(string(raw), dir) {+ t.Fatal("absolute repository path leaked into payload")+ }+ changes := msg.Input["changes"].([]any)+ kinds := map[string]any{}+ for _, value := range changes {+ file := value.(map[string]any)+ kinds[file["path"].(string)] = file["kind"]+ }+ if kinds["added.txt"] != "add" || kinds["file.txt"] != "delete" {+ t.Fatalf("wrong statuses: %v", kinds)+ }++ commitTestWrite(t, dir, "still-changing.txt", "unfinished\n")+ received = report(taskfailure.ReasonProcessCleanupUnconfirmed.String())+ if len(received) != 2 || received[0].Input["kind"] != diffCommits || received[0].Input["unavailable"] == true ||+ received[1].Input["kind"] != diffWorktree || received[1].Input["unavailable"] != true ||+ len(received[1].Input["changes"].([]any)) != 0 {+ t.Fatalf("expected commit changes and unavailable worktree: %+v", received)+ }+}++func TestCommitDiffRedactsPatchBeforeSending(t *testing.T) {+ dir := commitTestRepo(t)+ deletedSecret := "ghp_" + strings.Repeat("A", 36)+ addedSecret := "glpat-" + strings.Repeat("B", 24)+ commitTestWrite(t, dir, "file.txt", "old credential "+deletedSecret+"\n")+ commitTestCommit(t, dir)+ recorder := newCommitDiffRecorder()+ t.Cleanup(recorder.close)+ recorder.record(dir)+ commitTestWrite(t, dir, "file.txt", "new credential "+addedSecret+"\nordinary source\n")+ commitTestWrite(t, dir, "small.pem", "-----BEGIN PRIVATE KEY-----\nsynthetic-private-key-body\n-----END PRIVATE KEY-----\n")+ // Oversized private key patches must be omitted, not sent as a prefix.+ commitTestWrite(t, dir, "oversized.pem", "-----BEGIN PRIVATE KEY-----\n"+strings.Repeat("test-only-key-material\n", 4000)+"-----END PRIVATE KEY-----\n")+ commitTestCommit(t, dir)+ requests := make(chan []byte, 1)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {+ raw, err := io.ReadAll(req.Body)+ if err != nil {+ t.Error(err)+ }+ requests <- raw+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte("{}"))+ }))+ defer srv.Close()+ d := &Daemon{client: NewClient(srv.URL)}+ var seq atomic.Int32+ d.reportCommitDiff("redaction-test", recorder, &seq, slog.Default(), true, "")+ var raw []byte+ select {+ case raw = <-requests:+ default:+ t.Fatal("no diff request received")+ }+ for _, secret := range []string{deletedSecret, addedSecret, "synthetic-private-key-body", "test-only-key-material", "-----BEGIN PRIVATE KEY-----"} {+ if bytes.Contains(raw, []byte(secret)) {+ t.Fatal("unredacted fixture credential reached the HTTP request")+ }+ }+ var body struct {+ Messages []TaskMessageData `json:"messages"`+ }+ if err := json.Unmarshal(raw, &body); err != nil {+ t.Fatal(err)+ }+ if len(body.Messages) != 2 {+ t.Fatalf("expected commit and worktree comparisons, got %d", len(body.Messages))+ }+ for _, message := range body.Messages {+ files := message.Input["changes"].([]any)+ if len(files) != 3 {+ t.Fatalf("expected all three file entries, got %d", len(files))+ }+ for _, entry := range files {+ file := entry.(map[string]any)+ switch file["path"] {+ case "file.txt":+ patch, _ := file["diff"].(string)+ for _, want := range []string{"-old credential [REDACTED GITHUB TOKEN]", "+new credential [REDACTED GITLAB TOKEN]", "+ordinary source"} {+ if !strings.Contains(patch, want) {+ t.Fatal("redacted patch lost expected source or masking markers")+ }+ }+ case "oversized.pem":+ if file["truncated"] != true || file["diff"] != nil {+ t.Fatal("oversized patch was not omitted")+ }+ case "small.pem":+ patch, _ := file["diff"].(string)+ if !strings.Contains(patch, "[REDACTED PRIVATE KEY]") {+ t.Fatal("complete multiline private key was not masked")+ }+ default:+ t.Fatalf("unexpected file %v", file["path"])+ }+ }+ }+}+func TestCommitDiffFileLimitIsExplicit(t *testing.T) {+ dir := commitTestRepo(t)+ base := commitTestGit(t, dir, "rev-parse", "HEAD")+ for i := 0; i < commitDiffMaxFiles+1; i++ {+ commitTestWrite(t, dir, fmt.Sprintf("file-%03d.txt", i), "new\n")+ }+ commitTestCommit(t, dir)+ budget := commitDiffMaxBytes+ got := collectDiff(context.Background(), commitRepo{root: dir, base: base}, diffCommits, base, "HEAD", nil, &budget)+ if got["truncated"] != true || len(got["changes"].([]map[string]any)) != commitDiffMaxFiles {+ t.Fatal("file limit must be visible")+ }+}++func TestCommitDiffRestoresCheckoutWithFreshBaseline(t *testing.T) {+ root := t.TempDir()+ workDir := filepath.Join(root, "workdir")+ if err := os.MkdirAll(workDir, 0700); err != nil {+ t.Fatal(err)+ }+ repo := filepath.Join(workDir, "project")+ if err := os.Rename(commitTestRepo(t), repo); err != nil {+ t.Fatal(err)+ }+ first := newCommitDiffRecorder()+ t.Cleanup(first.close)+ first.restoreCheckouts(root, workDir)+ first.record(repo)+ commitTestWrite(t, repo, "first-only.txt", "first run\n")+ firstHead := commitTestCommit(t, repo)++ // A new recorder models environment reuse after a daemon restart. This turn+ // does not call repo checkout, and must start from the previous turn's HEAD.+ second := newCommitDiffRecorder()+ t.Cleanup(second.close)+ second.restoreCheckouts(root, workDir)+ if len(second.repos) != 1 {+ t.Fatalf("registered checkout was lost: %v", second.repos)+ }+ commitTestWrite(t, repo, "second-only.txt", "second run\n")+ secondHead := commitTestCommit(t, repo)+ for _, registered := range second.repos {+ diffs := collectRunDiffs(context.Background(), []commitRepo{registered}, true)+ if len(diffs) != 2 || diffs[1]["kind"] != diffWorktree {+ t.Fatalf("expected both comparisons, got %v", diffs)+ }+ diff := diffs[1]+ if diff["base"] != firstHead || diff["head"] != secondHead {+ t.Fatalf("stale range: %v -> %v", diff["base"], diff["head"])+ }+ files := diff["changes"].([]map[string]any)+ if len(files) != 1 || files[0]["path"] != "second-only.txt" {+ t.Fatalf("wrong turn's files: %v", files)+ }+ }+}++func TestCommitDiffKeepsTextMentioningBinaryMarker(t *testing.T) {+ repo := commitTestRepo(t)+ base := commitTestGit(t, repo, "rev-parse", "HEAD")+ commitTestWrite(t, repo, "file.txt", "Binary files a/test and b/test differ\n")+ commitTestCommit(t, repo)+ budget := commitDiffMaxBytes+ diff := collectDiff(context.Background(), commitRepo{root: repo, base: base}, diffCommits, base, "HEAD", nil, &budget)+ file := diff["changes"].([]map[string]any)[0]+ if file["binary"] == true || !strings.Contains(fmt.Sprint(file["diff"]), "+Binary files a/test and b/test differ") {+ t.Fatal("ordinary text was classified as binary")+ }+}++func TestCommitDiffReportsUnavailableWorktreeWithUnchangedHead(t *testing.T) {+ dir := commitTestRepo(t)+ recorder := newCommitDiffRecorder()+ t.Cleanup(recorder.close)+ recorder.record(dir)+ var repo commitRepo+ for _, registered := range recorder.repos {+ repo = registered+ }+ if repo.baseTree == "" {+ t.Fatal("fixture did not capture its starting tree")+ }+ commitTestWrite(t, dir, "file.txt", "uncommitted edit\n")+ // Let Git see a real cancelled snapshot without waiting on a slow disk.+ ctx, cancel := context.WithTimeout(context.Background(), 0)+ defer cancel()+ withHead := repo+ withHead.head = repo.base+ budget := commitDiffMaxBytes+ if diff := collectWorktreeDiff(ctx, withHead, &budget); diff["unavailable"] != true {+ t.Fatalf("expired capture deadline was not reported: %v", diff)+ }+ // A failed starting snapshot is represented by an absent starting tree.+ repo.baseTree = ""+ diffs := collectRunDiffs(context.Background(), []commitRepo{repo}, true)+ if len(diffs) != 1 || diffs[0]["kind"] != diffWorktree || diffs[0]["unavailable"] != true || diffs[0]["head"] != repo.base {+ t.Fatalf("capture failure must remain visible with no commits: %v", diffs)+ }+}++func TestCommitDiffReportsUnavailableBaselineForFirstCommit(t *testing.T) {+ dir := t.TempDir()+ commitTestGit(t, dir, "init", "-b", "main")+ recorder := newCommitDiffRecorder()+ t.Cleanup(recorder.close)+ recorder.record(dir)++ commitTestWrite(t, dir, "file.txt", "first commit\n")+ commitTestGit(t, dir, "add", "--", "file.txt")+ commitTestGit(t, dir, "-c", "user.name=Test", "-c", "[email protected]", "-c", "commit.gpgsign=false", "commit", "-m", "first")+ head := commitTestGit(t, dir, "rev-parse", "HEAD")++ repos := make([]commitRepo, 0, len(recorder.repos))+ for _, repo := range recorder.repos {+ repos = append(repos, repo)+ }+ diffs := collectRunDiffs(context.Background(), repos, true)+ if len(diffs) != 2 || diffs[0]["kind"] != diffCommits || diffs[1]["kind"] != diffWorktree {+ t.Fatalf("expected status for both comparisons, got %v", diffs)+ }+ for _, diff := range diffs {+ if diff["unavailable"] != true || diff["base"] != nil || diff["head"] != head {+ t.Fatalf("expected an unavailable comparison with no baseline, got %v", diff)+ }+ }+}++func TestCommitDiffPreservedWorktreeWithCleanFilter(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("filter fixture uses POSIX sed")+ }+ dir := commitTestRepo(t)+ commitTestGit(t, dir, "config", "filter.fixture.clean", "sed s/WORKING/STORED/g")+ commitTestGit(t, dir, "config", "filter.fixture.smudge", "sed s/STORED/WORKING/g")+ commitTestWrite(t, dir, ".gitattributes", "filtered.txt filter=fixture\n")+ commitTestWrite(t, dir, "filtered.txt", "WORKING\n")+ base := commitTestCommit(t, dir)+ if status := commitTestGit(t, dir, "status", "--porcelain"); status != "" {+ t.Fatalf("filter fixture must be clean, got %q", status)+ }+ recorder := newCommitDiffRecorder()+ t.Cleanup(recorder.close)+ recorder.preserved(dir, base)+ var repo commitRepo+ for _, registered := range recorder.repos {+ repo = registered+ }+ // A clean filtered file must never be reported as a run change.+ diffs := collectRunDiffs(context.Background(), []commitRepo{repo}, true)+ if len(diffs) != 1 || diffs[0]["kind"] != diffWorktree || diffs[0]["unavailable"] != true ||+ len(diffs[0]["changes"].([]map[string]any)) != 0 {+ t.Fatalf("expected unavailable working-tree comparison, got %v", diffs)+ }+ commitTestWrite(t, dir, "agent.txt", "committed output\n")+ head := commitTestCommit(t, dir)+ commitTestWrite(t, dir, "draft.txt", "uncommitted draft\n")+ diffs = collectRunDiffs(context.Background(), []commitRepo{repo}, true)+ if len(diffs) != 2 || diffs[0]["kind"] != diffCommits || diffs[0]["base"] != base || diffs[0]["head"] != head ||+ diffs[1]["kind"] != diffWorktree || diffs[1]["unavailable"] != true {+ t.Fatalf("valid commit range was not retained: %v", diffs)+ }+ files := diffs[0]["changes"].([]map[string]any)+ if len(files) != 1 || files[0]["path"] != "agent.txt" || !strings.Contains(fmt.Sprint(files[0]["diff"]), "+committed output") {+ t.Fatalf("expected only the actual committed change, got %v", files)+ }+}++func TestCommitDiffReportsRepositoryLimit(t *testing.T) {+ root := t.TempDir()+ workDir := filepath.Join(root, "workdir")+ if err := os.Mkdir(workDir, 0700); err != nil {+ t.Fatal(err)+ }+ newRepo := func(index int) string {+ t.Helper()+ path := filepath.Join(workDir, fmt.Sprintf("repo-%02d", index))+ if err := os.Rename(commitTestRepo(t), path); err != nil {+ t.Fatal(err)+ }+ return path+ }+ recorder := newCommitDiffRecorder()+ t.Cleanup(recorder.close)+ recorder.restoreCheckouts(root, workDir)+ for i := 0; i < commitDiffMaxRepos; i++ {+ recorder.record(newRepo(i))+ }+ if recorder.repositoriesOmitted {+ t.Fatal("exactly eight repositories must not report omissions")+ }+ // Refreshing a known checkout at the limit must still be permitted.+ var existing string+ for root := range recorder.repos {+ existing = root+ break+ }+ recorder.recordBaseline(existing, true)+ if recorder.repositoriesOmitted {+ t.Fatal("refreshing a known repository incorrectly reported omissions")+ }+ ignored := newRepo(commitDiffMaxRepos)+ recorder.record(ignored)+ if len(recorder.repos) != commitDiffMaxRepos || !recorder.repositoriesOmitted {+ t.Fatal("repository limit was not preserved or reported")+ }+ if _, exists := recorder.repos[ignored]; exists {+ t.Fatal("ninth repository was captured")+ }+ commitTestWrite(t, ignored, "ignored.txt", "ninth repository result\n")+ received := make(chan []TaskMessageData, 1)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {+ var body struct {+ Messages []TaskMessageData `json:"messages"`+ }+ if err := json.NewDecoder(req.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ received <- body.Messages+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte("{}"))+ }))+ defer srv.Close()+ var seq atomic.Int32+ d := &Daemon{client: NewClient(srv.URL)}+ assertOmitted := func(taskID string, r *commitDiffRecorder) {+ t.Helper()+ d.reportCommitDiff(taskID, r, &seq, slog.Default(), true, "")+ var messages []TaskMessageData+ select {+ case messages = <-received:+ default:+ t.Fatal("no status was reported for unchanged repositories")+ }+ if len(messages) != commitDiffMaxRepos {+ t.Fatalf("expected eight worktree records, got %d", len(messages))+ }+ for _, message := range messages {+ if message.Input["repositories_omitted"] != true || message.Input["kind"] != diffWorktree ||+ len(message.Input["changes"].([]any)) != 0 {+ t.Fatal("repository omission was not reported independently of file changes")+ }+ }+ }+ assertOmitted("repo-limit", recorder)+ registry, err := os.ReadFile(filepath.Join(root, "commit-repositories.json"))+ if err != nil {+ t.Fatal(err)+ }+ var paths []string+ if err := json.Unmarshal(registry, &paths); err != nil || len(paths) != commitDiffMaxRepos+1 {+ t.Fatalf("expected all nine repositories in registry: %s, err=%v", registry, err)+ }+ next := newCommitDiffRecorder()+ t.Cleanup(next.close)+ next.restoreCheckouts(root, workDir)+ if len(next.repos) != commitDiffMaxRepos || len(next.registeredRepos) != commitDiffMaxRepos+1 {+ t.Fatal("restoring repositories lost registration or exceeded capture limit")+ }+ // No checkout call this turn: the agent can reuse the ninth directory directly.+ commitTestWrite(t, ignored, "ignored.txt", "second turn result\n")+ assertOmitted("repo-limit-next-turn", next)+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 9d214774d4..8de019df8a 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8482,6 +8482,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// Hermes overlay's task-local state.db — carried over from the prior task.envReused = env != nil}+ commitDiff := newCommitDiffRecorder()+ defer commitDiff.close()if env == nil {var err errorprepParams := execenv.PrepareParams{@@ -8580,6 +8582,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i} else {if localAssignment != nil {prepParams.LocalWorkDir = localAssignment.AbsPath+ commitDiff.record(localAssignment.AbsPath)}env, err = d.prepareExecutionEnvironment(prepareCtx, prepParams)if err != nil {@@ -8588,6 +8591,14 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}}phaseRecorder.Mark(taskPhaseEnvironmentReady)+ var msgSeq atomic.Int32+ includeWorktreeDiff := true+ defer func() {+ d.reportCommitDiff(task.ID, commitDiff, &msgSeq, taskLog, includeWorktreeDiff, taskResult.FailureReason)+ }()+ if !env.LocalDirectory && env.LocalWorktree == nil {+ commitDiff.restoreCheckouts(env.RootDir, env.WorkDir)+ }// Belt-and-suspenders: also mark whatever root we ended up with, in case// future changes diverge from ResolveRootDir.if env.RootDir != resolvedRoot && env.RootDir != "" {@@ -8616,6 +8627,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot itaskResult.BranchName = outcome.Branch}if finalizeErr == nil {+ commitDiff.finalized(env.LocalWorktree.GitRoot, outcome.BaseCommit, outcome.HeadCommit, outcome.LeftoverRef)// The configured local_directory becomes authoritative only after// Finalize confirms the disposable task worktree is actually gone.if localAssignment != nil {@@ -8623,6 +8635,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}return}+ commitDiff.preserved(env.LocalWorktree.Path, env.LocalWorktree.BaseCommit)// Finalize could not complete its delivery contract, so the task// worktree remains authoritative. This covers both an uncommitted// change set and a committed branch whose worktree removal could not@@ -8679,6 +8692,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif env.LocalDirectory || env.LocalWorktree != nil {defer func() {if taskResult.FailureReason == taskfailure.ReasonProcessCleanupUnconfirmed.String() {+ includeWorktreeDiff = falsereturn // Preserve files that an unconfirmed process may still use.}var cleanupErr error@@ -8709,9 +8723,12 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// inspection. (In place there is no commit and no branch, so a// cleanup failure stays a warning: the leftover files are visible// in the user's own tree and removable by hand.)- if cleanupErr != nil && env.LocalWorktree != nil {- env.LocalWorktree.AbortWithReason(fmt.Errorf(- "could not remove the runtime's own files from the worktree before committing: %w", cleanupErr))+ if cleanupErr != nil {+ includeWorktreeDiff = false+ if env.LocalWorktree != nil {+ env.LocalWorktree.AbortWithReason(fmt.Errorf(+ "could not remove the runtime's own files from the worktree before committing: %w", cleanupErr))+ }}}()}@@ -9178,6 +9195,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iWorkspaceID: task.WorkspaceID,TaskID: task.ID,IssueID: task.IssueID,+ CommitDiff: commitDiff,AgentID: task.AgentID,AgentName: task.Agent.Name,WorkDir: env.WorkDir,@@ -9222,7 +9240,6 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// Shared across the resume-retry below so the retry's transcript rows// keep ascending seq values for the same task.- var msgSeq atomic.Int32d.reportThinkingLevelWarning(ctx, task.ID, selection.ThinkingLevelWarning, &msgSeq, taskLog)outputObserver := &taskOutputObserver{}ctx = withTaskOutputObserver(ctx, outputObserver)diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.goindex 03ac609083..366396decd 100644--- a/server/internal/daemon/execenv/local_worktree.go+++ b/server/internal/daemon/execenv/local_worktree.go@@ -289,6 +289,9 @@ func (w *LocalWorktree) UnmarshalJSON(data []byte) error {// LocalWorktreeOutcome is what a finished worktree task delivered.type LocalWorktreeOutcome struct {+ // BaseCommit and HeadCommit identify the delivered range after successful cleanup.+ BaseCommit string+ HeadCommit string// Branch is the branch holding the task's work, or "" when the task made// no changes at all (a read-only run) — in that case the branch is deleted// so it never shows up in the user's `git branch` as an empty artifact.@@ -761,6 +764,8 @@ func (w *LocalWorktree) Finalize(logger *slog.Logger) (LocalWorktreeOutcome, err"continued", w.Continued,)}+ outcome.BaseCommit = w.BaseCommit+ outcome.HeadCommit = tipreturn outcome, nil}diff --git a/server/internal/daemon/execenv/local_worktree_test.go b/server/internal/daemon/execenv/local_worktree_test.goindex a1c950acf0..e3df03bc66 100644--- a/server/internal/daemon/execenv/local_worktree_test.go+++ b/server/internal/daemon/execenv/local_worktree_test.go@@ -2427,3 +2427,26 @@ func TestIsolatedPrepareKeepsTheReadOnlyBranchDrop(t *testing.T) {t.Error("a turn that changed nothing left its branch behind")}}++func TestFinalizeReturnsImmutableCommitRange(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user edits\n")+ wt := prepareForTest(t, repo)+ base := wt.BaseCommit+ writeFile(t, filepath.Join(wt.WorkDir, "result.txt"), "agent output\n")+ outcome, err := wt.Finalize(worktreeTestLogger())+ if err != nil {+ t.Fatal(err)+ }+ if outcome.BaseCommit != base || outcome.HeadCommit == "" {+ t.Fatalf("missing committed receipt: %+v", outcome)+ }+ diff := gitRun(t, repo, "diff", outcome.BaseCommit, outcome.HeadCommit, "--")+ if !strings.Contains(diff, "agent output") || strings.Contains(diff, "user edits") {+ t.Fatalf("wrong turn boundary: %s", diff)+ }+ if _, err := os.Stat(wt.Path); !os.IsNotExist(err) {+ t.Fatalf("receipt must survive worktree cleanup: %v", err)+ }+}diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex 2b33c1543f..8bfbbcff9c 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -124,6 +124,7 @@ type repoCheckoutRequest struct {}type activeRepoCheckoutTask struct {+ CommitDiff *commitDiffRecorderWorkspaceID stringTaskID stringIssueID string@@ -607,6 +608,10 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {return}+ if activeTask.CommitDiff != nil {+ activeTask.CommitDiff.recordBaseline(result.Path, result.Kept == "")+ }+w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(result)}diff --git a/server/internal/integrations/telegram/outbound_progress_test.go b/server/internal/integrations/telegram/outbound_progress_test.goindex 6fa8b0fc74..b71291a0ff 100644--- a/server/internal/integrations/telegram/outbound_progress_test.go+++ b/server/internal/integrations/telegram/outbound_progress_test.go@@ -394,6 +394,18 @@ func TestOutboundTakesTheStepsOffACancelledReply(t *testing.T) {}// Who sees a step's argument is the mode's decision and the chat's.+func TestStepForHidesCommitDiff(t *testing.T) {+ for _, mode := range []ProgressMode{ProgressAuto, ProgressSummary, ProgressDetail} {+ o := &Outbound{progress: mode}+ for _, private := range []bool{false, true} {+ step, ok := o.stepFor(&replyTarget{private: private}, toolCall("multica_commit_diff", map[string]any{"repository": "private-repository"}))+ if ok {+ t.Fatalf("internal record became a Telegram step: %+v", step)+ }+ }+ }+}+func TestStepForShowsArgumentsByModeAndChat(t *testing.T) {call := toolCall("Bash", map[string]any{"command": "cat notes.txt"})cases := []struct {diff --git a/server/internal/integrations/wecom/progress_export_test.go b/server/internal/integrations/wecom/progress_export_test.goindex f01274369e..9145a0772f 100644--- a/server/internal/integrations/wecom/progress_export_test.go+++ b/server/internal/integrations/wecom/progress_export_test.go@@ -26,6 +26,18 @@ func TestDescribeStepWordsAStepForAnotherAdapter(t *testing.T) {}}+func TestCommitDiffIsHiddenFromProgress(t *testing.T) {+ msg := toolUse("multica_commit_diff", map[string]any{"repository": "private-repository", "head": "private-head"})+ if step, ok := stepFromTaskMessage(msg); ok {+ t.Fatalf("internal record became a WeCom step: %+v", step)+ }+ for _, detail := range []bool{false, true} {+ if step, ok := DescribeStep(msg, LocaleEn, detail); ok {+ t.Fatalf("internal record became an exported step: %+v", step)+ }+ }+}+// TestDescribeStepWithoutArgumentKeepsOnlyTheKindOfWork — a reader the run// does not belong to sees what sort of work it is and nothing the agent// composed.diff --git a/server/internal/integrations/wecom/progress_render.go b/server/internal/integrations/wecom/progress_render.goindex dbbd1a258c..5ce1031da0 100644--- a/server/internal/integrations/wecom/progress_render.go+++ b/server/internal/integrations/wecom/progress_render.go@@ -295,6 +295,9 @@ func stepFromTaskMessage(payload any) (progressStep, bool) {func stepFromMessage(msg taskMessage) (progressStep, bool) {switch msg.msgType {case "tool_use":+ if msg.tool == "multica_commit_diff" {+ return progressStep{}, false+ }return stepFromToolUse(msg.tool, msg.input), truecase "error":return progressStep{kind: progressError, arg: safeFragment(msg.content)}, true