Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(web): smooth agent tool grouping and collapse animations (#6942)

Eric Hayesead25e0bb8c7
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
index 08d81ed7e0..aec49079c5 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
@@ -82,16 +82,18 @@ vi.mock('../ui', () => ({
{props.notice.title}
</div>
),
- ToolGroup: (props: {
+}));
+vi.mock('../views/LiveToolGroup', () => ({
+ LiveToolGroup: (props: {
count: number;
active: boolean;
- live: boolean;
+ activeIndex?: number;
children: JSX.Element;
}) => (
<div
data-active={String(props.active)}
data-count={props.count}
- data-live={String(props.live)}
+ data-active-index={props.activeIndex}
data-testid="group"
>
{props.children}
@@ -161,7 +163,7 @@ describe('Message tool grouping', () => {
const group = view.getByTestId('group');
expect(group.dataset.count).toBe('3');
expect(group.dataset.active).toBe('false');
- expect(group.dataset.live).toBe('false');
+ expect(group.dataset.activeIndex).toBeUndefined();
expect(view.getAllByTestId('tool').map((el) => el.dataset.index)).toEqual([
'1',
'2',
@@ -173,14 +175,14 @@ describe('Message tool grouping', () => {
]);
});
- it('leaves a lone tool call as its own card', () => {
+ it('starts a stable group with the first tool call', () => {
const view = render(() => (
<Message
message={message([text('Looking.'), tool('read')])}
inFlight={false}
/>
));
- expect(view.queryByTestId('group')).toBeNull();
+ expect(view.getByTestId('group').dataset.count).toBe('1');
expect(view.getByTestId('tool').dataset.index).toBe('1');
});
@@ -253,6 +255,53 @@ describe('Message tool grouping', () => {
expect(view.getByTestId('group').dataset.active).toBe('true');
});
+ it('follows unfinished work even when later calls have completed', () => {
+ const view = render(() => (
+ <Message
+ message={message(
+ [tool('slow', { status: 'running' }), tool('fast')],
+ null
+ )}
+ inFlight
+ />
+ ));
+ expect(view.getByTestId('group').dataset.activeIndex).toBe('0');
+ });
+
+ it('keeps delegated agents visible between tool bursts', () => {
+ const view = render(() => (
+ <Message
+ message={message(
+ [
+ tool('before'),
+ tool('agent', {
+ status: 'running',
+ detail: {
+ kind: 'subagent',
+ title: 'Investigate',
+ agentType: null,
+ description: null,
+ background: false,
+ prompt: null,
+ children: [],
+ result: null,
+ },
+ }),
+ tool('after'),
+ ],
+ null
+ )}
+ inFlight
+ />
+ ));
+ const agent = view
+ .getAllByTestId('tool')
+ .find((el) => el.textContent === 'agent');
+ expect(agent?.closest('[data-testid="group"]')).toBeNull();
+ expect(agent?.dataset.index).toBe('1');
+ expect(view.getAllByTestId('group')).toHaveLength(2);
+ });
+
it('settles a run the log left running once the turn is no longer live', () => {
// A superseded turn keeps `stop: null` and its last call `running`
// forever; a dead runtime leaves the tail the same way.
@@ -282,7 +331,7 @@ describe('Message tool grouping', () => {
);
expect(view.getByTestId('group')).toBe(group);
expect(group.dataset.count).toBe('3');
- expect(group.dataset.live).toBe('true');
+ expect(group.dataset.activeIndex).toBeUndefined();
expect(view.getAllByTestId('tool').map((el) => el.dataset.index)).toEqual([
'1',
'2',
@@ -290,12 +339,13 @@ describe('Message tool grouping', () => {
]);
});
- it('promotes a lone call to a group when a second follows it', () => {
+ it('keeps the first tool and its group mounted when a second follows it', () => {
const [store, setStore] = createStore({
message: message([text('Looking.'), tool('a')], null),
});
const view = render(() => <Message message={store.message} inFlight />);
- expect(view.queryByTestId('group')).toBeNull();
+ const group = view.getByTestId('group');
+ const firstTool = view.getByTestId('tool');
const prose = view.getByTestId('text');
setStore(
@@ -303,6 +353,8 @@ describe('Message tool grouping', () => {
reconcile(message([text('Looking.'), tool('a'), tool('b')], null))
);
expect(view.getByTestId('group').dataset.count).toBe('2');
+ expect(view.getByTestId('group')).toBe(group);
+ expect(view.getAllByTestId('tool')[0]).toBe(firstTool);
expect(view.getByTestId('text')).toBe(prose);
});
@@ -324,11 +376,11 @@ describe('Message tool grouping', () => {
expect(view.getAllByTestId('tool')[2].dataset.status).toBe('running');
});
- it('marks a completed batch as live so its arrivals remain visible briefly', () => {
+ it('keeps completed batches inactive even at the live tail', () => {
const view = render(() => (
<Message message={message([tool('a'), tool('b')], null)} inFlight />
));
- expect(view.getByTestId('group').dataset.live).toBe('true');
+ expect(view.getByTestId('group').dataset.activeIndex).toBeUndefined();
expect(view.getByTestId('group').dataset.active).toBe('false');
});
@@ -343,7 +395,7 @@ describe('Message tool grouping', () => {
/>
));
expect(view.getByTestId('group').dataset.active).toBe('true');
- expect(view.getByTestId('group').dataset.live).toBe('false');
+ expect(view.getByTestId('group').dataset.activeIndex).toBe('1');
expect(view.getAllByTestId('tool').map((row) => row.dataset.live)).toEqual([
'true',
'true',
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index afb69cfdeb..853af9fd03 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -28,9 +28,9 @@ import {
FailureNoticeCard,
isToolActive,
Thought,
- ToolGroup,
WorkingLine,
} from '../ui';
+import { LiveToolGroup } from '../views/LiveToolGroup';
import { AttachmentPart } from './parts/AttachmentPart';
import { ControlPart } from './parts/ControlPart';
import { ElicitationPart } from './parts/ElicitationPart';
@@ -123,29 +123,39 @@ function ToolGroupPart(props: {
const parts = () => props.message.parts.slice(props.start, props.end);
const calls = () =>
parts().filter((part): part is ToolUsePart => part.kind === 'tool_use');
- const live = () => props.inFlight && props.end === props.message.parts.length;
// A call the log left running in a finished turn is over (see
// `settledToolStatus`), so a settled turn's run is never "Calling".
- const active = () =>
- props.inFlight && calls().some((call) => isToolActive(call.status));
+ const activeIndex = () =>
+ props.inFlight
+ ? parts().findIndex(
+ (part) => part.kind === 'tool_use' && isToolActive(part.status)
+ )
+ : -1;
+ const active = () => activeIndex() !== -1;
const renderParts = () => (
<Index each={parts()}>
{(part, offset) => (
- <AgentMessagePart
- part={part()}
- message={props.message}
- index={props.start + offset}
- inFlight={props.inFlight}
- />
+ <div class="min-h-8 shrink-0">
+ <AgentMessagePart
+ part={part()}
+ message={props.message}
+ index={props.start + offset}
+ inFlight={props.inFlight}
+ />
+ </div>
)}
</Index>
);
return (
<Show when={calls().length > 0} fallback={renderParts()}>
- <ToolGroup count={calls().length} active={active()} live={live()}>
+ <LiveToolGroup
+ count={calls().length}
+ active={active()}
+ activeIndex={active() ? activeIndex() : undefined}
+ >
{renderParts()}
- </ToolGroup>
+ </LiveToolGroup>
</Show>
);
}
diff --git a/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx b/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx
index 0bc73d525c..e016cea2f5 100644
--- a/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx
@@ -131,15 +131,22 @@ export function SubagentToolCall(props: {
)}
</Show>
<Show when={props.detail.children.length > 0}>
- <div class="flex flex-col gap-1 border-l-2 border-edge-muted pl-2">
+ <div
+ role="region"
+ aria-label="Agent activity"
+ tabIndex={0}
+ class="flex max-h-40 flex-col overflow-y-auto overscroll-contain border-l-2 border-edge-muted pl-2"
+ >
<Index each={props.detail.children}>
{(child, index) => (
- <ChildPart
- part={child()}
- index={index}
- childCount={props.detail.children.length}
- context={childContext()}
- />
+ <div class="min-h-8 shrink-0">
+ <ChildPart
+ part={child()}
+ index={index}
+ childCount={props.detail.children.length}
+ context={childContext()}
+ />
+ </div>
)}
</Index>
</div>
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index 7899eae645..4e17c9eee0 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -45,9 +45,9 @@ import {
TodoList,
ToolCard,
ToolErrorCard,
- ToolGroup,
ToolStatusTitle,
} from '../ui';
+import { LiveToolGroup } from '../views/LiveToolGroup';
/**
* A Cursor-shaped catalog: long enough to scroll, with one grouped tail. Auto
@@ -1117,7 +1117,7 @@ export default function AgentUiGallery() {
</Item>
<Item label="ToolGroup (active / settled)">
- <ToolGroup count={3} active={pulse()}>
+ <LiveToolGroup count={3} active={pulse()}>
<ToolCard
title="Read"
icon={<FileText />}
@@ -1136,8 +1136,8 @@ export default function AgentUiGallery() {
subtitle="cargo test -p agent_fold"
status={pulse() ? 'running' : 'completed'}
/>
- </ToolGroup>
- <ToolGroup count={2} active={false} defaultOpen>
+ </LiveToolGroup>
+ <LiveToolGroup count={2} active={false} defaultOpen>
<ToolCard
title="Search"
icon={<MagnifyingGlass />}
@@ -1146,7 +1146,7 @@ export default function AgentUiGallery() {
trailing="3 results"
/>
<ToolCard title="Read" icon={<FileText />} status="completed" />
- </ToolGroup>
+ </LiveToolGroup>
</Item>
<Item label="Thought (active / settled)">
diff --git a/apps/web/src/features/block-agent/primitives/tool-group-disclosure.test.ts b/apps/web/src/features/block-agent/primitives/tool-group-disclosure.test.ts
new file mode 100644
index 0000000000..a2192c2b97
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/tool-group-disclosure.test.ts
@@ -0,0 +1,246 @@
+// @vitest-environment jsdom
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ createToolGroupDisclosure,
+ TOOL_GROUP_COMPLETION_DELAY_MS,
+ TOOL_GROUP_MIN_VISIBLE_MS,
+ TOOL_GROUP_REVEAL_DELAY_MS,
+} from './tool-group-disclosure';
+
+const disposers: (() => void)[] = [];
+
+function setup(initialActive = false, defaultOpen?: boolean) {
+ return createRoot((dispose) => {
+ disposers.push(dispose);
+ const [active, setActive] = createSignal(initialActive);
+ return {
+ ...createToolGroupDisclosure({ active, defaultOpen }),
+ setActive,
+ dispose,
+ };
+ });
+}
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ for (const dispose of disposers.splice(0)) dispose();
+ vi.useRealTimers();
+});
+
+describe('tool group disclosure', () => {
+ it('keeps historical groups collapsed unless initially opened', () => {
+ const closed = setup();
+ const opened = setup(false, true);
+
+ vi.runAllTimers();
+
+ expect(closed.expanded()).toBe(false);
+ expect(opened.expanded()).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('never expands a batch that completes before the reveal delay', () => {
+ const group = setup(true);
+
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS - 1);
+ expect(group.expanded()).toBe(false);
+ group.setActive(false);
+ vi.runAllTimers();
+
+ expect(group.expanded()).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('holds an automatically opened batch for the minimum visible time', () => {
+ const group = setup(true);
+
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS);
+ expect(group.expanded()).toBe(true);
+ group.setActive(false);
+ vi.advanceTimersByTime(TOOL_GROUP_MIN_VISIBLE_MS - 1);
+ expect(group.expanded()).toBe(true);
+ vi.advanceTimersByTime(1);
+
+ expect(group.expanded()).toBe(false);
+ });
+
+ it('keeps long-running work open until completion settles', () => {
+ const group = setup(true);
+
+ vi.advanceTimersByTime(60_000);
+ expect(group.expanded()).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ group.setActive(false);
+ vi.advanceTimersByTime(TOOL_GROUP_COMPLETION_DELAY_MS - 1);
+ expect(group.expanded()).toBe(true);
+ vi.advanceTimersByTime(1);
+
+ expect(group.expanded()).toBe(false);
+ });
+
+ it('shares one hold deadline across a hundred more calls', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS);
+
+ for (let index = 0; index < 100; index++) {
+ group.setActive(false);
+ vi.advanceTimersByTime(1);
+ group.setActive(true);
+ }
+ group.setActive(false);
+ expect(vi.getTimerCount()).toBe(2);
+ vi.advanceTimersByTime(TOOL_GROUP_MIN_VISIBLE_MS - 101);
+ expect(group.expanded()).toBe(true);
+ vi.advanceTimersByTime(1);
+
+ expect(group.expanded()).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does not close resumed work when the original hold expires', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS);
+ group.setActive(false);
+ vi.advanceTimersByTime(TOOL_GROUP_MIN_VISIBLE_MS - 1);
+ group.setActive(true);
+ vi.advanceTimersByTime(1);
+
+ expect(group.expanded()).toBe(true);
+ group.setActive(false);
+ vi.advanceTimersByTime(TOOL_GROUP_COMPLETION_DELAY_MS);
+ expect(group.expanded()).toBe(false);
+ });
+
+ it('waits for completion to settle when it occurs near the hold deadline', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(
+ TOOL_GROUP_REVEAL_DELAY_MS + TOOL_GROUP_MIN_VISIBLE_MS - 1
+ );
+ group.setActive(false);
+ vi.advanceTimersByTime(TOOL_GROUP_COMPLETION_DELAY_MS - 1);
+ expect(group.expanded()).toBe(true);
+ vi.advanceTimersByTime(1);
+
+ expect(group.expanded()).toBe(false);
+ });
+
+ it('bridges a short idle gap after the minimum visible time', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(
+ TOOL_GROUP_REVEAL_DELAY_MS + TOOL_GROUP_MIN_VISIBLE_MS
+ );
+
+ group.setActive(false);
+ vi.advanceTimersByTime(20);
+ expect(group.expanded()).toBe(true);
+ group.setActive(true);
+ vi.advanceTimersByTime(TOOL_GROUP_COMPLETION_DELAY_MS);
+
+ expect(group.expanded()).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('shares one completion delay across a hundred short idle gaps', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(
+ TOOL_GROUP_REVEAL_DELAY_MS + TOOL_GROUP_MIN_VISIBLE_MS
+ );
+
+ for (let index = 0; index < 100; index++) {
+ group.setActive(false);
+ vi.advanceTimersByTime(20);
+ expect(group.expanded()).toBe(true);
+ expect(vi.getTimerCount()).toBe(1);
+ group.setActive(true);
+ }
+ group.setActive(false);
+ vi.advanceTimersByTime(TOOL_GROUP_COMPLETION_DELAY_MS);
+
+ expect(group.expanded()).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does not queue reveal timers across many instantaneous batches', () => {
+ const group = setup();
+
+ for (let index = 0; index < 100; index++) {
+ group.setActive(true);
+ vi.advanceTimersByTime(1);
+ group.setActive(false);
+ }
+ vi.runAllTimers();
+
+ expect(group.expanded()).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('lets a later sustained batch reveal after an earlier batch finished', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS - 1);
+ group.setActive(false);
+ group.setActive(true);
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS - 1);
+ expect(group.expanded()).toBe(false);
+ vi.advanceTimersByTime(1);
+
+ expect(group.expanded()).toBe(true);
+ });
+
+ it('lets manual expansion cancel reveal and remain open after completion', () => {
+ const group = setup(true);
+ group.toggle();
+ group.setActive(false);
+ vi.runAllTimers();
+
+ expect(group.expanded()).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('lets manual collapse win across completion and later activity', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS);
+ group.toggle();
+ group.setActive(false);
+ group.setActive(true);
+ vi.runAllTimers();
+
+ expect(group.expanded()).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('lets manual expansion cancel a pending automatic close', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS);
+ group.setActive(false);
+ group.setExpanded(true);
+ vi.runAllTimers();
+
+ expect(group.expanded()).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it.each([0, TOOL_GROUP_REVEAL_DELAY_MS])(
+ 'cleans up pending timers when disposed after %d ms',
+ (elapsed) => {
+ const group = setup(true);
+ vi.advanceTimersByTime(elapsed);
+ expect(vi.getTimerCount()).toBe(1);
+
+ group.dispose();
+
+ expect(vi.getTimerCount()).toBe(0);
+ }
+ );
+
+ it('cleans up both the visible hold and pending completion on disposal', () => {
+ const group = setup(true);
+ vi.advanceTimersByTime(TOOL_GROUP_REVEAL_DELAY_MS);
+ group.setActive(false);
+ expect(vi.getTimerCount()).toBe(2);
+
+ group.dispose();
+
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/apps/web/src/features/block-agent/primitives/tool-group-disclosure.ts b/apps/web/src/features/block-agent/primitives/tool-group-disclosure.ts
new file mode 100644
index 0000000000..ceb865cff0
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/tool-group-disclosure.ts
@@ -0,0 +1,72 @@
+import { debounce } from '@solid-primitives/scheduled';
+import { type Accessor, createEffect, createSignal, on } from 'solid-js';
+
+export const TOOL_GROUP_REVEAL_DELAY_MS = 150;
+export const TOOL_GROUP_MIN_VISIBLE_MS = 600;
+export const TOOL_GROUP_COMPLETION_DELAY_MS = 150;
+
+/** Keep fast batches compact and give visible batches time to settle. */
+export function createToolGroupDisclosure(options: {
+ active: Accessor<boolean>;
+ defaultOpen?: boolean;
+}) {
+ const [expanded, setOpen] = createSignal(options.defaultOpen ?? false);
+ let manuallyControlled = false;
+ let minimumVisibleElapsed = true;
+ let completionDelayElapsed = false;
+
+ // The hold belongs to an opening, so a hundred calls share the same delay.
+ const finishMinimumVisible = debounce(() => {
+ minimumVisibleElapsed = true;
+ if (completionDelayElapsed && !options.active()) setOpen(false);
+ }, TOOL_GROUP_MIN_VISIBLE_MS);
+
+ // A brief idle gap often separates sequential batches in the same run.
+ const finishCompletion = debounce(() => {
+ completionDelayElapsed = true;
+ if (minimumVisibleElapsed && !options.active()) setOpen(false);
+ }, TOOL_GROUP_COMPLETION_DELAY_MS);
+
+ const beginMinimumVisible = () => {
+ minimumVisibleElapsed = false;
+ finishMinimumVisible();
+ };
+
+ const reveal = debounce(() => {
+ if (!options.active()) return;
+ setOpen(true);
+ beginMinimumVisible();
+ }, TOOL_GROUP_REVEAL_DELAY_MS);
+
+ // Synchronize the external timers with activity; completion never waits on
+ // an individual tool, and resumed work retains the original hold deadline.
+ createEffect(
+ on(options.active, (active, previousActive) => {
+ if (manuallyControlled) return;
+ reveal.clear();
+ finishCompletion.clear();
+ completionDelayElapsed = false;
+
+ if (active) {
+ if (!expanded()) reveal();
+ else if (previousActive === undefined) beginMinimumVisible();
+ } else if (previousActive !== undefined && expanded()) {
+ finishCompletion();
+ }
+ })
+ );
+
+ const setExpanded = (open: boolean) => {
+ manuallyControlled = true;
+ reveal.clear();
+ finishMinimumVisible.clear();
+ finishCompletion.clear();
+ setOpen(open);
+ };
+
+ return {
+ expanded,
+ setExpanded,
+ toggle: () => setExpanded(!expanded()),
+ };
+}
diff --git a/apps/web/src/features/block-agent/state/tool-groups.test.ts b/apps/web/src/features/block-agent/state/tool-groups.test.ts
index c413651741..3dfa1a9924 100644
--- a/apps/web/src/features/block-agent/state/tool-groups.test.ts
+++ b/apps/web/src/features/block-agent/state/tool-groups.test.ts
@@ -7,9 +7,8 @@ import { describe, expect, it } from 'vitest';
import { rendersOwnView, segmentParts } from './tool-groups';
const text = (): MessagePart => ({ kind: 'text', text: 'hi' });
-const tool = (
- overrides?: Partial<Extract<MessagePart, { kind: 'tool_use' }>>
-): MessagePart => ({
+type ToolUsePart = Extract<MessagePart, { kind: 'tool_use' }>;
+const tool = (overrides?: Partial<ToolUsePart>): ToolUsePart => ({
kind: 'tool_use',
id: 'call',
name: { kind: 'native', name: 'Read' },
@@ -50,14 +49,25 @@ describe('segmentParts', () => {
]);
});
- it('keeps a lone tool call as its own part', () => {
+ it('starts a group with the first tool call', () => {
expect(segmentParts([text(), tool(), text()])).toEqual([
{ kind: 'part', start: 0, end: 1 },
- { kind: 'part', start: 1, end: 2 },
+ { kind: 'tools', start: 1, end: 2 },
{ kind: 'part', start: 2, end: 3 },
]);
});
+ it('keeps the group kind and start as later tools extend a lone call', () => {
+ expect(segmentParts([text(), tool()])).toEqual([
+ { kind: 'part', start: 0, end: 1 },
+ { kind: 'tools', start: 1, end: 2 },
+ ]);
+ expect(segmentParts([text(), tool(), tool(), tool()])).toEqual([
+ { kind: 'part', start: 0, end: 1 },
+ { kind: 'tools', start: 1, end: 4 },
+ ]);
+ });
+
it('folds a run of consecutive tool calls into one group', () => {
expect(segmentParts([text(), tool(), tool(), tool(), text()])).toEqual([
{ kind: 'part', start: 0, end: 1 },
@@ -174,8 +184,28 @@ describe('segmentParts', () => {
it('leaves a thought after a single tool as its own part', () => {
expect(segmentParts([tool(), thought()])).toEqual([
+ { kind: 'tools', start: 0, end: 1 },
+ { kind: 'part', start: 1, end: 2 },
+ ]);
+ });
+
+ it('keeps every trailing thought visible after the last tool', () => {
+ expect(segmentParts([tool(), thought(), thought()])).toEqual([
+ { kind: 'tools', start: 0, end: 1 },
+ { kind: 'part', start: 1, end: 2 },
+ { kind: 'part', start: 2, end: 3 },
+ ]);
+ });
+
+ it('keeps a thought-only run as individual visible parts', () => {
+ expect(
+ segmentParts([text(), thought(), thought(), thought(), text()])
+ ).toEqual([
{ kind: 'part', start: 0, end: 1 },
{ kind: 'part', start: 1, end: 2 },
+ { kind: 'part', start: 2, end: 3 },
+ { kind: 'part', start: 3, end: 4 },
+ { kind: 'part', start: 4, end: 5 },
]);
});
@@ -217,9 +247,9 @@ describe('segmentParts', () => {
it('keeps a view-rendering call alone even between single calls', () => {
expect(segmentParts([tool(), displayResults(), tool()])).toEqual([
- { kind: 'part', start: 0, end: 1 },
+ { kind: 'tools', start: 0, end: 1 },
{ kind: 'part', start: 1, end: 2 },
- { kind: 'part', start: 2, end: 3 },
+ { kind: 'tools', start: 2, end: 3 },
]);
});
@@ -238,6 +268,53 @@ describe('segmentParts', () => {
{ kind: 'part', start: 3, end: 4 },
]);
});
+
+ it.each(['pending', 'running', 'completed', 'failed'] as const)(
+ 'keeps %s subagents visible outside ordinary tool groups',
+ (status) => {
+ const subagent = tool({
+ status,
+ detail: {
+ kind: 'subagent',
+ title: 'Investigate a bug',
+ description: null,
+ agentType: null,
+ prompt: null,
+ background: false,
+ children: [],
+ result: null,
+ },
+ });
+ expect(
+ segmentParts([tool(), thought(), subagent, thought(), tool()])
+ ).toEqual([
+ { kind: 'tools', start: 0, end: 2 },
+ { kind: 'part', start: 2, end: 3 },
+ { kind: 'tools', start: 3, end: 5 },
+ ]);
+ }
+ );
+
+ it.each(['pending', 'running', 'completed', 'failed'] as const)(
+ 'keeps %s user tools visible outside ordinary tool groups',
+ (status) => {
+ const userTool = tool({
+ status,
+ detail: {
+ kind: 'user_tool',
+ input: {},
+ outcome: { kind: 'pending' },
+ },
+ });
+ expect(
+ segmentParts([thought(), tool(), userTool, tool(), tool()])
+ ).toEqual([
+ { kind: 'tools', start: 0, end: 2 },
+ { kind: 'part', start: 2, end: 3 },
+ { kind: 'tools', start: 3, end: 5 },
+ ]);
+ }
+ );
});
describe('rendersOwnView', () => {
diff --git a/apps/web/src/features/block-agent/state/tool-groups.ts b/apps/web/src/features/block-agent/state/tool-groups.ts
index 80448f9e90..7f2af3e014 100644
--- a/apps/web/src/features/block-agent/state/tool-groups.ts
+++ b/apps/web/src/features/block-agent/state/tool-groups.ts
@@ -1,8 +1,10 @@
/**
- * Where a message's parts fold for display: a run of two or more consecutive
- * tool calls and thinking blocks reads as one collapsed row (`ui/ToolGroup`),
- * everything else as itself. A lone call stays a card of its own — a group of
- * one would hide the call behind a count that says nothing the card did not.
+ * Where a message's parts fold for display: consecutive ordinary tool calls
+ * and their thinking blocks share a group, everything else stays visible.
+ * The group starts with the first call so receiving another call does not
+ * replace the first call's host in the middle of its animation.
+ * Subagents and user tools stay outside groups so delegated work and user
+ * interactions remain visible regardless of the surrounding tool traffic.
* DisplayResults is inline answer content and always breaks the run, including
* while its arguments are still arriving.
*
@@ -58,8 +60,11 @@ export function rendersOwnView(part: MessagePart | undefined): boolean {
/** Whether a part may be folded into a collapsed run with its neighbours. */
function isGroupable(part: MessagePart | undefined): boolean {
return (
- (part?.kind === 'tool_use' || part?.kind === 'thought') &&
- !rendersOwnView(part)
+ part?.kind === 'thought' ||
+ (part?.kind === 'tool_use' &&
+ part.detail.kind !== 'subagent' &&
+ part.detail.kind !== 'user_tool' &&
+ !rendersOwnView(part))
);
}
@@ -67,23 +72,29 @@ export function segmentParts(parts: readonly MessagePart[]): PartSegment[] {
const segments: PartSegment[] = [];
let start = 0;
while (start < parts.length) {
- let end = start + 1;
- if (isGroupable(parts[start])) {
- while (isGroupable(parts[end])) end += 1;
- if (
- end - start >= 2 &&
- end === parts.length &&
- parts[end - 1]?.kind === 'thought'
- ) {
- end -= 1;
- }
+ if (!isGroupable(parts[start])) {
+ segments.push({ kind: 'part', start, end: start + 1 });
+ start += 1;
+ continue;
+ }
+
+ let end = start;
+ let lastCallEnd = start;
+ while (isGroupable(parts[end])) {
+ if (parts[end].kind === 'tool_use') lastCallEnd = end + 1;
+ end += 1;
+ }
+ if (lastCallEnd > start) {
+ const groupEnd = end === parts.length ? lastCallEnd : end;
+ segments.push({ kind: 'tools', start, end: groupEnd });
+ start = groupEnd;
+ }
+ // At the message tail, every thought after the last call remains visible.
+ // Thought-only runs never become groups: a group needs an actual call.
+ while (start < end) {
+ segments.push({ kind: 'part', start, end: start + 1 });
+ start += 1;
}
- segments.push({
- kind: end - start >= 2 ? 'tools' : 'part',
- start,
- end,
- });
- start = end;
}
return segments;
}
diff --git a/apps/web/src/features/block-agent/ui/ToolGroup.test.tsx b/apps/web/src/features/block-agent/ui/ToolGroup.test.tsx
index eac7d51612..ea6d528d19 100644
--- a/apps/web/src/features/block-agent/ui/ToolGroup.test.tsx
+++ b/apps/web/src/features/block-agent/ui/ToolGroup.test.tsx
@@ -9,36 +9,31 @@ vi.mock('@phosphor/caret-right.svg', () => ({
default: () => <svg data-testid="caret" />,
}));
-let animationDefaults: HTMLStyleElement;
-
beforeEach(() => {
vi.useFakeTimers();
- // jsdom's absent CSS reports an empty animation name. Browser styles report
- // "none" when animation is disabled; Kobalte uses it to finish presence.
- animationDefaults = document.createElement('style');
- animationDefaults.textContent = '* { animation-name: none; }';
- document.head.append(animationDefaults);
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
});
afterEach(() => {
cleanup();
- animationDefaults.remove();
vi.useRealTimers();
+ vi.unstubAllGlobals();
});
-function mount(overrides?: {
- active?: boolean;
- live?: boolean;
- defaultOpen?: boolean;
-}) {
+function mount(overrides?: { active?: boolean; defaultOpen?: boolean }) {
const [active, setActive] = createSignal(overrides?.active ?? false);
- const [live, setLive] = createSignal(overrides?.live);
const [calls, setCalls] = createSignal(['Read', 'Edit', 'Shell']);
const view = render(() => (
<ToolGroup
count={calls().length}
active={active()}
- live={live()}
defaultOpen={overrides?.defaultOpen}
>
<Index each={calls()}>
@@ -46,7 +41,7 @@ function mount(overrides?: {
</Index>
</ToolGroup>
));
- return { ...view, setActive, setLive, setCalls };
+ return { ...view, setActive, setCalls };
}
describe('ToolGroup', () => {
@@ -61,86 +56,41 @@ describe('ToolGroup', () => {
expect(view.queryAllByTestId('call')).toHaveLength(0);
});
- it('keeps manual expansion of historical groups until the reader closes them', () => {
+ it('keeps manual expansion while calls arrive and settle', () => {
const view = mount();
view.getByRole('button').click();
expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
- expect(view.getAllByTestId('call')).toHaveLength(3);
- vi.advanceTimersByTime(2000);
- expect(view.getAllByTestId('call')).toHaveLength(3);
- view.getByRole('button').click();
- expect(view.queryAllByTestId('call')).toHaveLength(0);
- });
-
- it('starts an active group open and collects arriving calls in place', () => {
- const view = mount({ active: true });
const first = view.getAllByTestId('call')[0];
- expect(view.getByRole('button').textContent).toContain('Calling 3 tools');
- expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
+ view.setActive(true);
view.setCalls((calls) => [...calls, 'Search']);
- expect(view.getAllByTestId('call')).toHaveLength(4);
+ expect(view.getByRole('button').textContent).toContain('Calling 4 tools');
expect(view.getAllByTestId('call')[0]).toBe(first);
+ view.setActive(false);
vi.advanceTimersByTime(2000);
+ expect(view.getByRole('button').textContent).toContain('Called 4 tools');
expect(view.getAllByTestId('call')).toHaveLength(4);
- });
-
- it('settles the shimmer immediately and collapses after a readable pause', () => {
- const view = mount({ active: true });
- view.setActive(false);
- expect(view.getByRole('button').textContent).toContain('Called 3 tools');
- expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
- vi.advanceTimersByTime(699);
- expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
- vi.advanceTimersByTime(1);
- expect(view.getByRole('button').getAttribute('aria-expanded')).toBe(
- 'false'
- );
+ expect(view.getAllByTestId('call')[0]).toBe(first);
+ view.getByRole('button').click();
expect(view.queryAllByTestId('call')).toHaveLength(0);
});
- it('bridges quick gaps between calls and cancels the earlier collapse', () => {
+ it('leaves automatic opening to its owner', () => {
const view = mount({ active: true });
- const first = view.getAllByTestId('call')[0];
- view.setActive(false);
- vi.advanceTimersByTime(500);
- view.setCalls((calls) => [...calls, 'Search']);
- view.setActive(true);
- vi.advanceTimersByTime(500);
- expect(view.getAllByTestId('call')[0]).toBe(first);
- view.setActive(false);
- vi.advanceTimersByTime(699);
- expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
- vi.advanceTimersByTime(1);
+ expect(view.getByRole('button').textContent).toContain('Calling 3 tools');
+ vi.advanceTimersByTime(2000);
expect(view.getByRole('button').getAttribute('aria-expanded')).toBe(
'false'
);
- });
-
- it('briefly reveals completed calls arriving in a live batch', () => {
- const view = mount({ live: true });
- expect(view.getAllByTestId('call')).toHaveLength(3);
- expect(view.getByRole('button').textContent).toContain('Called 3 tools');
- vi.advanceTimersByTime(700);
- expect(view.queryAllByTestId('call')).toHaveLength(0);
- view.setCalls((calls) => [...calls, 'Search', 'Read']);
- expect(view.getAllByTestId('call')).toHaveLength(5);
- vi.advanceTimersByTime(700);
expect(view.queryAllByTestId('call')).toHaveLength(0);
});
- it('preserves manually reopened results after automatic collapse', () => {
- const view = mount({ active: true });
- view.setActive(false);
- vi.advanceTimersByTime(700);
- view.getByRole('button').click();
- vi.advanceTimersByTime(2000);
- expect(view.getAllByTestId('call')).toHaveLength(3);
- });
-
it('supports an initially expanded static example', () => {
const view = mount({ defaultOpen: true });
vi.advanceTimersByTime(2000);
expect(view.getAllByTestId('call')).toHaveLength(3);
+ expect(view.getByRole('region', { name: 'Tool calls' }).id).toBe(
+ view.getByRole('button').getAttribute('aria-controls')
+ );
});
it('does not construct results for a historical collapsed group', () => {
@@ -159,10 +109,34 @@ describe('ToolGroup', () => {
expect(bodyMounted).toHaveBeenCalledOnce();
});
- it('clears pending collapse work on unmount', () => {
- const view = mount({ active: true });
- view.setActive(false);
- view.unmount();
- expect(vi.getTimerCount()).toBe(0);
+ it('reports disclosure requests and waits for controlled state updates', () => {
+ const [open, setOpen] = createSignal(false);
+ const onOpenChange = vi.fn();
+ const view = render(() => (
+ <ToolGroup
+ count={1}
+ active={false}
+ open={open()}
+ onOpenChange={onOpenChange}
+ >
+ <div data-testid="call">Read</div>
+ </ToolGroup>
+ ));
+ const trigger = view.getByRole('button');
+ trigger.click();
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+ expect(view.queryByTestId('call')).toBeNull();
+
+ setOpen(true);
+ expect(trigger.getAttribute('aria-expanded')).toBe('true');
+ expect(view.getByTestId('call')).toBeTruthy();
+ trigger.click();
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ expect(trigger.getAttribute('aria-expanded')).toBe('true');
+
+ setOpen(false);
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+ expect(view.queryByTestId('call')).toBeNull();
});
});
diff --git a/apps/web/src/features/block-agent/ui/ToolGroup.tsx b/apps/web/src/features/block-agent/ui/ToolGroup.tsx
index 08929a6b62..57f09750a4 100644
--- a/apps/web/src/features/block-agent/ui/ToolGroup.tsx
+++ b/apps/web/src/features/block-agent/ui/ToolGroup.tsx
@@ -1,62 +1,175 @@
-/** Consecutive calls collect in an open group while live, then fold to one row. */
+/**
+ * A stable summary for a run of calls. Fast bursts stay compact; ongoing work
+ * opens a bounded, scrolling window and settles with one delay for the run.
+ *
+ * Shaped like `Thought` rather than `ToolCard`: a bare caret row, no surface,
+ * because the cards themselves appear once it opens.
+ */
-import { Collapsible } from '@kobalte/core/collapsible';
+import { CollapseTransition } from '@app/components/view-shell/CollapseTransition';
import CaretRight from '@phosphor/caret-right.svg';
-import { createWritableMemo } from '@solid-primitives/memo';
-import { createScheduled, debounce } from '@solid-primitives/scheduled';
-import { createMemo, type JSX, on, Show } from 'solid-js';
+import { createResizeObserver } from '@solid-primitives/resize-observer';
+import {
+ createEffect,
+ createSignal,
+ createUniqueId,
+ type JSX,
+ on,
+ onMount,
+} from 'solid-js';
import { TextShimmer } from './TextShimmer';
-/** Let a fast result remain readable and bridge brief gaps between calls. */
-const SETTLE_DELAY_MS = 700;
-
export interface ToolGroupProps {
count: number;
/** A call in the run is still in flight: reads "Calling" and shimmers. */
active: boolean;
- /** The live tail can receive calls already completed in the same batch. */
- live?: boolean;
+ /** Child position of the first running call, so later results cannot bury it. */
+ activeIndex?: number;
defaultOpen?: boolean;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ /** One element per call/thought, each at least one compact row tall. */
children: JSX.Element;
}
-export function ToolGroup(props: ToolGroupProps) {
- const settled = createScheduled((callback) =>
- debounce(callback, SETTLE_DELAY_MS)
- );
- const automaticOpen = createMemo((wasOpen: boolean) => {
- const active = props.active;
- // Each new call extends the grace period, including completed batches.
- const live = (props.live ?? active) && props.count > 0;
- const readyToClose = settled();
- return active || (!readyToClose && (live || wasOpen));
- }, false);
- const [expanded, setExpanded] = createWritableMemo<boolean>(
- on(automaticOpen, (open, previous) =>
- previous === undefined ? (props.defaultOpen ?? open) : open
+/** Five compact tool rows, with history available without growing the transcript. */
+function ToolWindow(props: {
+ children: JSX.Element;
+ follow: boolean;
+ activeIndex?: number;
+ id: string;
+ onInteract: () => void;
+}) {
+ let viewport!: HTMLDivElement;
+ const [content, setContent] = createSignal<HTMLDivElement>();
+ let following = props.follow;
+ let scrolling = false;
+ const atBottom = () =>
+ viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop < 16;
+ const scrollTarget = () => {
+ const row = content()?.children[props.activeIndex ?? -1];
+ if (!row) return viewport.scrollHeight;
+ return Math.max(
+ 0,
+ row.getBoundingClientRect().bottom -
+ viewport.getBoundingClientRect().top +
+ viewport.scrollTop -
+ viewport.clientHeight
+ );
+ };
+ const followLatest = () => {
+ if (!following) return;
+ scrolling = true;
+ viewport.scrollTo({
+ top: scrollTarget(),
+ behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ ? 'instant'
+ : 'smooth',
+ });
+ };
+ const stopFollowing = () => {
+ following = false;
+ scrolling = false;
+ props.onInteract();
+ };
+
+ createResizeObserver(content, followLatest);
+ createEffect(
+ on(
+ () => props.activeIndex,
+ (index) => {
+ if (index !== undefined) followLatest();
+ },
+ { defer: true }
)
);
+ onMount(() => {
+ // Follow unfinished work first; reviewing history starts at the top.
+ if (following) viewport.scrollTop = scrollTarget();
+ });
+
+ return (
+ <div
+ id={props.id}
+ ref={viewport}
+ role="region"
+ aria-label="Tool calls"
+ tabIndex={0}
+ class="max-h-40 overflow-y-auto overscroll-contain [overflow-anchor:none]"
+ onWheel={stopFollowing}
+ onTouchMove={stopFollowing}
+ onPointerDown={stopFollowing}
+ onFocusIn={stopFollowing}
+ onKeyDown={(event) => {
+ if (
+ [
+ 'ArrowUp',
+ 'ArrowDown',
+ 'PageUp',
+ 'PageDown',
+ 'Home',
+ 'End',
+ ' ',
+ ].includes(event.key)
+ ) {
+ stopFollowing();
+ }
+ }}
+ onScroll={() => {
+ if (!scrolling) following = atBottom();
+ }}
+ on:scrollend={() => {
+ scrolling = false;
+ }}
+ >
+ <div ref={setContent} class="flex min-w-0 flex-col pl-6">
+ {props.children}
+ </div>
+ </div>
+ );
+}
+
+export function ToolGroup(props: ToolGroupProps) {
+ const [uncontrolledOpen, setUncontrolledOpen] = createSignal(
+ props.defaultOpen ?? false
+ );
+ const expanded = () => props.open ?? uncontrolledOpen();
+ const setExpanded = (open: boolean) => {
+ setUncontrolledOpen(open);
+ props.onOpenChange?.(open);
+ };
+ const contentId = createUniqueId();
const title = () =>
`${props.active ? 'Calling' : 'Called'} ${props.count} ${props.count === 1 ? 'tool' : 'tools'}`;
return (
- <Collapsible
- open={expanded()}
- onOpenChange={setExpanded}
- class="min-w-0 text-sm leading-6 text-ink-extra-muted"
- >
- <Collapsible.Trigger class="group flex min-h-8 items-center gap-2 py-1 text-left text-ink-extra-muted hover:text-ink-muted">
+ <div class="min-w-0 text-sm leading-6 text-ink-extra-muted">
+ <button
+ type="button"
+ aria-expanded={expanded()}
+ aria-controls={contentId}
+ class="group flex min-h-8 items-center gap-2 py-1 text-left text-ink-extra-muted hover:text-ink-muted"
+ onClick={() => setExpanded(!expanded())}
+ >
<TextShimmer text={title()} active={props.active} />
<CaretRight
aria-hidden="true"
- class="size-4 shrink-0 opacity-0 group-data-expanded:rotate-90 group-hover:opacity-100 group-focus-visible:opacity-100"
+ class="size-4 shrink-0 opacity-0 transition-transform group-hover:opacity-100 group-focus-visible:opacity-100 motion-reduce:transition-none"
+ classList={{ 'rotate-90': expanded() }}
/>
- </Collapsible.Trigger>
- <Collapsible.Content class="data-closed:hidden">
- <Show when={expanded()}>
- <div class="flex min-w-0 flex-col pl-6">{props.children}</div>
- </Show>
- </Collapsible.Content>
- </Collapsible>
+ </button>
+ <CollapseTransition open={expanded()}>
+ <div>
+ <ToolWindow
+ id={contentId}
+ follow={props.active}
+ activeIndex={props.activeIndex}
+ onInteract={() => setExpanded(true)}
+ >
+ {props.children}
+ </ToolWindow>
+ </div>
+ </CollapseTransition>
+ </div>
);
}
diff --git a/apps/web/src/features/block-agent/views/LiveToolGroup.test.tsx b/apps/web/src/features/block-agent/views/LiveToolGroup.test.tsx
new file mode 100644
index 0000000000..ded0366ec3
--- /dev/null
+++ b/apps/web/src/features/block-agent/views/LiveToolGroup.test.tsx
@@ -0,0 +1,143 @@
+/** @vitest-environment jsdom */
+
+import { cleanup, render } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { LiveToolGroup as ToolGroup } from './LiveToolGroup';
+
+vi.mock('@phosphor/caret-right.svg', () => ({
+ default: () => <svg data-testid="caret" />,
+}));
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+function mount(overrides?: { active?: boolean; defaultOpen?: boolean }) {
+ return render(() => (
+ <ToolGroup
+ count={3}
+ active={overrides?.active ?? false}
+ defaultOpen={overrides?.defaultOpen}
+ >
+ <div data-testid="call">Read</div>
+ <div data-testid="call">Edit</div>
+ <div data-testid="call">Bash</div>
+ </ToolGroup>
+ ));
+}
+
+describe('LiveToolGroup', () => {
+ it('starts historical groups closed with just the count', () => {
+ const view = mount();
+ expect(view.getByRole('button').textContent).toContain('Called 3 tools');
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe(
+ 'false'
+ );
+ expect(view.queryAllByTestId('call')).toHaveLength(0);
+ });
+
+ it('opens and closes the calls on click', () => {
+ const view = mount();
+ view.getByRole('button').click();
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
+ expect(view.getAllByTestId('call')).toHaveLength(3);
+ view.getByRole('button').click();
+ expect(view.queryAllByTestId('call')).toHaveLength(0);
+ });
+
+ it('reads as in progress while a call is still running', () => {
+ const view = mount({ active: true });
+ expect(view.getByRole('button').textContent).toContain('Calling 3 tools');
+ });
+
+ it('can start open', () => {
+ const view = mount({ defaultOpen: true });
+ expect(view.getAllByTestId('call')).toHaveLength(3);
+ });
+
+ it('never opens a hundred calls that finish in the initial buffer', () => {
+ vi.useFakeTimers();
+ const [active, setActive] = createSignal(true);
+ const view = render(() => (
+ <ToolGroup count={100} active={active()}>
+ <div data-testid="calls">100 calls</div>
+ </ToolGroup>
+ ));
+ vi.advanceTimersByTime(20);
+ setActive(false);
+ vi.advanceTimersByTime(1000);
+ expect(view.queryByTestId('calls')).toBeNull();
+ expect(view.getByRole('button').textContent).toContain('Called 100 tools');
+ });
+
+ it('holds an opened run, then collapses without delaying its completion status', () => {
+ vi.useFakeTimers();
+ const [active, setActive] = createSignal(true);
+ const view = render(() => (
+ <ToolGroup count={3} active={active()}>
+ <div data-testid="calls">calls</div>
+ </ToolGroup>
+ ));
+ vi.advanceTimersByTime(150);
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
+ setActive(false);
+ expect(view.getByRole('button').textContent).toContain('Called 3 tools');
+ vi.advanceTimersByTime(599);
+ expect(view.getByTestId('calls')).toBeTruthy();
+ vi.advanceTimersByTime(1);
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe(
+ 'false'
+ );
+ });
+
+ it('keeps manually opened history open while calls arrive and settle', () => {
+ vi.useFakeTimers();
+ const [active, setActive] = createSignal(false);
+ const view = render(() => (
+ <ToolGroup count={3} active={active()}>
+ <div data-testid="calls">calls</div>
+ </ToolGroup>
+ ));
+ view.getByRole('button').click();
+ const calls = view.getByTestId('calls');
+ setActive(true);
+ vi.advanceTimersByTime(200);
+ setActive(false);
+ vi.advanceTimersByTime(1000);
+ expect(view.getByTestId('calls')).toBe(calls);
+ expect(view.getByRole('region', { name: 'Tool calls' }).id).toBe(
+ view.getByRole('button').getAttribute('aria-controls')
+ );
+ });
+
+ it('keeps keyboard inspection open after the calls finish', () => {
+ vi.useFakeTimers();
+ const [active, setActive] = createSignal(true);
+ const view = render(() => (
+ <ToolGroup count={1} active={active()}>
+ <button type="button">Inspect result</button>
+ </ToolGroup>
+ ));
+ vi.advanceTimersByTime(150);
+ view.getByRole('button', { name: 'Inspect result' }).focus();
+ setActive(false);
+ vi.advanceTimersByTime(1000);
+ expect(document.activeElement).toBe(
+ view.getByRole('button', { name: 'Inspect result' })
+ );
+ });
+});
diff --git a/apps/web/src/features/block-agent/views/LiveToolGroup.tsx b/apps/web/src/features/block-agent/views/LiveToolGroup.tsx
new file mode 100644
index 0000000000..6894e8d176
--- /dev/null
+++ b/apps/web/src/features/block-agent/views/LiveToolGroup.tsx
@@ -0,0 +1,20 @@
+import { createToolGroupDisclosure } from '../primitives/tool-group-disclosure';
+import { ToolGroup, type ToolGroupProps } from '../ui/ToolGroup';
+
+/** Apply live-run timing without making the presentation own tool lifecycle. */
+export function LiveToolGroup(
+ props: Omit<ToolGroupProps, 'open' | 'onOpenChange'>
+) {
+ const disclosure = createToolGroupDisclosure({
+ active: () => props.active,
+ defaultOpen: props.defaultOpen,
+ });
+
+ return (
+ <ToolGroup
+ {...props}
+ open={disclosure.expanded()}
+ onOpenChange={disclosure.setExpanded}
+ />
+ );
+}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 4880a36b28..e63edcfecd 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -521,15 +521,24 @@ Only tools with a supported result view can expand. Unknown tools, unsupported
drafts, and payloads that do not fit their renderer stay as summary rows with
no caret. Tool arguments and results never fall back to raw JSON.
-Consecutive calls collect under an expanded **Calling N tools** group while
-running. Rows appear as calls arrive; after the calls finish, the group briefly
-settles and collapses to **Called N tools**. Group growth and collapse happen
-immediately, without animation, including fast batches. Completed groups in
-history start collapsed and can be reopened. The group caret sits immediately
-after its label and appears on hover or keyboard focus. Expand an edit row to
-view its diffs. Result bodies load only when their row opens; syntax highlighting
-may appear after the diff text. Opening a session or expanding a group should
-leave the app responsive, even when the session contains many file edits.
+Tool runs keep one group from their first call. Historical runs start collapsed;
+live calls get a 150 ms buffer, so fast parallel bursts can finish as **Called N
+tools** without flashing a list. Ongoing work opens a scrollable window of at
+most five compact rows. The window follows unfinished calls first, keeping slow
+work visible even when later calls finish, until you scroll or interact with it;
+scrolling back to the bottom resumes following. An automatically opened window
+stays visible for at least 600 ms and waits for 150 ms without an active call
+before collapsing smoothly. These delays are shared by the group, never queued
+per call, and do not delay answer text or tool execution. Manually opening,
+closing, or interacting with a group overrides automatic collapse. Subagents
+and tools requiring user input remain outside these groups so they stay visible
+during other tool bursts. Nested agent activity has its own scrollable window.
+
+The group caret sits immediately after its label and appears on hover or keyboard
+focus. Expand an edit row to view its diffs. Result bodies load only when their
+row opens; syntax highlighting may appear after the diff text. Opening a session
+or expanding a group should leave the app responsive, even when the session
+contains many file edits.
`DisplayResults` renders its dynamic view directly in the reply and stays visible
without opening a tool row. It breaks tool groups before and after itself,
@@ -544,8 +553,9 @@ server do not currently receive this tool.
The development gallery at `/app/component/agent-ui` includes **Replay tool
calls** and **Replay fast batch**, both using the message renderer. Check that
-rows accumulate, completed calls stop shimmering, the group collapses after
-completion without height animation, and its carets still expand the results.
+ongoing rows accumulate in the five-row window, completed calls stop shimmering,
+fast batches stay compact, and the group collapses smoothly after completion.
+Its carets should still expand the results, and reduced motion disables animation.
Check that rich result controls still work and `DisplayResults` stays visible
between surrounding groups. In **AgentMessage (end-to-end)**, expand the group
and confirm unknown tools have no individual disclosure or JSON payload. Repeat