feat: auggie subagent detection and single-repo review diff (#1385)

This commit is contained in:
Carlos Florêncio
2026-06-15 20:50:11 +01:00
committed by GitHub
parent e29290fea7
commit 92ed76b438
10 changed files with 504 additions and 31 deletions
@@ -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 ---
@@ -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-<type>: `; 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-<type>:"
//
// 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-<type>: <description>"
// 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-<type>:" 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
}
}
@@ -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)")
}
}
@@ -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-<type>:"
// 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"`
@@ -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 `<repo>\x00<path>` 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");
});
});
+9 -17
View File
@@ -41,24 +41,16 @@ function addCumulativeDiffFiles(
files: CumulativeDiff["files"],
gitStatusFiles: Record<string, FileInfo> | 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 `<repo>\x00<path>`
// 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<string, ReviewFile>, files: PRDiffFile[]) {
}
}
function buildAllFiles(
export function buildAllFiles(
gitStatusFiles: Record<string, FileInfo> | null,
cumulativeDiff: CumulativeDiff | null,
prDiffFiles?: PRDiffFile[],
@@ -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({
</div>
);
}
if (resultText) {
return (
<div className={NESTED_BORDER}>
<p
data-testid="subagent-result-text"
className="text-xs text-foreground/80 whitespace-pre-wrap break-words"
>
{resultText}
</p>
</div>
);
}
if (prompt) {
return (
<div className={NESTED_BORDER}>
@@ -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<boolean | null>(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}
/>
</div>
+3
View File
@@ -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 = {
@@ -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 `<repo>\x00<path>` 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 `<repo>:<repo>\x00<path>` (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,
@@ -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<string, CumulativeFile>,
uncommittedPaths: Set<string>,
) {
for (const [path, file] of Object.entries(files)) {
for (const [mapKey, file] of Object.entries(files)) {
// Multi-repo cumulative payloads use a NUL-composite `<repo>\x00<path>`
// 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;