From 92ed76b4385a42ad7b6decb36a4e11710d946947 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Mon, 15 Jun 2026 20:50:11 +0100 Subject: [PATCH] feat: auggie subagent detection and single-repo review diff (#1385) --- .../server/adapter/transport/acp/normalize.go | 23 ++- .../server/adapter/transport/acp/subagent.go | 77 +++++++- .../adapter/transport/acp/subagent_test.go | 167 ++++++++++++++++++ .../agentctl/types/streams/tool_payload.go | 22 +++ .../review/review-dialog.build-files.test.ts | 122 +++++++++++++ apps/web/components/review/review-dialog.tsx | 26 +-- .../chat/messages/tool-subagent-message.tsx | 51 +++++- apps/web/components/task/chat/types.ts | 3 + .../session/use-review-sources.test.ts | 30 ++++ .../domains/session/use-review-sources.ts | 14 +- 10 files changed, 504 insertions(+), 31 deletions(-) create mode 100644 apps/web/components/review/review-dialog.build-files.test.ts diff --git a/apps/backend/internal/agentctl/server/adapter/transport/acp/normalize.go b/apps/backend/internal/agentctl/server/adapter/transport/acp/normalize.go index e3284edd7c..0a86ff1127 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/acp/normalize.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/acp/normalize.go @@ -492,21 +492,38 @@ func (n *Normalizer) normalizeSubagent(args map[string]any) (*streams.Normalized if !ok { return nil, false } - return streams.NewSubagentTask(desc, prompt, subagentType), true + payload := streams.NewSubagentTask(desc, prompt, subagentType) + // Mark Auggie subagents at recognition time so the result extractor + // (which reads a generic `rawOutput.output` string) only runs for + // payloads whose tool_call title actually carried the Auggie prefix. + if _, _, isAuggie := auggieSubagentTitleFields(title); isAuggie { + payload.SubagentTask().SetIsAuggie(true) + } + return payload, true } // EnrichSubagentResult fills the result fields of a subagent payload from a // completion tool_call_update. Claude's result lives in meta, OpenCode's and -// Cursor's in rawOutput — so this takes both. No-op for non-subagent payloads. +// Cursor's in rawOutput — so this takes both. Auggie's `rawOutput.output` is +// extracted separately and only when the payload was recognized as Auggie at +// tool_call time. No-op for non-subagent payloads. func (n *Normalizer) EnrichSubagentResult(payload *streams.NormalizedPayload, meta map[string]any, rawOutput any) { if payload == nil || payload.Kind() != streams.ToolKindSubagentTask { return } + sa := payload.SubagentTask() res, ok := extractSubagentResult(meta, rawOutput) + if sa.IsAuggie() { + if out, isMap := rawOutput.(map[string]any); isMap { + if auggieSubagentResult(out, &res) { + ok = true + } + } + } if !ok { return } - applySubagentResult(payload.SubagentTask(), res) + applySubagentResult(sa, res) } // --- Helper functions --- diff --git a/apps/backend/internal/agentctl/server/adapter/transport/acp/subagent.go b/apps/backend/internal/agentctl/server/adapter/transport/acp/subagent.go index 6bbc1d2a35..6ac1e36f07 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/acp/subagent.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/acp/subagent.go @@ -7,13 +7,16 @@ import ( ) // Subagent (Task) tool detection constants. These are the wire-level tool -// identifiers three real agents use to spawn a child agent ("subagent"): +// identifiers four real agents use to spawn a child agent ("subagent"): // - Claude-acp tags it via `_meta.claudeCode.toolName == "Agent"`. // - OpenCode reports tool title == "task" (case-insensitive). // - Cursor reports `rawInput._toolName == "task"` (title "Task: Subagent task"). +// - Auggie reports a tool_call with `kind == "other"` and a title prefixed +// with `sub-agent-: `; no meta or rawInput is provided. const ( - subagentClaudeToolName = "Agent" - subagentTaskName = "task" + subagentClaudeToolName = "Agent" + subagentTaskName = "task" + subagentAuggieTitlePrefix = "sub-agent-" ) // rawInput field keys carrying subagent invocation details. These arrive on a @@ -48,6 +51,10 @@ type SubagentTaskResult struct { IsAsync bool OutputFile string CanReadOutputFile bool + + // ResultText carries the silent-subagent final text (Auggie). Empty when + // the agent streams progress as nested tool calls instead. + ResultText string } // subagentAsyncLaunchedStatus is the Claude Code marker that the Task tool @@ -75,13 +82,15 @@ func isSubagentAsyncLaunched(meta map[string]any) bool { } // recognizeSubagent reports whether a tool call spawns a subagent (Task) and -// pulls description/prompt/subagent_type out of rawInput when present. The -// detection mirrors monitor.go: defensive over untyped maps, no logging. +// pulls description/prompt/subagent_type out of rawInput (or, for Auggie, the +// title) when present. The detection mirrors monitor.go: defensive over +// untyped maps, no logging. // // A tool call is a subagent if ANY of: // - Claude: meta.claudeCode.toolName == "Agent" // - OpenCode: title == "task" (case-insensitive) // - Cursor: rawInput._toolName == "task" +// - Auggie: title starts with "sub-agent-:" // // The Claude "Monitor"/"ScheduleWakeup" tool names are deliberately NOT matched // here so their dedicated handling stays intact. @@ -90,10 +99,20 @@ func recognizeSubagent(meta map[string]any, title string, rawInput any) (descrip return "", "", "", false } description, prompt, subagentType = subagentInputFields(rawInput) + // Auggie carries the subagent type + a truncated description in the title; + // rawInput is empty so we fall back to parsing the title. + if titleType, titleDesc, isAuggie := auggieSubagentTitleFields(title); isAuggie { + if subagentType == "" { + subagentType = titleType + } + if description == "" { + description = titleDesc + } + } return description, prompt, subagentType, true } -// isSubagentSignal implements the three detection rules. +// isSubagentSignal implements the four detection rules. func isSubagentSignal(meta map[string]any, title string, rawInput any) bool { if isClaudeAgentMeta(meta) { return true @@ -106,9 +125,32 @@ func isSubagentSignal(meta map[string]any, title string, rawInput any) bool { return true } } + if _, _, ok := auggieSubagentTitleFields(title); ok { + return true + } return false } +// auggieSubagentTitleFields parses Auggie's "sub-agent-: " +// title. Returns ok=false when the title doesn't carry the prefix, omits the +// ":" separator, or the type segment is empty after trimming. The description +// is whatever follows the first ":" (Auggie truncates it; we keep it as-is). +func auggieSubagentTitleFields(title string) (subagentType, description string, ok bool) { + rest, found := strings.CutPrefix(title, subagentAuggieTitlePrefix) + if !found { + return "", "", false + } + typeName, desc, hasColon := strings.Cut(rest, ":") + if !hasColon { + return "", "", false + } + typeName = strings.TrimSpace(typeName) + if typeName == "" { + return "", "", false + } + return typeName, strings.TrimSpace(desc), true +} + // parentToolUseID returns `_meta.claudeCode.parentToolUseId` — the tool-call id // of the subagent (Task) that issued this tool call. claude-agent-acp sets it // on a subagent's internal tool calls (Bash/Read/…) and leaves it empty for @@ -162,6 +204,11 @@ func subagentInputFields(rawInput any) (description, prompt, subagentType string // - OpenCode: rawOutput.metadata = {sessionId, parentSessionId, // model:{providerID, modelID}} // - Cursor: rawOutput = {durationMs, isBackground} +// +// Auggie's `rawOutput.output` shape is intentionally NOT extracted here — it's +// too generic (a bare "output" string field) to attribute reliably. The caller +// (EnrichSubagentResult) gates it on the payload's IsAuggie flag, which is set +// at recognition time from the "sub-agent-:" title prefix. func extractSubagentResult(meta map[string]any, rawOutput any) (res SubagentTaskResult, ok bool) { if claudeSubagentResponse(meta, &res) { ok = true @@ -177,6 +224,21 @@ func extractSubagentResult(meta map[string]any, rawOutput any) (res SubagentTask return res, ok } +// auggieSubagentResult reads Auggie's `rawOutput.output` (the final result +// text) into res. Auggie sub-agents are silent — they never emit intermediate +// tool calls or structured metrics — so this text is the only completion +// signal we get to surface in the UI. Called only when the parent payload was +// recognized as Auggie at tool_call time; the generic shape is unsafe for +// other agents. +func auggieSubagentResult(out map[string]any, res *SubagentTaskResult) bool { + output, _ := out["output"].(string) + if output == "" { + return false + } + res.ResultText = output + return true +} + // claudeSubagentResponse reads `_meta.claudeCode.toolResponse` into res. func claudeSubagentResponse(meta map[string]any, res *SubagentTaskResult) bool { if meta == nil { @@ -301,4 +363,7 @@ func applySubagentResult(p *streams.SubagentTaskPayload, res SubagentTaskResult) if res.CanReadOutputFile { p.CanReadOutputFile = true } + if res.ResultText != "" && p.ResultText == "" { + p.ResultText = res.ResultText + } } diff --git a/apps/backend/internal/agentctl/server/adapter/transport/acp/subagent_test.go b/apps/backend/internal/agentctl/server/adapter/transport/acp/subagent_test.go index b262daf62c..bc01cc2dde 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/acp/subagent_test.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/acp/subagent_test.go @@ -442,3 +442,170 @@ func TestEnrichSubagentResult_Cursor(t *testing.T) { t.Errorf("DurationMs = %d", payload.SubagentTask().DurationMs) } } + +// --- Auggie subagent detection --- + +func TestAuggieSubagentTitleFields(t *testing.T) { + for _, tc := range []struct { + name, title, wantType, wantDesc string + wantOK bool + }{ + {"simple", "sub-agent-explore: find the bug", "explore", "find the bug", true}, + {"hyphenated type", "sub-agent-code-review: look at PR 12", "code-review", "look at PR 12", true}, + {"truncated description", "sub-agent-explore: a very long thing (und...", "explore", "a very long thing (und...", true}, + {"no description", "sub-agent-qa:", "qa", "", true}, + {"missing colon", "sub-agent-explore find the bug", "", "", false}, + {"missing prefix", "explore: find the bug", "", "", false}, + {"empty type after prefix", "sub-agent-: foo", "", "", false}, + {"empty title", "", "", "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + gotType, gotDesc, gotOK := auggieSubagentTitleFields(tc.title) + if gotOK != tc.wantOK || gotType != tc.wantType || gotDesc != tc.wantDesc { + t.Errorf("got (%q,%q,%v) want (%q,%q,%v)", gotType, gotDesc, gotOK, tc.wantType, tc.wantDesc, tc.wantOK) + } + }) + } +} + +func TestRecognizeSubagent_AuggieTitleNoInput(t *testing.T) { + desc, prompt, st, ok := recognizeSubagent(nil, "sub-agent-explore: find the bug", nil) + if !ok { + t.Fatal("expected Auggie title to be recognized as subagent") + } + if st != "explore" { + t.Errorf("SubagentType = %q, want explore", st) + } + if desc != "find the bug" { + t.Errorf("Description = %q, want find the bug", desc) + } + if prompt != "" { + t.Errorf("Prompt = %q, want empty (Auggie does not provide it)", prompt) + } +} + +func TestRecognizeSubagent_AuggieDoesNotOverrideRawInput(t *testing.T) { + // Hypothetical: title looks Auggie-shaped but rawInput carries fuller + // fields (e.g. a future agent that adopts both). rawInput must win for + // fields it provides; the title fills only the gaps. + rawInput := map[string]any{"description": "from rawInput", "subagent_type": "research"} + desc, _, st, ok := recognizeSubagent(nil, "sub-agent-explore: from title", rawInput) + if !ok { + t.Fatal("expected recognition") + } + if desc != "from rawInput" { + t.Errorf("Description = %q, want from rawInput (rawInput wins)", desc) + } + if st != "research" { + t.Errorf("SubagentType = %q, want research (rawInput wins)", st) + } +} + +func TestAuggieSubagentResult_Output(t *testing.T) { + var res SubagentTaskResult + if !auggieSubagentResult(map[string]any{"output": "Subagent found the issue: foo.go:42 is wrong."}, &res) { + t.Fatal("expected Auggie rawOutput.output to be extracted") + } + if res.ResultText != "Subagent found the issue: foo.go:42 is wrong." { + t.Errorf("ResultText = %q", res.ResultText) + } +} + +func TestAuggieSubagentResult_EmptyOrWrongType(t *testing.T) { + var res SubagentTaskResult + if auggieSubagentResult(map[string]any{"output": ""}, &res) { + t.Error("empty output must not register as a result") + } + if auggieSubagentResult(map[string]any{"output": 42}, &res) { + t.Error("non-string output must not register as a result") + } +} + +// extractSubagentResult must NOT pick up Auggie's generic `output` field on +// its own — that path is gated on the payload's IsAuggie flag inside +// EnrichSubagentResult so a future agent emitting `{output: "..."}` alongside +// its own structured metadata can't silently surface as Auggie text. +func TestExtractSubagentResult_IgnoresAuggieOutput(t *testing.T) { + rawOutput := map[string]any{"output": "this should not be picked up by extract"} + res, ok := extractSubagentResult(nil, rawOutput) + if ok { + t.Error("extractSubagentResult must not recognize bare rawOutput.output") + } + if res.ResultText != "" { + t.Errorf("ResultText = %q, want empty", res.ResultText) + } +} + +func TestEnrichSubagentResult_Auggie(t *testing.T) { + n := NewNormalizer("") + payload := streams.NewSubagentTask("find the bug", "", "explore") + payload.SubagentTask().SetIsAuggie(true) + n.EnrichSubagentResult(payload, nil, map[string]any{"output": "Done. Bug is at foo.go:42."}) + sa := payload.SubagentTask() + if sa.ResultText != "Done. Bug is at foo.go:42." { + t.Errorf("ResultText = %q", sa.ResultText) + } + // JSON must surface result_text for the frontend. + out, err := json.Marshal(payload) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if !strings.Contains(string(out), `"result_text":"Done. Bug is at foo.go:42."`) { + t.Errorf("expected result_text in JSON, got %s", out) + } +} + +// EnrichSubagentResult must NOT populate ResultText for non-Auggie payloads +// even when rawOutput happens to carry an `output` string. Guards against the +// regression Greptile/Claude flagged on the original Auggie PR. +func TestEnrichSubagentResult_NonAuggieIgnoresOutput(t *testing.T) { + n := NewNormalizer("") + payload := streams.NewSubagentTask("Investigate", "do it", "general-purpose") + n.EnrichSubagentResult(payload, nil, map[string]any{"output": "stray string from some other agent"}) + if got := payload.SubagentTask().ResultText; got != "" { + t.Errorf("ResultText = %q, want empty (non-Auggie payload)", got) + } +} + +func TestNormalizeToolCall_AuggieSubagent(t *testing.T) { + n := NewNormalizer("") + args := map[string]any{ + "kind": "other", + "title": "sub-agent-explore: investigate flaky test", + } + payload := n.NormalizeToolCall("other", args) + if payload.Kind() != streams.ToolKindSubagentTask { + t.Fatalf("Kind = %q, want subagent_task", payload.Kind()) + } + sa := payload.SubagentTask() + if sa.SubagentType != "explore" { + t.Errorf("SubagentType = %q, want explore", sa.SubagentType) + } + if sa.Description != "investigate flaky test" { + t.Errorf("Description = %q, want investigate flaky test", sa.Description) + } + if !sa.IsAuggie() { + t.Error("IsAuggie() = false, want true (title carries Auggie prefix)") + } +} + +func TestNormalizeToolCall_NonAuggieSubagentNotMarked(t *testing.T) { + n := NewNormalizer("") + // OpenCode-style title=task subagent must NOT be flagged as Auggie. + args := map[string]any{ + "kind": "other", + "title": "task", + "raw_input": map[string]any{ + "description": "Investigate", + "prompt": "Find the bug", + "subagent_type": "general-purpose", + }, + } + payload := n.NormalizeToolCall("other", args) + if payload.Kind() != streams.ToolKindSubagentTask { + t.Fatalf("Kind = %q, want subagent_task", payload.Kind()) + } + if payload.SubagentTask().IsAuggie() { + t.Error("IsAuggie() = true, want false (OpenCode-style title=task)") + } +} diff --git a/apps/backend/internal/agentctl/types/streams/tool_payload.go b/apps/backend/internal/agentctl/types/streams/tool_payload.go index 65887f0cd1..bf89724e1d 100644 --- a/apps/backend/internal/agentctl/types/streams/tool_payload.go +++ b/apps/backend/internal/agentctl/types/streams/tool_payload.go @@ -258,6 +258,13 @@ type SubagentTaskPayload struct { // Cursor) stay omitted rather than surfacing a misleading "0 tools" chip. ToolUseCount *int `json:"tool_use_count,omitempty"` + // ResultText is the final summary returned by the subagent. Populated for + // silent subagents (Auggie) that don't stream intermediate tool calls and + // only deliver a single text payload on completion via `rawOutput.output`. + // Claude/OpenCode/Cursor leave this empty because their progress is + // visible as nested child messages. + ResultText string `json:"result_text,omitempty"` + // Async/backgrounded subagent fields. Claude Code's Task tool with // `run_in_background: true` returns `_meta.claudeCode.toolResponse.status: // "async_launched"` and includes `isAsync`, `outputFile`, @@ -266,8 +273,23 @@ type SubagentTaskPayload struct { IsAsync bool `json:"is_async,omitempty"` OutputFile string `json:"output_file,omitempty"` CanReadOutputFile bool `json:"can_read_output_file,omitempty"` + + // isAuggie marks payloads recognized via Auggie's "sub-agent-:" + // title prefix. Internal to the adapter; not serialized. Gates the + // Auggie-specific result extractor (which keys off a generic + // `rawOutput.output` string) so it never fires for unrelated agents that + // happen to emit a similarly-shaped completion frame. + isAuggie bool } +// IsAuggie reports whether the subagent was recognized via Auggie's title +// prefix. Used by the normalizer to gate Auggie-only result extraction. +func (p *SubagentTaskPayload) IsAuggie() bool { return p.isAuggie } + +// SetIsAuggie marks the payload as an Auggie subagent. Called by the +// normalizer at recognition time; never set by JSON unmarshal. +func (p *SubagentTaskPayload) SetIsAuggie(v bool) { p.isAuggie = v } + // ShowPlanPayload contains normalized data for plan display operations. type ShowPlanPayload struct { Summary string `json:"summary"` diff --git a/apps/web/components/review/review-dialog.build-files.test.ts b/apps/web/components/review/review-dialog.build-files.test.ts new file mode 100644 index 0000000000..65253b4cbe --- /dev/null +++ b/apps/web/components/review/review-dialog.build-files.test.ts @@ -0,0 +1,122 @@ +import { describe, it, expect } from "vitest"; +import { buildAllFiles } from "./review-dialog"; +import type { CumulativeDiff } from "@/lib/state/slices/session-runtime/types"; + +describe("buildAllFiles (review dialog)", () => { + // Regression for the "No changes to review" bug introduced by multi-repo + // support (PR #767). Single-repo cumulative diffs from `parseCommitDiff` + // carry the path only on the map key — `file.path` is undefined. The dialog + // used to skip every such entry with a console.warn, so a 14-file commit + // rendered as an empty review. Verify we fall back to the map key. + it("single-repo cumulative diff: uses map key when file.path is missing", () => { + const cumulativeDiff = { + session_id: "s1", + base_commit: "abc", + head_commit: "def", + total_commits: 1, + files: { + "src/a.ts": { + status: "modified", + staged: false, + additions: 1, + deletions: 1, + diff: "@@ -1 +1 @@\n-a\n+b\n", + }, + "src/b.ts": { + status: "added", + staged: false, + additions: 5, + deletions: 0, + diff: "@@ -0,0 +1,5 @@\n+new\n", + }, + }, + } as unknown as CumulativeDiff; + + const result = buildAllFiles(null, cumulativeDiff); + expect(result).toHaveLength(2); + const paths = result.map((f) => f.path).sort(); + expect(paths).toEqual(["src/a.ts", "src/b.ts"]); + expect(result.every((f) => f.source === "committed")).toBe(true); + expect(result.every((f) => !f.repository_name)).toBe(true); + }); + + // Multi-repo: `mergeCumulativeFiles` uses a `\x00` composite map + // key and stamps the clean repo-relative path on `file.path`. The displayed + // path must come from the stamped value, never from the composite key. + it("multi-repo cumulative diff: prefers stamped path over composite map key", () => { + const cumulativeDiff = { + session_id: "s1", + base_commit: "abc", + head_commit: "def", + total_commits: 2, + files: { + "frontend\u0000src/app.tsx": { + status: "modified", + staged: false, + additions: 2, + deletions: 1, + diff: "@@ -1 +1 @@\n-x\n+y\n", + repository_name: "frontend", + path: "src/app.tsx", + }, + "backend\u0000main.go": { + status: "modified", + staged: false, + additions: 3, + deletions: 0, + diff: "@@ -1 +1,3 @@\n+a\n+b\n+c\n", + repository_name: "backend", + path: "main.go", + }, + }, + } as unknown as CumulativeDiff; + + const result = buildAllFiles(null, cumulativeDiff); + expect(result).toHaveLength(2); + const byRepo = Object.fromEntries(result.map((f) => [f.repository_name, f])); + expect(byRepo["frontend"]?.path).toBe("src/app.tsx"); + expect(byRepo["backend"]?.path).toBe("main.go"); + // No NUL or composite-key leakage into displayed paths. + expect(result.every((f) => !f.path.includes("\u0000"))).toBe(true); + }); + + it("returns empty array when all sources are empty/null", () => { + expect(buildAllFiles(null, null)).toEqual([]); + }); + + it("uncommitted gitStatus wins over cumulative for the same path", () => { + const cumulativeDiff = { + session_id: "s1", + base_commit: "abc", + head_commit: "def", + total_commits: 1, + files: { + "src/shared.ts": { + status: "modified", + staged: false, + additions: 1, + deletions: 1, + diff: "@@ -1 +1 @@\n-c\n+c\n", + }, + }, + } as unknown as CumulativeDiff; + + const gitStatusFiles = { + "src/shared.ts": { + path: "src/shared.ts", + status: "modified" as const, + staged: false, + additions: 1, + deletions: 1, + diff: "@@ -1 +1 @@\n-u\n+u\n", + }, + }; + + const result = buildAllFiles(gitStatusFiles, cumulativeDiff); + expect(result).toHaveLength(1); + expect(result[0].source).toBe("uncommitted"); + // Exact equality (not toContain) so a future normalization change that + // appends or rewrites diff content can't silently pass this guard. + expect(result[0].diff).toBe("@@ -1 +1 @@\n-u\n+u"); + }); +}); diff --git a/apps/web/components/review/review-dialog.tsx b/apps/web/components/review/review-dialog.tsx index 6205655cca..efcac3fe95 100644 --- a/apps/web/components/review/review-dialog.tsx +++ b/apps/web/components/review/review-dialog.tsx @@ -41,24 +41,16 @@ function addCumulativeDiffFiles( files: CumulativeDiff["files"], gitStatusFiles: Record | null, ) { - // Multi-repo: backend always stamps each per-file payload with - // `repository_name` + the repo-relative `path`. Single-repo (or legacy) - // payloads keep the bare path on the map key. We trust `file.path` to be - // set in the multi-repo shape — a missing `path` would be a backend - // contract violation and indicates the caller is on an outdated agentctl; - // surface it loudly via a console warning rather than silently injecting - // the composite map key into the displayed path (which used to corrupt - // the file tree node names). + // Multi-repo: backend stamps each per-file payload with `repository_name` + // + the repo-relative `path`, and uses a NUL-composite `\x00` + // map key. Single-repo payloads from `parseCommitDiff` carry the bare path + // only on the map key (no `path` field on the value). Prefer the stamped + // value so the composite key doesn't bleed into the displayed path, and + // fall back to the map key so single-repo files aren't silently dropped. for (const [mapKey, file] of Object.entries(files)) { const repoName = file.repository_name; - const path = file.path; - if (!path) { - console.warn("[review] cumulative diff entry missing `path` field; skipping", { - mapKey, - repoName, - }); - continue; - } + const path = file.path ?? mapKey; + if (!path) continue; const key = fileMapKey(path, repoName); if (fileMap.has(key)) continue; const diff = file.diff ? normalizeDiffContent(file.diff) : ""; @@ -140,7 +132,7 @@ function addPRFiles(fileMap: Map, files: PRDiffFile[]) { } } -function buildAllFiles( +export function buildAllFiles( gitStatusFiles: Record | null, cumulativeDiff: CumulativeDiff | null, prDiffFiles?: PRDiffFile[], diff --git a/apps/web/components/task/chat/messages/tool-subagent-message.tsx b/apps/web/components/task/chat/messages/tool-subagent-message.tsx index 82b83e704c..9fbbe84245 100644 --- a/apps/web/components/task/chat/messages/tool-subagent-message.tsx +++ b/apps/web/components/task/chat/messages/tool-subagent-message.tsx @@ -5,9 +5,22 @@ import { IconChevronDown, IconChevronRight } from "@tabler/icons-react"; import { GridSpinner } from "@/components/grid-spinner"; import { cn } from "@/lib/utils"; import type { Message } from "@/lib/types/http"; -import type { ToolCallMetadata } from "@/components/task/chat/types"; +import type { SubagentTaskPayload, ToolCallMetadata } from "@/components/task/chat/types"; import { SubagentMetaRow } from "@/components/task/chat/messages/subagent-meta-row"; +// deriveSubagentBody picks which secondary block (result text or prompt) the +// card should render below the header. Result text wins because it carries the +// silent-subagent summary that prompt placeholders cannot substitute for. +function deriveSubagentBody( + childCount: number, + payload: SubagentTaskPayload | undefined, +): { resultText?: string; prompt?: string } { + if (childCount > 0) return {}; + if (payload?.result_text) return { resultText: payload.result_text }; + if (payload?.prompt) return { prompt: payload.prompt }; + return {}; +} + type ToolSubagentMessageProps = { comment: Message; childMessages: Message[]; @@ -92,6 +105,7 @@ type SubagentContentProps = { childMessages: Message[]; isActive: boolean; prompt?: string; + resultText?: string; renderChild: (message: Message) => React.ReactNode; }; @@ -100,6 +114,7 @@ function SubagentContent({ childMessages, isActive, prompt, + resultText, renderChild, }: SubagentContentProps) { if (!isExpanded) return null; @@ -119,6 +134,18 @@ function SubagentContent({ ); } + if (resultText) { + return ( +
+

+ {resultText} +

+
+ ); + } if (prompt) { return (
@@ -149,13 +176,28 @@ export const ToolSubagentMessage = memo(function ToolSubagentMessage({ const isActive = status === "running"; const showMeta = !isActive; - const prompt = childCount === 0 ? subagentTask?.prompt : undefined; + const { resultText, prompt } = deriveSubagentBody(childCount, subagentTask); // Track manual override state - null means "use auto behavior" const [manualExpandState, setManualExpandState] = useState(null); - // Auto behavior: expand if active, collapse otherwise - const autoExpanded = isActive; + // Auto behavior: expand if active or if we have a result text to surface + // (silent Auggie-style subagents have no child messages, so we want the + // final summary visible without an extra click). + const autoExpanded = isActive || Boolean(resultText); + + // Reset the manual override the first time a result_text arrives so a card + // the user collapsed while the subagent was running auto-opens to show the + // summary. "Adjust state during render" pattern (preferred over useEffect): + // https://react.dev/learn/you-might-not-need-an-effect — only fires on the + // empty -> non-empty transition; later user collapses persist. + const [prevResultText, setPrevResultText] = useState(resultText); + if (resultText !== prevResultText) { + setPrevResultText(resultText); + if (resultText && !prevResultText) { + setManualExpandState(null); + } + } // Derive expanded state: manual override takes precedence, otherwise use auto const isExpanded = manualExpandState ?? autoExpanded; @@ -180,6 +222,7 @@ export const ToolSubagentMessage = memo(function ToolSubagentMessage({ childMessages={childMessages} isActive={isActive} prompt={prompt} + resultText={resultText} renderChild={renderChild} />
diff --git a/apps/web/components/task/chat/types.ts b/apps/web/components/task/chat/types.ts index a41dab7ca9..79b7c4a78c 100644 --- a/apps/web/components/task/chat/types.ts +++ b/apps/web/components/task/chat/types.ts @@ -17,6 +17,9 @@ export type SubagentTaskPayload = { is_async?: boolean; output_file?: string; can_read_output_file?: boolean; + // Final summary returned by silent subagents (Auggie) that don't stream + // intermediate tool calls. Rendered inline when there are no child messages. + result_text?: string; }; export type GenericPayload = { diff --git a/apps/web/hooks/domains/session/use-review-sources.test.ts b/apps/web/hooks/domains/session/use-review-sources.test.ts index 82c67c3ebe..fbf8c72b37 100644 --- a/apps/web/hooks/domains/session/use-review-sources.test.ts +++ b/apps/web/hooks/domains/session/use-review-sources.test.ts @@ -413,6 +413,36 @@ describe("buildReviewSources", () => { expect(result.sourceCounts).toEqual({ uncommitted: 2, committed: 0, pr: 0 }); }); + // Regression for the multi-repo cumulative-diff bug: backend's + // `mergeCumulativeFiles` uses a `\x00` map key and stamps the + // clean repo-relative path on `file.path`. The old code read the path from + // the map key, so the displayed path contained the embedded NUL+repo and + // the dedup key was `:\x00` (mismatched against any + // other source). Verify we now use `file.path` when present. + it("multi-repo cumulative: NUL-composite map key + stamped path renders clean path", () => { + const result = buildReviewSources({ + gitStatus: undefined, + statusByRepo: undefined, + cumulativeDiff: { + files: { + "frontend\u0000src/x.ts": { + diff: "@@x@@", + status: "modified", + additions: 1, + deletions: 0, + repository_name: "frontend", + path: "src/x.ts", + }, + }, + }, + prDiffFiles: undefined, + }); + expect(result.allFiles).toHaveLength(1); + expect(result.allFiles[0].path).toBe("src/x.ts"); + expect(result.allFiles[0].repository_name).toBe("frontend"); + expect(result.allFiles[0].source).toBe("committed"); + }); + it("sorts files by repository_name then path", () => { const result = buildReviewSources({ gitStatus: undefined, diff --git a/apps/web/hooks/domains/session/use-review-sources.ts b/apps/web/hooks/domains/session/use-review-sources.ts index d8ea320aed..451b4f0d4c 100644 --- a/apps/web/hooks/domains/session/use-review-sources.ts +++ b/apps/web/hooks/domains/session/use-review-sources.ts @@ -29,6 +29,12 @@ type CumulativeFile = { additions?: number; deletions?: number; repository_name?: string; + /** + * Repo-relative path. Stamped by the backend's multi-repo cumulative-diff + * merge (`mergeCumulativeFiles` in agentctl); single-repo payloads omit + * this and carry the path only on the map key. + */ + path?: string; }; function addUncommittedFiles( @@ -60,7 +66,13 @@ function addCumulativeFiles( files: Record, uncommittedPaths: Set, ) { - for (const [path, file] of Object.entries(files)) { + for (const [mapKey, file] of Object.entries(files)) { + // Multi-repo cumulative payloads use a NUL-composite `\x00` + // map key and stamp the clean repo-relative path on `file.path`. + // Single-repo keeps the bare path on the map key with no `file.path`. + // Prefer the stamped value so the composite key doesn't bleed into the + // displayed path; fall back to the map key for single-repo. + const path = file.path ?? mapKey; const key = file.repository_name ? `${file.repository_name}:${path}` : path; const hasRepoUnawareCollision = key !== path && fileMap.has(path); if (fileMap.has(key) || uncommittedPaths.has(key) || hasRepoUnawareCollision) continue;