From 8df70c5886366932d4c97b54a6c1e114dad439e2 Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Wed, 2 Sep 2026 16:13:15 +0000 Subject: [PATCH] fix(web): batch subagent rows per user message instead of per turn Direct subagent spawns were batched into one "Kicked off N subagents" row per turn, so steering a turn mid-run left the row stranded in the segment of the first spawn, counting agents that were launched after the steer. Each direct spawn now gets its own work-log row, and the timeline merges the spawns a segment holds into that segment's first row, so each side of a steer shows its own row with its own agents. Co-Authored-By: Claude Fable 5.1 --- .../chat/MessagesTimeline.logic.test.ts | 21 ++--- .../components/chat/MessagesTimeline.logic.ts | 30 +------ .../src/components/chat/MessagesTimeline.tsx | 2 +- apps/web/src/session-logic.test.ts | 90 +++++++++++++++---- apps/web/src/session-logic.ts | 69 +++++++++----- 5 files changed, 137 insertions(+), 75 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 90fbabb18334d..f8cdf8aabf158 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1559,13 +1559,14 @@ describe("deriveMessagesTimelineRows", () => { return { ...base, entry: { ...base.entry, agentSpawn: { workflowId, agentTaskIds } } }; }; - it("merges direct-spawn CTA rows across a synthetic continuation into the segment's first one", () => { + it("keeps every spawn CTA row visible when the fold collapses", () => { + // deriveTimelineEntries already batched the segment's direct spawns into + // one row, so the fold only has to leave the spawn rows where they are. const timelineEntries = [ userEntry("user-1", "2026-01-01T00:00:00Z"), workEntry("work-1", "2026-01-01T00:00:05Z", "turn-1"), - spawnEntry("spawn-1", "2026-01-01T00:00:06Z", "turn-1", ["agent-a"]), + spawnEntry("spawn-1", "2026-01-01T00:00:06Z", "turn-1", ["agent-a", "agent-b"]), workEntry("work-2", "2026-01-01T00:00:15Z", "turn-2"), - spawnEntry("spawn-2", "2026-01-01T00:00:16Z", "turn-2", ["agent-b"]), // A workflow CTA keeps its own row: the workflow outlives the turn. spawnEntry("spawn-wf", "2026-01-01T00:00:17Z", "turn-2", ["wf-1", "agent-c"], "wf-1"), assistantEntry("assistant-final", "2026-01-01T00:00:30Z", "turn-2"), @@ -1585,25 +1586,21 @@ describe("deriveMessagesTimelineRows", () => { "spawn-wf-entry", "assistant-final-entry", ]); - const mergedRow = rows.find((row) => row.id === "spawn-1-entry"); - expect(mergedRow?.kind === "work" && mergedRow.groupedEntries[0]?.agentSpawn).toEqual({ + const spawnRow = rows.find((row) => row.id === "spawn-1-entry"); + expect(spawnRow?.kind === "work" && spawnRow.groupedEntries[0]?.agentSpawn).toEqual({ workflowId: null, agentTaskIds: ["agent-a", "agent-b"], }); - // Expanding the fold shows every CTA as it was recorded. + // Expanding the fold brings the work rows it hid back. const expandedRows = deriveMessagesTimelineRows({ ...baseFoldInput, timelineEntries, latestTurn, expandedTurnIds: new Set(["turn-2" as never]), }); - expect(expandedRows.map((row) => row.id)).toContain("spawn-2-entry"); - const originalRow = expandedRows.find((row) => row.id === "spawn-1-entry"); - expect(originalRow?.kind === "work" && originalRow.groupedEntries[0]?.agentSpawn).toEqual({ - workflowId: null, - agentTaskIds: ["agent-a"], - }); + expect(expandedRows.map((row) => row.id)).toContain("work-toggle:work-1-entry"); + expect(expandedRows.map((row) => row.id)).toContain("spawn-1-entry"); }); it("keeps the response and its spawn row in the post-steer segment only", () => { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 2c8bc847f654a..535dcb3dea920 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -343,8 +343,6 @@ interface TurnFold { createdAt: string; hiddenEntryIds: ReadonlySet; label: string; - /** The segment's direct-spawn CTA, carrying every direct spawn the fold absorbed. */ - spawnRow: { entryId: string; entry: WorkLogEntry } | null; /** The assistant message that closes the segment, when one does. */ terminalEntryId: string | null; } @@ -452,7 +450,6 @@ function deriveTurnFolds(input: { const terminalEntry = lastEntry.kind === "message" && lastEntry.message.role === "assistant" ? lastEntry : null; const hiddenEntryIds = new Set(); - let spawnRow: TurnFold["spawnRow"] = null; for (const entry of segment.entries) { if (entry === terminalEntry) { continue; @@ -460,24 +457,10 @@ function deriveTurnFolds(input: { // Agent-spawn CTA rows never fold: workflows outlive their launching // turn (dynamic spawns, background execution), and folding the CTA // when the turn settles makes a still-running fleet invisible. Direct - // spawns are batched per turn id upstream, so a synthetic continuation - // yields a second CTA; the fold merges them into the segment's first one. + // spawns are already one row per segment (deriveTimelineEntries), so + // keeping every spawn row visible leaves the segment one CTA. if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) { - if (entry.entry.agentSpawn.workflowId !== null) { - continue; - } - if (spawnRow === null) { - spawnRow = { entryId: entry.id, entry: entry.entry }; - continue; - } - const agentTaskIds = new Set([ - ...(spawnRow.entry.agentSpawn?.agentTaskIds ?? []), - ...entry.entry.agentSpawn.agentTaskIds, - ]); - spawnRow.entry = { - ...spawnRow.entry, - agentSpawn: { workflowId: null, agentTaskIds: [...agentTaskIds] }, - }; + continue; } hiddenEntryIds.add(entry.id); } @@ -509,7 +492,6 @@ function deriveTurnFolds(input: { createdAt: firstHiddenEntry.createdAt, hiddenEntryIds, label, - spawnRow, terminalEntryId: terminalEntry?.id ?? null, }); } @@ -542,7 +524,6 @@ export function deriveMessagesTimelineRows(input: { unsettledTurnId, }); const collapsedEntryIds = new Set(); - const mergedSpawnEntries = new Map(); const foldTerminalEntryIds = new Set(); for (const fold of foldsByAnchorEntryId.values()) { if (fold.terminalEntryId !== null) { @@ -552,9 +533,6 @@ export function deriveMessagesTimelineRows(input: { for (const entryId of fold.hiddenEntryIds) { collapsedEntryIds.add(entryId); } - if (fold.spawnRow) { - mergedSpawnEntries.set(fold.spawnRow.entryId, fold.spawnRow.entry); - } } } @@ -693,7 +671,7 @@ export function deriveMessagesTimelineRows(input: { kind: "work", id: timelineEntry.id, createdAt: timelineEntry.createdAt, - groupedEntries: [mergedSpawnEntries.get(timelineEntry.id) ?? timelineEntry.entry], + groupedEntries: [timelineEntry.entry], isExpandedToolGroupEntry: false, isLastExpandedToolGroupEntry: false, }); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 348475129b32c..e98b6a8aae068 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -2325,7 +2325,7 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string { const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation(); /** - * A1 spawn CTA: one anchored row per workflow run (or per-turn direct-spawn + * A1 spawn CTA: one anchored row per workflow run (or per-segment direct-spawn * batch). Live status is derived from the shared agent panel model at render * time — the row itself never re-renders a roster; the Agents panel is the * only roster. Freezes to past tense when every member settles. Static dot, diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index dc32f84b1e5d6..bb72a4156985f 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -1927,6 +1927,60 @@ describe("deriveTimelineEntries", () => { }, }); }); + + it("batches a turn's direct spawns per segment, so a steer splits the CTA row", () => { + const userMessage = (id: string, createdAt: string) => ({ + id: MessageId.make(id), + role: "user" as const, + text: "go", + createdAt, + turnId: null, + updatedAt: createdAt, + streaming: false, + }); + const spawn = (id: string, createdAt: string, taskId: string) => ({ + id, + createdAt, + label: "Kicked off subagent", + tone: "info" as const, + turnId: TurnId.make("turn-1"), + taskId, + agentSpawn: { workflowId: null, agentTaskIds: [taskId] }, + }); + + const entries = deriveTimelineEntries( + [ + userMessage("user-1", "2026-02-23T00:00:00.000Z"), + userMessage("user-steer", "2026-02-23T00:00:03.000Z"), + ], + [], + [ + spawn("spawn-1", "2026-02-23T00:00:01.000Z", "task-a"), + spawn("spawn-2", "2026-02-23T00:00:02.000Z", "task-b"), + spawn("spawn-3", "2026-02-23T00:00:04.000Z", "task-c"), + spawn("spawn-4", "2026-02-23T00:00:05.000Z", "task-d"), + ], + ); + + expect(entries.map((entry) => entry.id)).toEqual([ + "user-1", + "spawn-1", + "user-steer", + "spawn-3", + ]); + expect( + entries.flatMap((entry) => (entry.kind === "work" ? [entry.entry.agentSpawn] : [])), + ).toEqual([ + { workflowId: null, agentTaskIds: ["task-a", "task-b"] }, + { workflowId: null, agentTaskIds: ["task-c", "task-d"] }, + ]); + // The surviving row keeps the first spawn's identity, so the CTA renders + // where the fleet started. + expect(entries[1]).toMatchObject({ + createdAt: "2026-02-23T00:00:01.000Z", + entry: { id: "spawn-1", turnId: "turn-1" }, + }); + }); }); describe("deriveWorkLogEntries context window handling", () => { @@ -2135,12 +2189,18 @@ describe("deriveWorkLogEntries quiet-timeline guarantee", () => { } const entries = deriveWorkLogEntries(activities); - // A1 CTA design: all direct spawns in one turn collapse into ONE - // call-to-action row carrying the batch's agent ids. + // A1 CTA design: every tick and completion of one agent collapses into + // that agent's single call-to-action row. Batching those rows into one + // "Kicked off 5 subagents" CTA happens per timeline segment, later. const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined); - expect(spawnRows).toHaveLength(1); - expect(spawnRows[0]!.agentSpawn!.agentTaskIds).toHaveLength(5); - expect(spawnRows[0]!.agentSpawn!.workflowId).toBeNull(); + expect(spawnRows.map((row) => row.agentSpawn!.agentTaskIds)).toEqual([ + ["task-0"], + ["task-1"], + ["task-2"], + ["task-3"], + ["task-4"], + ]); + expect(spawnRows.every((row) => row.agentSpawn!.workflowId === null)).toBe(true); // No agent-attributed tool rows leak into the main log. expect(entries.some((entry) => entry.sourceActivityKind?.startsWith("tool."))).toBe(false); }); @@ -2188,9 +2248,7 @@ describe("deriveWorkLogEntries quiet-timeline guarantee", () => { expect(entries).toHaveLength(1); }); - it("folds timelineBypass agent rows into one CTA (Codex children, workflow members)", () => { - // Codex children carry their parent's spawn turn (spawnTurnId stamping), - // which is what batches a fleet into one CTA. + it("keeps timelineBypass agent rows as CTA rows (Codex children, workflow members)", () => { const entries = deriveWorkLogEntries([ makeActivity({ kind: "task.progress", @@ -2207,10 +2265,12 @@ describe("deriveWorkLogEntries quiet-timeline guarantee", () => { turnId: "turn-spawn", }), ]); - // Not suppressed outright (a Codex fleet's rows are ALL bypassed and - // still need a CTA anchor) — but never more than the batch's single row. - expect(entries).toHaveLength(1); - expect(entries[0]!.agentSpawn?.agentTaskIds).toEqual(["child-1", "child-2"]); + // Not suppressed outright: a Codex fleet's rows are ALL bypassed and + // still need a CTA anchor — one per child, never one per progress tick. + expect(entries.map((entry) => entry.agentSpawn?.agentTaskIds)).toEqual([ + ["child-1"], + ["child-2"], + ]); }); it("timelineBypass non-agent rows (background shells) stay suppressed", () => { @@ -2245,9 +2305,9 @@ describe("deriveWorkLogEntries quiet-timeline guarantee", () => { }); describe("rerun workflows", () => { - it("turn-less direct spawns do not collapse into one global batch", () => { - // Rows that lost their turn id (defensive path) group per task, so two - // unrelated turn-less spawns never merge into one immortal CTA. + it("direct spawns do not collapse into one global batch", () => { + // Direct spawns group per task, so two unrelated spawns never merge into + // one immortal CTA accumulating every agent the thread ever ran. const entries = deriveWorkLogEntries([ makeActivity({ kind: "task.started", diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 6d853dc3ea1e7..38139320075c9 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -90,8 +90,8 @@ export interface WorkLogEntry { /** Agent role (subagent_type) for labeled timeline rows. */ agentRole?: string; /** - * Present on agent-spawn CTA rows: one per workflow run or per-turn batch - * of direct spawns. The row renders as a call-to-action ("Kicked off N + * Present on agent-spawn CTA rows: one per workflow run or per-segment + * batch of direct spawns. The row renders as a call-to-action ("Kicked off N * subagents") whose live status is derived from the agent panel model at * render time; clicking opens the Agents panel. */ @@ -987,7 +987,9 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo /** * Spawn-group key for a subagent lifecycle row. Workflow members and their - * coordinator share the coordinator's group; direct spawns batch per turn. + * coordinator share the coordinator's group; a direct spawn is its own group, + * so its progress and completion rows collapse into its own row. Direct + * spawns batch one step later, per timeline segment, in deriveTimelineEntries. * One CTA row per group (A1 design): "Kicked off N subagents". */ function agentSpawnGroupKey(entry: DerivedWorkLogEntry): string { @@ -1002,13 +1004,7 @@ function agentSpawnGroupKey(entry: DerivedWorkLogEntry): string { if (entry.isWorkflowCoordinator) { return `wf:${taskId}`; } - // No turn id means no batch signal at all: fall back to one group per - // task. Unrelated turn-less spawns (separate fleets whose rows lost their - // turn) must not collapse into one immortal "direct:no-turn" CTA - // accumulating every agent the thread ever ran (review finding). Adapters - // stamp spawn turns (Codex spawnTurnId; Claude rows ride real turns), so - // this path is defensive. - return entry.turnId ? `direct:${entry.turnId}` : `direct:task:${taskId}`; + return `direct:task:${taskId}`; } function toolLifecycleCollapseMapKey(entry: DerivedWorkLogEntry): string | undefined { @@ -1026,16 +1022,14 @@ function collapseDerivedWorkLogEntries( ): DerivedWorkLogEntry[] { const collapsed: DerivedWorkLogEntry[] = []; // Subagent rows collapse by spawn group, not adjacency: a workflow run (or - // a turn's batch of direct spawns) is ONE narrative event in the chat — a - // CTA row that opens the Agents panel — no matter how many agents it - // contains or how their progress rows interleave (quiet-timeline - // guarantee). + // a single direct spawn) is ONE narrative event in the chat — a CTA row + // that opens the Agents panel — no matter how many progress rows it emits + // or how they interleave (quiet-timeline guarantee). const spawnRowIndex = new Map(); - // Batch membership is decided once, at the FIRST row seen for a taskId. - // Claude background subagents settle between turns, so their completion - // rows carry fresh synthetic turn ids (or none) — keying each row by its - // own turn splintered one batch into a stream of "Kicked off N subagents" - // rows (live-test finding, thread 7ac7ef05). + // Group membership is decided once, at the FIRST row seen for a taskId: a + // later row can lose the fields the key reads (a workflow coordinator's + // completion payload may drop its workflow name) and must stay in the + // group its spawn joined. const groupKeyByTaskId = new Map(); const toolLifecycleRowIndex = new Map(); for (const entry of entries) { @@ -1807,11 +1801,44 @@ export function deriveTimelineEntries( createdAt: entry.createdAt, entry, })); - return [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) => - a.createdAt.localeCompare(b.createdAt), + return batchDirectSpawnsPerSegment( + [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) => + a.createdAt.localeCompare(b.createdAt), + ), ); } +/** + * User messages cut the timeline into segments, and the direct spawns a + * segment holds are one launch: later ones merge into the segment's first + * spawn row, which keeps its id, time and turn so the CTA renders where the + * fleet started. A steer opens a new segment, so the agents kicked off before + * it and the ones it caused each get their own CTA row. + */ +function batchDirectSpawnsPerSegment(entries: ReadonlyArray): TimelineEntry[] { + let anchor: Extract | null = null; + return entries.filter((entry) => { + if (entry.kind === "message" && entry.message.role === "user") { + anchor = null; + } else if (entry.kind === "work" && entry.entry.agentSpawn?.workflowId === null) { + if (anchor === null) { + anchor = entry; + } else { + const agentTaskIds = new Set([ + ...anchor.entry.agentSpawn!.agentTaskIds, + ...entry.entry.agentSpawn.agentTaskIds, + ]); + anchor.entry = { + ...anchor.entry, + agentSpawn: { workflowId: null, agentTaskIds: [...agentTaskIds] }, + }; + return false; + } + } + return true; + }); +} + export function inferCheckpointTurnCountByTurnId( summaries: ReadonlyArray, ): Record {