From 35853883457e0004ac95c196384608b077e240ff Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Sat, 7 Nov 2026 12:33:32 -0800 Subject: [PATCH] Show live agent work only at the end of its conversation Live agent work had several places it could show: a bubble under the request message, the end of the conversation, and the shimmer and Stop control on recorded coordination history. Mounted components negotiated which one showed through a presence registry. Mounted is not visible (the timeline keeps rows within 1600px mounted), so the same work moved as you scrolled, sometimes showed nowhere, briefly showed twice, and got stranded above the agent's own later replies. Now live work has one place: the end of the conversation it happens in, where its reply will land. The request message shows only what happened to it (failed, unconfirmed, stopped). Coordination history is history: it never animates and has no Stop. One rule decides which conversation work belongs to: a top-level request is its own conversation until it has replies, then it is a thread. The channel's end, the thread reply summary, the end indicator's Stop controls and the outcome caption all apply it. The presence registry (typing-presentation), useActivityIndicator, the live bubble and the history's live status projection are deleted. The history projection no longer reads live activity at all. Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz> Signed-off-by: Bradley Axen --- docs/agents.md | 54 +- docs/buzz-help.md | 33 +- scripts/flake-check-costs.json | 3 - src/app/pages.integration.test.mjs | 9 +- .../ActivityAccessory.module.css | 8 - .../agent-activity/ActivityAccessory.test.tsx | 2245 +++++++---------- .../agent-activity/ActivityAccessory.tsx | 787 ++---- src/bundled/agent-activity/README.md | 6 +- .../activity-presentation.test.ts | 129 - .../agent-activity/activity-presentation.ts | 90 - .../agent-activity/current-activity.test.ts | 82 - .../agent-activity/current-activity.ts | 60 - src/bundled/agent-activity/index.tsx | 14 +- src/bundled/agent-activity/manifest.json | 2 +- src/features/agents/current-activity.ts | 45 +- src/features/agents/thread-working.ts | 38 +- src/features/agents/work-stop.ts | 21 +- src/features/conversation/Conversation.tsx | 7 +- .../conversation/typing-presentation.test.tsx | 82 - .../conversation/typing-presentation.tsx | 238 -- .../messages/ActivityGroupActions.tsx | 100 +- .../messages/ActivityGroupPreview.test.tsx | 30 +- .../messages/ActivityGroupPreview.tsx | 43 +- src/features/messages/ChannelTimeline.tsx | 6 +- .../ChannelTimeline.viewport.test.tsx | 159 +- src/features/messages/MediaReviewViewer.tsx | 6 +- src/features/messages/MessageComposer.tsx | 21 +- src/features/messages/MessageRow.test.tsx | 20 +- src/features/messages/MessageRow.tsx | 52 +- src/features/messages/Messages.module.css | 10 +- .../messages/ThreadPanel.identity.test.tsx | 6 +- src/features/messages/ThreadPanel.tsx | 13 +- .../messages/TypingIndicator.test.tsx | 31 +- src/features/messages/TypingIndicator.tsx | 80 +- src/features/messages/activity-groups.test.ts | 375 +-- .../messages/activity-presentation.test.tsx | 88 +- .../messages/activity-presentation.ts | 217 +- .../messages/use-activity-indicator.ts | 83 - .../browser/agent-activity-overhaul.spec.mjs | 525 +--- tests/browser/local-agent-activity.spec.mjs | 426 +--- tests/browser/nested-replies.spec.mjs | 24 +- tests/browser/thread-resize.spec.mjs | 43 +- 42 files changed, 1599 insertions(+), 4712 deletions(-) delete mode 100644 src/bundled/agent-activity/activity-presentation.test.ts delete mode 100644 src/bundled/agent-activity/activity-presentation.ts delete mode 100644 src/bundled/agent-activity/current-activity.test.ts delete mode 100644 src/bundled/agent-activity/current-activity.ts delete mode 100644 src/features/conversation/typing-presentation.test.tsx delete mode 100644 src/features/conversation/typing-presentation.tsx delete mode 100644 src/features/messages/use-activity-indicator.ts diff --git a/docs/agents.md b/docs/agents.md index 6d2e1d8722..48d1c34403 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -1360,15 +1360,28 @@ tasks unknown. ### Activity updates in the conversation -When no live activity bubble on the triggering message shows an agent, the live -conversation indicator remains visible while it works, even when recorded -activity is collapsed or expanded. While that bubble shows, it is the agent's -working indicator and the conversation adds no second one; the conversation cue -returns once recorded history owns the work. The indicator keeps dots beside -current tool labels; reduced motion leaves the dots static. Activity text may -shimmer too, but does not replace that persistent working cue. -When local request evidence is available, old activity does not inherit the -working/thinking state of a different request in the same thread. +Live agent work has one place: the end of the conversation it happens in, where +its reply will land. The timeline's end and a thread's end each show their own +conversation's work; the channel's reply summary says when an agent works in a +thread. Live work never shows on the triggering message or in recorded history, +whatever is mounted or scrolled into view, so it cannot show twice. That +indicator carries the current step, the transcript link and **Stop**, keeps dots +beside current tool labels, and stacks under the agent's latest reply. Reduced +motion leaves the dots static. When local request evidence is available, old +activity does not inherit the working/thinking state of a different request in +the same thread. + +A top-level request is its own conversation until it has replies: its work shows +at the channel's end. Once the request has replies, it is a thread, and its work +is that thread's (its summary in the channel, its end in the thread). Work in a +thread whose root is outside the loaded channel window counts as the channel's. +Turns whose records do not name a thread root use their triggering messages' +thread. + +The triggering message shows only what happened to its request: a failure it +can retry or dismiss, a result Buzz couldn't confirm, or a stop. Once the agent +has replied, that note follows the agent's latest reply instead. Outcomes follow +the same conversation rule as live work. Agent-to-agent coordination messages remain in the conversation as collapsed, expandable history, including after completion, stopping, steering, or reload. @@ -1383,15 +1396,10 @@ not its messages. When lifecycle evidence is missing, a related public reply can retire the old live treatment without claiming that execution completed. Current work continues to appear in the conversation indicator. -A public reply alone does not replace the request's live indicator. Mounted -update history can own the current step and request controls while the live -conversation indicator remains available. When public replies -split one request's updates into several runs, only the latest run for each agent -owns its live shimmer and Stop control; earlier runs remain readable history. -Other agents and requests retain their own live presentation. -Codex transfers live activity to an accepted follow-up in the same conversation. -Top-level DM messages share that presentation scope; actual DM threads remain -independent, even when they share a harness session. +A public reply does not end live work: the conversation's end keeps showing it +until its lifecycle finishes. Update history never animates and has no Stop; it +keeps transcript links. Codex transfers live activity to an accepted follow-up +in the same conversation. The historical-reply fallback requires the reply author to have participated in the exchange or received the helper’s last update. It never overrides available @@ -1408,11 +1416,11 @@ telemetry publication enabled, then give it work. This activity plugin does not start agents. No records may mean publishing is off, no new traffic, or an interrupted feed, not that an agent is idle. -Select an active agent above the channel or thread composer, or its bubble under -the triggering message: it opens the agent's profile on its Activity tab. Disable -the **Agent Activity** plugin in **Settings → Plugins → Manage plugins**, give the -agent work, then re-enable: the bubble and working indicator should return for new -work only. +Select an active agent at the end of the channel or thread: it opens the agent's +profile on its Activity tab. The **Agent Activity** plugin shows what happened to +each request on its message (failures, stops); disabling it in **Settings → +Plugins → Manage plugins** hides those notes, while the end-of-conversation +indicator stays. The feed is best-effort telemetry: producers coalesce/batch and may elide oversized content. It is not a complete ACP transcript. diff --git a/docs/buzz-help.md b/docs/buzz-help.md index c3cf5a9a4e..6dff858b32 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -789,27 +789,22 @@ available rather than silently discarding it. transcripts in the agent's profile. An open transcript updates by itself while the agent works; **Refresh transcript** stays at the top as you scroll. A turn's **Thread** or **Channel** label - opens that conversation. Choosing an agent in the activity under a message, - or a Working now agent whose conversation is known, opens that - conversation's transcript. Working indicators describe current work, - not a guarantee that an agent is available or that a message was delivered. - Expand grouped work updates to read each message; the collapsed excerpt names - its speaker. Thread work appears inside its thread; the channel’s reply summary - still shows when an agent is working there. While the activity under your - message shows an agent working, it is that agent's only working indicator. - Otherwise dots remain at the end of the conversation while agents work, - alongside current step details when available. With Reduce Motion enabled, - the dots stay still. Open the live indicator or expand recorded work to view - the agent’s activity or **Stop** the running request. The live indicator - keeps its controls while recorded updates are visible. Stop availability - depends on the agent type. + opens that conversation. Choosing a Working now agent whose conversation is + known opens that conversation's transcript. Working indicators describe + current work, not a guarantee that an agent is available or that a message + was delivered. + An agent's current work shows in one place: at the end of the conversation, + where its reply will land, with dots and its current step when available. + Thread work appears at the end of its thread; the channel's reply summary + shows when an agent is working there. A message you sent shows only what + happened to it: **Couldn’t finish** (with **Retry** or dismiss), an + unconfirmed result, or **Stopped**. With Reduce Motion enabled, the dots stay + still. Open the indicator at the end to view the agent's activity or **Stop** + the running request. Stop availability depends on the agent type. - Agent-to-agent messages stay in the conversation as collapsed history after work finishes or you reopen a thread. Expand them to read dispatches, handoffs, - and results. The working indicator shows current activity separately. - If more updates arrive after a reply, the newest update group carries that - agent’s live activity and Stop control; earlier groups remain readable history. - In Codex DMs, an accepted follow-up takes over the live indicator; separate - threads keep their own. + and results, or open a transcript. Current work shows at the conversation's + end, not in this history. - A Goose agent's Activity lists the sessions Buzz recorded on this device for each conversation. A conversation with no recorded session, such as one from an earlier version of Buzz or another computer, offers **Search older diff --git a/scripts/flake-check-costs.json b/scripts/flake-check-costs.json index 6aac5da150..39abf3ceb3 100644 --- a/scripts/flake-check-costs.json +++ b/scripts/flake-check-costs.json @@ -3362,8 +3362,6 @@ "src/app/shortcuts.test.tsx": 0.7, "src/bundled/admin-access.test.ts": 0.8, "src/bundled/agent-activity/ActivityAccessory.test.tsx": 3.6, - "src/bundled/agent-activity/activity-presentation.test.ts": 0, - "src/bundled/agent-activity/current-activity.test.ts": 0, "src/bundled/agent-activity/message-activity.test.ts": 0, "src/bundled/agent-activity/request-activity.test.ts": 0, "src/bundled/agents/AgentBrowse.test.tsx": 2, @@ -3815,7 +3813,6 @@ "src/features/conversation/message-preview-text.test.ts": 0, "src/features/conversation/opener.test.tsx": 0.2, "src/features/conversation/service.test.tsx": 1.1, - "src/features/conversation/typing-presentation.test.tsx": 0, "src/features/decisions/agent-tool.test.ts": 0.1, "src/features/decisions/service.test.ts": 0.1, "src/features/developer/client-metrics.test.ts": 0, diff --git a/src/app/pages.integration.test.mjs b/src/app/pages.integration.test.mjs index 3275dbbeb9..c34b75b4fe 100644 --- a/src/app/pages.integration.test.mjs +++ b/src/app/pages.integration.test.mjs @@ -341,15 +341,12 @@ test("the app runtime exposes ready bundled pages and removes them on disable", .snapshot() .some((panel) => panel.pluginId === "buzz.agent-activity"), ); - assert.equal(services.conversation.accessories.snapshot().length, 2); + assert.equal(services.conversation.accessories.snapshot().length, 1); assert.deepEqual( services.conversation.accessories .snapshot() .map(({ id, placement }) => [id, placement]), - [ - ["activity", "response"], - ["typing-presentation", undefined], - ], + [["activity", "response"]], ); assert.equal( services.conversation.accessories.snapshot()[0].pluginId, @@ -359,7 +356,7 @@ test("the app runtime exposes ready bundled pages and removes them on disable", assert.equal(services.conversation.accessories.snapshot().length, 0); await services.plugins.change("enable", "buzz.agent-activity"); await vi.waitFor(() => - assert.equal(services.conversation.accessories.snapshot().length, 2), + assert.equal(services.conversation.accessories.snapshot().length, 1), ); await services.plugins.change("enable", "buzz.bestie"); diff --git a/src/bundled/agent-activity/ActivityAccessory.module.css b/src/bundled/agent-activity/ActivityAccessory.module.css index de1251aa2e..e9d0ed0eeb 100644 --- a/src/bundled/agent-activity/ActivityAccessory.module.css +++ b/src/bundled/agent-activity/ActivityAccessory.module.css @@ -23,9 +23,6 @@ text-overflow: ellipsis; white-space: nowrap; } -.detail { - color: var(--text-subtle); -} .summaryActivity { color: var(--text-subtle); @@ -51,11 +48,6 @@ color: var(--text-danger); } -/* Tabler’s point-up octagon becomes the flat-top stop-sign orientation. */ -.stopIcon { - transform: rotate(22.5deg); -} - .action { align-self: center; flex-shrink: 0; diff --git a/src/bundled/agent-activity/ActivityAccessory.test.tsx b/src/bundled/agent-activity/ActivityAccessory.test.tsx index c029e69202..ac088898ef 100644 --- a/src/bundled/agent-activity/ActivityAccessory.test.tsx +++ b/src/bundled/agent-activity/ActivityAccessory.test.tsx @@ -1,12 +1,9 @@ -import { ActivityGroupPreview } from "../../features/messages/ActivityGroupPreview"; // @vitest-environment jsdom -import { - activityPresentation, - useActivityPresentation, -} from "../../features/messages/activity-presentation"; +import { ActivityGroupPreview } from "../../features/messages/ActivityGroupPreview"; +import { activityPresentation } from "../../features/messages/activity-presentation"; import { MessageRow } from "../../features/messages/MessageRow"; -import { createRelaySession } from "../../features/relay/session"; import { createLocalAgentActivity } from "../../features/agents/local-activity"; +import { createRelaySession } from "../../features/relay/session"; import "@testing-library/jest-dom/vitest"; import { stubAvatarBrowserApis } from "../../features/agents/avatar-testing"; stubAvatarBrowserApis(); @@ -19,23 +16,18 @@ import { within, } from "@testing-library/react"; -import { Profiler } from "react"; import { afterEach, expect, it, vi } from "vitest"; -import { - ActivityAccessory, - ActivityTypingReplacement, -} from "./ActivityAccessory"; -import { - ActivityIndicatorPresentation, - TypingPresentation, -} from "../../features/conversation/typing-presentation"; +import { ActivityAccessory } from "./ActivityAccessory"; import { TypingIndicator } from "../../features/messages/TypingIndicator"; +import { AgentsContext } from "../../features/agents/react"; +import type { Agents } from "../../features/agents/service"; import { claimProfileTranscript, profileTranscriptRequest, } from "../../features/profiles/target"; import { createAgentActivity } from "../../features/agents/activity"; import { createAgentLibrary } from "../../features/agents/library"; +import type { ChannelMessage } from "../../features/relay/contracts"; import type { RelaySession } from "../../features/relay/session"; // Stop's results are host toasts; the shared Toast owns how they show. @@ -86,6 +78,7 @@ function fixture(local?: ReturnType) { [A, { name: "Blossom", isAgent: true as const }], [B, { name: "Bubbles", isAgent: true as const }], ]); + let rows: readonly ChannelMessage[] = []; const session = { viewer, presence: { @@ -100,6 +93,12 @@ function fixture(local?: ReturnType) { subscribe: () => () => {}, ensure: vi.fn(async () => {}), }, + typing: { snapshot: () => noTyping, subscribe: () => () => {} }, + // The loaded channel window, which tells the timeline's end which threads exist. + channels: { + window: () => ({ rows }), + subscribeWindow: () => () => {}, + }, live: { retry: () => activity.state(live) }, media: () => undefined, } as unknown as RelaySession; @@ -154,6 +153,15 @@ function fixture(local?: ReturnType) { activity, release, send, + // A hosted turn for the request, in the conversation its harness names. + start: (agent: string, turnId: string) => + send(agent, turnId, 1, "turn_started", { + triggeringEventIds: [root], + threadRootEventId: root, + }), + setRows: (next: readonly ChannelMessage[]) => { + rows = next; + }, props, live, profiles, @@ -163,262 +171,303 @@ function fixture(local?: ReturnType) { }, }; } +const noTyping: readonly never[] = []; +type Props = ReturnType["props"] & + Partial[0]>; +/** The request message's accessory and its conversation's end indicator, as a + * thread or (with `channel`) the channel timeline mounts them. */ +function Conversation({ + agents, + channel = false, + ...props +}: Props & { agents?: Agents; channel?: boolean }) { + return ( + +
+ +
+
+ +
+
+ ); +} +const settle = () => act(async () => {}); +const request = () => within(screen.getByTestId("request")); +const end = () => within(screen.getByTestId("end")); +const endTrigger = () => + screen + .getByTestId("end") + .querySelector("[data-agent-activity-trigger]"); +const openOutcome = () => + fireEvent.click( + (screen.queryByTestId("request") ? request() : screen).getByRole("button", { + name: /View agent activity/, + }), + ); +const openEnd = () => { + const trigger = endTrigger(); + if (!trigger) throw new Error("No live work at the conversation's end"); + fireEvent.click(trigger); +}; +const stopButton = () => screen.queryByRole("button", { name: "Stop Blossom" }); +// Reopen the end's popup, if anything closed it, to read the agent's row. +const look = () => { + const trigger = endTrigger(); + if (trigger && !screen.queryByRole("dialog")) fireEvent.click(trigger); + return screen; +}; +const stopPending = () => + expect(stopButton()).toHaveAttribute("aria-disabled", "true"); +const stopReady = () => + expect(stopButton()).not.toHaveAttribute("aria-disabled"); +function hosted(running: boolean | Promise = true) { + return { + subscribe: () => () => {}, + snapshot: () => undefined, + interruptible: vi.fn(() => true), + interrupt: vi.fn(async () => running), + }; +} +const asAgents = (agents: ReturnType) => + agents as unknown as Agents; -it("shows one bubble with one avatar per agent across multiple turns, removing only the settled agent", () => { - const f = fixture(); - const view = render(); - try { - f.send(A, "a1", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(A, "a2", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(B, "b1", 1, "turn_started", { triggeringEventIds: [root] }); - expect( - screen.getAllByRole("button", { name: /View agent activity/ }), - ).toHaveLength(1); - expect(screen.getAllByTitle("Blossom")).toHaveLength(1); - expect(screen.getAllByTitle("Bubbles")).toHaveLength(1); - expect(view.container.querySelector(".buzz-avatar-status-dot")).toBeNull(); - f.send(A, "a1", 2, "turn_completed"); - expect( - screen.getByRole("button", { name: /View agent activity: Blossom/ }), - ).toBeInTheDocument(); - f.send(A, "a2", 2, "turn_completed"); - expect( - screen.queryByRole("button", { name: /Blossom/ }), - ).not.toBeInTheDocument(); - expect( - screen.getByRole("button", { name: /View agent activity: Bubbles/ }), - ).toBeInTheDocument(); - f.send(B, "b1", 2, "turn_completed"); - expect( - screen.queryByLabelText("Agent activity on this message"), - ).not.toBeInTheDocument(); - } finally { - view.unmount(); - f.dispose(); - } -}); -it("does not show sibling thread work and reports lost freshness without pretending completion", () => { - const f = fixture(); - const view = render(); - try { - f.send(A, "other", 1, "turn_started", { triggeringEventIds: [next] }); - expect(screen.queryByRole("button")).not.toBeInTheDocument(); - f.send(B, "here", 1, "turn_started", { triggeringEventIds: [root] }); - act(() => vi.advanceTimersByTime(31000)); - expect(screen.getByText("Status unavailable")).toBeInTheDocument(); - f.send(B, "here", 2, "turn_completed"); - expect(screen.queryByRole("button")).not.toBeInTheDocument(); - } finally { - view.unmount(); - f.dispose(); - } -}); -it("keeps a stopped agent visible beside another agent's persistent failure", () => { - const f = fixture(); - const view = render(); - try { - f.send(A, "failed", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(B, "stopped", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(A, "failed", 2, "turn_completed", { outcome: "failed" }); - f.send(B, "stopped", 2, "turn_completed", { outcome: "cancelled" }); - expect(screen.getByText("Couldn’t finish")).toBeInTheDocument(); - expect(screen.getByText("Bubbles · Stopped")).toBeInTheDocument(); - fireEvent.click( - screen.getByRole("button", { - name: /View agent activity: Blossom, failed/, - }), - ); - expect(screen.getByText("Bubbles · Stopped")).toBeInTheDocument(); - expect( - screen.getByText(/This request ended before it could finish/), - ).toBeInTheDocument(); - } finally { - view.unmount(); - f.dispose(); - } -}); -it.each([ - ["failed", "Couldn’t finish"], - ["terminated", "Couldn’t finish"], - ["cancelled", "Stopped"], -])( - "shows remote %s after stale activity and raw-buffer eviction", - (outcome, label) => { - const f = fixture(); - const view = render(); +it.each([false, true])( + "shows live work only at the conversation's end, never on its request (channel=%s)", + (channel) => { + const local = createLocalAgentActivity(); + const f = fixture(local); + const view = render(); try { - f.send(A, "remote", 1, "turn_started", { triggeringEventIds: [root] }); - act(() => vi.advanceTimersByTime(31000)); - expect(screen.getByText("Status unavailable")).toBeInTheDocument(); - f.send(A, "remote", 2, "turn_completed", { outcome }); - expect(screen.getByText(new RegExp(label))).toBeInTheDocument(); - for (let seq = 1; seq <= 201; seq++) - f.send(B, "unrelated", seq, "acp_read"); - expect(screen.queryByText("Status unavailable")).not.toBeInTheDocument(); - expect(screen.getByText(new RegExp(label))).toBeInTheDocument(); - if (outcome !== "cancelled") { - fireEvent.click( - screen.getByRole("button", { - name: /View agent activity: Blossom, failed/, - }), - ); - expect( - screen.getByText(/This request ended before it could finish/), - ).toBeInTheDocument(); - expect( - screen.queryByRole("button", { name: "View activity for Blossom" }), - ).not.toBeInTheDocument(); + let work!: ReturnType; + act(() => { + work = local.begin({ + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }); + }); + const expectOnlyAtEnd = () => { + console.log(screen.getByTestId("end").innerHTML); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); + expect(endTrigger()).toBeVisible(); expect( - screen.queryByRole("button", { name: /Dismiss error/ }), - ).not.toBeInTheDocument(); - } + view.container.querySelectorAll("[data-agent-activity-trigger]"), + ).toHaveLength(1); + }; + expectOnlyAtEnd(); + act(() => work.started()); + expectOnlyAtEnd(); + act(() => work.step("Read", "notes.txt")); + expectOnlyAtEnd(); + expect(end().getByText("Reading notes.txt")).toBeVisible(); + // What happened to the request stays on it; the end has nothing live. + act(() => work.finish({ ok: false, error: "Provider unavailable" })); + expect(endTrigger()).toBeNull(); + expect(request().getByText("Couldn’t finish")).toBeVisible(); } finally { view.unmount(); f.dispose(); } }, ); -it.each(["payload", "prompt"])( - "keeps %s thread scope through partial and full raw-record eviction", - (scope) => { + +it.each([false, true])( + "shows a hosted turn only at its conversation's end (channel=%s)", + (channel) => { const f = fixture(); - const view = render(); + const view = render( + , + ); try { - f.send(A, "thread", 1, "turn_started", { - triggeringEventIds: [root], - ...(scope === "payload" ? { threadRootEventId: root } : {}), - }); - f.send(A, "thread", 2, "acp_write", { - method: "session/prompt", - params: { - prompt: [ - { - type: "text", - text: `\nScope: thread\nThread root: ${root}\n`, - }, - ], - }, - }); - expect( - screen.queryByRole("button", { name: /View agent activity/ }), - ).not.toBeInTheDocument(); - for (let seq = 1; seq <= 150; seq++) - f.send(B, "unrelated", seq, "acp_read"); - f.send(A, "thread", 3, "acp_read"); - for (let seq = 151; seq <= 201; seq++) - f.send(B, "unrelated", seq, "acp_read"); - expect( - screen.queryByRole("button", { name: /View agent activity/ }), - ).not.toBeInTheDocument(); - for (let seq = 202; seq <= 402; seq++) - f.send(B, "unrelated", seq, "acp_read"); + f.start(A, "a"); + f.start(B, "b"); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); expect( - screen.queryByRole("button", { name: /View agent activity/ }), - ).not.toBeInTheDocument(); - view.rerender(); + end().getByRole("button", { name: "Activity: 2 agents working" }), + ).toBeVisible(); + f.send(A, "a", 2, "turn_completed"); expect( - screen.getByRole("button", { name: /View agent activity: Blossom/ }), - ).toBeInTheDocument(); + end().getByRole("button", { name: "Activity: Bubbles working" }), + ).toBeVisible(); + f.send(B, "b", 2, "turn_completed", { outcome: "failed" }); + expect(endTrigger()).toBeNull(); + expect(request().getByText("Couldn’t finish")).toBeVisible(); } finally { view.unmount(); f.dispose(); } }, ); -it("keeps namesakes as separate exact identities", () => { - const f = fixture(); - f.profiles.set(B, { name: "Blossom", isAgent: true as const }); - const view = render(); - try { - f.send(A, "a", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(B, "b", 1, "turn_started", { triggeringEventIds: [root] }); - const avatars = screen.getAllByTitle(/Blossom/); - expect(avatars).toHaveLength(2); - expect(avatars[0]?.getAttribute("title")).not.toBe( - avatars[1]?.getAttribute("title"), - ); - } finally { - view.unmount(); - f.dispose(); - } -}); -it("previews only live scoped actions and retains profile navigation", () => { - const f = fixture(); - const view = render(); +it("moves a top-level request's work from the channel's end into its thread once the thread exists", () => { + const local = createLocalAgentActivity(); + const f = fixture(local); + const view = render(); try { - f.send(A, "old", 1, "turn_started", { triggeringEventIds: [root] }); - const thought = (text: string) => ({ - method: "session/update", - params: { - update: { - sessionUpdate: "agent_thought_chunk", - content: { type: "text", text }, - }, - }, + act(() => { + local + .begin({ + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }) + .started(); }); - f.send(A, "old", 2, "acp_read", thought("Old thought")); - f.send(A, "old", 3, "turn_completed"); - f.send(A, "new", 1, "turn_started", { triggeringEventIds: [root] }); - fireEvent.click( - screen.getByRole("button", { name: /View agent activity/ }), - ); - expect( - screen.getByText("Waiting for activity details"), - ).toBeInTheDocument(); - expect(screen.queryByText("Old thought")).not.toBeInTheDocument(); - f.send(A, "new", 2, "acp_read", thought("Current thought")); - expect(screen.getByText("Current thought")).toBeInTheDocument(); - f.send(B, "sibling", 1, "turn_started", { triggeringEventIds: [next] }); - f.send(B, "sibling", 2, "acp_read", thought("Private sibling thought")); - expect( - screen.queryByText("Private sibling thought"), - ).not.toBeInTheDocument(); - fireEvent.click( - screen.getByRole("button", { name: "View activity for Blossom" }), - ); - const activity = `buzz:profile?agent=${A}&tab=activity`; - expect(f.props.open).toHaveBeenCalledExactlyOnceWith(activity); - // It asks that Activity for this message's transcript, once. - expect(claimProfileTranscript(activity)).toBeDefined(); - act(() => vi.advanceTimersByTime(31000)); - fireEvent.click( - screen.getByRole("button", { name: /View agent activity/ }), - ); - expect( - screen.getByText(/Buzz couldn’t confirm whether this request finished/), - ).toBeInTheDocument(); - expect(screen.queryByText("Current thought")).not.toBeInTheDocument(); + f.start(B, "b"); expect( - screen.queryByRole("button", { name: "View activity for Blossom" }), - ).not.toBeInTheDocument(); - } finally { - view.unmount(); - f.dispose(); - } -}); -it("removes the whole popup when access is revoked", () => { - const f = fixture(); - const view = render(); - try { - f.send(A, "a", 1, "turn_started", { triggeringEventIds: [root] }); - fireEvent.click( - screen.getByRole("button", { name: /View agent activity/ }), - ); - expect(screen.getByRole("dialog")).toBeInTheDocument(); - view.rerender( false} />); - expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); - expect(screen.queryByRole("button")).not.toBeInTheDocument(); + end().getByRole("button", { name: "Activity: 2 agents working" }), + ).toBeVisible(); + // A reply makes the request a thread: its work is that thread's now, and + // the channel shows it in the thread's reply summary instead. + f.setRows([{ ...f.props.message, replyCount: 1 }]); + view.rerender(); + expect(endTrigger()).toBeNull(); } finally { view.unmount(); f.dispose(); } }); -it("makes the compact avatar and tool preview one action, retaining the popup when opening fails", () => { - const f = fixture(); - const activity = `buzz:profile?agent=${A}&tab=activity`; - let asked: number | undefined; +it("keeps coordination history readable but never live: no sheen and no Stop", () => { + const local = createLocalAgentActivity(); + const f = fixture(local); + const stop = vi.fn(async () => {}); + const work = local.begin({ + scope: "test", + agent: A, + channelId: "c", + messageId: root, + threadRootId: root, + thread: true, + }); + work.interruptible(stop); + work.step("Read", "files"); + const row = { + ...f.props.message, + id: "step", + authorId: A, + threadRootId: root, + replyParentId: root, + audience: "agents" as const, + content: "Checking the files", + }; + const { groups, byRow } = activityPresentation([row], new Set([A]), root); + // History rows need the full session surface (reporting and its menus). + const owner = createRelaySession(null); + const session = { ...owner.session, ...f.props.session }; + const group = groups[0]; + if (!group) throw new Error("Missing activity history"); + const view = render( + <> +
+ undefined} + expanded + onToggle={() => {}} + openActivity={f.props.open} + canOpenActivity={f.props.canOpen} + renderHistory={(entry) => ( + undefined} + onOpenLink={f.props.open} + day={false} + retry={undefined} + recordedActivity={{ + ...(byRow.get(entry.id) ?? { container: "bubble" }), + container: "history", + }} + /> + )} + /> +
+ + , + ); + try { + const history = screen.getByTestId("history"); + expect(within(history).getByText("Checking the files")).toBeVisible(); + expect(history.querySelector("[data-active]")).toBeNull(); + expect(end().getByText("Reading files")).toBeVisible(); + // Its one Stop is at the conversation's end; history keeps the transcript. + expect(stopButton()).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "View transcript" })); + const activity = `buzz:profile?agent=${A}&tab=activity`; + expect(f.props.open).toHaveBeenCalledWith(activity, { rootId: root }); + expect(claimProfileTranscript(activity)).toBeDefined(); + openEnd(); + expect( + screen.getAllByRole("button", { name: "Stop Blossom" }), + ).toHaveLength(1); + } finally { + view.unmount(); + owner.dispose(); + f.dispose(); + } +}); + +it("shows a local failure without requiring an ACP transcript, and opens the agent profile", () => { + const local = createLocalAgentActivity(); + const f = fixture(local); + const view = render(); + try { + act(() => { + local + .begin({ + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }) + .finish({ ok: false, error: "Provider unavailable" }); + }); + expect(screen.getByText("Couldn’t finish")).toBeInTheDocument(); + const details = screen.getByRole("button", { + name: /View agent activity: Blossom/, + }); + expect(details.querySelector("[data-state]")).toBeNull(); + fireEvent.click(details); + expect(screen.getByText("Provider unavailable")).toBeInTheDocument(); + fireEvent.click( + screen.getByRole("button", { name: "View activity for Blossom" }), + ); + const activity = `buzz:profile?agent=${A}&tab=activity`; + expect(f.props.open).toHaveBeenCalledExactlyOnceWith(activity); + expect(claimProfileTranscript(activity)).toBeDefined(); + } finally { + view.unmount(); + f.dispose(); + } +}); + +it("keeps the outcome popup when opening the transcript fails, and removes it when access is revoked", () => { + const local = createLocalAgentActivity(); + const f = fixture(local); + const activity = `buzz:profile?agent=${A}&tab=activity`; + let asked: number | undefined; // Opening fails, after seeing whether a transcript was asked for. f.props.open.mockImplementation(() => { asked = profileTranscriptRequest(activity); @@ -426,102 +475,178 @@ it("makes the compact avatar and tool preview one action, retaining the popup wh }); const view = render(); try { - f.send(A, "a", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(A, "a", 2, "acp_read", { - method: "session/update", - params: { - update: { - sessionUpdate: "tool_call", - toolCallId: "read", - title: "buzz-dev-mcp__read_file", - status: "in_progress", - rawInput: { path: "/project/file.ts" }, - }, - }, + act(() => { + local + .begin({ + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }) + .finish({ ok: false, error: "Provider unavailable" }); }); fireEvent.click( screen.getByRole("button", { name: /View agent activity/ }), ); - const popup = within( - screen.getByRole("dialog", { name: "Agent activity" }), + fireEvent.click( + screen.getByRole("button", { name: "View activity for Blossom" }), ); - // The agent's row is the popup's one action; no separate Activity heading. - expect(popup.getAllByRole("button")).toHaveLength(1); - for (const text of [ - "Agent activity", - "Latest reported activity for this message.", - "Blossom", - "View activity", - "Close", - ]) - expect(popup.queryByText(text, { exact: true })).not.toBeInTheDocument(); - const row = popup.getByRole("button", { - name: "View activity for Blossom", - }); - expect(row).toHaveTextContent("Read file · Running"); - expect(row.querySelector(".buzz-avatar")).not.toBeNull(); - fireEvent.click(row); expect(f.props.open).toHaveBeenCalledExactlyOnceWith(activity); expect(asked).toBeDefined(); // The failed opening leaves no request behind for a later Activity. expect(claimProfileTranscript(activity)).toBeUndefined(); expect(screen.getByRole("dialog")).toBeInTheDocument(); - view.rerender( - !target.startsWith("buzz:profile?")} - />, + view.rerender( false} />); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(screen.queryByRole("button")).not.toBeInTheDocument(); + } finally { + view.unmount(); + f.dispose(); + } +}); + +it("keeps namesakes as separate exact identities", () => { + const f = fixture(); + f.profiles.set(B, { name: "Blossom", isAgent: true as const }); + const view = render(); + try { + f.send(A, "a", 1, "turn_started", { triggeringEventIds: [root] }); + f.send(B, "b", 1, "turn_started", { triggeringEventIds: [root] }); + f.send(A, "a", 2, "turn_completed", { outcome: "failed" }); + f.send(B, "b", 2, "turn_completed", { outcome: "failed" }); + const titles = screen + .getAllByTitle(/Blossom/) + .map((avatar) => avatar.getAttribute("title")); + expect(new Set(titles).size).toBe(2); + } finally { + view.unmount(); + f.dispose(); + } +}); + +it.each(["payload", "prompt"])( + "keeps %s thread scope through partial and full raw-record eviction", + (scope) => { + const f = fixture(); + // The request's thread exists, so its work is that thread's. + f.props.message.replyCount = 1; + const view = render(); + try { + f.send(A, "thread", 1, "turn_started", { + triggeringEventIds: [root], + ...(scope === "payload" ? { threadRootEventId: root } : {}), + }); + f.send(A, "thread", 2, "acp_write", { + method: "session/prompt", + params: { + prompt: [ + { + type: "text", + text: `\nScope: thread\nThread root: ${root}\n`, + }, + ], + }, + }); + for (let seq = 1; seq <= 150; seq++) + f.send(B, "unrelated", seq, "acp_read"); + f.send(A, "thread", 3, "acp_read"); + for (let seq = 151; seq <= 201; seq++) + f.send(B, "unrelated", seq, "acp_read"); + f.send(A, "thread", 4, "turn_completed", { outcome: "failed" }); + expect( + screen.queryByRole("button", { name: /View agent activity/ }), + ).not.toBeInTheDocument(); + for (let seq = 202; seq <= 402; seq++) + f.send(B, "unrelated", seq, "acp_read"); + expect( + screen.queryByRole("button", { name: /View agent activity/ }), + ).not.toBeInTheDocument(); + view.rerender(); + expect( + screen.getByRole("button", { name: /View agent activity: Blossom/ }), + ).toBeInTheDocument(); + } finally { + view.unmount(); + f.dispose(); + } + }, +); + +it.each([false, true])( + "keeps a thread request's outcome in its thread (local=%s)", + (isLocal) => { + const local = createLocalAgentActivity(); + const f = fixture(isLocal ? local : undefined); + f.props.message.replyCount = 1; + if (isLocal) + local + .begin({ + scope: "test", + agent: A, + channelId: "c", + messageId: root, + threadRootId: root, + thread: true, + }) + .finish({ ok: false, error: "Provider unavailable" }); + else { + f.start(A, "turn"); + f.send(A, "turn", 2, "turn_completed", { outcome: "failed" }); + } + const view = render( + , ); - expect( - screen.queryByRole("button", { name: "View activity for Blossom" }), - ).not.toBeInTheDocument(); - expect(f.props.open).toHaveBeenCalledOnce(); + try { + expect( + screen.queryByLabelText("Agent activity on this message"), + ).toBeNull(); + view.rerender(); + expect( + screen.getByLabelText("Agent activity on this message"), + ).toBeVisible(); + } finally { + view.unmount(); + f.dispose(); + } + }, +); + +it("does not show sibling thread work and reports lost freshness without pretending completion", () => { + const f = fixture(); + const view = render(); + try { + f.send(A, "other", 1, "turn_started", { triggeringEventIds: [next] }); + expect(screen.queryByRole("button")).not.toBeInTheDocument(); + f.send(B, "here", 1, "turn_started", { triggeringEventIds: [root] }); + act(() => vi.advanceTimersByTime(31000)); + expect(screen.getByText("Status unavailable")).toBeInTheDocument(); + f.send(B, "here", 2, "turn_completed"); + expect(screen.queryByRole("button")).not.toBeInTheDocument(); } finally { view.unmount(); f.dispose(); } }); -it("keeps conversation dots visible alongside message-linked activity", () => { +it("keeps a stopped agent visible beside another agent's persistent failure", () => { const f = fixture(); - const typing = [{ pubkey: A, channelId: "c", threadRootId: root }]; - const session = { - ...f.props.session, - typing: { snapshot: () => typing, subscribe: () => () => {} }, - } as unknown as RelaySession; - const props = { ...f.props, session }; - const ui = (replacement: boolean) => ( - - {/* MessageRow gives each row its own presentation scope. */} - - - - {replacement && } - - - ); - const view = render(ui(true)); + const view = render(); try { - f.send(A, "unlinked", 1, "turn_liveness"); - expect( - screen.getByRole("button", { name: "Activity: Blossom working" }), - ).toBeInTheDocument(); - f.send(A, "sibling", 1, "turn_started", { triggeringEventIds: [next] }); - expect( - screen.getByRole("button", { name: "Activity: Blossom working" }), - ).toBeInTheDocument(); - f.send(A, "here", 1, "turn_started", { triggeringEventIds: [root] }); - expect( + f.send(A, "failed", 1, "turn_started", { triggeringEventIds: [root] }); + f.send(B, "stopped", 1, "turn_started", { triggeringEventIds: [root] }); + f.send(A, "failed", 2, "turn_completed", { outcome: "failed" }); + f.send(B, "stopped", 2, "turn_completed", { outcome: "cancelled" }); + expect(screen.getByText("Couldn’t finish")).toBeInTheDocument(); + expect(screen.getByText("Bubbles · Stopped")).toBeInTheDocument(); + fireEvent.click( screen.getByRole("button", { - name: "View agent activity: Blossom, working", + name: /View agent activity: Blossom, failed/, }), - ).toBeInTheDocument(); - expect( - screen.getByRole("button", { name: "Activity: Blossom working" }), - ).toBeInTheDocument(); - view.rerender(ui(false)); + ); + expect(screen.getByText("Bubbles · Stopped")).toBeInTheDocument(); expect( - screen.getByRole("button", { name: "Activity: Blossom working" }), + screen.getByText(/This request ended before it could finish/), ).toBeInTheDocument(); } finally { view.unmount(); @@ -529,53 +654,263 @@ it("keeps conversation dots visible alongside message-linked activity", () => { } }); -it("shows local receipt and failure without requiring an ACP transcript, and opens the agent profile", () => { +it.each([ + ["failed", "Couldn’t finish"], + ["terminated", "Couldn’t finish"], + ["cancelled", "Stopped"], +])( + "shows remote %s after stale activity and raw-buffer eviction", + (outcome, label) => { + const f = fixture(); + const view = render(); + try { + f.send(A, "remote", 1, "turn_started", { triggeringEventIds: [root] }); + act(() => vi.advanceTimersByTime(31000)); + expect(screen.getByText("Status unavailable")).toBeInTheDocument(); + f.send(A, "remote", 2, "turn_completed", { outcome }); + expect(screen.getByText(new RegExp(label))).toBeInTheDocument(); + for (let seq = 1; seq <= 201; seq++) + f.send(B, "unrelated", seq, "acp_read"); + expect(screen.queryByText("Status unavailable")).not.toBeInTheDocument(); + expect(screen.getByText(new RegExp(label))).toBeInTheDocument(); + if (outcome !== "cancelled") { + fireEvent.click( + screen.getByRole("button", { + name: /View agent activity: Blossom, failed/, + }), + ); + expect( + screen.getByText(/This request ended before it could finish/), + ).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "View activity for Blossom" }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: /Dismiss error/ }), + ).not.toBeInTheDocument(); + } + } finally { + view.unmount(); + f.dispose(); + } + }, +); + +it.each([false, true])( + "returns focus after retiring the last error unless focus moved: %s", + async (moved) => { + const local = createLocalAgentActivity(); + const f = fixture(local); + const onFocusedRemoval = vi.fn(); + const view = render( + <> + + + , + ); + try { + act(() => { + local + .begin({ + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }) + .finish({ ok: false, error: "Provider unavailable" }); + }); + fireEvent.click( + screen.getByRole("button", { name: /View agent activity/ }), + ); + const dismiss = screen.getByRole("button", { + name: "Dismiss error from Blossom", + }); + act(() => dismiss.focus()); + fireEvent.click(dismiss); + // The owned clock holds the handoff microtask after React removes the + // popup, so a deliberate focus move wins before that handoff runs. + expect(onFocusedRemoval).not.toHaveBeenCalled(); + if (moved) + act(() => screen.getByRole("button", { name: "Other task" }).focus()); + await act(async () => vi.runAllTicks()); + expect(onFocusedRemoval).toHaveBeenCalledTimes(moved ? 0 : 1); + expect(screen.queryByText("Provider unavailable")).toBeNull(); + } finally { + view.unmount(); + f.dispose(); + } + }, +); + +it("does not duplicate a replied thread failure on its channel request", () => { + const f = fixture(); + const view = render( + <> +
+ +
+
+ +
+ , + ); + try { + f.send(A, "thread", 1, "turn_started", { + triggeringEventIds: [root], + threadRootEventId: root, + }); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); + f.send(A, "thread", 2, "turn_completed", { outcome: "terminated" }); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); + expect(screen.getByTestId("sibling")).toBeEmptyDOMElement(); + expect(f.props.open).not.toHaveBeenCalled(); + } finally { + view.unmount(); + f.dispose(); + } +}); + +it.each(["thread", "continuation"] as const)( + "keeps a thread request's stopped note on a %s reply", + async (layout) => { + const local = createLocalAgentActivity(); + const f = fixture(local); + const reply = { + ...f.props.message, + id: next, + authorId: A, + threadRootId: root, + replyParentId: root, + createdAt: 2, + content: "On it", + }; + const view = render( + <> +
+ +
+
+ +
+ , + ); + try { + act(() => { + local + .begin({ + scope: "test", + agent: A, + channelId: "c", + messageId: root, + threadRootId: root, + thread: true, + }) + .interruptible(async () => {}); + }); + await act(() => f.props.session.agentActivity.interrupt(A, "c", root)); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); + expect( + within(screen.getByTestId("reply")).getByText("Stopped"), + ).toBeInTheDocument(); + } finally { + view.unmount(); + f.dispose(); + } + }, +); + +it("notes only stopped requests once their work settles", () => { const local = createLocalAgentActivity(); const f = fixture(local); const view = render(); try { - let work!: ReturnType; act(() => { - work = local.begin({ + local + .begin({ + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }) + .finish({ ok: true }); + }); + expect( + screen.queryByLabelText("Agent activity on this message"), + ).not.toBeInTheDocument(); + expect(screen.queryByText(/Stopped/)).not.toBeInTheDocument(); + } finally { + view.unmount(); + f.dispose(); + } +}); + +it("says why a failed request could not be retried, keeping it to try again or dismiss", () => { + const local = createLocalAgentActivity(); + const f = fixture(local); + const view = render(); + const retry = vi.fn(() => { + throw new Error("Blossom isn't running here."); + }); + const begin = (agent: string, again?: () => void) => + local.begin( + { scope: "test", channelId: "c", threadRootId: root, messageId: root, - agent: A, - }); - }); - const bubble = screen.getByRole("button", { - name: "View agent activity: Blossom, Received · waiting to start", + agent, + }, + again, + ); + try { + act(() => { + begin(A, retry).finish({ ok: false, error: "Provider unavailable" }); + begin(B).finish({ ok: false, error: "Busy" }); }); - expect(bubble.querySelector('[data-state="waiting"]')).not.toBeNull(); - act(() => work.started()); - expect(bubble).toHaveAccessibleName( - "View agent activity: Blossom, Starting", - ); - expect(bubble.querySelector('[data-state="waiting"]')).not.toBeNull(); - act(() => work.step("send_message")); - expect(bubble).not.toHaveTextContent("Sending a message"); - expect(bubble.querySelector('[data-state="working"]')).not.toBeNull(); - act(() => work.step("Read", "notes.txt")); - expect(bubble).toHaveAccessibleName( - "View agent activity: Blossom, Reading notes.txt", + openOutcome(); + // Only a request that can be asked again offers Retry. + expect( + screen.queryByRole("button", { name: "Retry Bubbles" }), + ).not.toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Dismiss error from Bubbles" }), + ).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Retry Blossom" })); + expect(retry).toHaveBeenCalledOnce(); + expect(notify).toHaveBeenCalledExactlyOnceWith( + "Couldn’t retry Blossom. Blossom isn't running here.", + "error", ); - expect(bubble).toHaveTextContent("Reading notes.txt"); - expect(bubble.querySelector('[data-state="working"]')).not.toBeNull(); - act(() => work.finish({ ok: false, error: "Provider unavailable" })); - expect(screen.getByText("Couldn’t finish")).toBeInTheDocument(); - const details = screen.getByRole("button", { - name: /View agent activity: Blossom/, - }); - expect(details.querySelector("[data-state]")).toBeNull(); - fireEvent.click(details); expect(screen.getByText("Provider unavailable")).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Retry Blossom" }), + ).toBeInTheDocument(); fireEvent.click( - screen.getByRole("button", { name: "View activity for Blossom" }), + screen.getByRole("button", { name: "Dismiss error from Blossom" }), ); - const activity = `buzz:profile?agent=${A}&tab=activity`; - expect(f.props.open).toHaveBeenCalledExactlyOnceWith(activity); - expect(claimProfileTranscript(activity)).toBeDefined(); + expect(screen.queryByText("Provider unavailable")).toBeNull(); + expect(retry).toHaveBeenCalledOnce(); } finally { view.unmount(); f.dispose(); @@ -587,7 +922,7 @@ it("dismisses only that agent's error on this message, without changing other wo const f = fixture(local); const onFocusedRemoval = vi.fn(); const view = render( - , + , ); const begin = (agent: string, messageId: string) => local.begin({ @@ -606,18 +941,14 @@ it("dismisses only that agent's error on this message, without changing other wo begin(A, next).finish({ ok: false, error: "Elsewhere" }); begin(B, root).step("Read", "notes.txt"); }); - const mixed = screen.getByRole("button", { name: /View agent activity/ }); - expect(mixed).toHaveTextContent("1 failed"); - const failedBadge = mixed.querySelector("[data-activity-failure]"); - const workingBadge = mixed.querySelector("[data-thread-working]"); - expect( - screen.getByRole("img", { name: "Blossom, Bubbles" }), - ).toBeInTheDocument(); - expect(failedBadge?.parentElement).toBe(workingBadge?.parentElement); - expect(workingBadge).toHaveTextContent("Reading notes.txt"); - fireEvent.click( - screen.getByRole("button", { name: /View agent activity/ }), - ); + // The failure is the request's; the other agent's live step is the end's. + const failed = request().getByRole("button", { + name: /View agent activity/, + }); + expect(request().getByText("Couldn’t finish")).toBeVisible(); + expect(request().queryByText("Reading notes.txt")).toBeNull(); + expect(end().getByText("Reading notes.txt")).toBeVisible(); + fireEvent.click(failed); expect( screen.getByText("Provider unavailable after a long and detailed reason") .parentElement, @@ -629,13 +960,8 @@ it("dismisses only that agent's error on this message, without changing other wo screen.getByRole("button", { name: "Dismiss error from Blossom" }), ); expect(f.props.open).not.toHaveBeenCalled(); - expect(onFocusedRemoval).not.toHaveBeenCalled(); - expect( - screen.getByRole("button", { name: "View activity for Bubbles" }), - ).toBeInTheDocument(); - expect( - screen.queryByRole("button", { name: "View activity for Blossom" }), - ).toBeNull(); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); + expect(end().getByText("Reading notes.txt")).toBeVisible(); expect( local.reader .work() @@ -652,147 +978,8 @@ it("dismisses only that agent's error on this message, without changing other wo } }); -it.each([false, true])( - "returns focus after retiring the last error unless focus moved: %s", - async (moved) => { - const local = createLocalAgentActivity(); - const f = fixture(local); - const onFocusedRemoval = vi.fn(); - const view = render( - <> - - - , - ); - try { - act(() => { - local - .begin({ - scope: "test", - channelId: "c", - threadRootId: root, - messageId: root, - agent: A, - }) - .finish({ ok: false, error: "Provider unavailable" }); - }); - fireEvent.click( - screen.getByRole("button", { name: /View agent activity/ }), - ); - const dismiss = screen.getByRole("button", { - name: "Dismiss error from Blossom", - }); - act(() => dismiss.focus()); - fireEvent.click(dismiss); - // The owned clock holds the handoff microtask after React removes the - // popup, so a deliberate focus move wins before that handoff runs. - expect(onFocusedRemoval).not.toHaveBeenCalled(); - if (moved) - act(() => screen.getByRole("button", { name: "Other task" }).focus()); - await act(async () => vi.runAllTicks()); - expect(onFocusedRemoval).toHaveBeenCalledTimes(moved ? 0 : 1); - expect(screen.queryByText("Provider unavailable")).toBeNull(); - } finally { - view.unmount(); - f.dispose(); - } - }, -); - -it.each([false, true])( - "keeps live activity after a public reply without hiding other work (thread=%s)", - async (thread) => { - const f = fixture(); - const onFocusedRemoval = vi.fn(); - const view = render( - , - ); - try { - expect( - screen.queryByLabelText("Agent activity on this message"), - ).toBeNull(); - f.send(A, "here", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(B, "other", 1, "turn_started", { triggeringEventIds: [root] }); - const response = { - ...f.props.message, - id: "response", - authorId: A, - agentEnvelope: true as const, - content: "Here is the answer", - replyParentId: root, - }; - const rows = [ - f.props.message, - { ...f.props.message, id: next }, - response, - ]; - const represented = activityPresentation( - thread ? rows.slice(1) : rows, - undefined, - new Set([A, B]), - thread ? root : undefined, - ).representedAgents; - view.rerender( - , - ); - expect(screen.getByTitle("Blossom")).toBeInTheDocument(); - expect(screen.getByTitle("Bubbles")).toBeInTheDocument(); - expect(represented.get(next)).toBeUndefined(); - act(() => - screen.getByRole("button", { name: /View agent activity/ }).focus(), - ); - f.send(B, "other", 2, "turn_completed"); - expect(screen.getByTitle("Blossom")).toBeInTheDocument(); - f.send(A, "here", 2, "turn_completed"); - await act(async () => vi.runAllTicks()); - expect(onFocusedRemoval).toHaveBeenCalledOnce(); - expect( - screen.queryByLabelText("Agent activity on this message"), - ).toBeNull(); - view.rerender( - , - ); - expect(screen.queryByTitle("Blossom")).toBeNull(); - } finally { - view.unmount(); - f.dispose(); - } - }, -); - -const settle = () => act(async () => {}); -const openBubble = () => - fireEvent.click(screen.getByRole("button", { name: /View agent activity/ })); -const stopButton = () => screen.queryByRole("button", { name: "Stop Blossom" }); -// Reopen the popup, if anything closed it, to read the agent's row. -const look = () => { - const activity = screen.queryByRole("button", { - name: /View agent activity/, - }); - if (activity && !screen.queryByRole("dialog")) fireEvent.click(activity); - return screen; -}; -const stopPending = () => - expect(stopButton()).toHaveAttribute("aria-disabled", "true"); -const stopReady = () => - expect(stopButton()).not.toHaveAttribute("aria-disabled"); -function hosted(running: boolean | Promise = true) { - return { - interruptible: vi.fn(() => true), - interrupt: vi.fn(async () => running), - }; -} - it.each(["waiting", "working"])( - "stops a local request that is %s through its harness, then notes it stopped", + "stops a local request that is %s from the conversation's end, then notes it stopped on the request", async (state) => { const local = createLocalAgentActivity(); const f = fixture(local); @@ -803,7 +990,7 @@ it.each(["waiting", "working"])( agentActivity: { ...queries, interrupt }, }; const stop = vi.fn(async () => {}); - const view = render(); + const view = render(); try { act(() => { const work = local.begin({ @@ -816,7 +1003,7 @@ it.each(["waiting", "working"])( work.interruptible(stop); if (state === "working") work.started(); }); - openBubble(); + openEnd(); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); expect(interrupt).toHaveBeenCalledExactlyOnceWith(A, "c", root); await settle(); @@ -825,10 +1012,8 @@ it.each(["waiting", "working"])( "Stopped Blossom", "success", ); - expect( - screen.queryByRole("button", { name: /View agent activity/ }), - ).not.toBeInTheDocument(); - expect(screen.getByText("Blossom · Stopped")).toBeInTheDocument(); + expect(endTrigger()).toBeNull(); + expect(request().getByText("Blossom · Stopped")).toBeInTheDocument(); // Handling the same message again replaces the note with its live work. act(() => { local @@ -842,9 +1027,7 @@ it.each(["waiting", "working"])( .started(); }); expect(screen.queryByText(/Stopped/)).not.toBeInTheDocument(); - expect( - screen.getByRole("button", { name: /View agent activity: Blossom/ }), - ).toBeInTheDocument(); + expect(endTrigger()).toBeVisible(); } finally { view.unmount(); f.dispose(); @@ -874,9 +1057,7 @@ it.each([ }) .interruptible(async () => {}); }); - expect( - screen.getByRole("button", { name: /View agent activity: Blossom/ }), - ).toBeInTheDocument(); + expect(view.container).toBeEmptyDOMElement(); // Stop retains its exact request and response-side notice. await act(() => f.props.session.agentActivity.interrupt(A, "c", root)); expect( @@ -907,162 +1088,50 @@ it("moves a stopped note below the agent's latest public reply", async () => {
-
- -
- , - ); - try { - act(() => { - local - .begin({ - scope: "test", - channelId: "c", - threadRootId: root, - messageId: root, - agent: A, - }) - .interruptible(async () => {}); - }); - // Live work stays on its request; a reply does not take the bubble. - expect( - within(screen.getByTestId("request")).getByRole("button", { - name: /View agent activity: Blossom/, - }), - ).toBeInTheDocument(); - expect(screen.getByTestId("reply")).toBeEmptyDOMElement(); - await act(() => f.props.session.agentActivity.interrupt(A, "c", root)); - expect(screen.getByTestId("request")).toBeEmptyDOMElement(); - expect( - within(screen.getByTestId("reply")).getByText("Stopped"), - ).toBeInTheDocument(); - } finally { - view.unmount(); - f.dispose(); - } -}); -it.each(["failed", "terminated", "unknown"])( - "places a remote %s caption beneath its reply without repeating the agent identity", - (outcome) => { - const f = fixture(); - const reply = { - ...f.props.message, - id: next, - authorId: A, - createdAt: 2, - content: "An agent reply", - }; - const view = render( - <> -
- -
-
- -
- , - ); - try { - f.send(A, "remote", 1, "turn_started", { triggeringEventIds: [root] }); - expect( - within(screen.getByTestId("request")).getByRole("button", { - name: /View agent activity/, - }), - ).toBeInTheDocument(); - expect(screen.getByTestId("reply")).toBeEmptyDOMElement(); - if (outcome === "unknown") act(() => vi.advanceTimersByTime(31000)); - else f.send(A, "remote", 2, "turn_completed", { outcome }); - expect(screen.getByTestId("request")).toBeEmptyDOMElement(); - const caption = within(screen.getByTestId("reply")); - expect( - caption.getByText( - outcome === "unknown" ? "Status unavailable" : "Couldn’t finish", - ), - ).toBeInTheDocument(); - expect(caption.queryByText("Blossom")).not.toBeInTheDocument(); - expect( - screen.getByTestId("reply").querySelector("[data-avatar-stack]"), - ).toBeNull(); - fireEvent.click( - caption.getByRole("button", { name: /View agent activity/ }), - ); - expect( - screen.getByRole("dialog", { name: "Agent activity" }), - ).toHaveTextContent( - outcome === "unknown" - ? "Buzz couldn’t confirm" - : "This request ended before it could finish", - ); - expect(f.props.open).not.toHaveBeenCalled(); - } finally { - view.unmount(); - f.dispose(); - } - }, -); -it("does not duplicate a replied thread failure on its channel request", () => { - const f = fixture(); - const view = render( - <> -
- -
-
+
, ); try { - f.send(A, "thread", 1, "turn_started", { - triggeringEventIds: [root], - threadRootEventId: root, + act(() => { + local + .begin({ + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }) + .interruptible(async () => {}); }); + // Neither message shows live work. expect(screen.getByTestId("request")).toBeEmptyDOMElement(); - f.send(A, "thread", 2, "turn_completed", { outcome: "terminated" }); + expect(screen.getByTestId("reply")).toBeEmptyDOMElement(); + await act(() => f.props.session.agentActivity.interrupt(A, "c", root)); expect(screen.getByTestId("request")).toBeEmptyDOMElement(); - expect(screen.getByTestId("sibling")).toBeEmptyDOMElement(); - expect(f.props.open).not.toHaveBeenCalled(); + expect( + within(screen.getByTestId("reply")).getByText("Stopped"), + ).toBeInTheDocument(); } finally { view.unmount(); f.dispose(); } }); -it.each(["thread", "continuation"] as const)( - "keeps a thread request's stopped note on a %s reply", - async (layout) => { - const local = createLocalAgentActivity(); - const f = fixture(local); +it.each(["failed", "terminated", "unknown"])( + "places a remote %s caption beneath its reply without repeating the agent identity", + (outcome) => { + const f = fixture(); const reply = { ...f.props.message, id: next, authorId: A, - threadRootId: root, - replyParentId: root, createdAt: 2, - content: "On it", + content: "An agent reply", }; const view = render( <> @@ -1077,63 +1146,92 @@ it.each(["thread", "continuation"] as const)(
, ); try { - act(() => { - local - .begin({ - scope: "test", - agent: A, - channelId: "c", - messageId: root, - threadRootId: root, - thread: true, - }) - .interruptible(async () => {}); - }); - await act(() => f.props.session.agentActivity.interrupt(A, "c", root)); + f.send(A, "remote", 1, "turn_started", { triggeringEventIds: [root] }); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); + expect(screen.getByTestId("reply")).toBeEmptyDOMElement(); + if (outcome === "unknown") act(() => vi.advanceTimersByTime(31000)); + else f.send(A, "remote", 2, "turn_completed", { outcome }); expect(screen.getByTestId("request")).toBeEmptyDOMElement(); + const caption = within(screen.getByTestId("reply")); expect( - within(screen.getByTestId("reply")).getByText("Stopped"), + caption.getByText( + outcome === "unknown" ? "Status unavailable" : "Couldn’t finish", + ), ).toBeInTheDocument(); + expect(caption.queryByText("Blossom")).not.toBeInTheDocument(); + expect( + screen.getByTestId("reply").querySelector("[data-avatar-stack]"), + ).toBeNull(); + fireEvent.click( + caption.getByRole("button", { name: /View agent activity/ }), + ); + expect( + screen.getByRole("dialog", { name: "Agent activity" }), + ).toHaveTextContent( + outcome === "unknown" + ? "Buzz couldn’t confirm" + : "This request ended before it could finish", + ); + expect(f.props.open).not.toHaveBeenCalled(); } finally { view.unmount(); f.dispose(); } }, ); -it("notes only stopped requests once their work settles", () => { + +it("retries a failed local request from its row, before Dismiss, which begins it again at the conversation's end", () => { const local = createLocalAgentActivity(); const f = fixture(local); - const view = render(); + const view = render(); + const retry = vi.fn(() => void begin()); + function begin() { + return local.begin( + { + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }, + retry, + ); + } try { - act(() => { - local - .begin({ - scope: "test", - channelId: "c", - threadRootId: root, - messageId: root, - agent: A, - }) - .finish({ ok: true }); - }); + act(() => begin().finish({ ok: false, error: "Provider unavailable" })); + openOutcome(); + const again = screen.getByRole("button", { name: "Retry Blossom" }); + expect(again).toHaveTextContent("Retry"); expect( - screen.queryByLabelText("Agent activity on this message"), + again.compareDocumentPosition( + screen.getByRole("button", { name: "Dismiss error from Blossom" }), + ) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + fireEvent.click(again); + expect(retry).toHaveBeenCalledOnce(); + expect(f.props.open).not.toHaveBeenCalled(); + expect(notify).not.toHaveBeenCalled(); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); + expect( + end().getByRole("button", { name: "Activity: Blossom working" }), + ).toBeVisible(); + expect( + screen.queryByRole("button", { name: "Retry Blossom" }), ).not.toBeInTheDocument(); - expect(screen.queryByText(/Stopped/)).not.toBeInTheDocument(); } finally { view.unmount(); f.dispose(); } }); -it("hands focus back to the host when a focused Stop retires with its work", async () => { +it("hands focus back to the host when a focused Retry retires its outcome", async () => { const local = createLocalAgentActivity(); const f = fixture(local); const onFocusedRemoval = vi.fn(); @@ -1143,21 +1241,31 @@ it("hands focus back to the host when a focused Stop retires with its work", asy try { act(() => { local - .begin({ - scope: "test", - channelId: "c", - threadRootId: root, - messageId: root, - agent: A, - }) - .interruptible(async () => {}); + .begin( + { + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }, + () => { + local.begin({ + scope: "test", + channelId: "c", + threadRootId: root, + messageId: root, + agent: A, + }); + }, + ) + .finish({ ok: false, error: "Provider unavailable" }); }); - openBubble(); - const stop = stopButton() as HTMLElement; - act(() => stop.focus()); - fireEvent.click(stop); - await settle(); - expect(stop.isConnected).toBe(false); + openOutcome(); + const again = screen.getByRole("button", { name: "Retry Blossom" }); + act(() => again.focus()); + fireEvent.click(again); + expect(again.isConnected).toBe(false); await act(async () => vi.runAllTicks()); expect(onFocusedRemoval).toHaveBeenCalledOnce(); } finally { @@ -1176,7 +1284,7 @@ it("shows a local request as stopping until its harness has stopped it", async ( release = resolve; }), ); - const view = render(); + const view = render(); try { act(() => { local @@ -1189,7 +1297,7 @@ it("shows a local request as stopping until its harness has stopped it", async ( }) .interruptible(stop); }); - openBubble(); + openEnd(); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); expect(look().getByText("Stopping…")).toBeInTheDocument(); stopPending(); @@ -1198,7 +1306,7 @@ it("shows a local request as stopping until its harness has stopped it", async ( expect(notify).not.toHaveBeenCalled(); release(); await settle(); - expect(look().queryByText("Stopping…")).not.toBeInTheDocument(); + expect(screen.queryByText("Stopping…")).not.toBeInTheDocument(); expect(notify).toHaveBeenCalledExactlyOnceWith( "Stopped Blossom", "success", @@ -1212,7 +1320,7 @@ it("shows a local request as stopping until its harness has stopped it", async ( it("offers no Stop for a local request that cannot be stopped or has failed", () => { const local = createLocalAgentActivity(); const f = fixture(local); - const view = render(); + const view = render(); const begin = (agent: string) => local.begin({ scope: "test", @@ -1228,11 +1336,12 @@ it("offers no Stop for a local request that cannot be stopped or has failed", () failed.interruptible(async () => {}); failed.finish({ ok: false, error: "Provider unavailable" }); }); - openBubble(); + openEnd(); expect(stopButton()).not.toBeInTheDocument(); expect( screen.queryByRole("button", { name: "Stop Bubbles" }), ).not.toBeInTheDocument(); + openOutcome(); expect( screen.getByRole("button", { name: "Dismiss error from Bubbles" }), ).toBeInTheDocument(); @@ -1242,112 +1351,13 @@ it("offers no Stop for a local request that cannot be stopped or has failed", () } }); -it("retries a failed local request from its row, before Dismiss, which begins it again", () => { - const local = createLocalAgentActivity(); - const f = fixture(local); - const view = render(); - const retry = vi.fn(() => void begin()); - function begin() { - return local.begin( - { - scope: "test", - channelId: "c", - threadRootId: root, - messageId: root, - agent: A, - }, - retry, - ); - } - try { - act(() => begin().finish({ ok: false, error: "Provider unavailable" })); - openBubble(); - const again = screen.getByRole("button", { name: "Retry Blossom" }); - expect(again).toHaveTextContent("Retry"); - expect( - again.compareDocumentPosition( - screen.getByRole("button", { name: "Dismiss error from Blossom" }), - ) & Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); - fireEvent.click(again); - expect(retry).toHaveBeenCalledOnce(); - expect(f.props.open).not.toHaveBeenCalled(); - expect(notify).not.toHaveBeenCalled(); - expect( - screen.getByRole("button", { - name: "View agent activity: Blossom, Received · waiting to start", - }), - ).toBeInTheDocument(); - look(); - expect(screen.getByText("Received · waiting to start")).toBeInTheDocument(); - expect( - screen.queryByRole("button", { name: "Retry Blossom" }), - ).not.toBeInTheDocument(); - } finally { - view.unmount(); - f.dispose(); - } -}); - -it("says why a failed request could not be retried, keeping it to try again or dismiss", () => { - const local = createLocalAgentActivity(); - const f = fixture(local); - const view = render(); - const retry = vi.fn(() => { - throw new Error("Blossom isn't running here."); - }); - const begin = (agent: string, again?: () => void) => - local.begin( - { - scope: "test", - channelId: "c", - threadRootId: root, - messageId: root, - agent, - }, - again, - ); - try { - act(() => { - begin(A, retry).finish({ ok: false, error: "Provider unavailable" }); - begin(B).finish({ ok: false, error: "Busy" }); - }); - openBubble(); - // Only a request that can be asked again offers Retry. - expect( - screen.queryByRole("button", { name: "Retry Bubbles" }), - ).not.toBeInTheDocument(); - expect( - screen.getByRole("button", { name: "Dismiss error from Bubbles" }), - ).toBeInTheDocument(); - fireEvent.click(screen.getByRole("button", { name: "Retry Blossom" })); - expect(retry).toHaveBeenCalledOnce(); - expect(notify).toHaveBeenCalledExactlyOnceWith( - "Couldn’t retry Blossom. Blossom isn't running here.", - "error", - ); - expect(screen.getByText("Provider unavailable")).toBeInTheDocument(); - expect( - screen.getByRole("button", { name: "Retry Blossom" }), - ).toBeInTheDocument(); - fireEvent.click( - screen.getByRole("button", { name: "Dismiss error from Blossom" }), - ); - expect(screen.queryByText("Provider unavailable")).toBeNull(); - expect(retry).toHaveBeenCalledOnce(); - } finally { - view.unmount(); - f.dispose(); - } -}); - it("stops a hosted agent's turn through its provider in this thread", async () => { const f = fixture(); const agents = hosted(true); - const view = render(); + const view = render(); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); expect(agents.interruptible).toHaveBeenCalledWith(A); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); expect(agents.interrupt).toHaveBeenCalledExactlyOnceWith(A, { @@ -1363,45 +1373,23 @@ it("stops a hosted agent's turn through its provider in this thread", async () = "success", ); f.send(A, "t", 2, "turn_completed"); - expect( - screen.queryByRole("button", { name: /View agent activity/ }), - ).not.toBeInTheDocument(); - } finally { - view.unmount(); - f.dispose(); - } -}); - -it("stops a hosted agent in the thread its message replies to", () => { - const f = fixture(); - const agents = hosted(); - const reply = { ...f.props.message, id: next, threadRootId: root }; - const view = render( - , - ); - try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [next] }); - openBubble(); - fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); - expect(agents.interrupt).toHaveBeenCalledExactlyOnceWith(A, { - channelId: "c", - threadRootId: root, - }); + expect(endTrigger()).toBeNull(); + expect(screen.getByTestId("request")).toBeEmptyDOMElement(); } finally { view.unmount(); f.dispose(); } }); -it("offers each agent its own Stop in the activity popup", async () => { +it("offers each agent its own Stop at the conversation's end", async () => { const f = fixture(); const agents = hosted(true); - const view = render(); + const view = render(); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(B, "u", 1, "turn_started", { triggeringEventIds: [root] }); + f.start(A, "t"); + f.start(B, "u"); expect(stopButton()).not.toBeInTheDocument(); - openBubble(); + openEnd(); const popup = within(screen.getByRole("dialog")); expect( popup.getByRole("button", { name: "Stop Blossom" }), @@ -1430,16 +1418,16 @@ it("offers each agent its own Stop in the activity popup", async () => { it("returns a hosted agent to its activity when its provider had nothing running to stop", async () => { const f = fixture(); const view = render( - , + , ); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); await settle(); expect(look().queryByText("Stopping…")).not.toBeInTheDocument(); expect( - look().getByText("Waiting for activity details"), + look().getByText("No current step details received."), ).toBeInTheDocument(); stopReady(); expect(notify).toHaveBeenCalledExactlyOnceWith( @@ -1456,10 +1444,10 @@ it("says why a hosted agent could not be stopped and lets the owner try again", const f = fixture(); const agents = hosted(); agents.interrupt.mockRejectedValueOnce(new Error("Provider is busy.")); - const view = render(); + const view = render(); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); expect(look().getByText("Stopping…")).toBeInTheDocument(); await settle(); @@ -1481,15 +1469,14 @@ it("says why a hosted agent could not be stopped and lets the owner try again", it("forgets a stop once its agent's work here has ended", async () => { const f = fixture(); const agents = hosted(); - const view = render(); + const view = render(); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); await settle(); f.send(A, "t", 2, "turn_completed"); - f.send(A, "u", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "u"); expect(look().queryByText("Stopping…")).not.toBeInTheDocument(); stopReady(); } finally { @@ -1502,17 +1489,18 @@ it("offers no Stop for a hosted agent that is not interruptible, or whose activi const f = fixture(); const agents = hosted(); agents.interruptible.mockReturnValue(false); - const view = render(); + const view = render(); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); expect(stopButton()).not.toBeInTheDocument(); // Interruptible, but no longer known to be working. agents.interruptible.mockReturnValue(true); - view.rerender(); + view.rerender(); expect(stopButton()).toBeInTheDocument(); act(() => vi.advanceTimersByTime(31000)); - expect(screen.getByText("Status unavailable")).toBeInTheDocument(); + expect(request().getByText("Status unavailable")).toBeInTheDocument(); + expect(endTrigger()).toBeNull(); expect(stopButton()).not.toBeInTheDocument(); } finally { view.unmount(); @@ -1522,10 +1510,10 @@ it("offers no Stop for a hosted agent that is not interruptible, or whose activi it("offers no Stop for a hosted agent when the host supplies no agents", () => { const f = fixture(); - const view = render(); + const view = render(); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); expect(stopButton()).not.toBeInTheDocument(); } finally { view.unmount(); @@ -1533,21 +1521,6 @@ it("offers no Stop for a hosted agent when the host supplies no agents", () => { } }); -it("shows no activity, and so no Stop, without a message", () => { - const f = fixture(); - const agents = hosted(); - const { message: _message, ...props } = f.props; - const view = render(); - try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - expect(screen.queryByRole("button")).not.toBeInTheDocument(); - expect(agents.interruptible).not.toHaveBeenCalled(); - } finally { - view.unmount(); - f.dispose(); - } -}); - const NOT_STOPPED = "Blossom hasn’t stopped yet. Try again."; const notStopped = () => notify.mock.calls.filter(([title]) => title === NOT_STOPPED).length; @@ -1558,10 +1531,10 @@ const alive = (f: ReturnType, turn: string, seq: number) => it("lets the owner try Stop again when a hosted turn is still working 30 seconds after it was stopped", async () => { const f = fixture(); const agents = hosted(true); - const view = render(); + const view = render(); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); await settle(); expect(look().getByText("Stopping…")).toBeInTheDocument(); @@ -1590,17 +1563,16 @@ it("lets the owner try Stop again when a hosted turn is still working 30 seconds it("does not let an older stop's timeout overwrite a newer stop of the same agent", async () => { const f = fixture(); const agents = hosted(true); - const view = render(); + const view = render(); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); await settle(); // The turn ends and the agent starts another before the first timeout. elapse(10_000); f.send(A, "t", 2, "turn_completed"); - f.send(A, "u", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "u"); expect(look().queryByText("Stopping…")).not.toBeInTheDocument(); fireEvent.click(stopButton() as HTMLElement); await settle(); @@ -1624,521 +1596,22 @@ it("does not let an older stop's timeout overwrite a newer stop of the same agen it("shows nothing later when a stopped hosted turn ends before its 30 seconds", async () => { const f = fixture(); - const view = render(); + const view = render( + , + ); try { - f.send(A, "t", 1, "turn_started", { triggeringEventIds: [root] }); - openBubble(); + f.start(A, "t"); + openEnd(); fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); await settle(); elapse(10_000); f.send(A, "t", 2, "turn_completed"); elapse(60_000); expect(notStopped()).toBe(0); - expect(look().queryByText("Stopping…")).not.toBeInTheDocument(); + expect(screen.queryByText("Stopping…")).not.toBeInTheDocument(); expect(screen.queryByRole("button")).not.toBeInTheDocument(); } finally { view.unmount(); f.dispose(); } }); - -it.each([ - [false, false], - [true, false], - [false, true], - [true, true], -])( - "shows one step label through handoff (stoppable=%s, thinking=%s)", - async (stoppable, thinking) => { - const local = createLocalAgentActivity(); - const f = fixture(local); - const typing = [{ pubkey: A, channelId: "c", threadRootId: root }]; - const session = { - ...f.props.session, - typing: { snapshot: () => typing, subscribe: () => () => {} }, - } as unknown as RelaySession; - const props = { ...f.props, session }; - const ui = (representedAgents: string[]) => ( - - - - - - - - ); - const work = local.begin({ - scope: "test", - agent: A, - channelId: "c", - messageId: root, - threadRootId: root, - }); - const label = thinking ? "Thinking" : "Reading notes.txt"; - work.step( - thinking ? "Thinking" : "Read", - thinking ? undefined : "notes.txt", - ); - const stop = vi.fn(async () => {}); - if (stoppable) work.interruptible(stop); - const view = render(ui([])); - try { - expect( - screen.getByRole("button", { - name: `View agent activity: Blossom, ${label}`, - }), - ).toBeVisible(); - // The message bubble is the agent's one working indicator here. - expect( - screen.queryByRole("button", { name: /Activity: .*working/ }), - ).toBeNull(); - expect(screen.getAllByText(label)).toHaveLength(1); - view.rerender(ui([A])); - expect( - screen.getByRole("button", { - name: `View agent activity: Blossom, ${label}`, - }), - ).toBeVisible(); - expect( - screen.queryByRole("button", { name: /Activity: .*working/ }), - ).toBeNull(); - expect( - screen.queryByRole("button", { name: "Reading notes.txt" }), - ).toBeNull(); - openBubble(); - if (stoppable) { - fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); - await settle(); - expect(stop).toHaveBeenCalledOnce(); - return; - } - expect(stopButton()).toBeNull(); - } finally { - view.unmount(); - f.dispose(); - } - }, -); -it("does not re-render the typing replacement for liveness that leaves its agents unchanged", () => { - const f = fixture(); - const onRender = vi.fn(); - const view = render( - - - , - ); - try { - f.send(A, "here", 1, "turn_started", { triggeringEventIds: [root] }); - const renders = onRender.mock.calls.length; - f.send(A, "here", 2, "turn_liveness"); - f.send(A, "here", 3, "turn_liveness"); - expect(onRender).toHaveBeenCalledTimes(renders); - f.send(B, "there", 1, "turn_started", { triggeringEventIds: [root] }); - expect(onRender.mock.calls.length).toBeGreaterThan(renders); - } finally { - view.unmount(); - f.dispose(); - } -}); - -it.each([false, true])( - "keeps thread request activity in its thread (local=%s)", - (isLocal) => { - const local = createLocalAgentActivity(); - const f = fixture(isLocal ? local : undefined); - if (isLocal) - local.begin({ - scope: "test", - agent: A, - channelId: "c", - messageId: root, - threadRootId: root, - thread: true, - }); - else - f.send(A, "turn", 1, "turn_started", { - triggeringEventIds: [root], - threadRootEventId: root, - }); - const view = render( - , - ); - try { - expect( - screen.queryByLabelText("Agent activity on this message"), - ).toBeNull(); - view.rerender(); - expect( - screen.getByLabelText("Agent activity on this message"), - ).toBeVisible(); - } finally { - view.unmount(); - f.dispose(); - } - }, -); - -it("lets a thread root's live bubble replace that thread's indicator", () => { - const local = createLocalAgentActivity(); - const f = fixture(local); - const typing = [{ pubkey: A, channelId: "c", threadRootId: root }]; - const session = { - ...f.props.session, - typing: { snapshot: () => typing, subscribe: () => () => {} }, - } as unknown as RelaySession; - // MessageRow passes the row's own thread root: none for a thread's root row. - const props = { ...f.props, session, threadRootId: undefined }; - local.begin({ - scope: "test", - agent: A, - channelId: "c", - messageId: root, - threadRootId: root, - thread: true, - }); - const ui = (layout: "thread" | "timeline") => ( - - - - - ); - const view = render(ui("thread")); - try { - expect( - screen.getByLabelText("Agent activity on this message"), - ).toBeVisible(); - expect( - screen.queryByRole("button", { name: /Activity: .*working/ }), - ).toBeNull(); - // In the channel timeline the root shows no thread bubble, so the thread - // keeps its own indicator. - view.rerender(ui("timeline")); - expect( - screen.queryByLabelText("Agent activity on this message"), - ).toBeNull(); - expect( - screen.getByRole("button", { name: /Activity: .*working/ }), - ).toBeVisible(); - } finally { - view.unmount(); - f.dispose(); - } -}); - -it("shows thinking once across the live bubble, recorded history and conversation indicator", () => { - const local = createLocalAgentActivity(); - const f = fixture(local); - const owner = createRelaySession(null); - const session = { ...owner.session, ...f.props.session }; - const work = local.begin({ - scope: "test", - agent: A, - channelId: "c", - messageId: root, - threadRootId: root, - thread: true, - }); - work.step("Thinking"); - const row = { - ...f.props.message, - id: "thinking-step", - authorId: A, - threadRootId: root, - replyParentId: root, - audience: "agents" as const, - content: "Thinking", - }; - const rows = [row]; - const empty: typeof rows = []; - const agents = new Set([A]); - function Flow({ - recorded, - expanded, - }: { - recorded: boolean; - expanded: boolean; - }) { - const presentation = useActivityPresentation( - recorded ? rows : empty, - session.agentActivity, - agents, - root, - ); - const group = presentation.groups[0]; - return ( - <> - - {group && ( - undefined} - expanded={expanded} - onToggle={() => {}} - renderHistory={(entry) => { - const activity = presentation.byRow.get(entry.id); - if (!activity) throw new Error("Missing recorded activity"); - return ( - undefined} - onOpenLink={f.props.open} - day={false} - retry={undefined} - recordedActivity={{ - ...activity, - container: "history", - }} - /> - ); - }} - /> - )} - - - ); - } - const ui = (recorded: boolean, expanded = false) => ( - - - - ); - const view = render(ui(false)); - try { - expect(screen.getAllByText("Thinking")).toHaveLength(1); - // Until history owns the work, the message bubble is its one indicator. - expect( - screen.queryByRole("button", { name: /Activity: .*working/ }), - ).toBeNull(); - view.rerender(ui(true)); - expect( - screen.queryByLabelText("Agent activity on this message"), - ).toBeNull(); - expect(screen.getAllByText("Thinking")).toHaveLength(1); - expect( - screen.getByRole("button", { name: "Activity: Blossom working" }), - ).toBeVisible(); - view.rerender(ui(true, true)); - expect(screen.getAllByText("Thinking")).toHaveLength(1); - expect( - screen.getByRole("button", { name: "Activity: Blossom working" }), - ).toBeVisible(); - act(() => work.finish({ ok: true })); - expect(screen.getByText("Thinking")).not.toHaveAttribute("data-active"); - expect( - screen.queryByRole("button", { name: "Activity: Blossom working" }), - ).toBeNull(); - } finally { - view.unmount(); - owner.dispose(); - f.dispose(); - } -}); - -it("hands live work to only the latest history for each agent and keeps Stop and transcript there", async () => { - const local = createLocalAgentActivity(); - const f = fixture(local); - const stop = vi.fn(async () => {}); - const work = local.begin({ - scope: "test", - agent: A, - channelId: "c", - messageId: root, - threadRootId: root, - thread: true, - }); - work.interruptible(stop); - work.step("Read", "files"); - const row = { - ...f.props.message, - id: "step", - authorId: A, - threadRootId: root, - replyParentId: root, - audience: "agents" as const, - content: "Checking the files", - }; - const { audience: _audience, ...reply } = row; - const groups = activityPresentation( - [ - row, - { ...reply, id: "reply" }, - { ...row, id: "later", content: "Checking more files" }, - ], - f.props.session.agentActivity.snapshot(), - new Set([A]), - root, - ).groups; - const ui = (expanded: boolean) => ( - - - {groups.map((group) => ( - undefined} - expanded={expanded} - onToggle={() => {}} - openActivity={f.props.open} - canOpenActivity={f.props.canOpen} - /> - ))} - - ); - const view = render(ui(false)); - try { - expect(screen.getByText("Checking the files")).not.toHaveAttribute( - "data-active", - ); - expect(screen.getByText("Checking more files")).toHaveAttribute( - "data-active", - "true", - ); - view.rerender(ui(true)); - expect( - screen.queryByLabelText("Agent activity on this message"), - ).toBeNull(); - expect( - screen.getAllByRole("button", { name: "Stop Blossom" }), - ).toHaveLength(1); - const transcript = screen.getAllByRole("button", { - name: "View transcript", - })[1]; - if (!transcript) - throw new Error("Missing latest history transcript control"); - fireEvent.click(transcript); - const activity = `buzz:profile?agent=${A}&tab=activity`; - expect(f.props.open).toHaveBeenCalledWith(activity, { rootId: root }); - expect(claimProfileTranscript(activity)).toBeDefined(); - fireEvent.click(screen.getByRole("button", { name: "Stop Blossom" })); - await settle(); - expect(stop).toHaveBeenCalledOnce(); - } finally { - view.unmount(); - f.dispose(); - } -}); - -it.each([ - { - runtime: "block.builderlab/builderlab", - fallback: "Running remotely on Builderlab…", - }, - { runtime: "other/provider", fallback: "Running on a remote machine…" }, -])( - "keeps one byline hint and a remote fallback until current steps arrive: $runtime", - async ({ runtime, fallback }) => { - const f = fixture(); - const base = f.props.session.agentChoices; - const choices = { - ...base.snapshot(), - identities: [ - { - pubkey: B, - name: "Bubbles", - managed: false, - execution: "remote", - runtime, - }, - ], - }; - Object.assign(f.props.session, { - agentChoices: { ...base, snapshot: () => choices }, - }); - const update = (seq: number, update: unknown) => { - // The latest step wins, so each one arrives later than the last. - vi.setSystemTime(Date.now() + 1000); - f.send(B, "b1", seq, "acp_read", { - method: "session/update", - params: { update }, - }); - }; - const hint = () => { - const bubble = screen.getByRole("button", { - name: /View agent activity: Bubbles, remote, /, - }); - const preview = bubble.closest("[data-agent-response-preview]"); - if (!(preview instanceof HTMLElement)) throw new Error("Missing preview"); - const labels = within(preview).getAllByText("Remote"); - expect(labels).toHaveLength(1); - expect(labels[0]?.closest("strong")).toBeNull(); - expect(labels[0]?.closest("button")).toBeNull(); - expect(within(bubble).queryByText("Remote")).toBeNull(); - return labels[0]; - }; - render(); - try { - f.send(B, "b1", 1, "turn_started", { triggeringEventIds: [root] }); - expect(hint()).toBeVisible(); - await act(async () => { - fireEvent.click( - screen.getByRole("button", { - name: /View agent activity: Bubbles, remote, /, - }), - ); - vi.advanceTimersToNextFrame(); - }); - expect(screen.getByText(fallback)).toBeVisible(); - update(2, { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "On it" }, - }); - expect(hint()).toBeVisible(); - expect(screen.queryByText(fallback)).toBeNull(); - update(3, { - sessionUpdate: "agent_thought_chunk", - content: { type: "text", text: "Checking the row" }, - }); - expect(hint()).toBeVisible(); - update(4, { - sessionUpdate: "tool_call", - toolCallId: "read", - title: "buzz-dev-mcp__read_file", - status: "in_progress", - rawInput: { path: "/project/file.ts" }, - }); - expect(hint()).toBeVisible(); - f.send(B, "b1", 5, "turn_completed"); - // A local agent's tool call never shows it. - f.send(A, "a1", 1, "turn_started", { triggeringEventIds: [root] }); - f.send(A, "a1", 2, "acp_read", { - method: "session/update", - params: { - update: { - sessionUpdate: "tool_call", - toolCallId: "read", - title: "buzz-dev-mcp__read_file", - status: "in_progress", - rawInput: { path: "/project/file.ts" }, - }, - }, - }); - const local = screen.getByRole("button", { - name: /View agent activity: Blossom/, - }); - expect(local).not.toHaveAccessibleName(/remote/); - expect(within(local).queryByText("Remote")).not.toBeInTheDocument(); - } finally { - f.dispose(); - } - }, -); diff --git a/src/bundled/agent-activity/ActivityAccessory.tsx b/src/bundled/agent-activity/ActivityAccessory.tsx index 712a51c377..f71b8d71c7 100644 --- a/src/bundled/agent-activity/ActivityAccessory.tsx +++ b/src/bundled/agent-activity/ActivityAccessory.tsx @@ -1,5 +1,4 @@ import { activityTranscript } from "../../features/agents/activity-transcript"; -import { useRecordedActivityAgents } from "../../features/conversation/typing-presentation"; import { useToastNotification } from "../../shared/design-system/ui/Toast"; import { useProfileGeneration } from "../../features/relay/react"; import { @@ -14,7 +13,6 @@ import { Avatar } from "../../shared/design-system/ui/Avatar"; import { AvatarStack } from "../../shared/design-system/ui/AvatarStack"; import type { ComposerAccessoryProps } from "../../features/conversation/contracts"; import { useChannelIdentityNames } from "../../features/identity-names/react"; -import type { activityRecords } from "../../features/agents/activity-records"; import { openProfileTranscript, profileActivityViewTarget, @@ -22,52 +20,33 @@ import { import { publicKeyLabels } from "../../shared/identity/public-key"; import { Button } from "../../shared/design-system/ui/Button"; import { IconButton } from "../../shared/design-system/ui/IconButton"; -import { - OctagonIcon, - WarningCircleIcon, - XIcon, -} from "../../shared/design-system/icons"; +import { WarningCircleIcon, XIcon } from "../../shared/design-system/icons"; import { NavigationCard, NavigationItem, } from "../../shared/design-system/ui/NavigationItem"; -import { ShimmerText } from "../../shared/design-system/ui/ShimmerText"; -import { ActivityStepPreview } from "../../features/messages/ActivityStepPreview"; import { PopoverRoot, PopoverTrigger, PopoverPopup, } from "../../shared/design-system/ui/Popover"; -import { currentActivity } from "./current-activity"; import { messageWork } from "./message-activity"; -import type { ActivityTurn } from "../../features/agents/activity"; -import { workStop, type WorkStopAgents } from "../../features/agents/work-stop"; -import { useWorkStops } from "../../features/agents/use-work-stops"; -import { - requestWork, - type RequestWork, -} from "../../features/agents/request-work"; -import { - localWorkLabel, - type WorkStep, -} from "../../features/agents/local-activity"; -import { - useTypingReplacement, - useActivityTypingReplacement, -} from "../../features/conversation/typing-presentation"; +import type { RequestWork } from "../../features/agents/request-work"; +import { localWorkLabel } from "../../features/agents/local-activity"; import styles from "./ActivityAccessory.module.css"; import messageStyles from "../../features/messages/Messages.module.css"; import { avatarMedia } from "../../shared/avatar-source"; -import { AgentResponsePreview } from "../../features/messages/AgentResponsePreview"; -import { RemoteAgentHint } from "../../features/messages/RemoteAgentHint"; import { remoteWorkDetail } from "../../features/agents/execution-location"; const noSubscribe = () => () => {}; -export type ActivityAgents = WorkStopAgents; -type ActivityProps = ComposerAccessoryProps & { agents?: ActivityAgents }; +type ActivityProps = ComposerAccessoryProps; const noWork: RequestWork[] = []; -/** Activity belongs to the exact triggering message, not the composer. Once an - * agent has publicly replied, its outcome follows that reply instead. */ +const isOutcome = (entry: Pick) => + entry.state === "error" || entry.state === "unknown"; +/** What happened to the exact triggering message: a failure, an unconfirmed + * result or a stop. Live work is never shown here; the conversation's end + * indicator is its only place. Once an agent has publicly replied, its outcome + * follows that reply instead. */ export function ActivityAccessory(props: ActivityProps) { if ( props.message?.notice === "execution-failure" && @@ -79,9 +58,9 @@ export function ActivityAccessory(props: ActivityProps) { const author = props.message?.authorId; return ( <> - + {request && author && ( - { - if (!messageId) return false; - const work = messageWork( - session.agentActivity.snapshot(), - channelId, - messageId, - ); - return work.live.length > 0 || work.stopped.length > 0; - }); + // Every row mounts this; only rows with an outcome subscribe to each + // activity, profile and choice change. Others read once and wait. + const hasOutcome = useSyncExternalStore( + session.agentActivity.subscribe, + () => { + if (!messageId) return false; + const work = messageWork( + session.agentActivity.snapshot(), + channelId, + messageId, + ); + return work.live.some(isOutcome) || work.stopped.length > 0; + }, + ); const snapshot = useSyncExternalStore( - hasWork ? session.agentActivity.subscribe : noSubscribe, + hasOutcome ? session.agentActivity.subscribe : noSubscribe, session.agentActivity.snapshot, ); const work = useMemo( () => - messageId && hasWork + messageId && hasOutcome ? messageWork(snapshot, channelId, messageId) : { live: noWork, stopped: noWork }, - [snapshot, channelId, messageId, hasWork], + [snapshot, channelId, messageId, hasOutcome], + ); + const entries = work.live.filter( + (entry) => + isOutcome(entry) && + (stoppedAgent + ? entry.agent === stoppedAgent + : !props.repliedAgents?.includes(entry.agent)), ); - const entries = work.live.filter((entry) => { - const outcome = entry.state === "error" || entry.state === "unknown"; - return stoppedAgent - ? outcome && entry.agent === stoppedAgent - : !outcome || !props.repliedAgents?.includes(entry.agent); - }); const stopped = stoppedAgent ? work.stopped.filter((entry) => entry.agent === stoppedAgent) : work.stopped.filter( (entry) => !props.repliedAgents?.includes(entry.agent), ); const profiles = useSyncExternalStore( - hasWork ? session.profiles.subscribe : noSubscribe, + hasOutcome ? session.profiles.subscribe : noSubscribe, session.profiles.snapshot, ); const choices = useSyncExternalStore( - hasWork ? session.agentChoices.subscribe : noSubscribe, + hasOutcome ? session.agentChoices.subscribe : noSubscribe, session.agentChoices.snapshot, ); const resolveName = useChannelIdentityNames(session, channelId); @@ -173,138 +155,67 @@ function MessageActivity( ? `${name} · ${suffixes.get(agent)}` : name; }; + // An outcome belongs to the conversation its work ran in: thread work is + // reported in that thread, not on the channel's copy of its first message. const visible = (entry: RequestWork) => { if (!canOpen(profileActivityViewTarget(entry.agent) ?? "")) return false; - if ( - recorded.has(entry.agent) && - entry.state !== "error" && - entry.state !== "unknown" && - entry.state !== "stopped" - ) - return false; const threadScoped = props.threadScoped ?? (props.messageLayout === "thread" || !!message?.threadRootId); - if (!threadScoped) { - const local = (snapshot.local ?? []).filter( + if (threadScoped) return true; + const local = (snapshot.local ?? []).filter( + (work) => + work.agent === entry.agent && + work.channelId === channelId && + work.messageId === messageId, + ); + if (local.length) + return local.some( (work) => - work.agent === entry.agent && - work.channelId === channelId && - work.messageId === messageId, + !work.thread && + !( + message && + message.replyCount > 0 && + work.threadRootId === message.id + ), ); - if (local.length) - return local.some( - (work) => - !work.thread && - !( - message && - message.replyCount > 0 && - work.threadRootId === message.id + // A top-level request is its own root until replies make it a thread. + const inThread = (root: string | null | undefined) => + !!root && (root !== messageId || (message?.replyCount ?? 0) > 0); + const turns = activityTranscript(entry.selected.records, { + agent: entry.agent, + channelId, + }).turns; + return !(entry.turns.length + ? entry.turns.every( + (turn) => + inThread(turn.threadRootId) || + turns.some( + (raw) => raw.turnId === turn.turnId && inThread(raw.threadRootId), ), - ); - const turns = activityTranscript(entry.selected.records, { - agent: entry.agent, - channelId, - }).turns; - if ( - entry.turns.length - ? entry.turns.every( - (turn) => - !!turn.threadRootId || - turns.some( - (raw) => raw.turnId === turn.turnId && !!raw.threadRootId, - ), - ) - : turns.length && turns.every((turn) => !!turn.threadRootId) - ) - return false; - } - return true; + ) + : turns.length && turns.every((turn) => inThread(turn.threadRootId))); }; - const shown: Entry[] = entries - // Published replies do not end work. Only a mounted history owner can - // replace this indicator (via recorded), including when Stop is unavailable. - .filter(visible) - .map((entry) => { - const choice = choices.identities.find( - (row) => row.pubkey === entry.agent, - ); - return { - agent: entry.agent, - name: named(entry.agent), - picture: profiles.get(entry.agent)?.picture, - remoteStatus: session.viewer - ? remoteWorkDetail(choice?.execution, choice?.runtime) - : undefined, - working: entry.working, - state: entry.state, - reason: entry.reason, - ...(entry.step ? { step: entry.step } : {}), - ...(entry.stoppable ? { stoppable: true } : {}), - ...(entry.retryable ? { retryable: true } : {}), - lifecycle: entry.lifecycle, - records: entry.selected.records, - turns: entry.turns, - }; - }); - // When work ends (not when access is revoked), keep the last bubble long - // enough for the shared leave recipe, then remove it. - const section = useRef(null); - const focusAfterRetry = () => - section.current - ?.querySelector( - 'button[aria-label^="View agent activity:"]', - ) - ?.focus(); - const retained = useRef([]); - const [leaving, setLeaving] = useState(null); - const ended = !entries.length; - useLayoutEffect(() => { - // Child closes its portal and restores focus before this subtree is inert. - if (section.current) section.current.inert = !shown.length; - if (shown.length) { - retained.current = shown; - if (leaving) setLeaving(null); - return; - } - if (ended && retained.current.length) setLeaving(retained.current); - retained.current = []; - }); - useLayoutEffect(() => { - if (!leaving) return; - const animations = section.current?.getAnimations?.() ?? []; - if (!animations.length) { - setLeaving(null); - return; - } - let live = true; - const done = () => { - if (live) setLeaving(null); - }; - void Promise.all(animations.map((animation) => animation.finished)).then( - done, - done, - ); - return () => { - live = false; + const shown: Entry[] = entries.filter(visible).map((entry) => { + const choice = choices.identities.find((row) => row.pubkey === entry.agent); + return { + agent: entry.agent, + name: named(entry.agent), + picture: profiles.get(entry.agent)?.picture, + remoteStatus: session.viewer + ? remoteWorkDetail(choice?.execution, choice?.runtime) + : undefined, + state: entry.state, + reason: entry.reason, + ...(entry.retryable ? { retryable: true } : {}), + lifecycle: entry.lifecycle, }; - }, [leaving]); - // The render where work ends keeps the same element (from the last shown - // entries) so the list never loses and regains its height mid-handoff. - const bubble = ( - shown.length ? shown : (leaving ?? (ended ? retained.current : [])) - ).filter( - (entry) => - !recorded.has(entry.agent) || - entry.state === "error" || - entry.state === "unknown", - ); - // Once its own live bubble has left, a stopped request stays noted here. It sits - // in the incoming message frame without a gutter, so it starts at the reply - // avatars' edge. + }); + // A stopped request stays noted here. It sits in the incoming message frame + // without a gutter, so it starts at the reply avatars' edge. const noted = stopped.filter( (entry) => - visible(entry) && !bubble.some((row) => row.agent === entry.agent), + visible(entry) && !shown.some((row) => row.agent === entry.agent), ); const note = noted.length ? (
) : null; - if (!bubble.length) return note; - const primary = bubble[0]; - if (!primary) return note; - const compact = bubble.every( - (entry) => entry.state === "error" || entry.state === "unknown", - ); - if (compact) - return ( - <> -
- {stoppedAgent &&
} -
- {!stoppedAgent && ( - <> - ({ - id: entry.agent, - name: entry.name, - src: avatarMedia(entry.picture, session.media), - shape: "squircle", - }))} - /> - {bubble.map((entry) => entry.name).join(", ")} · - - )} - 0} - onRetried={focusAfterRetry} - compact - /> -
-
- {note} - - ); + if (!shown.length) return note; return ( <>
- - } - participants={bubble.map((entry) => ({ - id: entry.agent, - name: entry.name, - picture: avatarMedia(entry.picture, session.media), - }))} - picture={avatarMedia(primary.picture, session.media)} - layout={props.messageLayout} + {stoppedAgent &&
} +
- {shown.map((entry) => ( - - ))} - 0} - onRetried={focusAfterRetry} - /> - + {!stoppedAgent && ( + <> + ({ + id: entry.agent, + name: entry.name, + src: avatarMedia(entry.picture, session.media), + shape: "squircle", + }))} + /> + {shown.map((entry) => entry.name).join(", ")} · + + )} + +
{note} @@ -439,54 +287,23 @@ type Entry = { agent: string; name: string; picture: string | undefined; - /** Active fallback for a known remote agent without current step details. */ + /** Shown for a known remote agent. */ remoteStatus: string | undefined; - working: boolean; state: RequestWork["state"]; reason: string | undefined; - step?: WorkStep; - stoppable?: boolean; retryable?: boolean; lifecycle: boolean; - records: ReturnType; - turns: readonly ActivityTurn[]; }; -function ActivityBubble({ +function OutcomeDetails({ entries, - interactive, - compact = false, - onRetried, - agents, ...props -}: ActivityProps & { - entries: Entry[]; - interactive: boolean; - compact?: boolean; - onRetried: () => void; -}) { +}: ActivityProps & { entries: Entry[] }) { const [expanded, setExpanded] = useState(false); const message = props.message; - const controls = new Map( - entries.flatMap((entry) => { - const control = - message && - workStop( - entry, - { - channelId: props.channelId, - messageId: message.id, - threadRootId: message.threadRootId ?? message.id, - }, - props.session.agentActivity, - agents, - ); - return control ? [[entry.agent, control] as const] : []; - }), - ); - const { pending: stops, stop } = useWorkStops([...controls.values()]); const notify = useToastNotification(); - // A retried request begins again; its popup closes on the new row. + // A retried request begins again: its live work shows at the conversation's + // end, and this outcome retires (the unmount below hands focus back). const retry = (entry: Entry) => { if (!message) return; try { @@ -496,8 +313,6 @@ function ActivityBubble({ message.id, ); setExpanded(false); - // Retry replaces the compact failure trigger with the active work row. - queueMicrotask(onRetried); } catch (error) { notify( `Couldn’t retry ${entry.name}. ${error instanceof Error ? error.message : String(error)}`, @@ -507,96 +322,42 @@ function ActivityBubble({ }; const trigger = useRef(null); const popup = useRef(null); - const retirement = useRef({ - interactive, - onFocusedRemoval: props.onFocusedRemoval, - }); + const onFocusedRemoval = useRef(props.onFocusedRemoval); useLayoutEffect(() => { - retirement.current = { - interactive, - onFocusedRemoval: props.onFocusedRemoval, - }; + onFocusedRemoval.current = props.onFocusedRemoval; }); - useLayoutEffect( - () => () => { - // Published content removes this preview immediately, without a leave phase. - // Ordinary completion uses the existing interactive=false handoff below. - if (!retirement.current.interactive) return; - const focused = trigger.current?.ownerDocument.activeElement; - if ( - focused && - (trigger.current?.contains(focused) || popup.current?.contains(focused)) - ) - retirement.current.onFocusedRemoval?.(); - }, - [], - ); useLayoutEffect(() => { - if (interactive) return; - const source = popup.current; const button = trigger.current; - const document = (source ?? button)?.ownerDocument; - const active = document?.activeElement; - setExpanded(false); - if (active && (button?.contains(active) || source?.contains(active))) { - // Commit closure before handing off: its overlay currently hides the - // host's target. DOM observers release that target at this checkpoint. - // Keep the retired nodes so unmount does not erase focus ownership. + return () => { + // Dismiss or retry removes this outcome. Unless focus has moved on by + // then, return it to the host once the removal has committed. + const document = button?.ownerDocument; + const focused = document?.activeElement; + if ( + !focused || + !(button?.contains(focused) || popup.current?.contains(focused)) + ) + return; queueMicrotask(() => { const current = document?.activeElement; - if ( - current === document?.body || - (current && (button?.contains(current) || source?.contains(current))) - ) - props.onFocusedRemoval?.(); + if (!current || current === document?.body) + onFocusedRemoval.current?.(); }); - } - }, [interactive, props.onFocusedRemoval]); - const working = entries.some((entry) => entry.working); - // Local work breathes until its first step ("Starting"), like the sidebar and thread. - const starting = (entry: Entry) => - entry.lifecycle && - (entry.state === "waiting" || (entry.state === "working" && !entry.step)); - const waiting = entries.some(starting); - const stepping = entries.some((entry) => entry.working && !starting(entry)); - + }; + }, []); const unknown = entries.some((entry) => entry.state === "unknown"); const failedCount = entries.filter((entry) => entry.state === "error").length; + // Local requests have no unknown state: their outcome is a failure. const label = (entry: Entry) => entry.lifecycle ? localWorkLabel({ - state: - entry.state === "ended" - ? "done" - : entry.state === "unknown" - ? "error" - : entry.state, + state: "error", ...(entry.reason ? { error: entry.reason } : {}), - ...(entry.step ? { step: entry.step } : {}), }) : entry.state === "error" ? "failed" - : entry.working - ? "working" - : "status unknown"; + : "status unknown"; const failedEntries = entries.filter((entry) => entry.state === "error"); - const otherEntries = entries.filter( - (entry) => !failedEntries.includes(entry), - ); - const current = - otherEntries.find((entry) => entry.working && entry.step) ?? - otherEntries.find((entry) => entry.working); - const currentPreview = - current && !current.lifecycle - ? currentActivity(current.records, current.turns) - : undefined; - const stepText = current?.step - ? label(current) - : currentPreview - ? [currentPreview.title, currentPreview.detail] - .filter(Boolean) - .join(" · ") - : undefined; const avatars = (group: Entry[]) => ( ); - const content = ( - - {otherEntries.length > 0 && ( - - {(working || waiting) && ( - - )} - {unknown && Status unavailable} - - )} - {failedCount > 0 && ( - - {avatars( - failedEntries.filter((entry) => entry.agent !== entries[0]?.agent), - )} - - )} - - ); - if (!entries.length) return null; return ( - setExpanded(interactive && open)} - > - {compact && content} + + + {unknown && ( + + Status unavailable + + )} + {failedCount > 0 && ( + + {avatars( + failedEntries.filter( + (entry) => entry.agent !== entries[0]?.agent, + ), + )} + + )} + { - if (!interactive) { - event.preventBaseUIHandler(); - return; - } - }} + openOnHover="preview" render={ - compact ? ( - - ) : ( - - ) + } /> { // Opens the agent's Activity on this message's transcript. const target = profileActivityViewTarget(entry.agent); - const preview = entry.working - ? currentActivity(entry.records, entry.turns) - : undefined; - const control = controls.get(entry.agent); - const stopping = !!control && stops.has(control.key); return ( - {compact && !entry.lifecycle ? ( + {!entry.lifecycle ? (
{entry.name} @@ -726,43 +445,25 @@ function ActivityBubble({ setExpanded(false); }} icon={ - } label={ - - {(stopping ? "Stopping…" : undefined) ?? - (entry.lifecycle || entry.state === "error" - ? label(entry) - : !entry.working - ? "Activity interrupted or out of date" - : (preview?.title ?? - entry.remoteStatus ?? - "Waiting for activity details"))} - - {preview?.detail && ( - - - {preview.detail} - - - )} + {label(entry)} } /> )} - {entry.lifecycle && entry.state === "error" ? ( + {entry.lifecycle && ( {entry.retryable && ( - - ) : undefined} + )} ); })} @@ -824,104 +504,3 @@ function ActivityBubble({ ); } - -/** Message-linked work replaces the composer control; unassociated work keeps - * main's existing presentation rather than disappearing without a bubble. */ -export function ActivityTypingReplacement(props: ComposerAccessoryProps) { - // Subscribe to which agents are replaced, not every observer frame. - const agents = useSyncExternalStore( - props.session.agentActivity.subscribe, - () => replacedAgents(props), - ); - return ( - <> - {agents - .split(",") - .filter(Boolean) - .map((agent) => ( - - ))} - - ); -} -function replacedAgents(props: ComposerAccessoryProps) { - const activity = props.session.agentActivity.snapshot(); - const ids = [ - ...(props.threadRootId ? [props.threadRootId] : []), - ...(activity.local ?? []) - .filter( - (request) => - request.channelId === props.channelId && - (!props.threadRootId || - (request.threadRootId ?? request.messageId) === props.threadRootId), - ) - .map((request) => request.messageId), - ...activity.turns.flatMap((turn) => - turn.channelId === props.channelId - ? (turn.requests ?? []) - .filter( - (request) => - !props.threadRootId || - request.threadRootId === props.threadRootId, - ) - .map((request) => request.messageId) - : [], - ), - ]; - return requestWork(activity, props.channelId, ids) - .map(({ agent }) => agent) - .join(","); -} -function TypingReplacement({ - session, - channelId, - threadRootId, - message, - messageLayout, - agent, - shared = false, -}: ComposerAccessoryProps & { - agent: string; - /** Only the live bubble shares its registration. It shows the agent working, - * so the conversation shows no second cue (presence). */ - shared?: boolean; -}) { - // A thread's root row has no thread root of its own, but its bubble shows in - // that thread's conversation, so it owns that thread's indicator. - const shownIn = - threadRootId ?? (messageLayout === "thread" ? message?.id : undefined); - useActivityTypingReplacement( - { - session, - channelId, - threadRootId: shownIn, - pubkey: agent, - presence: shared, - }, - shared, - ); - useTypingReplacement( - { session, channelId, threadRootId, pubkey: agent }, - true, - ); - return null; -} - -function ActivityAvatar({ - session, - entry, - size = "compact", -}: Pick & { - entry: Entry; - size?: "compact" | "small"; -}) { - return ( - - ); -} diff --git a/src/bundled/agent-activity/README.md b/src/bundled/agent-activity/README.md index 3f00e3d2dd..e6bfa5fcc7 100644 --- a/src/bundled/agent-activity/README.md +++ b/src/bundled/agent-activity/README.md @@ -1,9 +1,9 @@ # Agent Activity -Shows an incoming agent response on the left while your request is being handled. The same avatar and bubble begin with typing dots, then show the current tool step. Published agent content replaces this live preview; recorded coordination history keeps its completed-step disclosure. +Shows what happened to your request on the message you sent: a failure you can retry or dismiss, a result Buzz couldn't confirm, or a stop. An agent's live work is never shown here: it has one place, the end of its conversation, where its reply will land. ## Getting started 1. Mention an agent in a conversation. -2. Its picture and typing bubble appear on the agent's side of the conversation. -3. Tool details appear in that bubble as they arrive. Hover for activity controls, including Stop, or click to open the thread when available. +2. While it works, the end of the conversation shows its picture, typing dots and current step, with Stop. +3. If the request fails or is stopped, the message notes it; once the agent has replied, the note follows its latest reply. diff --git a/src/bundled/agent-activity/activity-presentation.test.ts b/src/bundled/agent-activity/activity-presentation.test.ts deleted file mode 100644 index 4e72e97d16..0000000000 --- a/src/bundled/agent-activity/activity-presentation.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { expect, it } from "vitest"; -import { activityPresentation } from "./activity-presentation"; -import type { ToolItem } from "../../features/agents/activity-transcript"; -const entry = ( - toolName: string, - input: unknown = {}, - output = "", -): ToolItem => ({ - id: "tool", - type: "tool", - kind: "other", - toolCallId: "tool", - at: 0, - diffs: [], - paths: [], - truncated: false, - title: toolName, - input: JSON.stringify(input), - output, - status: "completed", -}); -it("maps only exact tools and structured paths; commands remain indivisible", () => { - expect( - activityPresentation( - entry("buzz-dev-mcp__read_file", { path: "/work/src/Composer.tsx" }), - ), - ).toMatchObject({ title: "Read file", target: "Composer.tsx" }); - expect( - activityPresentation( - entry("buzz-dev-mcp__str_replace", { path: "C:\\work\\Composer.tsx" }), - ), - ).toMatchObject({ title: "Edit file", target: "Composer.tsx" }); - expect( - activityPresentation( - entry("buzz-dev-mcp__shell", { - workdir: "/work/project", - command: "read file; send message", - }), - ), - ).toMatchObject({ title: "Run command", target: "read file; send message" }); - expect( - activityPresentation(entry("unknown_shell", { path: "/work/secret" })), - ).toMatchObject({ title: "unknown_shell", target: undefined }); -}); -it("never invents a file target from malformed or directory paths", () => { - for (const path of [ - "", - "/", - "/work/", - "C:\\", - "..", - 12, - { path: "file" }, - "a\nb", - ]) { - expect( - activityPresentation(entry("buzz-dev-mcp__read_file", { path })), - ).toMatchObject({ title: "buzz-dev-mcp__read_file", target: undefined }); - } -}); -it("preserves stderr, empty output and wrapper warnings without interpreting markup", () => { - const result = { - stdout: "", - stderr: "warning", - exit_code: 2, - timed_out: false, - stdout_truncated: true, - stderr_truncated: false, - }; - expect( - activityPresentation( - entry("buzz-dev-mcp__shell", {}, JSON.stringify(result)), - ).shellOutput, - ).toEqual({ - stdout: "", - stderr: "warning", - failed: true, - note: "Exit code 2 · Output was truncated by the tool", - }); - expect( - activityPresentation( - entry( - "buzz-dev-mcp__shell", - {}, - JSON.stringify({ ...result, stdout: "", stderr: "" }), - ), - ).shellOutput?.stdout, - ).toBe(""); - expect( - activityPresentation(entry("other", {}, JSON.stringify(result))) - .shellOutput, - ).toBeUndefined(); - for (const output of [ - "broken", - JSON.stringify({ ...result, stderr: null }), - JSON.stringify({ stdout: "hi" }), - ]) - expect( - activityPresentation(entry("buzz-dev-mcp__shell", {}, output)) - .shellOutput, - ).toBeUndefined(); -}); -it("previews distinct command text rather than repeated working directories", () => { - const first = activityPresentation( - entry("buzz-dev-mcp__shell", { - command: "\ncat > REPORT.md <<'EOF'\nprivate text", - workdir: ".buzz", - }), - ); - const second = activityPresentation( - entry("buzz-dev-mcp__shell", { - command: "wc -w REPORT.md", - workdir: ".buzz", - }), - ); - expect(first.target).toBe("cat > REPORT.md <<'EOF'"); - expect(second.target).toBe("wc -w REPORT.md"); - expect(first.target).not.toContain("private text"); - expect( - activityPresentation( - entry("buzz-dev-mcp__shell", { command: "x".repeat(120) }), - ).target, - ).toBe(`${"x".repeat(90)}…`); - expect( - activityPresentation( - entry("buzz-dev-mcp__shell", { command: "\t\u001bwc -w file" }), - ).target, - ).toBe("wc -w file"); -}); diff --git a/src/bundled/agent-activity/activity-presentation.ts b/src/bundled/agent-activity/activity-presentation.ts deleted file mode 100644 index 894c9f2812..0000000000 --- a/src/bundled/agent-activity/activity-presentation.ts +++ /dev/null @@ -1,90 +0,0 @@ -import type { ToolItem } from "../../features/agents/activity-transcript"; -const object = (value: unknown): Record | undefined => - value !== null && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : undefined; -function parsed(value: string) { - try { - return object(JSON.parse(value)); - } catch { - return; - } -} -function basename(value: unknown): string | undefined { - if ( - typeof value !== "string" || - !value.trim() || - /[/\\]$/.test(value) || - /[\r\n]/.test(value) - ) - return; - const name = value.split(/[/\\]/).at(-1); - return name && name !== "." && name !== ".." ? name : undefined; -} - -/** Display only. Never feeds send association, status, permissions or execution. */ -export function activityPresentation(entry: ToolItem) { - const input = parsed(entry.input); - const name = entry.title; - let title = entry.title, - target: string | undefined; - if (name === "buzz-dev-mcp__shell") { - title = "Run command"; - const line = - typeof input?.command === "string" - ? input.command - .split(/\r?\n/) - .find((part) => part.trim()) - ?.replace(/\p{Cc}/gu, " ") - .trim() - : undefined; - target = line - ? `${line.slice(0, 90)}${line.length > 90 ? "…" : ""}` - : undefined; - } else if ( - name === "buzz-dev-mcp__read_file" || - name === "buzz-dev-mcp__str_replace" || - name === "buzz-dev-mcp__view_image" - ) { - target = basename(input?.path); - title = target - ? name.endsWith("read_file") - ? "Read file" - : name.endsWith("str_replace") - ? "Edit file" - : "View image" - : entry.title; - } - // Only unwrap the observed shell wrapper. Missing/malformed fields retain the - // exact output text; raw source is accessible for every presentation below. - const result = - name === "buzz-dev-mcp__shell" ? parsed(entry.output) : undefined; - const shellOutput = - result && - typeof result.stdout === "string" && - typeof result.stderr === "string" && - Number.isInteger(result.exit_code) && - typeof result.timed_out === "boolean" && - typeof result.stdout_truncated === "boolean" && - typeof result.stderr_truncated === "boolean" - ? { - stdout: result.stdout, - stderr: result.stderr, - failed: result.exit_code !== 0 || result.timed_out, - note: [ - result.exit_code !== 0 ? `Exit code ${result.exit_code}` : "", - result.timed_out ? "Command timed out" : "", - result.stdout_truncated || result.stderr_truncated - ? "Output was truncated by the tool" - : "", - ] - .filter(Boolean) - .join(" · "), - } - : undefined; - const command = - name === "buzz-dev-mcp__shell" && typeof input?.command === "string" - ? input.command - : undefined; - return { title, target, shellOutput, command }; -} diff --git a/src/bundled/agent-activity/current-activity.test.ts b/src/bundled/agent-activity/current-activity.test.ts deleted file mode 100644 index 2ba8e0804f..0000000000 --- a/src/bundled/agent-activity/current-activity.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { expect, it } from "vitest"; -import { currentActivity } from "./current-activity"; -import type { ActivityRecord } from "../../features/agents/activity-records"; -const frame = (id: string, turnId: string, update: object): ActivityRecord => ({ - id, - envelopeId: id, - agent: "a", - kind: "acp_read", - receivedAt: 1, - plaintext: JSON.stringify({ - kind: "acp_read", - channelId: "c", - turnId, - payload: { method: "session/update", params: { update } }, - }), -}); -const tool = { - sessionUpdate: "tool_call", - toolCallId: "t", - title: "buzz-dev-mcp__read_file", - status: "in_progress", - rawInput: { path: "/project/file.ts" }, -}; -it("does not borrow historical actions when typing has no live turn", () => { - const records = [frame("1", "old", tool)]; - expect(currentActivity(records, [])).toBeUndefined(); - expect( - currentActivity(records, [{ turnId: "old", state: "ended" }]), - ).toBeUndefined(); - expect( - currentActivity(records, [{ turnId: "old", state: "unknown" }]), - ).toBeUndefined(); - expect( - currentActivity(records, [{ turnId: "new", state: "working" }]), - ).toBeUndefined(); -}); -it("prefers the latest tool over later prose, including folded completions and failures", () => { - const turns = [{ turnId: "t", state: "working" }]; - const records = [ - frame("1", "t", tool), - frame("2", "t", { - sessionUpdate: "agent_thought_chunk", - content: { type: "text", text: "Thinking text" }, - }), - ]; - expect(currentActivity(records, turns)).toEqual({ - title: "Read file · Running", - detail: "file.ts", - }); - records.push( - frame("3", "t", { - sessionUpdate: "tool_call_update", - toolCallId: "t", - status: "completed", - }), - ); - expect(currentActivity(records, turns)).toEqual({ - title: "Read file · Completed", - detail: "file.ts", - }); - records.push( - frame("4", "t", { - sessionUpdate: "tool_call_update", - toolCallId: "t", - status: "failed", - }), - ); - expect(currentActivity(records, turns)?.title).toBe("Read file · Failed"); -}); -it("bounds long preview text without rendering it as markup", () => { - const result = currentActivity( - [ - frame("1", "t", { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "