Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agent-activity): show an agent's progress as one working line (#9276)
teo462c4737b63d
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 58fc68ad86..4fbcff92c4 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -606,6 +606,11 @@ if (LOCAL_ONLY) {lazy(() => import('@app/features/block-agent/debug/replay/Replay')));+ registerComponent(+ 'agent-progress',+ lazy(() => import('@app/features/agent-activity/debug/ProgressPlayground'))+ );+registerComponent('agent-changes-ui',lazy(() => import('@app/features/changes/debug/Gallery'))diff --git a/apps/web/src/features/agent-activity/agent-activity.test.tsx b/apps/web/src/features/agent-activity/agent-activity.test.tsxindex 972b22f7e0..b115588ed4 100644--- a/apps/web/src/features/agent-activity/agent-activity.test.tsx+++ b/apps/web/src/features/agent-activity/agent-activity.test.tsx@@ -8,7 +8,7 @@ import { cleanup, render, waitFor } from '@solidjs/testing-library';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';import { ok } from 'neverthrow';import { createSignal } from 'solid-js';-import { afterEach, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';const live = vi.hoisted(() => ({ acquired: [] as (string | undefined)[] }));const code = vi.hoisted(() => ({ read: vi.fn() }));@@ -24,6 +24,8 @@ vi.mock('./queries/live-session', () => ({}));vi.mock('@app/features/block-agent/ui', () => ({TextShimmer: (props: { text: string }) => <>{props.text}</>,+ WorkingDots: () => null,+ DisclosureCaret: () => null,}));import type { AgentActivityData } from '@macro-inc/lexical-core';@@ -37,8 +39,21 @@ function AgentActivity(props: AgentActivityData) {);}+// jsdom has no ResizeObserver; the summary's disclosure measures with one.+beforeEach(() => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+ }+ );+});+afterEach(() => {cleanup();+ vi.unstubAllGlobals();live.acquired.length = 0;setMessages([]);code.read.mockReset();@@ -71,21 +86,37 @@ const steps = (view: ReturnType<typeof render>) =>.getAllByRole('listitem').map((item) => [item.textContent, item.dataset.status]);-it('shows a sealed run as the snapshot the message carries, without the session', () => {+/** The step an open run's line names, and where it got to. */+const line = (view: ReturnType<typeof render>) => {+ const step = view+ .getByRole('status')+ .querySelector<HTMLElement>('[data-status]');+ return [step?.textContent, step?.dataset.status];+};++it('folds a sealed run to a summary that opens to its steps, without the session', () => {const view = render(() => (<AgentActivityagentSessionId="session"turn={2}segment={1}- rows={[{ id: 't1', label: 'Ran', detail: 'cargo', status: 'completed' }]}+ rows={[+ { id: 't1', label: 'Ran', detail: 'cargo', status: 'completed' },+ { id: 't2', label: 'Read', detail: 'lib.rs', status: 'failed' },+ ]}sealed/>));- expect(steps(view)).toEqual([['Rancargo', 'completed']]);expect(live.acquired).toEqual([]);+ expect(view.queryAllByRole('listitem')).toEqual([]);+ view.getByRole('button', { name: 'Used 2 tools · 1 failed' }).click();+ expect(steps(view)).toEqual([+ ['Ran', 'completed'],+ ['ReadFailed', 'failed'],+ ]);});-it('ticks an open run live from the session, keeping the snapshot until it loads', () => {+it('shows an open run as one line naming the step it is on, live from the session', () => {const view = render(() => (<AgentActivityagentSessionId="session"@@ -96,7 +127,7 @@ it('ticks an open run live from the session, keeping the snapshot until it loads/>));expect(live.acquired).toEqual(['session']);- expect(steps(view)).toEqual([['Runningcargo', 'running']]);+ expect(line(view)).toEqual(['Running', 'running']);setMessages([reply([@@ -104,31 +135,54 @@ it('ticks an open run live from the session, keeping the snapshot until it loads{ id: 't2', label: 'Reading', detail: 'lib.rs', status: 'running' },]),]);- expect(steps(view)).toEqual([- ['Rancargo', 'completed'],- ['Readinglib.rs', 'running'],+ expect(line(view)).toEqual(['Reading', 'running']);+ expect(view.queryAllByRole('listitem')).toEqual([]);++ // Between steps the line keeps the last one rather than going blank.+ setMessages([+ reply([+ { id: 't1', label: 'Ran', detail: 'cargo', status: 'completed' },+ { id: 't2', label: 'Read', detail: 'lib.rs', status: 'completed' },+ ]),]);+ expect(line(view)).toEqual(['Read', 'completed']);});-it('folds a long run behind a count of its earlier steps', () => {- const rows = Array.from({ length: 8 }, (_, index) => ({- id: `t${index}`,- label: `Step ${index}`,- status: 'completed' as const,- }));- const view = render(() => (- <AgentActivity- agentSessionId="session"- turn={2}- segment={1}- rows={rows}- sealed- />- ));- expect(view.getByRole('button', { name: '2 earlier steps' })).toBeTruthy();- expect(view.queryByText('Step 1')).toBeNull();- view.getByRole('button', { name: '2 earlier steps' }).click();- expect(view.getByText('Step 1')).toBeTruthy();+it('takes turns among tools called at once, and a new call takes the line at once', () => {+ vi.useFakeTimers();+ try {+ const view = render(() => (+ <AgentActivity+ agentSessionId="session"+ turn={2}+ segment={1}+ rows={snapshot}+ sealed={false}+ />+ ));+ const entities = {+ id: 't1',+ label: 'List entities',+ detail: null,+ status: 'running' as const,+ };+ const tags = { ...entities, id: 't2', label: 'List tags' };+ setMessages([reply([entities, tags])]);+ expect(line(view)[0]).toBe('List tags');+ vi.advanceTimersByTime(2000);+ expect(line(view)[0]).toBe('List entities');+ vi.advanceTimersByTime(2000);+ expect(line(view)[0]).toBe('List tags');+ vi.advanceTimersByTime(2000);+ expect(line(view)[0]).toBe('List entities');++ setMessages([+ reply([entities, tags, { ...entities, id: 't3', label: 'Search' }]),+ ]);+ expect(line(view)[0]).toBe('Search');+ } finally {+ vi.useRealTimers();+ }});it('replaces a live code step with observed SDK operations and preserves uncertain outcomes', async () => {@@ -178,12 +232,7 @@ it('replaces a live code step with observed SDK operations and preserves uncerta},];setMessages([message]);- await waitFor(() =>- expect(steps(view)).toEqual([- ['Search documents', 'completed'],- ['Read email', 'running'],- ])- );+ await waitFor(() => expect(line(view)).toEqual(['Read email', 'running']));expect(code.read).toHaveBeenCalledWith('session', executionId);client.setQueriesData(@@ -198,30 +247,22 @@ it('replaces a live code step with observed SDK operations and preserves uncerta});await waitFor(() =>- expect(steps(view)).toEqual([- ['Search documents', 'completed'],- ['Read email', 'interrupted'],- ])+ expect(line(view)).toEqual(['Read email', 'interrupted']));expect(view.queryByText(record.source)).toBeNull();code.read.mockRejectedValue(new Error('Temporary network failure'));await client.refetchQueries({ queryKey: ['agentCodeExecution'] });- expect(steps(view)).toEqual([- ['Search documents', 'completed'],- ['Read email', 'interrupted'],- ]);+ expect(line(view)).toEqual(['Read email', 'interrupted']);client.setQueriesData({ queryKey: ['agentCodeExecution'] },{ ...record, source: 'another execution' });- await waitFor(() =>- expect(steps(view)).toEqual([['Execute code', 'running']])- );+ await waitFor(() => expect(line(view)).toEqual(['Execute code', 'running']));});-it('updates a live row in place as the run paints, rather than redrawing it', () => {+it('keeps the step in place as the run paints, rather than redrawing it', () => {const view = render(() => (<AgentActivityagentSessionId="session"@@ -231,16 +272,18 @@ it('updates a live row in place as the run paints, rather than redrawing it', ()sealed={false}/>));+ const shown = () =>+ view.getByRole('status').querySelector<HTMLElement>('[data-status]');setMessages([reply([{ id: 't1', label: 'Running', detail: 'cargo', status: 'running' }]),]);- const row = view.getByRole('listitem');+ const step = shown();// Every paint carries the run as new objects.setMessages([reply([{ id: 't1', label: 'Running', detail: 'cargo', status: 'running' }]),]);- expect(view.getByRole('listitem')).toBe(row);+ expect(shown()).toBe(step);setMessages([reply([@@ -248,14 +291,10 @@ it('updates a live row in place as the run paints, rather than redrawing it', (){ id: 't2', label: 'Reading', detail: 'lib.rs', status: 'running' },]),]);- expect(view.getAllByRole('listitem')[0]).toBe(row);- expect(steps(view)).toEqual([- ['Rancargo', 'completed'],- ['Readinglib.rs', 'running'],- ]);+ expect(line(view)).toEqual(['Reading', 'running']);});-it('keeps snapshots free of tool details while authorized live rows retain them', () => {+it('names each step without what it ran or read, even to a reader of the live session', () => {const safe = [{ id: 't1', label: 'Ran', status: 'completed' as const }];const snapshotView = render(() => (<AgentActivity@@ -266,6 +305,7 @@ it('keeps snapshots free of tool details while authorized live rows retain them'sealed/>));+ snapshotView.getByRole('button', { name: 'Used 1 tool' }).click();expect(snapshotView.getByRole('listitem').textContent).toBe('Ran');expect(live.acquired).toEqual([]);snapshotView.unmount();@@ -278,11 +318,10 @@ it('keeps snapshots free of tool details while authorized live rows retain them'sealed={false}/>));- expect(liveView.getByRole('listitem').textContent).toBe('Ran');+ expect(line(liveView)[0]).toBe('Ran');setMessages([reply([{ ...safe[0], detail: 'TOKEN=private-value run-report' }]),]);- expect(liveView.getByRole('listitem').textContent).toBe(- 'RanTOKEN=private-value run-report'- );+ expect(line(liveView)[0]).toBe('Ran');+ expect(liveView.queryByText(/private-value/)).toBeNull();});diff --git a/apps/web/src/features/agent-activity/agent-activity.tsx b/apps/web/src/features/agent-activity/agent-activity.tsxindex 348aade082..312c99c5a6 100644--- a/apps/web/src/features/agent-activity/agent-activity.tsx+++ b/apps/web/src/features/agent-activity/agent-activity.tsx@@ -1,6 +1,8 @@import type { AgentActivityData } from '@macro-inc/lexical-core';import { Show } from 'solid-js';-import { ActivityRows } from './components/activity-rows';+import { ActivityLine } from './components/activity-line';+import type { ActivityRowView } from './components/activity-rows';+import { ActivitySummary } from './components/activity-summary';import { replyToTurn, segmentRows } from './core/live-reply';import { createCodeActivityRows } from './queries/code-activity';import { createLiveSession } from './queries/live-session';@@ -8,16 +10,20 @@ import { createLiveSession } from './queries/live-session';/*** The steps of an agent's reply inside a channel message.*- * Live while the run of steps is still open, from the session's own fold, so- * a step ticks from running to done where it was posted. Once the run seals,- * or for a viewer who cannot read the session, the snapshot the server wrote- * into the message keeps the status and label. Raw commands and tool-input- * details are available only in the authorized live session view.+ * While the run of steps is open it is one shimmering line naming the step+ * the agent is on, live from the session's own fold. Once the run seals, or+ * for a viewer who cannot read the session, the snapshot the server wrote+ * into the message keeps the status and label; a sealed run folds to a+ * summary that opens to its steps. Raw commands and tool-input details are+ * available only in the authorized live session view.*/export function AgentActivity(props: AgentActivityData) {return (<div class="min-w-0 max-w-full" data-agent-activity={props.agentSessionId}>- <Show when={!props.sealed} fallback={<ActivityRows rows={props.rows} />}>+ <Show+ when={!props.sealed}+ fallback={<ActivitySummary rows={props.rows} />}+ ><LiveActivity {...props} /></Show></div>@@ -37,5 +43,19 @@ function LiveActivity(props: AgentActivityData) {() => props.segment,rows);- return <ActivityRows rows={activity()} />;+ return <ActivityLine rows={activity()} />;+}++const THINKING: ActivityRowView = {+ id: 'thinking',+ label: 'Thinking',+ status: 'running',+};++/**+ * A reply whose turn is running with no open run to show: the line a run+ * uses, so the reply never reads as finished while the agent works.+ */+export function AgentThinking() {+ return <ActivityLine rows={[THINKING]} />;}diff --git a/apps/web/src/features/agent-activity/agent-typing.test.tsx b/apps/web/src/features/agent-activity/agent-typing.test.tsxindex df013b4c06..b047001f24 100644--- a/apps/web/src/features/agent-activity/agent-typing.test.tsx+++ b/apps/web/src/features/agent-activity/agent-typing.test.tsx@@ -9,6 +9,7 @@ import {waitFor,within,} from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';import { ok } from 'neverthrow';import { createSignal, For, type JSX, Show } from 'solid-js';import { afterEach, beforeEach, expect, it, vi } from 'vitest';@@ -17,7 +18,6 @@ const mocks = vi.hoisted(() => ({issue: vi.fn(),failure: vi.fn(),canEdit: true,- profileLoading: false,liveSessions: 0,cards: 0,}));@@ -44,14 +44,15 @@ vi.mock('@queries/agent-session/session', () => ({}),}));vi.mock('@queries/bots/profiles', () => ({- useBotProfile: () =>- mocks.profileLoading- ? { isPending: true, isError: false, data: undefined }- : {- isPending: false,- isError: false,- data: { name: 'Researcher', avatarUrl: undefined, deleted: false },- },+ useBotProfile: () => ({+ isPending: false,+ isError: false,+ data: { name: 'Researcher', avatarUrl: undefined, deleted: false },+ }),+}));+vi.mock('@app/features/block-agent/ui', () => ({+ TextShimmer: (props: { text: string }) => <>{props.text}</>,+ WorkingDots: () => null,}));vi.mock('@app/features/agent-dms/components/persona-avatar', () => ({PersonaAvatar: () => null,@@ -92,12 +93,24 @@ import {handleCommsTyping,TYPING_INDICATOR_TIMEOUT_MS,} from '@queries/messages/typing';-import { AgentTyping, AgentTypingProvider } from './agent-typing';+import { AgentTyping } from './agent-typing';const parent = { type: 'channel', id: 'dm' } as const;const BOT = 'bot|0a8f5e1c-2b3d-4e5f-8a9b-0c1d2e3f4a5b';-function typing(phase: 'thinking' | 'working' | 'waiting') {+/** Rendered where the app renders it, under a query client. */+function show(ui: () => JSX.Element) {+ const client = new QueryClient();+ return render(ui, {+ wrapper: (props) => (+ <QueryClientProvider client={client}>+ {props.children}+ </QueryClientProvider>+ ),+ });+}++function typing(phase: 'thinking' | 'writing' | 'working' | 'waiting') {handleCommsTyping({action: 'start',@@ -147,7 +160,6 @@ function asking(requestId: string): SessionMetadata {beforeEach(() => {clearTypingIndicators();mocks.canEdit = true;- mocks.profileLoading = false;mocks.liveSessions = 0;mocks.cards = 0;mocks.issue.mockResolvedValue(ok({}));@@ -168,24 +180,21 @@ it('shows an agent typing with what it is doing, and nothing for people', () =>{ action: 'start', parent, user_id: 'macro|[email protected]' },'macro|[email protected]');- const view = render(() => <AgentTyping parent={parent} threadId={null} />);+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);expect(view.queryByRole('status')).toBeNull();typing('thinking');- expect(view.getByRole('status').textContent).toContain(- 'Researcher is thinking'- );+ expect(view.getByRole('status').textContent).toBe('Thinking');typing('working');- expect(view.getByRole('status').textContent).toContain(- 'Researcher is working'- );+ expect(view.getByRole('status').textContent).toBe('Working');});-it('streams the unfinished passage beneath and stops the turn', async () => {- typing('thinking');+it('says it is writing without streaming the passage, and stops the turn', async () => {+ typing('writing');setMessages([writing('Looking at the failing test')]);- const view = render(() => <AgentTyping parent={parent} threadId={null} />);- expect(view.getByText('Looking at the failing test')).toBeTruthy();+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);+ expect(view.getByRole('status').textContent).toBe('Writing');+ expect(view.queryByText('Looking at the failing test')).toBeNull();await fireEvent.click(view.getByRole('button', { name: 'Stop' }));await waitFor(() =>@@ -197,7 +206,7 @@ it('allows Stop to be retried after its request rejects', async () => {typing('working');setMessages([writing('Partial')]);mocks.issue.mockRejectedValueOnce(new Error('Disconnected'));- const view = render(() => <AgentTyping parent={parent} threadId={null} />);+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);const stop = view.getByRole<HTMLButtonElement>('button', { name: 'Stop' });await fireEvent.click(stop);@@ -235,7 +244,7 @@ it('puts a question for the running turn under the row', () => {},],} as unknown as SessionMetadata);- const view = render(() => <AgentTyping parent={parent} threadId={null} />);+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);expect(view.getAllByRole('region', { name: 'Question' }).map((q) => q.textContent)).toEqual(['ask-1']);@@ -245,22 +254,46 @@ it('offers no Stop to a viewer who cannot drive the session', () => {mocks.canEdit = false;typing('working');setMessages([writing('Partial')]);- const view = render(() => <AgentTyping parent={parent} threadId={null} />);+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);expect(view.queryByRole('button', { name: 'Stop' })).toBeNull();});-it('names nobody until the persona is known, rather than a placeholder', () => {- mocks.profileLoading = true;- typing('thinking');- const view = render(() => <AgentTyping parent={parent} threadId={null} />);- expect(view.getByRole('status').textContent).toBe('...');+it('names the step the open run is on, and never what it ran', () => {+ typing('working');+ setMessages([+ {+ ...writing('Checking the tests first.'),+ segments: [+ { index: 0, kind: 'prose', start: 0, end: 1, sealed: true, rows: [] },+ {+ index: 1,+ kind: 'activity',+ start: 1,+ end: 2,+ sealed: false,+ rows: [+ {+ id: 't1',+ label: 'Running',+ detail: 'cargo test',+ status: 'running',+ },+ ],+ },+ ],+ phase: 'working',+ },+ ]);+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);+ expect(view.getByRole('status').textContent).toBe('Running');+ expect(view.queryByText(/cargo/)).toBeNull();});it('keeps a card as it was left through a metadata event that resends it', () => {typing('waiting');setMessages([writing('')]);setMetadata(asking('ask-1'));- const view = render(() => <AgentTyping parent={parent} threadId={null} />);+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);const answer = view.getByRole<HTMLInputElement>('textbox', {name: 'Answer',});@@ -271,13 +304,30 @@ it('keeps a card as it was left through a metadata event that resends it', () =>expect(mocks.cards).toBe(1);});-it('moves the live turn with the newest row rather than starting it over', () => {- typing('waiting');- setMessages([writing('')]);- setMetadata(asking('ask-1'));+it('follows the newest message with the step the turn is on', () => {+ typing('working');+ setMessages([+ {+ ...writing('Checking first.'),+ segments: [+ { index: 0, kind: 'prose', start: 0, end: 1, sealed: true, rows: [] },+ {+ index: 1,+ kind: 'activity',+ start: 1,+ end: 2,+ sealed: false,+ rows: [+ { id: 't1', label: 'Reading', detail: null, status: 'running' },+ ],+ },+ ],+ phase: 'working',+ },+ ]);const [newest, setNewest] = createSignal<string>('first');- const view = render(() => (- <AgentTypingProvider parent={parent} threadId={null}>+ const view = show(() => (+ <><For each={['first', 'second']}>{(row) => (<div data-testid={row}>@@ -287,32 +337,22 @@ it('moves the live turn with the newest row rather than starting it over', () =></div>)}</For>- {/* Another place makes its own rows; nothing types there. */}+ {/* Nothing types in a thread here. */}<div data-testid="thread"><AgentTyping parent={parent} threadId="thread" /></div>- </AgentTypingProvider>+ </>));- const answer = within(view.getByTestId('first')).getByRole<HTMLInputElement>(- 'textbox',- { name: 'Answer' }- );- answer.value = 'main';+ expect(+ within(view.getByTestId('first')).getByRole('status').textContent+ ).toBe('Reading');- // A message arrives below, so the next row is the newest.+ // The agent posts a message, so the next row is the newest.setNewest('second');+ expect(within(view.getByTestId('first')).queryByRole('status')).toBeNull();expect(- within(view.getByTestId('second')).getByRole('textbox', { name: 'Answer' })- ).toBe(answer);- // The reader scrolls away, and the virtualized row unmounts, then back.- setNewest('');- expect(view.queryByRole('textbox', { name: 'Answer' })).toBeNull();- setNewest('second');- expect(view.getByRole('textbox', { name: 'Answer' })).toBe(answer);-- expect(answer.value).toBe('main');- expect(mocks.cards).toBe(1);- expect(mocks.liveSessions).toBe(1);+ within(view.getByTestId('second')).getByRole('status').textContent+ ).toBe('Reading');expect(within(view.getByTestId('thread')).queryByRole('status')).toBeNull();});@@ -322,15 +362,13 @@ it('keeps the row of a turn waiting on the viewer after its typing lapses', () =setMessages([writing('')]);setMetadata(asking('ask-1'));publishSessionTurn('session', 'blocked');- const view = render(() => <AgentTyping parent={parent} threadId={null} />);+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);const answer = view.getByRole('textbox', { name: 'Answer' });// No heartbeat for a while, as when a phone sleeps with the app open.vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS);expect(getTypingAgents(parent, null).size).toBe(0);- expect(view.getByRole('status').textContent).toContain(- 'Researcher is waiting for an answer'- );+ expect(view.getByRole('status').textContent).toBe('Waiting for an answer');expect(view.getByRole('textbox', { name: 'Answer' })).toBe(answer);// The turn ends, and the row goes with it.@@ -341,7 +379,7 @@ it('keeps the row of a turn waiting on the viewer after its typing lapses', () =it('lets a lapsed typing go when the fold has no turn open', () => {vi.useFakeTimers();typing('thinking');- const view = render(() => <AgentTyping parent={parent} threadId={null} />);+ const view = show(() => <AgentTyping parent={parent} threadId={null} />);expect(view.getByRole('status')).toBeTruthy();vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS);expect(view.queryByRole('status')).toBeNull();diff --git a/apps/web/src/features/agent-activity/agent-typing.tsx b/apps/web/src/features/agent-activity/agent-typing.tsxindex 124d9df3c7..8c8fc6c31b 100644--- a/apps/web/src/features/agent-activity/agent-typing.tsx+++ b/apps/web/src/features/agent-activity/agent-typing.tsx@@ -13,87 +13,44 @@ import { useAgentSessionQuery } from '@queries/agent-session/session';import { firstPartyBotName } from '@queries/bots/first-party-bot-name';import { useBotProfile } from '@queries/bots/profiles';import { queryReadyGate } from '@queries/gate';-import { parentKey } from '@queries/messages/keys';import { getTypingAgents, type TypingAgent } from '@queries/messages/typing';import type { MessagePart } from '@service-agent-fold/generated/types';import type { MessageParent } from '@service-storage/messages';import { Key } from '@solid-primitives/keyed';import {- createContext,createMemo,createSignal,For,- type JSX,onCleanup,- type ParentProps,Show,Suspense,- useContext,} from 'solid-js';import { LiveTail } from './components/live-tail';import { TypingRow } from './components/typing-row';-import { openReply, streamingProse, typingLabel } from './core/live-reply';+import { openReply, openRun, phaseRow } from './core/live-reply';+import { createCodeActivityRows } from './queries/code-activity';import { createLiveSession } from './queries/live-session';/** One place of a conversation: the timeline, or one thread. */type TypingPlace = { parent: MessageParent; threadId: string | null };-const KeptRowsContext = createContext<{- shows: (place: TypingPlace) => boolean;- rows: JSX.Element;-}>();-/*** Agents typing in one place of a conversation - the timeline, or one- * thread - each as a typing row. A viewer who can read the session also sees- * the turn as it runs beneath it: the passage being written, what it is- * waiting on, and Stop.+ * thread - each as a typing row that says what the agent is doing: the step+ * it is on to a viewer who can read the session, otherwise what its turn is+ * doing. That viewer also gets Stop, and anything the turn is waiting on+ * beneath the row.*- * Under an {@link AgentTypingProvider} for the same place, these are the- * provider's rows, moved here.+ * A list shows it under its newest row, so it mounts again whenever a message+ * arrives; the live session it reads is shared, so it picks up where it was.*/export function AgentTyping(props: TypingPlace) {- const kept = useContext(KeptRowsContext);+ // A boundary of its own: rows that suspend must not blank the message.return (- <Show- when={kept?.shows(props)}- fallback={- <AgentTypingRows parent={props.parent} threadId={props.threadId} />- }- >- {kept?.rows}- </Show>- );-}--/**- * Makes one place's typing rows once, for a list that shows them under- * whichever of its rows is newest: a row that changes when a message- * arrives, and that a virtualized list unmounts once the reader scrolls- * away. Rows made inside it would go with it - the turn's live view would- * load again, and every card beneath it would start over, dropping an- * answer or a draft the viewer had half written. Made here, the rows outlive- * the list's rows and only move between them.- */-export function AgentTypingProvider(props: ParentProps<TypingPlace>) {- // A boundary of their own: rows that suspend must not blank the list.- const rows = (<Suspense><AgentTypingRows parent={props.parent} threadId={props.threadId} /></Suspense>);- return (- <KeptRowsContext.Provider- value={{- shows: (place) =>- place.threadId === props.threadId &&- parentKey(place.parent) === parentKey(props.parent),- rows,- }}- >- {props.children}- </KeptRowsContext.Provider>- );}function AgentTypingRows(props: TypingPlace) {@@ -138,26 +95,29 @@ function AgentTypingEntry(props: {const botId = () => props.botUserId.replace(/^bot\|/, '');const firstParty = () => firstPartyBotName(botId());const profile = useBotProfile(() => (firstParty() ? '' : botId()));- // Undefined while the profile loads: the row shows only its dots rather- // than a placeholder name that changes a moment later.+ // Empty while the profile loads, rather than a placeholder name that+ // changes a moment later.const name = () => {const known = firstParty();if (known) return known;if (queryReadyGate(profile)) return profile.data?.name ?? 'Agent';- return profile.isError ? 'Agent' : undefined;+ return profile.isError ? 'Agent' : '';};const avatarUrl = () =>queryReadyGate(profile) ? profile.data?.avatarUrl : undefined;- const label = () => {- const known = name();- return known ? typingLabel(known, props.phase) : '';- };const live = createLiveSession(() => props.sessionId);const sessionQuery = useAgentSessionQuery(() => props.sessionId);const canEdit = () =>queryReadyGate(sessionQuery) ? sessionQuery.data?.canEdit : undefined;const reply = () => (live.loaded() ? openReply(live.messages()) : undefined);+ const run = () => openRun(reply());+ const rows = createCodeActivityRows(+ () => props.sessionId,+ reply,+ () => run()?.index,+ () => run()?.rows ?? [phaseRow(props.phase)]+ );// A held tool call is answered from the session, not here: a turn the// owner prompts, as every DM turn is, is never held for them.const pending = () =>@@ -197,25 +157,21 @@ function AgentTypingEntry(props: {avatar={<PersonaAvatarbotId={botId()}- name={name() ?? ''}+ name={name()}avatarUrl={avatarUrl()}- size="sm"+ size="md"/>}- label={label()}+ rows={rows()}+ onStop={+ canEdit() && reply()+ ? () => fireAndForget(stop(), 'agent-activity')+ : undefined+ }+ stopping={stopping()}>- <Show when={reply() || live.failed()}>- <LiveTail- prose={reply() ? streamingProse(reply()!) : undefined}- disconnected={live.failed()}- onReconnect={live.retry}- onStop={- canEdit() && reply()- ? () => fireAndForget(stop(), 'agent-activity')- : undefined- }- stopping={stopping()}- >+ <Show when={pending().length > 0 || live.failed()}>+ <LiveTail disconnected={live.failed()} onReconnect={live.retry}>{/* Each metadata event carries every request anew. Keyed by whatit asks, a card keeps whatever was typed into it. */}<Keydiff --git a/apps/web/src/features/agent-activity/components/activity-line.tsx b/apps/web/src/features/agent-activity/components/activity-line.tsxnew file mode 100644index 0000000000..2d7efd3e1a--- /dev/null+++ b/apps/web/src/features/agent-activity/components/activity-line.tsx@@ -0,0 +1,59 @@+import { TextShimmer, WorkingDots } from '@app/features/block-agent/ui';+import { Key } from '@solid-primitives/keyed';+import { createMemo, createSignal, on, onCleanup, onMount } from 'solid-js';+import type { ActivityRowView } from './activity-rows';++/** How long each of several steps running at once holds the line. */+const CYCLE_MS = 2000;++/**+ * An open run of steps as one shimmering line: the step the agent is on,+ * sliding in as it moves to the next, and taking turns with any others+ * running at the same time.+ */+export function ActivityLine(props: { rows: readonly ActivityRowView[] }) {+ const [tick, setTick] = createSignal(0);+ onMount(() => {+ const timer = setInterval(() => setTick((count) => count + 1), CYCLE_MS);+ onCleanup(() => clearInterval(timer));+ });+ const running = () => props.rows.filter((row) => row.status === 'running');+ const runningIds = createMemo(() =>+ running()+ .map((row) => row.id)+ .join('\n')+ );+ // A step that starts takes the line at once; the cycle counts from there.+ const cycleStart = createMemo(on(runningIds, () => tick()));+ const current = () => {+ const active = running();+ if (active.length === 0) return props.rows.at(-1);+ return active.at(-1 - ((tick() - cycleStart()) % active.length));+ };+ const shown = () => {+ const step = current();+ return step ? [step] : [];+ };+ return (+ <div+ class="my-1 flex min-h-6 min-w-0 items-center gap-2 overflow-hidden text-ink-extra-muted"+ role="status"+ >+ <WorkingDots />+ {/* Keyed by step: the next step slides in, while a step repainted as+ new objects keeps its node and its shimmer runs on. */}+ <Key each={shown()} by="id">+ {(step) => (+ <span+ class="flex min-w-0 animate-agent-step-in items-center gap-2 motion-reduce:animate-none"+ data-status={step().status}+ >+ <span class="min-w-0 truncate text-ink-muted">+ <TextShimmer text={step().label} active />+ </span>+ </span>+ )}+ </Key>+ </div>+ );+}diff --git a/apps/web/src/features/agent-activity/components/activity-rows.tsx b/apps/web/src/features/agent-activity/components/activity-rows.tsxindex 8f64638cb3..6f72914515 100644--- a/apps/web/src/features/agent-activity/components/activity-rows.tsx+++ b/apps/web/src/features/agent-activity/components/activity-rows.tsx@@ -1,104 +1,50 @@import { TextShimmer } from '@app/features/block-agent/ui';-import CheckIcon from '@icon/system/regular/check.svg';-import SpinnerIcon from '@icon/system/regular/spinner-gap.svg';-import WarningIcon from '@icon/system/regular/warning-circle.svg';-import XIcon from '@icon/system/regular/x.svg';import { Key } from '@solid-primitives/keyed';-import { createSignal, Match, Show, Switch } from 'solid-js';+import { Match, Switch } from 'solid-js';-/** One step of an agent's work, as the session's fold worded it. */+/**+ * One step of an agent's work, as the session's fold worded it. A+ * conversation names the step only: what it ran or read stays in the session.+ */export type ActivityRowView = {id: string;label: string;- detail?: string | null;status: 'running' | 'completed' | 'failed' | 'interrupted';};-/** Steps shown before the earlier ones fold behind a count. */-const VISIBLE_ROWS = 6;-/**- * The steps an agent took between two passages of its reply: what it did, to- * what, and how that went, one quiet line each. A long run keeps its latest- * steps in view and folds the rest behind a count.+ * The steps an agent took between two passages of its reply, one quiet line+ * each like the session's tool rows: what it did, and how it went only when+ * it did not simply finish.*/export function ActivityRows(props: { rows: readonly ActivityRowView[] }) {- const [expanded, setExpanded] = createSignal(false);- const hidden = () =>- expanded() ? 0 : Math.max(0, props.rows.length - VISIBLE_ROWS);return (- <ul class="my-1 flex min-w-0 flex-col gap-0.5 text-xs" aria-label="Steps">- <Show when={hidden() > 0}>- <li>- <button- type="button"- class="text-ink-extra-muted hover:text-ink-muted"- onClick={() => setExpanded(true)}- >- {hidden()} earlier {hidden() === 1 ? 'step' : 'steps'}- </button>- </li>- </Show>- {/* A live run's rows arrive as new objects with every paint. Keyed by- step, a row updates in place and its spinner and shimmer run on. */}- <Key each={props.rows.slice(hidden())} by="id">+ <ul class="my-1 flex min-w-0 flex-col gap-0.5" aria-label="Steps">+ {/* Rows can arrive as new objects with every paint. Keyed by step, a+ row updates in place and its shimmer runs on. */}+ <Key each={props.rows} by="id">{(row) => (<li- class="flex min-h-5 min-w-0 items-center gap-2"+ class="flex min-h-6 min-w-0 items-center gap-1.5"data-status={row().status}>- <StatusIcon status={row().status} />- <span class="shrink-0 text-ink-muted">+ <span class="shrink-0"><TextShimmertext={row().label}active={row().status === 'running'}/></span>- <Show when={row().detail}>- {(detail) => (- <span class="min-w-0 truncate font-mono text-ink-extra-muted">- {detail()}- </span>- )}- </Show>+ <Switch>+ <Match when={row().status === 'failed'}>+ <span class="shrink-0 text-failure">Failed</span>+ </Match>+ <Match when={row().status === 'interrupted'}>+ <span class="shrink-0 text-ink-disabled">Interrupted</span>+ </Match>+ </Switch></li>)}</Key></ul>);}--function StatusIcon(props: { status: ActivityRowView['status'] }) {- return (- <Switch>- <Match when={props.status === 'running'}>- <SpinnerIcon- aria-hidden={false}- class="size-3.5 shrink-0 animate-spin text-ink-muted"- aria-label="Running"- />- </Match>- <Match when={props.status === 'completed'}>- <CheckIcon- aria-hidden={false}- class="size-3.5 shrink-0 text-success"- aria-label="Done"- />- </Match>- <Match when={props.status === 'failed'}>- <XIcon- aria-hidden={false}- class="size-3.5 shrink-0 text-failure"- aria-label="Failed"- />- </Match>- <Match when={props.status === 'interrupted'}>- <WarningIcon- aria-hidden={false}- class="size-3.5 shrink-0 text-ink-muted"- aria-label="Interrupted: it may or may not have finished"- />- </Match>- </Switch>- );-}diff --git a/apps/web/src/features/agent-activity/components/activity-summary.tsx b/apps/web/src/features/agent-activity/components/activity-summary.tsxnew file mode 100644index 0000000000..f299d0bd68--- /dev/null+++ b/apps/web/src/features/agent-activity/components/activity-summary.tsx@@ -0,0 +1,47 @@+import { DisclosureCaret, TextShimmer } from '@app/features/block-agent/ui';+import { CollapseTransition } from '@ui/components/CollapseTransition';+import { createSignal, createUniqueId, Show } from 'solid-js';+import { ActivityRows, type ActivityRowView } from './activity-rows';++/**+ * A finished run of steps as one line that opens to the steps. Failed steps+ * are counted on the line, so folding the run never hides that one failed.+ */+export function ActivitySummary(props: { rows: readonly ActivityRowView[] }) {+ const [open, setOpen] = createSignal(false);+ const contentId = createUniqueId();+ const count = () => props.rows.length;+ const failed = () =>+ props.rows.filter((row) => row.status === 'failed').length;+ // A call held for permission can still finish after its run sealed.+ const running = () => props.rows.some((row) => row.status === 'running');+ return (+ <Show when={count() > 0}>+ <div class="my-1 min-w-0">+ <button+ type="button"+ aria-expanded={open()}+ aria-controls={contentId}+ class="group flex min-h-6 items-center gap-1 text-ink-extra-muted touch:min-h-[44px] not-touch:hover:text-ink-muted"+ onClick={() => setOpen(!open())}+ >+ <span>+ <TextShimmer+ text={`Used ${count()} ${count() === 1 ? 'tool' : 'tools'}`}+ active={running()}+ />+ <Show when={failed() > 0}>+ <span class="text-failure">{` · ${failed()} failed`}</span>+ </Show>+ </span>+ <DisclosureCaret open={open()} />+ </button>+ <CollapseTransition open={open()}>+ <div id={contentId}>+ <ActivityRows rows={props.rows} />+ </div>+ </CollapseTransition>+ </div>+ </Show>+ );+}diff --git a/apps/web/src/features/agent-activity/components/live-tail.tsx b/apps/web/src/features/agent-activity/components/live-tail.tsxindex 49216d5e61..352a973180 100644--- a/apps/web/src/features/agent-activity/components/live-tail.tsx+++ b/apps/web/src/features/agent-activity/components/live-tail.tsx@@ -1,59 +1,31 @@-import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { Button } from '@ui';import { type ParentProps, Show } from 'solid-js';/**- * The part of a running reply that is not a message yet: the passage the- * agent is writing, what it is waiting on (children), and the controls a- * person who can steer the session has. Finished passages are posted as their- * own messages, so nothing shown here is shown twice.+ * What a running turn is waiting on (children), beneath its typing row, and a+ * way back when the live view stopped updating. The reply itself is posted as+ * messages once each passage is finished, so nothing here repeats it.*/export function LiveTail(props: ParentProps<{- /** The unfinished passage, streaming. */- prose?: string;/** The live view stopped updating. */disconnected?: boolean;onReconnect?: () => void;- /** Present when the viewer may stop the turn. */- onStop?: () => void;- stopping?: boolean;}>) {return (<div class="flex min-w-0 flex-col gap-2">- <Show when={props.prose}>- {(prose) => (- <div class="min-w-0 text-sm text-ink">- <StaticMarkdown markdown={prose()} />- </div>- )}- </Show>{props.children}- <Show when={props.disconnected || props.onStop}>+ <Show when={props.disconnected}><div class="flex items-center gap-2 text-xs text-ink-muted">- <Show when={props.disconnected}>- <span>Live updates disconnected.</span>- <Button- size="xs"- variant="ghost"- onClick={() => props.onReconnect?.()}- >- Reconnect- </Button>- </Show>- <Show when={props.onStop}>- {(stop) => (- <Button- size="xs"- variant="ghost"- disabled={props.stopping}- onClick={() => stop()()}- >- Stop- </Button>- )}- </Show>+ <span>Live updates disconnected.</span>+ <Button+ size="xs"+ variant="ghost"+ onClick={() => props.onReconnect?.()}+ >+ Reconnect+ </Button></div></Show></div>diff --git a/apps/web/src/features/agent-activity/components/typing-row.tsx b/apps/web/src/features/agent-activity/components/typing-row.tsxindex b7251c9f2a..7fbfa84f9e 100644--- a/apps/web/src/features/agent-activity/components/typing-row.tsx+++ b/apps/web/src/features/agent-activity/components/typing-row.tsx@@ -1,33 +1,48 @@-import type { JSX, ParentProps } from 'solid-js';+import { Button } from '@ui';+import { type JSX, type ParentProps, Show } from 'solid-js';+import { ActivityLine } from './activity-line';+import type { ActivityRowView } from './activity-rows';/**- * An agent typing in a conversation: its avatar and what it is doing, the- * way a teammate's typing reads. Whatever the agent is writing right now, and- * anything it is waiting on, renders beneath as children.+ * An agent at work in a conversation, in one row under its newest message:+ * its avatar beside the working line, and Stop for a viewer who may stop it.+ * Anything the agent is waiting on renders beneath as children.*/export function TypingRow(- props: ParentProps<{ avatar: JSX.Element; label: string }>+ props: ParentProps<{+ avatar: JSX.Element;+ rows: readonly ActivityRowView[];+ /** Present when the viewer may stop the turn. */+ onStop?: () => void;+ stopping?: boolean;+ }>) {return (<div- class="flex min-w-0 items-start gap-2 py-1 pl-[var(--message-padding-x)] pr-[var(--message-padding-x)]"+ class="flex min-w-0 items-start gap-2 px-[var(--message-padding-x)] py-1"data-agent-typing>- <div class="flex w-[var(--user-icon-width)] shrink-0 justify-center pt-0.5">+ {/* As tall as the working line, so the avatar sits level with it. */}+ <div class="flex h-8 w-[var(--user-icon-width)] shrink-0 items-center justify-center">{props.avatar}</div><div class="min-w-0 flex-1">- <div- class="flex min-h-6 items-center text-xs text-ink-extra-muted"- role="status"- aria-live="polite"- >- <span>{props.label}</span>- <span class="flex" aria-hidden="true">- <span class="animate-typing-dot [animation-delay:0ms]">.</span>- <span class="animate-typing-dot [animation-delay:200ms]">.</span>- <span class="animate-typing-dot [animation-delay:400ms]">.</span>- </span>+ <div class="flex min-w-0 items-center gap-2">+ <div class="min-w-0 flex-1">+ <ActivityLine rows={props.rows} />+ </div>+ <Show when={props.onStop}>+ {(stop) => (+ <Button+ size="xs"+ variant="ghost"+ disabled={props.stopping}+ onClick={() => stop()()}+ >+ Stop+ </Button>+ )}+ </Show></div>{props.children}</div>diff --git a/apps/web/src/features/agent-activity/core/live-reply.test.ts b/apps/web/src/features/agent-activity/core/live-reply.test.tsindex 01f85f31d4..837bd8f9a2 100644--- a/apps/web/src/features/agent-activity/core/live-reply.test.ts+++ b/apps/web/src/features/agent-activity/core/live-reply.test.ts@@ -6,10 +6,10 @@ import type {import { describe, expect, it } from 'vitest';import {openReply,+ openRun,+ phaseRow,replyToTurn,segmentRows,- streamingProse,- typingLabel,} from './live-reply';function reply(@@ -59,7 +59,7 @@ describe('live reply', () => {expect(replyToTurn([done, running], 0)).toBe(done);});- it('streams only an unfinished passage', () => {+ it('finds the run the agent is in the middle of, and no finished one', () => {const writing = reply(0,[@@ -91,7 +91,7 @@ describe('live reply', () => {prose(2, 2, false),]);- expect(streamingProse(writing)).toBe('Still writing');+ expect(openRun(writing)).toBeUndefined();expect(segmentRows(writing, 1)).toEqual([{ id: 't1', label: 'Ran', detail: 'ls', status: 'completed' },]);@@ -101,14 +101,30 @@ describe('live reply', () => {[{ kind: 'text', text: 'All done' }],[prose(0, 0, true)]);- expect(streamingProse(finished)).toBeUndefined();+ expect(openRun(finished)).toBeUndefined();+ const working = reply(+ 0,+ [],+ [+ prose(0, 0, true),+ {+ index: 1,+ kind: 'activity',+ start: 1,+ end: 2,+ sealed: false,+ rows: [],+ },+ ]+ );+ expect(openRun(working)?.index).toBe(1);+ expect(openRun(undefined)).toBeUndefined();});- it('says what the agent is doing in words', () => {- expect(typingLabel('Macro', 'writing')).toBe('Macro is typing');- expect(typingLabel('Scout', 'working')).toBe('Scout is working');- expect(typingLabel('Scout', 'waiting')).toBe(- 'Scout is waiting for an answer'- );+ it('says what the turn is doing in words', () => {+ expect(phaseRow('thinking').label).toBe('Thinking');+ expect(phaseRow('writing').label).toBe('Writing');+ expect(phaseRow('working').label).toBe('Working');+ expect(phaseRow('waiting').label).toBe('Waiting for an answer');});});diff --git a/apps/web/src/features/agent-activity/core/live-reply.ts b/apps/web/src/features/agent-activity/core/live-reply.tsindex 35c54dd57a..89fed6e4b4 100644--- a/apps/web/src/features/agent-activity/core/live-reply.ts+++ b/apps/web/src/features/agent-activity/core/live-reply.ts@@ -1,6 +1,7 @@import type {ActivityRow,FoldedMessage,+ Segment,TurnPhase,} from '@service-agent-fold/generated/types';@@ -23,21 +24,10 @@ export function replyToTurn();}-/**- * The passage the agent is writing right now: the reply's last segment while- * it is unfinished prose. A finished passage is posted as its own message, so- * only this one streams live.- */-export function streamingProse(reply: FoldedMessage): string | undefined {- const last = reply.segments.at(-1);- if (!last || last.kind !== 'prose' || last.sealed) return undefined;- const text = reply.parts- .slice(last.start, last.end)- .flatMap((part) =>- part.kind === 'text' && part.text.trim() ? [part.text.trim()] : []- )- .join('\n\n');- return text || undefined;+/** The run of steps the agent is in the middle of, when it is in one. */+export function openRun(reply: FoldedMessage | undefined): Segment | undefined {+ const last = reply?.segments.at(-1);+ return last?.kind === 'activity' && !last.sealed ? last : undefined;}/** The live rows of one activity segment, by the index the server posted. */@@ -49,14 +39,22 @@ export function segmentRows(return found?.kind === 'activity' ? found.rows : undefined;}-const PHASE_VERBS: Record<TurnPhase, string> = {- thinking: 'is thinking',- writing: 'is typing',- working: 'is working',- waiting: 'is waiting for an answer',+const PHASE_LINES: Record<TurnPhase, string> = {+ thinking: 'Thinking',+ writing: 'Writing',+ working: 'Working',+ waiting: 'Waiting for an answer',};-/** What a typing indicator says an agent is doing. */-export function typingLabel(name: string, phase: TurnPhase): string {- return `${name} ${PHASE_VERBS[phase]}`;+/**+ * What a turn is doing, as a step: all its typing tells a viewer who cannot+ * read the session, and what a typing row says between runs.+ */+export function phaseRow(phase: TurnPhase): ActivityRow {+ return {+ id: phase,+ label: PHASE_LINES[phase],+ detail: null,+ status: 'running',+ };}diff --git a/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx b/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsxnew file mode 100644index 0000000000..3027f4de5c--- /dev/null+++ b/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx@@ -0,0 +1,1087 @@+/**+ * Local playground for how an agent's reply reads while it works and once it+ * is done: every state in a DM, as a channel mention's thread reply, and in+ * the agent session, one tab each, from one set of fixture parts. Mounted at+ * `/app/debug/agent-progress`.+ *+ * Messages are composed by the server's own serializer, so each is the+ * markdown a conversation would store; the session tab renders the same+ * parts through the session's message renderer.+ */++import { PersonaAvatar } from '@app/features/agent-dms/components/persona-avatar';+import { Message as AgentMessage } from '@app/features/block-agent/component/AgentMessage';+import { WorkingLine } from '@app/features/block-agent/ui/WorkingLine';+import { ChannelMessage } from '@channel/Message/ChannelMessage';+import { MACRO_AGENT_BOT_ID } from '@core/constant/macroAgent';+import type { MessageData } from '@core/messages/types';+import {+ type AgentChatReply,+ type AgentChatReplyBody,+ type AgentReplySegment,+ composeAgentChatReply,+} from '@macro-inc/lexical-core/utils/agent-chat-reply';+import type {+ ActivityRow,+ FoldedMessage,+ MessagePart,+ Segment,+ StopReason,+ ToolDetail,+ ToolName,+ ToolStatus,+ TurnPhase,+} from '@service-agent-fold/generated/types';+import { DEFAULT_DARK_THEME, DEFAULT_LIGHT_THEME } from '@theme/constants';+import { clearThemePreview, previewTheme } from '@theme/utils/themeUtils';+import { Button, Tabs } from '@ui';+import { createSignal, For, Index, type JSX, onCleanup, Show } from 'solid-js';+import { TypingRow } from '../components/typing-row';+import { openRun, phaseRow } from '../core/live-reply';++type ToolUsePart = Extract<MessagePart, { kind: 'tool_use' }>;++/** A reply at one moment, written once and shown in both surfaces. */+type Scenario = {+ id: string;+ title: string;+ /** What to look at. */+ note: string;+ parts: MessagePart[];+ /** The turn is still running. */+ inFlight: boolean;+ /** How a finished turn ended; `end_turn` unless set. */+ stop?: StopReason;+ /** The closing line the harness writes for a turn without an answer. */+ footer?: string;+};++/**+ * A session no backend knows: a live run fails to load it and keeps the+ * rows the message carries, as it does for a reader who cannot open it.+ */+const SESSION = '00000000-0000-4000-8000-00000000f01d';+const POSTED_AT = '2026-10-30T15:04:00.000Z';+const DOC_CHECKLIST = '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46';+const DOC_TIMELINE = '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e47';+const DOC_NOTES = '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e48';++// The harness's closing lines (agent_harness `channel_announcer`).+const CANCELLED_FALLBACK = 'I stopped before finishing that.';+const ERROR_FALLBACK = 'Sorry — I ran into an error while responding.';++function tool(+ id: string,+ name: string,+ detail: ToolDetail,+ status: ToolStatus = 'completed'+): ToolUsePart {+ return {+ kind: 'tool_use',+ id,+ name: { kind: 'native', name },+ status,+ detail,+ };+}++function macro(+ id: string,+ name: string,+ input: unknown,+ output: unknown,+ status: ToolStatus = 'completed',+ error: string | null = null+): ToolUsePart {+ return tool(id, name, { kind: 'macro', input, output, error }, status);+}++/** The call as it was before it finished: no result yet. */+function running(part: ToolUsePart): ToolUsePart {+ const detail = part.detail;+ if (detail.kind === 'macro')+ return { ...part, status: 'running', detail: { ...detail, output: null } };+ if (detail.kind === 'terminal')+ return {+ ...part,+ status: 'running',+ detail: { ...detail, output: null, exitCode: null },+ };+ return { ...part, status: 'running' };+}++const text = (value: string): MessagePart => ({ kind: 'text', text: value });++/** A document hit: in its text when given a snippet, else by name alone. */+function documentResult(id: string, name: string, snippet?: string) {+ return {+ type: 'document',+ id,+ name,+ owner_id: 'macro|[email protected]',+ document_id: id,+ document_name: name,+ file_type: 'md',+ document_search_results: snippet+ ? [{ node_id: `${id}-hit`, highlight: { content: [snippet] } }]+ : [{ highlight: { name } }],+ metadata: {+ created_at: '2026-10-20T15:00:00.000Z',+ updated_at: '2026-10-28T15:00:00.000Z',+ },+ };+}++const SEARCH_DOCS = macro(+ 'search-docs',+ 'ContentSearch',+ { query: 'launch checklist' },+ {+ results: [+ documentResult(+ DOC_CHECKLIST,+ 'Launch checklist',+ 'Confirm the <macro_em>launch</macro_em> date with design'+ ),+ documentResult(+ DOC_TIMELINE,+ 'Launch timeline',+ 'Rollout starts Monday after the <macro_em>checklist</macro_em> clears'+ ),+ documentResult(+ DOC_NOTES,+ 'Release notes',+ 'Agent progress in channels, <macro_em>launch</macro_em> week'+ ),+ ],+ }+);+const SEARCH_NAMES = macro(+ 'search-names',+ 'NameSearch',+ { name: 'launch' },+ {+ results: [+ documentResult(DOC_CHECKLIST, 'Launch checklist'),+ documentResult(DOC_TIMELINE, 'Launch timeline'),+ ],+ }+);+const SEARCH_SKILLS = macro(+ 'search-skills',+ 'SearchSkills',+ { name: 'launch checklist' },+ {+ results: [+ { documentId: DOC_CHECKLIST, name: 'Launch checklist', updatedAt: null },+ { documentId: DOC_TIMELINE, name: 'Launch timeline', updatedAt: null },+ { documentId: DOC_NOTES, name: 'Release notes', updatedAt: null },+ ],+ }+);+const SEARCH_NOTHING = macro(+ 'search-nothing',+ 'NameSearch',+ { name: 'postmortem' },+ { results: [] }+);+const READ_DOC = macro(+ 'read-doc',+ 'ReadContent',+ { documentId: DOC_CHECKLIST },+ {+ content: {+ text: '# Launch checklist\n\n- [x] Release notes\n- [ ] Confirm the date\n- [ ] Tell support',+ },+ comments: [],+ }+);+const LIST_FAILED = macro(+ 'list-entities',+ 'ListEntities',+ { limit: 5 },+ 'Failed to list entities: permission denied',+ 'failed',+ 'Failed to list entities: permission denied'+);+const WEB_SEARCH_FAILED = macro(+ 'web-search',+ 'WebSearch',+ { input: 'macro launch status' },+ {+ tool_use_id: 'web-search',+ content: {+ type: 'web_search_tool_result_error',+ error_code: 'unavailable',+ },+ }+);+const READ_FILE = tool('read-file', 'Read', {+ kind: 'read',+ paths: ['apps/web/src/features/agent-activity/agent-activity.tsx'],+});+const READ_FILES = tool('read-files', 'Read', {+ kind: 'read',+ paths: [+ 'apps/web/src/features/agent-activity/components/activity-line.tsx',+ 'apps/web/src/features/agent-activity/components/activity-rows.tsx',+ 'apps/web/src/features/agent-activity/components/activity-summary.tsx',+ ],+});+const GREP = tool('grep', 'Grep', {+ kind: 'search',+ paths: ['apps/web/src'],+ output:+ 'apps/web/src/features/agent-activity/agent-activity.tsx:4:import { ActivityLine }\napps/web/src/features/agent-activity/components/activity-line.tsx:20:export function ActivityLine(',+});+const SHELL = tool('shell', 'Bash', {+ kind: 'terminal',+ command: 'bun run check',+ output: 'Checked 1204 files in 3.1s\nNo problems found.',+ exitCode: 0,+});+const SHELL_FAILED = tool(+ 'shell-failed',+ 'Bash',+ {+ kind: 'terminal',+ command: 'bun run test src/features/agent-activity',+ output:+ 'FAIL agent-activity.test.tsx > cycles through running steps\nAssertionError: expected "Reading" to be "Searching"',+ exitCode: 1,+ },+ 'failed'+);+const EDIT = tool('edit', 'Edit', {+ kind: 'edit',+ diffs: [+ {+ path: 'docs/launch.md',+ oldText: '# Launch\n\n- [ ] Confirm the date\n',+ newText:+ '# Launch\n\n- [x] Confirm the date: Monday\n- [ ] Tell support\n',+ },+ ],+});+const FETCH_FAILED = tool(+ 'fetch',+ 'Fetch',+ {+ kind: 'fetch',+ output: 'Could not reach status.macro.com/api: connection refused.',+ },+ 'failed'+);+const THINK = tool('think', 'Think', {+ kind: 'think',+ output: 'The date moved, so support needs a heads-up first.',+});+const SUBAGENT = tool('subagent', 'Agent', {+ kind: 'subagent',+ title: 'Verify the launch checklist',+ description: 'Verify the launch checklist',+ agentType: 'subagent',+ prompt: 'Check docs/launch.md against the release notes.',+ background: false,+ children: [],+ result: {+ text: 'The launch checklist matches the release notes.',+ error: null,+ agentId: 'verify-checklist',+ model: null,+ durationMs: 3485,+ tokens: null,+ toolUses: 2,+ stats: null,+ },+});+const PLAN: MessagePart = {+ kind: 'plan',+ entries: [+ { content: 'Find the checklist', priority: 'medium', status: 'completed' },+ { content: 'Confirm the date', priority: 'high', status: 'completed' },+ { content: 'Tell support', priority: 'medium', status: 'pending' },+ ],+};+const THOUGHT: MessagePart = {+ kind: 'thought',+ text: 'The checklist is the source of truth; the timeline may be stale.',+};++const ANSWER =+ 'The <m-document-mention>{"documentId":"4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46","documentName":"Launch checklist","blockName":"md"}</m-document-mention> has two open items: confirming the date and telling support. <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]","displayName":"Ada"}</m-user-mention> owns the date.';++const LONG_QUERY =+ 'launch checklist for the agent progress line in channels and agent sessions, including the collapsed summary and every expanded row';++const SCENARIOS: Scenario[] = [+ {+ id: 'thinking',+ title: 'Before the first step',+ note: 'Nothing is posted yet. In a DM the typing row says Thinking; in a mention, the reply does.',+ parts: [],+ inFlight: true,+ },+ {+ id: 'one-running',+ title: 'One step running',+ note: 'One shimmering line with the working dots.',+ parts: [running(SEARCH_DOCS)],+ inFlight: true,+ },+ {+ id: 'parallel',+ title: 'Steps running at once',+ note: 'The channel line takes turns between them every 2s.',+ parts: [running(READ_DOC), running(SEARCH_SKILLS), running(GREP)],+ inFlight: true,+ },+ {+ id: 'after-prose',+ title: 'A passage, then working',+ note: 'A finished passage is part of the message; the open run follows it.',+ parts: [+ text('Looking into the launch checklist first.'),+ SEARCH_DOCS,+ running(READ_DOC),+ ],+ inFlight: true,+ },+ {+ id: 'held',+ title: 'Run sealed while a call is held',+ note: 'A later passage sealed the run, but one call still runs: the summary shimmers.',+ parts: [+ SEARCH_DOCS,+ running(READ_DOC),+ text('While that loads: the timeline says Monday.'),+ ],+ inFlight: true,+ },+ {+ id: 'streaming',+ title: 'Steps done, answer streaming',+ note: 'The run folds. The passage being written is posted once finished; until then the typing row of a DM says Writing.',+ parts: [SEARCH_DOCS, READ_DOC, text(ANSWER)],+ inFlight: true,+ },+ {+ id: 'answered',+ title: 'Answered',+ note: 'A sealed run as "Used N tools"; mentions in the accent color.',+ parts: [SEARCH_DOCS, READ_DOC, text(ANSWER)],+ inFlight: false,+ },+ {+ id: 'single',+ title: 'One tool',+ note: 'Singular summary.',+ parts: [SEARCH_SKILLS, text('Found three skills that match.')],+ inFlight: false,+ },+ {+ id: 'interleaved',+ title: 'Passages between runs',+ note: 'Each run folds on its own, between the passages around it.',+ parts: [+ text('Starting with the checklist.'),+ THOUGHT,+ SEARCH_SKILLS,+ READ_DOC,+ text('The date moved. Updating the doc and checking it builds.'),+ GREP,+ EDIT,+ SHELL,+ text(ANSWER),+ ],+ inFlight: false,+ },+ {+ id: 'failures',+ title: 'Some steps failed',+ note: 'Failures are counted on the summary and marked on their rows.',+ parts: [+ SEARCH_DOCS,+ LIST_FAILED,+ WEB_SEARCH_FAILED,+ SHELL_FAILED,+ FETCH_FAILED,+ text(+ 'Two sources were unreachable, so this is from the checklist alone.'+ ),+ ],+ inFlight: false,+ },+ {+ id: 'stopped',+ title: 'Stopped mid-run',+ note: 'Calls still running when the turn ended read as interrupted.',+ parts: [SEARCH_DOCS, running(READ_DOC), running(SHELL)],+ inFlight: false,+ stop: { kind: 'cancelled' },+ footer: CANCELLED_FALLBACK,+ },+ {+ id: 'errored',+ title: 'Turn failed',+ note: 'The runtime failed the prompt after one step.',+ parts: [SEARCH_DOCS],+ inFlight: false,+ stop: { kind: 'failed', message: 'Upstream model overloaded' },+ footer: ERROR_FALLBACK,+ },+ {+ id: 'no-results',+ title: 'Search with no results',+ note: 'A count of zero and nothing to open.',+ parts: [SEARCH_NOTHING, text('Nothing matches "postmortem" yet.')],+ inFlight: false,+ },+ {+ id: 'long',+ title: 'Long details',+ note: 'The session truncates queries and paths on one line; a conversation names only the step.',+ parts: [+ macro(+ 'long-search',+ 'ContentSearch',+ { query: LONG_QUERY },+ { results: [] }+ ),+ running(+ tool('long-read', 'Read', {+ kind: 'read',+ paths: [+ 'apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation/very-long-file-name.tsx',+ ],+ })+ ),+ ],+ inFlight: true,+ },+ {+ id: 'every-tool',+ title: 'Every kind of step',+ note: 'One of each, done: Macro tools, files, shell, edits, plan, subagent.',+ parts: [+ SEARCH_DOCS,+ SEARCH_NAMES,+ SEARCH_SKILLS,+ READ_DOC,+ READ_FILE,+ READ_FILES,+ GREP,+ SHELL,+ EDIT,+ THINK,+ PLAN,+ SUBAGENT,+ LIST_FAILED,+ FETCH_FAILED,+ text('Done.'),+ ],+ inFlight: false,+ },+];++/** A turn from first step to answer, one frame every few seconds. */+const REPLAY: { parts: MessagePart[]; inFlight: boolean }[] = [+ { parts: [], inFlight: true },+ { parts: [running(SEARCH_DOCS)], inFlight: true },+ {+ parts: [SEARCH_DOCS, running(READ_DOC), running(SEARCH_SKILLS)],+ inFlight: true,+ },+ {+ parts: [SEARCH_DOCS, READ_DOC, SEARCH_SKILLS, running(GREP)],+ inFlight: true,+ },+ {+ parts: [SEARCH_DOCS, READ_DOC, SEARCH_SKILLS, GREP, running(SHELL)],+ inFlight: true,+ },+ {+ parts: [SEARCH_DOCS, READ_DOC, SEARCH_SKILLS, GREP, SHELL, text(ANSWER)],+ inFlight: true,+ },+ {+ parts: [SEARCH_DOCS, READ_DOC, SEARCH_SKILLS, GREP, SHELL, text(ANSWER)],+ inFlight: false,+ },+];+const REPLAY_FRAME_MS = 2500;++// What follows mirrors agent_fold's `segment.rs`, so the channel reads its+// steps as the server words them.++/** A step's verbs while it runs, once done, and if it failed. */+const VERBS: Partial<+ Record<ToolDetail['kind'], readonly [string, string, string]>+> = {+ terminal: ['Running', 'Ran', 'Command failed'],+ edit: ['Editing', 'Edited', 'Edit failed'],+ read: ['Reading', 'Read', 'Read failed'],+ delete: ['Deleting', 'Deleted', 'Delete failed'],+ move: ['Moving', 'Moved', 'Move failed'],+ search: ['Searching', 'Searched', 'Search failed'],+ fetch: ['Fetching', 'Fetched', 'Fetch failed'],+ subagent: ['Delegating', 'Delegated', 'Delegation failed'],+};+/** `ListEntities` reads `List entities`; acronyms stay as written. */+function humanize(name: string): string {+ const words = name+ .split(/[_\-. ]+/)+ .flatMap((part) => part.split(/(?<=[a-z0-9])(?=[A-Z])/))+ .filter(Boolean)+ .map((word) =>+ word.length > 1 && /^[A-Z0-9]+$/.test(word) ? word : word.toLowerCase()+ );+ const sentence = words.join(' ');+ return sentence ? sentence[0]!.toUpperCase() + sentence.slice(1) : 'Tool';+}++function toolName(name: ToolName): string {+ return name.kind === 'native' ? name.name : name.tool;+}++function stepRow(part: ToolUsePart, closed: boolean): ActivityRow {+ const status: ActivityRow['status'] =+ part.status === 'completed'+ ? 'completed'+ : part.status === 'failed'+ ? 'failed'+ : closed+ ? 'interrupted'+ : 'running';+ const verbs = VERBS[part.detail.kind];+ if (verbs) {+ const [whileRunning, done, failed] = verbs;+ const label =+ status === 'running' ? whileRunning : status === 'failed' ? failed : done;+ return { id: part.id, label, detail: null, status };+ }+ if (part.detail.kind === 'think')+ return { id: part.id, label: 'Thought it through', detail: null, status };+ const named = humanize(toolName(part.name));+ return {+ id: part.id,+ label: status === 'failed' ? `${named} failed` : named,+ detail: null,+ status,+ };+}++function activityRows(+ parts: readonly MessagePart[],+ closed: boolean+): ActivityRow[] {+ return parts.flatMap((part): ActivityRow[] => {+ if (part.kind === 'tool_use') return [stepRow(part, closed)];+ if (part.kind !== 'plan') return [];+ const done = part.entries.filter(+ (entry) => entry.status === 'completed'+ ).length;+ return [+ {+ id: 'plan',+ label: 'Updated the plan',+ detail: `${done}/${part.entries.length} done`,+ status: 'completed',+ },+ ];+ });+}++function segmentKind(part: MessagePart): Segment['kind'] | undefined {+ if (part.kind === 'text') return part.text.trim() ? 'prose' : undefined;+ if (part.kind === 'tool_use' || part.kind === 'plan') return 'activity';+ return undefined;+}++function segmentsOf(parts: readonly MessagePart[], inFlight: boolean) {+ const segments: Segment[] = [];+ parts.forEach((part, index) => {+ const kind = segmentKind(part);+ if (!kind) return;+ const last = segments.at(-1);+ if (last?.kind === kind) last.end = index + 1;+ else+ segments.push({+ index: segments.length,+ kind,+ start: index,+ end: index + 1,+ sealed: true,+ rows: [],+ });+ });+ return segments.map((segment, index) => ({+ ...segment,+ sealed: !inFlight || index < segments.length - 1,+ rows:+ segment.kind === 'activity'+ ? activityRows(parts.slice(segment.start, segment.end), !inFlight)+ : [],+ }));+}++function phaseOf(parts: readonly MessagePart[]): TurnPhase {+ const last = parts.at(-1);+ if (!last) return 'thinking';+ return last.kind === 'text' ? 'writing' : 'working';+}++function foldedReply(scenario: Scenario): FoldedMessage {+ return {+ agentSessionId: SESSION,+ turn: 1,+ author: { kind: 'agent' },+ requestId: null,+ parts: scenario.parts,+ stop: scenario.inFlight ? null : (scenario.stop ?? { kind: 'end_turn' }),+ pending: false,+ segments: segmentsOf(scenario.parts, scenario.inFlight),+ phase: scenario.inFlight ? phaseOf(scenario.parts) : null,+ postedAt: null,+ };+}++/** A passage or a run of steps as a posted message stores it. */+function storedSegment(+ scenario: Scenario,+ segment: Segment+): AgentReplySegment | undefined {+ const parts = scenario.parts.slice(segment.start, segment.end);+ if (segment.kind === 'prose') {+ // An unfinished passage is not posted; it streams in the typing row.+ if (!segment.sealed) return undefined;+ const markdown = parts+ .flatMap((part) => (part.kind === 'text' ? [part.text] : []))+ .join('\n\n');+ return { kind: 'prose', markdown };+ }+ if (segment.kind !== 'activity') return undefined;+ return {+ kind: 'activity',+ turn: 1,+ segment: segment.index,+ sealed: segment.sealed,+ rows: segment.rows.map((row) => ({+ id: row.id,+ label: row.label,+ status: row.status,+ })),+ };+}++/**+ * Each run of steps with the passage it led to, as a DM posts them: a message+ * waits for its passage, so none shows a step running.+ */+function leadingRuns(stored: readonly AgentReplySegment[], inFlight: boolean) {+ const messages: AgentReplySegment[][] = [];+ let run: AgentReplySegment | undefined;+ for (const segment of stored) {+ if (segment.kind !== 'prose') {+ run = segment;+ continue;+ }+ messages.push(run ? [run, segment] : [segment]);+ run = undefined;+ }+ // A turn that ended on steps posts them with its closing line.+ if (run && !inFlight) messages.push([run]);+ return messages;+}++/**+ * The messages a reply posts (agent_harness `present.rs`). A mention's reply+ * is one message in its thread that leads with the session link and shows+ * the spinner while the turn runs. A DM posts a message per finished passage,+ * with the steps that led to it, and nothing until there is something to+ * say.+ */+function replyMessages(+ scenario: Scenario,+ conversation: Conversation+): AgentChatReply[] {+ const stored = segmentsOf(scenario.parts, scenario.inFlight).flatMap(+ (segment) => storedSegment(scenario, segment) ?? []+ );+ if (conversation === 'mention') {+ const body: AgentChatReplyBody =+ stored.length > 0+ ? {+ kind: 'segments',+ segments: stored,+ pending: scenario.inFlight,+ footer: scenario.footer,+ }+ : scenario.inFlight+ ? { kind: 'pending' }+ : { kind: 'markdown', markdown: scenario.footer ?? '' };+ return [{ sessionId: SESSION, link: true, body }];+ }+ const messages = leadingRuns(stored, scenario.inFlight);+ if (messages.length === 0) {+ return scenario.footer && !scenario.inFlight+ ? [+ {+ sessionId: SESSION,+ link: false,+ body: { kind: 'markdown', markdown: scenario.footer },+ },+ ]+ : [];+ }+ return messages.map((segments, index) => ({+ sessionId: SESSION,+ link: false,+ body: {+ kind: 'segments',+ segments,+ footer:+ !scenario.inFlight && index === messages.length - 1+ ? scenario.footer+ : undefined,+ },+ }));+}++function channelMessage(reply: AgentChatReply, id: string): MessageData {+ return {+ id,+ content: composeAgentChatReply(reply),+ sender_id: `bot|${MACRO_AGENT_BOT_ID}`,+ sender: {+ id: MACRO_AGENT_BOT_ID,+ type: 'bot',+ name: 'Macro',+ avatar_url: null,+ },+ created_at: POSTED_AT,+ updated_at: POSTED_AT,+ attachments: [],+ reactions: [],+ };+}++type Theme = 'app' | 'light' | 'dark';+type Viewer = 'reader' | 'member';+type Width = 'wide' | 'phone';+type Conversation = 'dm' | 'mention';+/** Where a reply is read: a conversation, or the agent session itself. */+type View = Conversation | 'session';++const VIEWS: readonly { value: View; label: string }[] = [+ { value: 'dm', label: 'DM' },+ { value: 'mention', label: 'Channel mention' },+ { value: 'session', label: 'Agent session' },+];++function Choice<T extends string>(props: {+ label: string;+ value: T;+ options: readonly { value: T; label: string }[];+ onChange: (value: T) => void;+}) {+ return (+ <div class="flex items-center gap-2">+ <span class="text-ink-extra-muted">{props.label}</span>+ <Tabs+ aria-label={props.label}+ size="sm"+ options={props.options}+ value={props.value}+ onChange={props.onChange}+ />+ </div>+ );+}++function Frame(props: { phone: boolean; children: JSX.Element }) {+ return (+ <div+ class="min-w-0 overflow-hidden rounded-lg border border-edge-muted bg-panel py-2"+ classList={{ 'w-[390px]': props.phone, 'max-w-3xl': !props.phone }}+ >+ {props.children}+ </div>+ );+}++/**+ * A conversation: the reply's messages, and in a DM the typing row while it+ * runs. A mention's reply sits in a thread, which shows no typing row.+ */+function ConversationView(props: {+ scenario: Scenario;+ conversation: Conversation;+ reader: boolean;+}) {+ const reply = () => foldedReply(props.scenario);+ const messages = () =>+ replyMessages(props.scenario, props.conversation).map((message, index) =>+ channelMessage(message, `playground-${props.scenario.id}-${index}`)+ );+ return (+ <>+ {/* By position, as the server reuses a reply's n-th message. */}+ <Index each={messages()}>+ {(message, index) => (+ <ChannelMessage+ message={message()}+ listMeta={{+ index,+ isNewMessage: false,+ isFirstNewMessage: false,+ isGroupedWithPrevious: index > 0,+ }}+ hideTriggeredBy+ />+ )}+ </Index>+ <Show when={props.conversation === 'dm' && props.scenario.inFlight}>+ {/* What the live session tells a reader; the typing, everyone else. */}+ <TypingRow+ avatar={+ <PersonaAvatar botId={MACRO_AGENT_BOT_ID} name="Macro" size="md" />+ }+ rows={+ (props.reader && openRun(reply())?.rows) || [+ phaseRow(phaseOf(props.scenario.parts)),+ ]+ }+ onStop={props.reader ? () => {} : undefined}+ />+ </Show>+ </>+ );+}++/** The session: the reply, or its working line before it has any parts. */+function SessionView(props: { scenario: Scenario }) {+ return (+ <div class="px-4 pb-2">+ <Show+ when={props.scenario.parts.length > 0}+ fallback={<WorkingLine label="Working" />}+ >+ <AgentMessage+ message={foldedReply(props.scenario)}+ inFlight={props.scenario.inFlight}+ />+ </Show>+ </div>+ );+}++function ScenarioRow(props: {+ scenario: Scenario;+ view: View;+ reader: boolean;+ phone: boolean;+ controls?: JSX.Element;+}) {+ const conversation = (): Conversation | undefined =>+ props.view === 'session' ? undefined : props.view;+ return (+ <section+ id={props.scenario.id}+ class="flex scroll-mt-16 flex-col gap-3 border-t border-edge-muted py-6"+ data-scenario={props.scenario.id}+ >+ <header class="flex flex-wrap items-baseline gap-x-3 gap-y-1">+ <h2 class="text-sm font-medium text-ink">{props.scenario.title}</h2>+ <p class="text-xs text-ink-muted">{props.scenario.note}</p>+ {props.controls}+ </header>+ <Frame phone={props.phone}>+ <Show+ when={conversation()}+ fallback={<SessionView scenario={props.scenario} />}+ >+ {(shown) => (+ <ConversationView+ scenario={props.scenario}+ conversation={shown()}+ reader={props.reader}+ />+ )}+ </Show>+ </Frame>+ </section>+ );+}++function ReplayRow(props: { view: View; reader: boolean; phone: boolean }) {+ const [frame, setFrame] = createSignal(0);+ const [playing, setPlaying] = createSignal(true);+ const timer = setInterval(() => {+ if (playing()) setFrame((index) => (index + 1) % REPLAY.length);+ }, REPLAY_FRAME_MS);+ onCleanup(() => clearInterval(timer));+ const scenario = (): Scenario => ({+ id: 'replay',+ title: 'Live replay',+ note: `Frame ${frame() + 1} of ${REPLAY.length}: first step to answer, ${REPLAY_FRAME_MS / 1000}s a frame.`,+ ...REPLAY[frame()]!,+ });+ return (+ <ScenarioRow+ scenario={scenario()}+ view={props.view}+ reader={props.reader}+ phone={props.phone}+ controls={+ <div class="flex items-center gap-2 text-xs">+ <Button+ variant="secondary"+ size="sm"+ onClick={() => setPlaying(!playing())}+ >+ {playing() ? 'Pause' : 'Play'}+ </Button>+ <input+ type="range"+ min={0}+ max={REPLAY.length - 1}+ value={frame()}+ aria-label="Replay frame"+ onInput={(event) => {+ setPlaying(false);+ setFrame(event.currentTarget.valueAsNumber);+ }}+ />+ </div>+ }+ />+ );+}++/**+ * Opens (or closes) every disclosure on the page, a few passes deep: a+ * group's rows only exist once the group is open.+ */+function toggleAll(root: HTMLElement | undefined, open: boolean) {+ let pass = 0;+ const step = () => {+ const toggles = root?.querySelectorAll<HTMLElement>(+ `button[aria-expanded="${open ? 'false' : 'true'}"]`+ );+ if (!toggles?.length) return;+ // Closing from the outside in hides the inner toggles with their group.+ for (const toggle of open ? toggles : [...toggles].reverse())+ toggle.click();+ if (++pass < 4) requestAnimationFrame(step);+ };+ step();+}++export default function ProgressPlayground() {+ const [view, setView] = createSignal<View>('dm');+ const [theme, setTheme] = createSignal<Theme>('app');+ const [viewer, setViewer] = createSignal<Viewer>('reader');+ const [width, setWidth] = createSignal<Width>('wide');+ const phone = () => width() === 'phone';+ let scenarios: HTMLDivElement | undefined;++ const applyPreview = (next: Theme) => {+ setTheme(next);+ if (next === 'app') clearThemePreview();+ else+ previewTheme(next === 'light' ? DEFAULT_LIGHT_THEME : DEFAULT_DARK_THEME);+ };+ onCleanup(() => clearThemePreview());++ return (+ <div class="size-full overflow-auto bg-surface text-ink">+ <div class="sticky top-0 z-10 flex flex-wrap items-center gap-x-5 gap-y-2 border-b border-edge-muted bg-surface px-6 py-2 text-xs">+ <span class="font-medium text-ink">Agent progress</span>+ <Tabs+ aria-label="Surface"+ size="sm"+ options={VIEWS}+ value={view()}+ onChange={setView}+ />+ <Choice+ label="Theme"+ value={theme()}+ options={[+ { value: 'app', label: 'App' },+ { value: 'light', label: 'Light' },+ { value: 'dark', label: 'Dark' },+ ]}+ onChange={applyPreview}+ />+ {/* Only a DM shows what the turn is doing beyond its messages. */}+ <Show when={view() === 'dm'}>+ <Choice+ label="Viewer"+ value={viewer()}+ options={[+ { value: 'reader', label: 'Can open session' },+ { value: 'member', label: "Can't open session" },+ ]}+ onChange={setViewer}+ />+ </Show>+ <Choice+ label="Width"+ value={width()}+ options={[+ { value: 'wide', label: 'Wide' },+ { value: 'phone', label: 'Phone' },+ ]}+ onChange={setWidth}+ />+ <div class="flex gap-2">+ <Button+ variant="secondary"+ size="sm"+ onClick={() => toggleAll(scenarios, true)}+ >+ Expand all+ </Button>+ <Button+ variant="secondary"+ size="sm"+ onClick={() => toggleAll(scenarios, false)}+ >+ Collapse all+ </Button>+ </div>+ <nav class="flex flex-wrap gap-x-2 text-ink-extra-muted">+ <a class="hover:text-ink" href="#replay">+ Replay+ </a>+ <For each={SCENARIOS}>+ {(scenario) => (+ <a class="hover:text-ink" href={`#${scenario.id}`}>+ {scenario.title}+ </a>+ )}+ </For>+ </nav>+ </div>+ <div ref={scenarios} class="px-6 pb-16">+ <ReplayRow+ view={view()}+ reader={viewer() === 'reader'}+ phone={phone()}+ />+ <For each={SCENARIOS}>+ {(scenario) => (+ <ScenarioRow+ scenario={scenario}+ view={view()}+ reader={viewer() === 'reader'}+ phone={phone()}+ />+ )}+ </For>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/agent-activity/queries/code-activity.ts b/apps/web/src/features/agent-activity/queries/code-activity.tsindex 3cb38365a0..955bc13aec 100644--- a/apps/web/src/features/agent-activity/queries/code-activity.ts+++ b/apps/web/src/features/agent-activity/queries/code-activity.ts@@ -9,11 +9,14 @@ import type {import { useQueries } from '@tanstack/solid-query';import { type Accessor, createMemo } from 'solid-js';-/** Share the session view's observed SDK activity while an inline run is open. */+/**+ * Share the session view's observed SDK activity while an inline run is open.+ * Without a `segment` there is no run to look into, and `rows` stand as given.+ */export function createCodeActivityRows(sessionId: Accessor<string>,reply: Accessor<FoldedMessage | undefined>,- segment: Accessor<number>,+ segment: Accessor<number | undefined>,rows: Accessor<readonly (ActivityRow | AgentActivityRow)[]>) {const calls = createMemo(() => {diff --git a/apps/web/src/features/block-agent/browser-test/index.html b/apps/web/src/features/block-agent/browser-test/index.htmlindex f9811929ca..5c694fdb1e 100644--- a/apps/web/src/features/block-agent/browser-test/index.html+++ b/apps/web/src/features/block-agent/browser-test/index.html@@ -1,2 +1,2 @@<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Session notification verification</title>-<style>:root{--color-content-0:#222;--color-content-1:#555;--color-content-2:#777}body{font:15px system-ui;background:#fafafa;color:#222;margin:0}main{max-width:640px;margin:32px auto;padding:16px}.review-card{border:1px solid #ddd;border-radius:12px;padding:20px;background:white}button{padding:10px;margin:4px;border:1px solid #bbb;border-radius:6px;background:white}nav{margin-top:24px;display:flex;flex-wrap:wrap}.agent-working-wave{display:inline-block;margin:8px;width:16px;height:16px}.agent-working-wave span{display:inline-block;width:3px;height:3px;background:#888}.text-xs{font-size:12px}h1{font-size:20px}h2{font-size:17px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.inline-grid{display:inline-grid}.col-start-1{grid-column-start:1}.row-start-1{grid-row-start:1}.opacity-0{opacity:0}.flex{display:flex}.items-center{align-items:center}.agent-working-wave{display:inline-flex;justify-content:space-between;align-items:center}</style></head><body><div id="root"></div><script type="module" src="/main.tsx"></script></body></html>+<style>:root{--color-content-0:#222;--color-content-1:#555;--color-content-2:#777}body{font:15px system-ui;background:#fafafa;color:#222;margin:0}main{max-width:640px;margin:32px auto;padding:16px}.review-card{border:1px solid #ddd;border-radius:12px;padding:20px;background:white}button{padding:10px;margin:4px;border:1px solid #bbb;border-radius:6px;background:white}nav{margin-top:24px;display:flex;flex-wrap:wrap}.text-xs{font-size:12px}h1{font-size:20px}h2{font-size:17px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.inline-grid{display:inline-grid}.col-start-1{grid-column-start:1}.row-start-1{grid-row-start:1}.opacity-0{opacity:0}.flex{display:flex}.items-center{align-items:center}</style></head><body><div id="root"></div><script type="module" src="/main.tsx"></script></body></html>diff --git a/apps/web/src/features/block-agent/browser-test/notifications.browser.e2e.ts b/apps/web/src/features/block-agent/browser-test/notifications.browser.e2e.tsindex cf5d57a906..824d24f4dd 100644--- a/apps/web/src/features/block-agent/browser-test/notifications.browser.e2e.ts+++ b/apps/web/src/features/block-agent/browser-test/notifications.browser.e2e.ts@@ -5,16 +5,16 @@ test('response timing follows the decision turn across busy output and the first}) => {await page.goto('/');await page.getByRole('button', { name: 'Decide', exact: true }).click();- await expect(page.locator('.agent-working-wave')).toBeVisible();+ await expect(page.getByLabel('Responding', { exact: true })).toBeVisible();await page.locator('main').screenshot({ path: test.info().outputPath('responding.png') });await page.getByRole('button', { name: 'Busy output' }).click();- await expect(page.locator('.agent-working-wave')).toBeVisible();+ await expect(page.getByLabel('Responding', { exact: true })).toBeVisible();await page.getByRole('button', { name: 'Receive decision' }).click();- await expect(page.locator('.agent-working-wave')).toBeVisible();+ await expect(page.getByLabel('Responding', { exact: true })).toBeVisible();await page.getByRole('button', { name: 'Agent reply' }).click();- await expect(page.locator('.agent-working-wave')).toHaveCount(0);+ await expect(page.getByLabel('Responding', { exact: true })).toHaveCount(0);await expect(page.locator('[data-turn="1"]')).toHaveText('Your review is complete.');@@ -25,13 +25,13 @@ test('request rejection and silent completion both clear the pending response',}) => {await page.goto('/');await page.getByRole('button', { name: 'Decide', exact: true }).click();- await expect(page.locator('.agent-working-wave')).toBeVisible();+ await expect(page.getByLabel('Responding', { exact: true })).toBeVisible();await page.getByRole('button', { name: 'Reject request' }).click();- await expect(page.locator('.agent-working-wave')).toHaveCount(0);+ await expect(page.getByLabel('Responding', { exact: true })).toHaveCount(0);await page.getByRole('button', { name: 'Decide', exact: true }).click();await page.getByRole('button', { name: 'Receive decision' }).click();await page.getByRole('button', { name: 'Silent completion' }).click();- await expect(page.locator('.agent-working-wave')).toHaveCount(0);+ await expect(page.getByLabel('Responding', { exact: true })).toHaveCount(0);await expect(page.locator('[data-turn]')).toHaveCount(0);});diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsxindex 9c207ed651..1cb26047c6 100644--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx@@ -87,6 +87,7 @@ function AgentMessagePart(props: {}inFlight={props.inFlight}hideIncompleteXml={props.message.author.kind === 'agent'}+ accentMentions={props.message.author.kind === 'agent'}observeRender={props.message.author.kind === 'agent'? (element) =>diff --git a/apps/web/src/features/block-agent/component/parts/CodeExecutionToolCall.tsx b/apps/web/src/features/block-agent/component/parts/CodeExecutionToolCall.tsxindex 7087b04be0..f893d1579b 100644--- a/apps/web/src/features/block-agent/component/parts/CodeExecutionToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/CodeExecutionToolCall.tsx@@ -1,4 +1,3 @@-import CodeIcon from '@icon/system/regular/code.svg';import type {ExecutionActivity,ExecutionRecord,@@ -39,7 +38,6 @@ export function CodeExecutionToolCall(props: {<Show when={activity().length === 0 || errorVisible()}><ToolCardtitle="Workspace activity"- icon={<CodeIcon />}status={props.common.status}muted={props.common.muted}trailing={diff --git a/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx b/apps/web/src/features/block-agent/component/parts/EditToolCall.tsxindex 8655ea031d..ce7be8e22a 100644--- a/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx@@ -1,6 +1,5 @@/** File modifications: +/− badge in the row, Pierre-rendered diffs in the body. */-import PencilIcon from '@icon/system/regular/pencil-simple.svg';import type { ToolDetail } from '@service-agent-fold/generated/types';import { createMemo, Show } from 'solid-js';import { countDiffChanges } from '../../state/session-summary';@@ -16,7 +15,6 @@ export function EditToolCall(props: {return (<ToolCard- icon={<PencilIcon class="size-4" />}title={props.common.label}subtitle={pathsSubtitle(props.detail.diffs.map((diff) => diff.path))}trailing={diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsxindex 246f0a4db9..beddabe81a 100644--- a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx@@ -16,12 +16,6 @@ import {RenderTool,} from '@core/component/AI/component/tool/handler';import { parseLegacyGeneratedImage } from '@core/component/AI/component/tool/legacy-generated-image';-import ReadIcon from '@icon/system/regular/file-text.svg';-import GlobeIcon from '@icon/system/regular/globe.svg';-import ListIcon from '@icon/system/regular/list-bullets.svg';-import SearchIcon from '@icon/system/regular/magnifying-glass.svg';-import PencilIcon from '@icon/system/regular/pencil-simple.svg';-import WrenchIcon from '@icon/system/regular/wrench.svg';import type { ToolDetail } from '@service-agent-fold/generated/types';import {deserializeToolCall,@@ -30,7 +24,6 @@ import {type ToolName,} from '@service-cognition/generated/tools/tool';import { createMemo, ErrorBoundary, type JSX, Show, Suspense } from 'solid-js';-import { match } from 'ts-pattern';import { isToolActive, ToolCard } from '../../ui';import type { ToolCallCommon, ToolCallContext } from './shared';@@ -97,7 +90,6 @@ export function MacroToolCall(props: {const fallback = () => (<ToolCard- icon={<MacroToolIcon name={props.common.label} />}title={props.common.label}subtitle={subtitle()}status={props.common.status}@@ -226,43 +218,3 @@ function responseError(response: ToolResponse | undefined): string | undefined {}return undefined;}--function MacroToolIcon(props: { name: string }): JSX.Element {- return match(props.name)- .with(- 'ContentSearch',- 'NameSearch',- 'SearchSkills',- 'SearchTools',- 'WebSearch',- () => <SearchIcon class="size-4" />- )- .with(- 'ReadContent',- 'ReadMetadata',- 'ReadThread',- 'ReadChat',- 'ReadAgentSession',- 'ReadProject',- 'ReadPresentation',- 'ReadDesign',- 'ReadPhotoshopDocument',- 'ReadIllustratorDocument',- 'ReadWordDocument',- 'ReadCalendarEvent',- () => <ReadIcon class="size-4" />- )- .with('WebFetch', () => <GlobeIcon class="size-4" />)- .with(- 'EditDocument',- 'EditSpreadsheet',- 'EditPresentation',- 'EditWordDocument',- 'CreateDocument',- () => <PencilIcon class="size-4" />- )- .with('ListEntities', 'ListSkills', 'ListCalendarEvents', () => (- <ListIcon class="size-4" />- ))- .otherwise(() => <WrenchIcon class="size-4" />);-}diff --git a/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx b/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsxindex 5aff9d5b7e..5472da513b 100644--- a/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx@@ -3,8 +3,6 @@* reported in the body — the chat block's GenericTool analog.*/-import BrainIcon from '@icon/system/regular/brain.svg';-import GlobeIcon from '@icon/system/regular/globe.svg';import type { ToolDetail } from '@service-agent-fold/generated/types';import { Show } from 'solid-js';import { FoldedOutput, ToolCard } from '../../ui';@@ -16,13 +14,6 @@ export function OutputToolCall(props: {}) {return (<ToolCard- icon={- props.detail.kind === 'fetch' ? (- <GlobeIcon class="size-4" />- ) : (- <BrainIcon class="size-4" />- )- }title={props.common.label}status={props.common.status}muted={props.common.muted}diff --git a/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx b/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsxindex 64f719753c..70806fa5c9 100644--- a/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx@@ -1,11 +1,7 @@/** A read, delete, or move: path (or count) in the row, full list in the body. */-import MoveIcon from '@icon/system/regular/arrows-left-right.svg';-import ReadIcon from '@icon/system/regular/file-text.svg';-import TrashIcon from '@icon/system/regular/trash.svg';import type { ToolDetail } from '@service-agent-fold/generated/types';import { Show } from 'solid-js';-import { match } from 'ts-pattern';import { FoldedPathList, ToolCard } from '../../ui';import { pathsSubtitle, type ToolCallCommon } from './shared';@@ -15,21 +11,11 @@ export function PathsToolCall(props: {}) {return (<ToolCard- icon={match(props.detail.kind)- .with('read', () => <ReadIcon class="size-4" />)- .with('delete', () => <TrashIcon class="size-4" />)- .with('move', () => <MoveIcon class="size-4" />)- .exhaustive()}title={props.common.label}subtitle={pathsSubtitle(props.detail.paths)}status={props.common.status}muted={props.common.muted}- trailing={- props.common.trailing ??- (props.common.status === 'completed' && props.detail.paths.length > 0- ? `${props.detail.paths.length} ${props.detail.paths.length === 1 ? 'file' : 'files'}`- : undefined)- }+ trailing={props.common.trailing}hasContent={props.detail.paths.length > 0}><Show when={props.detail.paths.length > 0}>diff --git a/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx b/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsxindex 27a3f2cdbd..47d74a9502 100644--- a/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx@@ -1,6 +1,5 @@/** A search: scope in the row, reported hits in the body. */-import SearchIcon from '@icon/system/regular/magnifying-glass.svg';import type { ToolDetail } from '@service-agent-fold/generated/types';import { Show } from 'solid-js';import { FoldedOutput, ToolCard } from '../../ui';@@ -12,7 +11,6 @@ export function SearchToolCall(props: {}) {return (<ToolCard- icon={<SearchIcon class="size-4" />}title={props.common.label}subtitle={pathsSubtitle(props.detail.paths)}status={props.common.status}diff --git a/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx b/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsxindex 3222701e46..edbaeb8507 100644--- a/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx@@ -5,7 +5,6 @@*/import { modelLabel } from '@core/component/AI/constant/model-label';-import AgentIcon from '@icon/system/regular/sparkle.svg';import type {MessagePart,SubagentResult,@@ -116,7 +115,6 @@ export function SubagentToolCall(props: {return (<ToolCard- icon={<AgentIcon class="size-4" />}title={props.detail.title}subtitle={subtitle()}status={props.common.status}diff --git a/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx b/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsxindex 696d137140..558dcb531d 100644--- a/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx@@ -1,6 +1,5 @@/** A shell command: `$ cmd` in the row, ANSI-colored output in the body. */-import TerminalIcon from '@icon/system/regular/terminal.svg';import type { ToolDetail } from '@service-agent-fold/generated/types';import { Show } from 'solid-js';import { FoldedTerminal, ToolCard } from '../../ui';@@ -14,7 +13,6 @@ export function TerminalToolCall(props: {props.detail.exitCode != null && props.detail.exitCode !== 0;return (<ToolCard- icon={<TerminalIcon class="size-4" />}title={props.common.label}subtitle={props.detail.command ?? undefined}status={props.common.status}diff --git a/apps/web/src/features/block-agent/component/parts/TextPart.tsx b/apps/web/src/features/block-agent/component/parts/TextPart.tsxindex 96a5162dd2..3233a8b712 100644--- a/apps/web/src/features/block-agent/component/parts/TextPart.tsx+++ b/apps/web/src/features/block-agent/component/parts/TextPart.tsx@@ -10,6 +10,12 @@ export function TextPart(props: {inFlight?: boolean;/** Agent prose stays truncated after a stop, interruption, or reload. */hideIncompleteXml?: boolean;+ /**+ * Set what the prose mentions (documents, sessions, pull requests,+ * contacts) in the accent color, as people mentions already are, so an+ * agent's references stand out from its text.+ */+ accentMentions?: boolean;observeRender?: (element: HTMLElement) => (() => void) | undefined;}) {// Memoized so an `inFlight` flip that leaves the text unchanged does not@@ -31,6 +37,7 @@ export function TextPart(props: {<divref={content}class="chat-markdown-container whitespace-pre-wrap wrap-break-word max-w-full text-base"+ classList={{ '[&_[data-mention]]:text-accent': props.accentMentions }}><StaticMarkdownmarkdown={markdown()}diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsxindex 39bea8164d..4eabfd91b6 100644--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx@@ -1298,14 +1298,14 @@ describe('ToolCallPart result summaries', () => {expect(rendered.getByTestId('terminal')).toBeTruthy();});- it('counts completed file reads and keeps a single path available in the body', () => {+ it('names completed file reads once and keeps the path available in the body', () => {const rendered = render(() => (<ToolCallPartpart={toolUse({ kind: 'read', paths: ['docs/launch.md'] })}context={context(false)}/>));- expect(rendered.getByTestId('trailing').textContent).toBe('1 file');+ expect(rendered.getByTestId('trailing').textContent).toBe('');expect(rendered.getByTestId('path-list').textContent).toBe('docs/launch.md');diff --git a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsxindex ceda62d18b..75c3a701e6 100644--- a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx@@ -11,8 +11,6 @@*/import { ItemPreview } from '@core/component/ItemPreview';-import CalendarIcon from '@icon/system/regular/calendar-blank.svg';-import EmailIcon from '@icon/system/regular/envelope.svg';import type {ToolDetail,UserToolOutcome,@@ -93,13 +91,6 @@ export function UserToolCall(props: {return (<ToolCard- icon={- props.common.label === 'CreateCalendarEvent' ? (- <CalendarIcon class="size-4" />- ) : (- <EmailIcon class="size-4" />- )- }title={props.common.label}status={props.common.status}subtitle={draft() && draftSubtitle(draft()!)}diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsxindex ed50895792..a9d16251ad 100644--- a/apps/web/src/features/block-agent/debug/Gallery.tsx+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx@@ -15,10 +15,6 @@ import type { MagicChipPresentation } from '@core/component/LexicalMarkdown/compimport { MarkdownImage } from '@core/component/LexicalMarkdown/component/decorator/MarkdownImage';import { MediaLoadingPlaceholder } from '@core/component/LexicalMarkdown/component/decorator/MediaLoadingPlaceholder';import { useUserId } from '@core/context/user';-import FileText from '@icon/system/regular/file-text.svg';-import MagnifyingGlass from '@icon/system/regular/magnifying-glass.svg';-import PencilSimple from '@icon/system/regular/pencil-simple.svg';-import Terminal from '@icon/system/regular/terminal.svg';import type {ElicitationSchema,FoldedMessage,@@ -1226,20 +1222,17 @@ export default function AgentUiGallery() {<Item label="ToolCard"><ToolCardtitle="Shell"- icon={<Terminal />}subtitle="cargo test -p agent_fold"status={status()}/><ToolCardtitle="Read"- icon={<FileText />}subtitle="crates/agent_fold/src/domain/fold.rs"args={{ limit: '200' }}status="completed"/><ToolCardtitle="Edit"- icon={<PencilSimple />}subtitle={FIXTURE_DIFF.path}trailing={<DiffChanges additions={4} deletions={3} />}status="completed"@@ -1252,19 +1245,16 @@ export default function AgentUiGallery() {<LiveToolGroup count={3} active={pulse()}><ToolCardtitle="Read"- icon={<FileText />}subtitle="crates/agent_fold/src/domain/fold.rs"status="completed"/><ToolCardtitle="Edit"- icon={<PencilSimple />}subtitle={FIXTURE_DIFF.path}status="completed"/><ToolCardtitle="Shell"- icon={<Terminal />}subtitle="cargo test -p agent_fold"status={pulse() ? 'running' : 'completed'}/>@@ -1272,12 +1262,11 @@ export default function AgentUiGallery() {<LiveToolGroup count={2} active={false} defaultOpen><ToolCardtitle="Search"- icon={<MagnifyingGlass />}subtitle="fold"status="completed"trailing="3 results"/>- <ToolCard title="Read" icon={<FileText />} status="completed" />+ <ToolCard title="Read" status="completed" /></LiveToolGroup></Item>diff --git a/apps/web/src/features/block-agent/ui/DisclosureCaret.tsx b/apps/web/src/features/block-agent/ui/DisclosureCaret.tsxnew file mode 100644index 0000000000..316859c289--- /dev/null+++ b/apps/web/src/features/block-agent/ui/DisclosureCaret.tsx@@ -0,0 +1,17 @@+/**+ * The caret after an agent activity label that opens it: shown while the+ * row is hovered or focused, and always on touch, where nothing hovers.+ * Place it inside a `group` button.+ */++import CaretRight from '@icon/system/regular/caret-right.svg';++export function DisclosureCaret(props: { open: boolean }) {+ return (+ <CaretRight+ aria-hidden="true"+ class="size-4 shrink-0 opacity-0 transition-transform group-hover:opacity-100 group-focus-visible:opacity-100 touch:opacity-100 motion-reduce:transition-none"+ classList={{ 'rotate-90': props.open }}+ />+ );+}diff --git a/apps/web/src/features/block-agent/ui/FoldedOutput.tsx b/apps/web/src/features/block-agent/ui/FoldedOutput.tsxindex 6d4d18fec1..f12111fdd6 100644--- a/apps/web/src/features/block-agent/ui/FoldedOutput.tsx+++ b/apps/web/src/features/block-agent/ui/FoldedOutput.tsx@@ -1,7 +1,7 @@/** Free-form text a tool call reported - a search hit, a fetched page, a raw fallback. */export function FoldedOutput(props: { text: string }) {return (- <pre class="overflow-x-auto rounded bg-surface p-2 font-mono text-xs whitespace-pre-wrap text-ink-muted wrap-break-word">+ <pre class="overflow-x-auto font-mono text-xs whitespace-pre-wrap wrap-break-word">{props.text}</pre>);diff --git a/apps/web/src/features/block-agent/ui/FoldedPathList.tsx b/apps/web/src/features/block-agent/ui/FoldedPathList.tsxindex 052c48f02e..a830075936 100644--- a/apps/web/src/features/block-agent/ui/FoldedPathList.tsx+++ b/apps/web/src/features/block-agent/ui/FoldedPathList.tsx@@ -1,18 +1,12 @@-import { Tool } from '@core/component/AI/component/tool/Tool';-import FileText from '@icon/system/regular/file-text.svg';import { For } from 'solid-js';/** The full path list behind a truncated inline summary. */export function FoldedPathList(props: { paths: string[] }) {return (- <Tool.List>+ <ul class="flex min-w-0 flex-col"><For each={props.paths}>- {(path) => (- <Tool.ListItem icon={<FileText class="size-4" />}>- <span class="truncate font-mono text-xs">{path}</span>- </Tool.ListItem>- )}+ {(path) => <li class="truncate font-mono">{path}</li>}</For>- </Tool.List>+ </ul>);}diff --git a/apps/web/src/features/block-agent/ui/Thought.tsx b/apps/web/src/features/block-agent/ui/Thought.tsxindex 4f8d09f2d4..68a45b97e4 100644--- a/apps/web/src/features/block-agent/ui/Thought.tsx+++ b/apps/web/src/features/block-agent/ui/Thought.tsx@@ -1,15 +1,17 @@/*** The agent's reasoning, modeled on the chat block's `ThinkingBlock`* (`@core/component/AI/component/message/ThinkingBlock.tsx`): a bare,- * borderless row — caret, then a "Thinking"/"Thought" label that shimmers- * while this thought is still the tail of an open turn — expanding to the- * reasoning text. Earlier thoughts settle the moment the next part arrives,- * the same rule production chat uses for `ThinkingBlock`.+ * borderless row — a "Thinking"/"Thought" label that shimmers while this+ * thought is still the tail of an open turn, then a caret on hover —+ * expanding to the reasoning text. While live it leads with the working+ * dots, where `WorkingLine` had them. Earlier thoughts settle the moment the+ * next part arrives, the same rule production chat uses for `ThinkingBlock`.*/-import CaretRight from '@icon/system/regular/caret-right.svg';import { createSignal, Show } from 'solid-js';+import { DisclosureCaret } from './DisclosureCaret';import { TextShimmer } from './TextShimmer';+import { WorkingDots } from './WorkingDots';export interface ThoughtProps {text: string;@@ -22,24 +24,24 @@ export function Thought(props: ThoughtProps) {const [expanded, setExpanded] = createSignal(props.defaultOpen ?? false);return (- <div class="relative text-xs leading-5 text-ink-extra-muted">+ <div class="relative text-sm leading-6 text-ink-extra-muted"><buttontype="button"aria-expanded={expanded()}- class="flex min-h-7 items-center gap-1 py-1 text-left text-ink-extra-muted hover:text-ink-muted"+ class="group flex min-h-8 items-center gap-2 py-1 text-left text-ink-extra-muted not-touch:hover:text-ink-muted"onClick={() => setExpanded((prev) => !prev)}>- <CaretRight- class="size-4 shrink-0"- classList={{ 'rotate-90': expanded() }}- />+ <Show when={props.active}>+ <WorkingDots />+ </Show><TextShimmertext={props.active ? 'Thinking' : 'Thought'}active={props.active ?? false}/>+ <DisclosureCaret open={expanded()} /></button><Show when={expanded()}>- <div class="pl-5 text-ink-muted whitespace-pre-wrap wrap-break-word select-text">+ <div class="text-ink-muted whitespace-pre-wrap wrap-break-word select-text">{props.text}</div></Show>diff --git a/apps/web/src/features/block-agent/ui/ToolCard.test.tsx b/apps/web/src/features/block-agent/ui/ToolCard.test.tsxindex 42f6760814..c78043b220 100644--- a/apps/web/src/features/block-agent/ui/ToolCard.test.tsx+++ b/apps/web/src/features/block-agent/ui/ToolCard.test.tsx@@ -12,24 +12,18 @@ vi.mock('@icon/system/regular/caret-right.svg', () => ({afterEach(cleanup);describe('ToolCard', () => {- it('shows a result summary and only shimmers while the tool is active', async () => {+ it('says only a failure and only shimmers while the tool is active', async () => {const [status, setStatus] = createSignal<'running' | 'completed' | 'failed'>('running');const view = render(() => (- <ToolCard- title="Search"- status={status()}- icon={<svg data-testid="search-icon" />}- >+ <ToolCard title="Search" status={status()}>Search results</ToolCard>));- expect(view.getByTestId('search-icon')).toBeTruthy();- expect(view.queryByText('Succeeded')).toBeNull();expect(view.container.querySelector('.magic-chip-shimmer')).toBeTruthy();setStatus('completed');- expect(view.getByText('Succeeded')).toBeTruthy();+ expect(view.getByRole('button', { name: 'Search' })).toBeTruthy();await waitFor(() =>expect(view.container.querySelector('.magic-chip-shimmer')).toBeNull());diff --git a/apps/web/src/features/block-agent/ui/ToolCard.tsx b/apps/web/src/features/block-agent/ui/ToolCard.tsxindex 3aefae4b45..60496ae99d 100644--- a/apps/web/src/features/block-agent/ui/ToolCard.tsx+++ b/apps/web/src/features/block-agent/ui/ToolCard.tsx@@ -1,5 +1,8 @@/**- * A bare tool row with an icon, a compact result, and lazy result disclosure.+ * A bare tool row, a compact result, and lazy result disclosure, shaped like+ * the session's other activity rows: the label, its detail beside it in a+ * dimmer tone, and a caret after them on hover. No icon and no indent, so a+ * run of calls reads as a quiet list in line with the prose around it.** Ported from opencode's* `packages/session-ui/src/v2/components/basic-tool-v2.tsx`@@ -7,22 +10,20 @@* and the `Tool` card idiom.*/-import CaretRight from '@icon/system/regular/caret-right.svg';-import Wrench from '@icon/system/regular/wrench.svg';import { Collapsible } from '@kobalte/core/collapsible';import { Tooltip } from '@ui/components/Tooltip';import { createSignal, For, type JSX, Show } from 'solid-js';+import { DisclosureCaret } from './DisclosureCaret';import { TextShimmer } from './TextShimmer';import { isToolActive, type ToolStatus } from './types';export interface ToolCardProps {- icon?: JSX.Element;title: JSX.Element | string;/** Mono, truncated detail next to the title (a path, a command, ...). */subtitle?: string;/** Compact `key=value` details after the subtitle. */args?: Record<string, string>;- /** Right-aligned slot before the chevron (status text, counts, ...). */+ /** Status text or counts after the detail; a failed call says so by default. */trailing?: JSX.Element;status: ToolStatus;/** Fade the whole card, the chat block's failed-tool treatment. */@@ -51,66 +52,57 @@ export function ToolCard(props: ToolCardProps) {// Conditional callers supply presence separately; Kobalte mounts the body.const hasChildren = () => props.hasContent ?? 'children' in props;const summary = () =>- props.trailing ??- (props.status === 'failed'- ? 'Failed'- : props.status === 'completed'- ? 'Succeeded'- : undefined);+ props.trailing ?? (props.status === 'failed' ? 'Failed' : undefined);const row = (expandable: boolean) => (<>- <span- aria-hidden="true"- class="flex size-4 shrink-0 items-center justify-center text-ink-extra-muted [&>svg]:size-4"- >- {props.icon ?? <Wrench />}- </span>- <span class="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden">- <span class="min-w-0 truncate text-ink-muted">- {typeof props.title === 'string' ? (- <Tooltip- label={props.title}- as="span"- class="min-w-0 max-w-full truncate"- >- <TextShimmer text={props.title} active={active()} />- </Tooltip>- ) : (- props.title- )}- </span>- <Show when={props.subtitle}>- {(subtitle) => (- <>- <span aria-hidden="true" class="shrink-0 text-ink-placeholder">- ·- </span>- <Tooltip label={subtitle()} as="span" class="min-w-0 truncate">- <span class="truncate font-mono">{subtitle()}</span>- </Tooltip>- </>- )}- </Show>- <For each={Object.entries(props.args ?? {})}>- {([key, value]) => (- <span class="min-w-0 truncate font-mono text-ink-extra-muted">- {key}={value}- </span>- )}- </For>+ {/* The detail gives way first: it shrinks a hundredfold faster, so a+ label truncates only once its detail is gone. */}+ <span class="min-w-0 truncate">+ {typeof props.title === 'string' ? (+ <Tooltip+ label={props.title}+ as="span"+ class="min-w-0 max-w-full truncate"+ >+ <TextShimmer text={props.title} active={active()} />+ </Tooltip>+ ) : (+ props.title+ )}</span>- <Show when={summary() || expandable}>- <span class="ml-auto flex shrink-0 items-center gap-2 whitespace-nowrap text-xs tabular-nums text-ink-extra-muted">+ <Show when={props.subtitle}>+ {(subtitle) => (+ <Tooltip+ label={subtitle()}+ as="span"+ class="min-w-0 shrink-[100] truncate text-ink-disabled"+ >+ {subtitle()}+ </Tooltip>+ )}+ </Show>+ <For each={Object.entries(props.args ?? {})}>+ {([key, value]) => (+ <span class="min-w-0 shrink-[100] truncate text-ink-disabled">+ {key}={value}+ </span>+ )}+ </For>+ <Show when={summary()}>+ <span+ class="shrink-0 whitespace-nowrap tabular-nums"+ classList={{+ 'text-failure': props.status === 'failed',+ 'text-ink-disabled': props.status !== 'failed',+ }}+ >{summary()}- <Show when={expandable}>- <CaretRight- aria-hidden="true"- class="size-3.5 shrink-0 text-ink-extra-muted group-data-expanded:rotate-90"- />- </Show></span></Show>+ <Show when={expandable}>+ <DisclosureCaret open={open()} />+ </Show></>);@@ -124,20 +116,18 @@ export function ToolCard(props: ToolCardProps) {<Showwhen={hasChildren()}fallback={- <div class="flex min-h-8 w-full min-w-0 items-center gap-2 py-1 text-left text-sm leading-6">+ <div class="flex min-h-8 w-full min-w-0 items-center gap-1.5 py-1 text-left text-sm leading-6">{row(false)}</div>}><Collapsible open={open()} onOpenChange={setOpen}>- <Collapsible.Trigger class="group flex min-h-8 w-full min-w-0 items-center gap-2 py-1 text-left text-sm leading-6 outline-offset-2 hover:text-ink focus-visible:outline-2 focus-visible:outline-accent">+ <Collapsible.Trigger class="group flex min-h-8 w-full min-w-0 items-center gap-1.5 py-1 text-left text-sm leading-6 outline-offset-2 not-touch:hover:text-ink-muted focus-visible:outline-2 focus-visible:outline-accent">{row(true)}</Collapsible.Trigger><Collapsible.Content class="data-closed:hidden"><Show when={open()}>- <div class="min-w-0 pb-2 pl-6 text-xs leading-5">- {props.children}- </div>+ <div class="min-w-0 pb-2 text-xs leading-5">{props.children}</div></Show></Collapsible.Content></Collapsible>diff --git a/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx b/apps/web/src/features/block-agent/ui/ToolErrorCard.tsxindex 769ac75379..46836311f4 100644--- a/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx+++ b/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx@@ -11,7 +11,6 @@import { fireAndForget } from '@core/util/fireAndForget';import Check from '@icon/system/regular/check.svg';import Copy from '@icon/system/regular/copy.svg';-import Prohibit from '@icon/system/regular/prohibit.svg';import { Button } from '@ui';import { createMemo, createSignal, Show } from 'solid-js';import { ToolCard } from './ToolCard';@@ -92,7 +91,6 @@ export function ToolErrorCard(props: ToolErrorCardProps) {<ToolCardtitle={title()}subtitle={subtitle() === 'Failed' ? undefined : subtitle()}- icon={<Prohibit />}status="failed"open={props.open}defaultOpen={props.defaultOpen}diff --git a/apps/web/src/features/block-agent/ui/ToolGroup.tsx b/apps/web/src/features/block-agent/ui/ToolGroup.tsxindex 2c88e1e7c6..8a2e004b1f 100644--- a/apps/web/src/features/block-agent/ui/ToolGroup.tsx+++ b/apps/web/src/features/block-agent/ui/ToolGroup.tsx@@ -6,7 +6,6 @@* because the cards themselves appear once it opens.*/-import CaretRight from '@icon/system/regular/caret-right.svg';import { createResizeObserver } from '@solid-primitives/resize-observer';import { CollapseTransition } from '@ui/components/CollapseTransition';import {@@ -17,6 +16,7 @@ import {on,onMount,} from 'solid-js';+import { DisclosureCaret } from './DisclosureCaret';import { TextShimmer } from './TextShimmer';export interface ToolGroupProps {@@ -122,7 +122,7 @@ function ToolWindow(props: {scrolling = false;}}>- <div ref={setContent} class="flex min-w-0 flex-col pl-6">+ <div ref={setContent} class="flex min-w-0 flex-col">{props.children}</div></div>@@ -152,11 +152,7 @@ export function ToolGroup(props: ToolGroupProps) {onClick={() => setExpanded(!expanded())}><TextShimmer text={title()} active={props.active} />- <CaretRight- aria-hidden="true"- 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() }}- />+ <DisclosureCaret open={expanded()} /></button><CollapseTransition open={expanded()}><div>diff --git a/apps/web/src/features/block-agent/ui/WorkingDots.tsx b/apps/web/src/features/block-agent/ui/WorkingDots.tsxnew file mode 100644index 0000000000..1af12ccbe9--- /dev/null+++ b/apps/web/src/features/block-agent/ui/WorkingDots.tsx@@ -0,0 +1,39 @@+/**+ * The loader leading an open agent turn: a plus of five dots - a 3×3 grid+ * without its corners - that turns to an × and back in 45° steps while its+ * dots brighten one at a time in a scattered order, on the+ * `agent-working-twirl` and `agent-working-dot` keyframes in `index.css`.+ */++import { For, Show } from 'solid-js';++/** One dot's brighten-and-fade; matches `agent-working-dot` in `index.css`. */+const TWINKLE_MS = 1400;++/**+ * When each cell, row by row, brightens within a cycle: the arms clockwise+ * from the top at 0, 840, 1120 and 560ms, the center at 280ms, so no path+ * reads. A corner has no dot.+ */+const TWINKLE_OFFSETS_MS = [null, 0, null, 560, 280, 840, null, 1120, null];++export function WorkingDots() {+ return (+ <span+ aria-hidden="true"+ class="agent-working-twirl grid size-[13px] shrink-0 grid-cols-3 gap-[2px] text-ink-muted"+ >+ <For each={TWINKLE_OFFSETS_MS}>+ {(offset) => (+ <Show when={offset !== null} fallback={<span />}>+ <span+ class="agent-working-dot size-[3px] rounded-full bg-current"+ // Negative delays start each dot mid-cycle, so none wait dim on mount.+ style={{ 'animation-delay': `${(offset ?? 0) - TWINKLE_MS}ms` }}+ />+ </Show>+ )}+ </For>+ </span>+ );+}diff --git a/apps/web/src/features/block-agent/ui/WorkingLine.tsx b/apps/web/src/features/block-agent/ui/WorkingLine.tsxindex e5144e4170..32575237a5 100644--- a/apps/web/src/features/block-agent/ui/WorkingLine.tsx+++ b/apps/web/src/features/block-agent/ui/WorkingLine.tsx@@ -1,18 +1,17 @@/*** The tail of an open turn that has produced nothing to read yet.*- * A sibling of `Thought`, deliberately shaped differently. A thought row leads- * with a caret because there is text behind it; this row has nothing to- * expand, so the caret gives way to three dots that ripple on the shimmer's- * own period, and the row is not a control at all. The leading slot keeps the- * caret's width so the label does not shift sideways once reasoning arrives- * and the row becomes a `Thought`.+ * A sibling of `Thought`, deliberately shaped differently. This row has+ * nothing to expand, so it is not a control at all: the working dots lead,+ * and a live `Thought` keeps them in the same place so the label does not+ * shift sideways once reasoning arrives and the row becomes one.** The label is the caller's: it says what the session is doing (`Sending`,* `Running tools`, `Stopping`), so it changes only when the state does.*/import { TextShimmer } from './TextShimmer';+import { WorkingDots } from './WorkingDots';export interface WorkingLineProps {/** What the turn is doing right now. Defaults to `Working`. */@@ -25,15 +24,8 @@ export function WorkingLine(props: WorkingLineProps) {const label = () => props.label ?? DEFAULT_LABEL;return (- <div class="flex min-h-7 items-center gap-1 py-1 text-xs leading-5 text-ink-extra-muted">- <span- aria-hidden="true"- class="agent-working-wave flex size-4 shrink-0 items-center justify-center gap-[2px]"- >- <span class="size-[3px] rounded-full bg-current" />- <span class="size-[3px] rounded-full bg-current" />- <span class="size-[3px] rounded-full bg-current" />- </span>+ <div class="flex min-h-8 items-center gap-2 py-1 text-sm leading-6 text-ink-extra-muted">+ <WorkingDots /><TextShimmer text={label()} label={label()} active /></div>);diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.tsindex 30163c5170..fc8477a65c 100644--- a/apps/web/src/features/block-agent/ui/index.ts+++ b/apps/web/src/features/block-agent/ui/index.ts@@ -31,6 +31,7 @@ export {} from './ComposerNotice';export { type CountItem, CountSummary } from './CountSummary';export { DiffChanges, type DiffChangesProps } from './DiffChanges';+export { DisclosureCaret } from './DisclosureCaret';export {FailureNoticeCard,type FailureNoticeCardProps,@@ -68,4 +69,5 @@ export {type TodoItem,type ToolStatus,} from './types';+export { WorkingDots } from './WorkingDots';export { WorkingLine } from './WorkingLine';diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsxindex 4ce4bdd879..94869fdbf9 100644--- a/apps/web/src/features/channel/Channel/Channel.tsx+++ b/apps/web/src/features/channel/Channel/Channel.tsx@@ -1,4 +1,3 @@-import { AgentTypingProvider } from '@app/features/agent-activity/agent-typing';import {AgentConversationContextBoundary,AgentConversationMessageStatus,@@ -803,217 +802,202 @@ export function Channel(props: ChannelProps) {container={threadListContainerEl}triggerBehavior="spring-back">- {/* The newest row shows the agents typing. Their- rows are made once, here, so a live turn moves- with that row instead of starting over in it. */}- <AgentTypingProvider- parent={{ type: 'channel', id: props.channelId }}- threadId={null}- >- <ThreadList- keys={() => messageIndex.entryKeys}- targetId={- targetMessageController.hasPendingElementScroll()- ? targetMessageController.activeTargetMessageId()- : undefined- }- insets={threadListScrollInsets()}- followOnAppend={!messagesQuery.hasPreviousPage}- onScrollNearTop={threadPaginator.shiftPaginate}- onScrollNearBottom={- threadPaginator.prependPaginate- }- onReady={onThreadListReady}- onScroll={onThreadListScroll}- onUserNavigation={cancelLatestNavigation}- initialPosition={- targetMessageController.activeTargetMessageId()+ <ThreadList+ keys={() => messageIndex.entryKeys}+ targetId={+ targetMessageController.hasPendingElementScroll()+ ? targetMessageController.activeTargetMessageId()+ : undefined+ }+ insets={threadListScrollInsets()}+ followOnAppend={!messagesQuery.hasPreviousPage}+ onScrollNearTop={threadPaginator.shiftPaginate}+ onScrollNearBottom={+ threadPaginator.prependPaginate+ }+ onReady={onThreadListReady}+ onScroll={onThreadListScroll}+ onUserNavigation={cancelLatestNavigation}+ initialPosition={+ targetMessageController.activeTargetMessageId()+ ? {+ type: 'element',+ id: targetMessageController.activeTargetMessageId()!,+ }+ : props.initialMessagesStateSnapshot?.scroll? {- type: 'element',- id: targetMessageController.activeTargetMessageId()!,+ type: 'restore',+ snapshot:+ props.initialMessagesStateSnapshot+ .scroll,}- : props.initialMessagesStateSnapshot?.scroll- ? {- type: 'restore',- snapshot:- props.initialMessagesStateSnapshot- .scroll,- }- : { type: 'latest' }- }- >- {(item) => {- const isNewestRow = () =>- item.id === messageIndex.entryKeys.at(-1);- const activity = () =>- messageIndex.activityByKey.get(item.id);- const message = () =>- messageById().get(item.id);+ : { type: 'latest' }+ }+ >+ {(item) => {+ const isNewestRow = () =>+ item.id === messageIndex.entryKeys.at(-1);+ const activity = () =>+ messageIndex.activityByKey.get(item.id);+ const message = () =>+ messageById().get(item.id);- return (- <Switch>- <Match when={activity()}>- {(activity) => (- <ThreadRow- channelId={props.channelId}- message={{- created_at:- activity().occurred_at,- }}- listMeta={listMetaByKey()[item.id]}- >- <SystemActivity- event={decodeSystemActivityRow(- messageIndex.activityGroupByKey.get(- item.id- ) ?? [activity()]- )}- />- <Show when={isNewestRow()}>- <ThreadTypingIndicator- parent={{- type: 'channel',- id: props.channelId,- }}- threadId={null}- />- </Show>- </ThreadRow>- )}- </Match>- <Match when={message()}>- {(m) => {- const state =- threadManager.getOrCreateThreadState(- item.id- );- return (- <ChannelThread- beforeMessage={- <AgentConversationContextBoundary- messageId={item.id}- />- }- afterMessage={- <AgentConversationMessageStatus- messageId={item.id}- />- }- hideTriggeredBy={- !!channel()?.agent_dm- }- data={m}- parent={() => ({+ return (+ <Switch>+ <Match when={activity()}>+ {(activity) => (+ <ThreadRow+ channelId={props.channelId}+ message={{+ created_at: activity().occurred_at,+ }}+ listMeta={listMetaByKey()[item.id]}+ >+ <SystemActivity+ event={decodeSystemActivityRow(+ messageIndex.activityGroupByKey.get(+ item.id+ ) ?? [activity()]+ )}+ />+ <Show when={isNewestRow()}>+ <ThreadTypingIndicator+ parent={{type: 'channel',- id: (() => props.channelId)(),- })}- isNewestThread={isNewestRow()}- getMessageActions={- getMessageActions- }- isFindBarOpen={findBar.isOpen}- targetNavigation={{- targetThreadId:- targetMessageController.activeTargetMessageId,- targetMessageId: () =>- !targetMessageController.pendingTargetReplyId()- ? targetMessageController.pendingScrollTargetId()- : undefined,- targetReplyId: () =>- targetMessageController.pendingScrollTargetId()- ? undefined- : targetMessageController.pendingTargetReplyId(),- activeTargetReplyId:- targetMessageController.activeTargetMessageReplyId,- positionTarget: (- _,- targetElement- ) =>- threadListNavigation()?.scrollToElement(- targetElement- ) ?? false,- onTargetMessageScrolled:- targetMessageController.completePendingScroll,- onTargetReplyScrolled: (- replyId- ) => {- targetMessageController.completePendingReplyScroll(- item.id,- replyId- );- },- onClearTarget:- releaseSelectionAndTarget,- }}- inputMode={- isUnifiedInputMode()- ? 'unified'- : 'inline'- }- unifiedReplyTarget={unifiedInput.replyTarget()}- onMessageMount={- unread.onMessageMount- }- onDisclosureMount={- unread.onDisclosureMount- }- unreadMessageIds={unread- .unreadByThread()- .get(item.id)}- isExpanded={state.isExpanded}- setIsExpanded={- state.setIsExpanded- }- isReplying={state.isReplying}- setIsReplying={- state.setIsReplying- }- replyInputState={- state.replyInputState- }- setReplyInputState={- state.setReplyInputState- }- setReplyInputEl={- state.setReplyInputEl- }- replyInputHandle={- state.replyInputHandle- }- setReplyInputHandle={- state.setReplyInputHandle- }- replyInputFocusRequest={- state.replyInputFocusRequest- }- listMeta={- listMetaByKey()[item.id]- }- messageEditor={messageEditor}- threadActions={{- onDismissNewMessages:- activityTracker.dismissNewMessages,+ id: props.channelId,}}- isNewMessage={- activityTracker.isNewMessage- }- selectedMessageId={- selection.selectedId- }- onSelectMessage={selectMessage}- onClearSelection={clearSelection}- messageListScopeId={- messageListScopeId- }+ threadId={null}/>+ </Show>+ </ThreadRow>+ )}+ </Match>+ <Match when={message()}>+ {(m) => {+ const state =+ threadManager.getOrCreateThreadState(+ item.id);- }}- </Match>- </Switch>- );- }}- </ThreadList>- </AgentTypingProvider>+ return (+ <ChannelThread+ beforeMessage={+ <AgentConversationContextBoundary+ messageId={item.id}+ />+ }+ afterMessage={+ <AgentConversationMessageStatus+ messageId={item.id}+ />+ }+ hideTriggeredBy={+ !!channel()?.agent_dm+ }+ data={m}+ parent={() => ({+ type: 'channel',+ id: (() => props.channelId)(),+ })}+ isNewestThread={isNewestRow()}+ getMessageActions={+ getMessageActions+ }+ isFindBarOpen={findBar.isOpen}+ targetNavigation={{+ targetThreadId:+ targetMessageController.activeTargetMessageId,+ targetMessageId: () =>+ !targetMessageController.pendingTargetReplyId()+ ? targetMessageController.pendingScrollTargetId()+ : undefined,+ targetReplyId: () =>+ targetMessageController.pendingScrollTargetId()+ ? undefined+ : targetMessageController.pendingTargetReplyId(),+ activeTargetReplyId:+ targetMessageController.activeTargetMessageReplyId,+ positionTarget: (+ _,+ targetElement+ ) =>+ threadListNavigation()?.scrollToElement(+ targetElement+ ) ?? false,+ onTargetMessageScrolled:+ targetMessageController.completePendingScroll,+ onTargetReplyScrolled: (+ replyId+ ) => {+ targetMessageController.completePendingReplyScroll(+ item.id,+ replyId+ );+ },+ onClearTarget:+ releaseSelectionAndTarget,+ }}+ inputMode={+ isUnifiedInputMode()+ ? 'unified'+ : 'inline'+ }+ unifiedReplyTarget={unifiedInput.replyTarget()}+ onMessageMount={+ unread.onMessageMount+ }+ onDisclosureMount={+ unread.onDisclosureMount+ }+ unreadMessageIds={unread+ .unreadByThread()+ .get(item.id)}+ isExpanded={state.isExpanded}+ setIsExpanded={state.setIsExpanded}+ isReplying={state.isReplying}+ setIsReplying={state.setIsReplying}+ replyInputState={+ state.replyInputState+ }+ setReplyInputState={+ state.setReplyInputState+ }+ setReplyInputEl={+ state.setReplyInputEl+ }+ replyInputHandle={+ state.replyInputHandle+ }+ setReplyInputHandle={+ state.setReplyInputHandle+ }+ replyInputFocusRequest={+ state.replyInputFocusRequest+ }+ listMeta={listMetaByKey()[item.id]}+ messageEditor={messageEditor}+ threadActions={{+ onDismissNewMessages:+ activityTracker.dismissNewMessages,+ }}+ isNewMessage={+ activityTracker.isNewMessage+ }+ selectedMessageId={+ selection.selectedId+ }+ onSelectMessage={selectMessage}+ onClearSelection={clearSelection}+ messageListScopeId={+ messageListScopeId+ }+ />+ );+ }}+ </Match>+ </Switch>+ );+ }}+ </ThreadList></SwipableRowProvider><Show when={!findBar.isOpen()}>diff --git a/apps/web/src/features/channel/Message/Content.tsx b/apps/web/src/features/channel/Message/Content.tsxindex 985c67d909..01f4e786e5 100644--- a/apps/web/src/features/channel/Message/Content.tsx+++ b/apps/web/src/features/channel/Message/Content.tsx@@ -3,6 +3,7 @@ import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/Simport { channelTheme } from '@core/component/LexicalMarkdown/theme';import { isEmojiOnly } from '@core/util/string';import CaretRight from '@icon/system/regular/caret-right.svg';+import { isBotSenderId } from '@queries/messages/message-sender';import { Button, cn } from '@ui';import {createMemo,@@ -42,6 +43,8 @@ export function Content(props: ContentProps) {// sender line renders (`Message.AgentSessionLink`), not part of the text.const content = createMemo(() => splitMessageContent(message()).body);const bigEmoji = createMemo(() => isEmojiOnly(content()));+ // An agent's references stand out from its text, as in its session view.+ const fromAgent = () => isBotSenderId(message().sender_id);const terms = createMemo(() => termsLookup?.(message().id));const [markdownRoot, setMarkdownRoot] = createSignal<HTMLDivElement>();@@ -68,6 +71,7 @@ export function Content(props: ContentProps) {class={cn('whitespace-pre-wrap wrap-break-word max-w-full',bigEmoji() ? 'text-4xl' : 'text-base',+ fromAgent() && '[&_[data-mention]]:text-accent',props.class)}>diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 8cec140c4d..b3f5b89dd2 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -541,6 +541,7 @@ body.tauri-ios {--animate-update-glow: update-glow-spin 8s infinite, update-glow-fade 8s linear infinite;--animate-accordion-down: accordion-down 150ms ease-out;--animate-accordion-up: accordion-up 150ms ease-out;+ --animate-agent-step-in: agent-step-in 240ms cubic-bezier(0.16, 1, 0.3, 1);/* Z-index scale — the single source of truth for stacking. Classes comefrom these tokens (`--z-index-foo` -> `z-foo`).@@ -1325,28 +1326,33 @@ html[data-platform='ios'][data-touch-device='true'] :is(}}+/* One pass, then a rest: the highlight crosses in the first 60% of the+ period and the label stays dim for the remainder. */@keyframes magic-chip-shimmer {0% {background-position: 100% 0;}+ 60%,100% {background-position: 0% 0;}}+/* A highlight wider than the label, with a sharp leading edge and a long+ tail, so the whole label lifts quickly from dim and fades back slowly. */.magic-chip-shimmer {background: linear-gradient(90deg,- var(--color-ink-extra-muted) 40%,- var(--color-ink) 50%,- var(--color-ink-extra-muted) 60%+ color-mix(in oklch, var(--color-ink-disabled) 60%, transparent) 25%,+ var(--color-ink-muted) 58%,+ color-mix(in oklch, var(--color-ink-disabled) 60%, transparent) 70%);- background-size: 250% 100%;+ background-size: 400% 100%;/* The highlight starts and ends just outside the text, without tiling. */background-repeat: no-repeat;background-clip: text;color: transparent;- animation: magic-chip-shimmer 1.8s linear infinite;+ animation: magic-chip-shimmer 1.2s linear infinite;}@media (prefers-reduced-motion: reduce) {@@ -1357,38 +1363,87 @@ html[data-platform='ios'][data-touch-device='true'] :is(}}-/* The three dots leading an open agent turn that has nothing to expand yet.- A staggered ripple on the shimmer's period, so the row reads as one motion,- not two. */-@keyframes agent-working-wave {+/* One dot of `WorkingDots`: it brightens, then fades back to faint for the+ rest of its cycle. */+@keyframes agent-working-dot {0%,- 60%,+ 70%,100% {- opacity: 0.35;- transform: translateY(0);+ opacity: 0.15;}- 30% {+ 35% {opacity: 1;- transform: translateY(-2px);}}-.agent-working-wave > * {- animation: agent-working-wave 1.8s ease-in-out infinite;+.agent-working-dot {+ animation: agent-working-dot 1.4s ease-in-out infinite;}-.agent-working-wave > :nth-child(2) {- animation-delay: 0.2s;+/* `WorkingDots` turning a full circle in eighths, so the loop ends where it+ began and no dot jumps: each 45° step turns for 0.2s, then holds for 0.4s. */+@keyframes agent-working-twirl {+ 0%,+ 8.5% {+ transform: rotate(0deg);+ }+ 12.5%,+ 21% {+ transform: rotate(45deg);+ }+ 25%,+ 33.5% {+ transform: rotate(90deg);+ }+ 37.5%,+ 46% {+ transform: rotate(135deg);+ }+ 50%,+ 58.5% {+ transform: rotate(180deg);+ }+ 62.5%,+ 71% {+ transform: rotate(225deg);+ }+ 75%,+ 83.5% {+ transform: rotate(270deg);+ }+ 87.5%,+ 96% {+ transform: rotate(315deg);+ }+ 100% {+ transform: rotate(360deg);+ }}-.agent-working-wave > :nth-child(3) {- animation-delay: 0.4s;+.agent-working-twirl {+ animation: agent-working-twirl 4.8s ease-in-out infinite;}@media (prefers-reduced-motion: reduce) {- .agent-working-wave > * {+ .agent-working-twirl {+ animation: none;+ }++ .agent-working-dot {animation: none;- opacity: 0.55;+ opacity: 0.6;+ }+}++/* The next step rising into an agent's one-line progress. */+@keyframes agent-step-in {+ from {+ opacity: 0;+ transform: translateY(60%);+ }+ to {+ opacity: 1;+ transform: translateY(0);}}diff --git a/apps/web/src/lib/core/component/AI/component/tool/BaseTool.tsx b/apps/web/src/lib/core/component/AI/component/tool/BaseTool.tsxindex 66e2dd46a6..8d9f989083 100644--- a/apps/web/src/lib/core/component/AI/component/tool/BaseTool.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/BaseTool.tsx@@ -37,10 +37,22 @@ function BaseToolCall(props: ToolCallProps) {expanded={showReason()}onToggle={() => setShowReason((shown) => !shown)}showToggle={reason() !== undefined}- status={<span class="text-ink">Failed</span>}+ status={+ <span+ classList={{ 'text-ink': !grouped(), 'text-failure': grouped() }}+ >+ Failed+ </span>+ }/>))- .with({ kind: 'stopped' }, () => <span class="text-xs">Stopped</span>)+ .with({ kind: 'stopped' }, () => (+ <span+ classList={{ 'text-xs': !grouped(), 'text-ink-disabled': grouped() }}+ >+ Stopped+ </span>+ )).exhaustive();};@@ -49,7 +61,6 @@ function BaseToolCall(props: ToolCallProps) {<Tool.Rowactive={props.renderContext.running}align={props.align}- grouped={grouped()}icon={props.icon}trailing={trailing()}>@@ -62,7 +73,7 @@ function BaseToolCall(props: ToolCallProps) {{(text) => (<pclass="whitespace-pre-wrap break-words pb-2"- classList={{ 'pl-6': grouped(), 'pl-9 pr-3': !grouped() }}+ classList={{ 'pl-9 pr-3': !grouped() }}>{text()}</p>diff --git a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsxindex 061b9de99c..9d40295840 100644--- a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx@@ -57,11 +57,7 @@ const EventDetails = (props: {onOpen: () => void;}) => (<Tool.List>- <button- type="button"- class="block w-full text-left hover:bg-hover"- onClick={props.onOpen}- >+ <Tool.ListButton onClick={props.onOpen}><Tool.ListItem icon={<CalendarBlank class="size-4" />}><div class="flex min-w-0 flex-col gap-0.5"><span class="truncate text-xs text-ink">{props.event.title}</span>@@ -90,7 +86,7 @@ const EventDetails = (props: {</Show></div></Tool.ListItem>- </button>+ </Tool.ListButton><Show when={props.event.macroCallUrl ?? props.event.conferenceUrl}>{(url) => (<Tool.ListItem icon={<VideoCamera class="size-4" />}>diff --git a/apps/web/src/lib/core/component/AI/component/tool/ListEntities.tsx b/apps/web/src/lib/core/component/AI/component/tool/ListEntities.tsxindex 58b915a053..f584db2782 100644--- a/apps/web/src/lib/core/component/AI/component/tool/ListEntities.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/ListEntities.tsx@@ -137,8 +137,11 @@ const ListEntitiesToolResponse = (props: {data={results()}bufferSize={itemHeight * 5}itemSize={itemHeight}+ // Sized by its rows, which are taller on touch and shorter among an+ // agent's grouped tool rows than the estimate.style={{- height: `${Math.min(results().length * itemHeight, maxHeight)}px`,+ height: 'auto',+ 'max-height': `${maxHeight}px`,contain: 'content',}}>@@ -146,17 +149,13 @@ const ListEntitiesToolResponse = (props: {const clickHandler = getClickHandler(item);return (- <button- type="button"- class="block w-full text-left hover:bg-hover"- onClick={clickHandler}- >+ <Tool.ListButton onClick={clickHandler}><Tool.ListItem icon={getItemIcon(item)}><div class="truncate text-xs text-ink">{getItemTitle(item)}</div></Tool.ListItem>- </button>+ </Tool.ListButton>);}}</VList>diff --git a/apps/web/src/lib/core/component/AI/component/tool/ReadProject.tsx b/apps/web/src/lib/core/component/AI/component/tool/ReadProject.tsxindex 3640de831d..13b492b5fe 100644--- a/apps/web/src/lib/core/component/AI/component/tool/ReadProject.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadProject.tsx@@ -77,8 +77,11 @@ const ReadProjectToolResponse = (props: { items: ReadProjectItem[] }) => {data={props.items}bufferSize={itemHeight * 5}itemSize={itemHeight}+ // Sized by its rows, which are taller on touch and shorter among an+ // agent's grouped tool rows than the estimate.style={{- height: `${Math.min(props.items.length * itemHeight, maxHeight)}px`,+ height: 'auto',+ 'max-height': `${maxHeight}px`,contain: 'content',}}>@@ -86,15 +89,11 @@ const ReadProjectToolResponse = (props: { items: ReadProjectItem[] }) => {const clickHandler = getClickHandler(item);return (- <button- type="button"- class="block w-full text-left hover:bg-hover"- onClick={clickHandler}- >+ <Tool.ListButton onClick={clickHandler}><Tool.ListItem icon={getItemIcon(item)}><div class="truncate text-xs text-ink">{item.name}</div></Tool.ListItem>- </button>+ </Tool.ListButton>);}}</VList>diff --git a/apps/web/src/lib/core/component/AI/component/tool/Search.tsx b/apps/web/src/lib/core/component/AI/component/tool/Search.tsxindex f9ab4b9c51..30220a8156 100644--- a/apps/web/src/lib/core/component/AI/component/tool/Search.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/Search.tsx@@ -38,11 +38,7 @@ function SearchResultRow(props: {const hit = () => props.entity.search.contentHitData?.[0];return (- <button- type="button"- class="block w-full text-left hover:bg-hover"- onClick={props.onClick}- >+ <Tool.ListButton onClick={props.onClick}><Tool.ListItem icon={<EntityRowIcon entity={props.entity} />}><div class="flex min-w-0 items-center gap-2"><div class="min-w-0 flex flex-1 items-center gap-1.5">@@ -68,7 +64,7 @@ function SearchResultRow(props: {</span></div></Tool.ListItem>- </button>+ </Tool.ListButton>);}diff --git a/apps/web/src/lib/core/component/AI/component/tool/SearchSkills.tsx b/apps/web/src/lib/core/component/AI/component/tool/SearchSkills.tsxindex 4c734746fe..ad9ad507f3 100644--- a/apps/web/src/lib/core/component/AI/component/tool/SearchSkills.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/SearchSkills.tsx@@ -34,11 +34,7 @@ function SkillResultRow(props: { result: SkillSearchResult }) {return (<Show when={entity()}>{(skill) => (- <button- type="button"- class="block w-full text-left hover:bg-hover"- onClick={openSkill}- >+ <Tool.ListButton onClick={openSkill}><Tool.ListItem icon={<EntityRowIcon entity={skill()} />}><div class="flex min-w-0 items-center gap-2"><span class="min-w-0 truncate text-ink">@@ -46,7 +42,7 @@ function SkillResultRow(props: { result: SkillSearchResult }) {</span></div></Tool.ListItem>- </button>+ </Tool.ListButton>)}</Show>);diff --git a/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx b/apps/web/src/lib/core/component/AI/component/tool/Tool.tsxindex 0e0a29f52c..8d0de74af0 100644--- a/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx@@ -1,13 +1,13 @@+import { DisclosureCaret } from '@app/features/block-agent/ui/DisclosureCaret';import CaretRight from '@icon/system/regular/caret-right.svg?component-solid';import { Button, Layer } from '@ui';-import type { Component, JSX } from 'solid-js';-import { Show } from 'solid-js';+import type { Accessor, Component, JSX } from 'solid-js';+import { createContext, Show, useContext } from 'solid-js';type ToolRowProps = {/** The call is still running: its text shimmers, as an active agent row does. */active?: boolean;align?: 'center' | 'start';- grouped?: boolean;children: JSX.Element;icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;trailing?: JSX.Element;@@ -43,17 +43,30 @@ type ToolListItemProps = {icon?: JSX.Element;};+type ToolListButtonProps = {+ children: JSX.Element;+ onClick?: (event: MouseEvent) => void;+};++/**+ * A grouped tool sits among an agent's other tool rows, so it drops its card,+ * icons, and indents to read as one more line of that list.+ */+const GroupedContext = createContext<Accessor<boolean>>(() => false);+function Root(props: ToolRootProps) {const content = () => (- <div- class="relative overflow-hidden text-xs leading-5 text-ink-extra-muted"- classList={{- 'opacity-50': props.muted,- 'rounded-lg bg-surface': !props.grouped,- }}- >- {props.children}- </div>+ <GroupedContext.Provider value={() => props.grouped ?? false}>+ <div+ class="relative overflow-hidden text-xs leading-5 text-ink-extra-muted"+ classList={{+ 'opacity-50': props.muted,+ 'rounded-lg bg-surface': !props.grouped,+ }}+ >+ {props.children}+ </div>+ </GroupedContext.Provider>);return (@@ -64,25 +77,37 @@ function Root(props: ToolRootProps) {}function Row(props: ToolRowProps) {+ const grouped = useContext(GroupedContext);const alignStart = () => props.align === 'start';return (<div- class="flex w-full gap-2"+ class="flex w-full"classList={{- 'min-h-8 py-1 text-sm leading-6': props.grouped,- 'min-h-9 px-3 py-2': !props.grouped,+ 'relative min-h-8 gap-1.5 py-1 text-sm leading-6 not-touch:has-[[aria-expanded]]:hover:text-ink-muted':+ grouped(),+ 'min-h-9 gap-2 px-3 py-2': !grouped(),'items-center': !alignStart(),'items-start': alignStart(),}}>- <props.icon- class="size-4 shrink-0 text-ink-extra-muted"- classList={{ 'mt-0.5': alignStart() }}- />+ <Show when={!grouped()}>+ <props.icon+ class="size-4 shrink-0 text-ink-extra-muted"+ classList={{ 'mt-0.5': alignStart() }}+ />+ </Show>+ {/* Grouped, the content takes only its text's width, so a count the+ renderer spaces to the far edge follows the detail at the row's gap+ instead, and the object a renderer highlights steps down to the+ detail's tone. */}<div- class="min-w-0 flex-1 overflow-hidden"- classList={{ 'magic-chip-shimmer': props.active }}+ class="min-w-0 overflow-hidden"+ classList={{+ 'flex-1': !grouped(),+ '*:gap-1.5 [--color-ink:var(--color-ink-disabled)]': grouped(),+ 'magic-chip-shimmer': props.active,+ }}>{props.children}</div>@@ -94,46 +119,78 @@ function Row(props: ToolRowProps) {}function Response(props: ToolResponseProps) {- return <div class="px-3 pb-2">{props.children}</div>;+ const grouped = useContext(GroupedContext);+ return (+ <div class="pb-2" classList={{ 'px-3': !grouped() }}>+ {props.children}+ </div>+ );}function ResultToggle(props: ToolResultToggleProps) {+ const grouped = useContext(GroupedContext);const canToggle = () => props.showToggle ?? true;+ const toggle = (event: MouseEvent) => {+ event.preventDefault();+ event.stopPropagation();+ props.onToggle(event);+ };return (<Showwhen={canToggle()}fallback={<Show when={props.status}>- <span class="shrink-0 whitespace-nowrap text-xs text-ink-extra-muted">+ <span+ class="shrink-0 whitespace-nowrap"+ classList={{+ 'text-ink-disabled': grouped(),+ 'text-xs text-ink-extra-muted': !grouped(),+ }}+ >{props.status}</span></Show>}>- <Button- type="button"- variant="ghost"- size="sm"- aria-expanded={props.expanded}- class="shrink-0 whitespace-nowrap px-1 text-ink-extra-muted hover:text-ink-muted"- onClick={(event) => {- event.preventDefault();- event.stopPropagation();- props.onToggle(event);- }}+ <Show+ when={grouped()}+ fallback={+ <Button+ type="button"+ variant="ghost"+ size="sm"+ aria-expanded={props.expanded}+ class="shrink-0 whitespace-nowrap px-1 text-ink-extra-muted hover:text-ink-muted"+ onClick={toggle}+ >+ <Show when={props.status}>+ <span>{props.status}</span>+ </Show>+ <CaretRight+ class="size-3 touch:size-6 shrink-0 pointer-events-none"+ aria-hidden="true"+ classList={{+ 'rotate-90': props.expanded,+ }}+ />+ </Button>+ }>- <Show when={props.status}>- <span>{props.status}</span>- </Show>- <CaretRight- class="size-3 touch:size-6 shrink-0 pointer-events-none"- aria-hidden="true"- classList={{- 'rotate-90': props.expanded,- }}- />- </Button>+ {/* Stretched over the row, so the whole row opens the results as the+ session's other tool rows do. */}+ <button+ type="button"+ aria-expanded={props.expanded}+ class="group flex shrink-0 items-center gap-1.5 whitespace-nowrap outline-none after:absolute after:inset-0 after:outline-offset-2 focus-visible:after:outline-2 focus-visible:after:outline-accent"+ onClick={toggle}+ >+ <Show when={props.status}>+ <span class="tabular-nums text-ink-disabled">{props.status}</span>+ </Show>+ <DisclosureCaret open={props.expanded} />+ </button>+ </Show></Show>);}@@ -149,13 +206,31 @@ function Group(props: ToolGroupProps) {}function List(props: ToolListProps) {- return <div class="-mx-3 -my-2">{props.children}</div>;+ const grouped = useContext(GroupedContext);+ return (+ <div+ classList={{+ '-mx-3 -my-2': !grouped(),+ // Results read in the row's tone, not as brighter content under it.+ '[--color-ink:currentColor]': grouped(),+ }}+ >+ {props.children}+ </div>+ );}function ListItem(props: ToolListItemProps) {+ const grouped = useContext(GroupedContext);return (- <div class="flex min-h-8 items-center gap-2 px-3 py-1.5 text-xs leading-4">- <Show when={props.icon}>+ <div+ class="flex items-center gap-2 text-xs"+ classList={{+ 'min-h-6 py-0.5 leading-5': grouped(),+ 'min-h-8 px-3 py-1.5 leading-4': !grouped(),+ }}+ >+ <Show when={!grouped() && props.icon}><div class="flex size-4 shrink-0 items-center justify-center text-ink-extra-muted">{props.icon}</div>@@ -165,9 +240,29 @@ function ListItem(props: ToolListItemProps) {);}+/** A result that opens what it found. */+function ListButton(props: ToolListButtonProps) {+ const grouped = useContext(GroupedContext);+ return (+ <button+ type="button"+ class="w-full text-left"+ classList={{+ 'grid items-center touch:min-h-[44px] not-touch:hover:text-ink-muted':+ grouped(),+ 'block hover:bg-hover': !grouped(),+ }}+ onClick={(event) => props.onClick?.(event)}+ >+ {props.children}+ </button>+ );+}+export const Tool = {Group,List,+ ListButton,ListItem,Response,ResultToggle,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsxindex 4b830721ad..5c8730564a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx@@ -1,4 +1,6 @@import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';+import { PENDING_REPLY_TEXT } from '@macro-inc/lexical-core';+import { composeAgentChatReply } from '@macro-inc/lexical-core/utils/agent-chat-reply';import { render, waitFor } from '@solidjs/testing-library';import { createSignal, type JSX } from 'solid-js';import { describe, expect, it, vi } from 'vitest';@@ -215,6 +217,27 @@ describe('display-only markdown previews', () => {});});+describe('agent reply pending markers', () => {+ it('shows a running agent reply as the working line and keeps other placeholders', () => {+ const pending = composeAgentChatReply({+ sessionId: '00000000-0000-4000-8000-00000000f01d',+ link: false,+ body: { kind: 'pending' },+ });+ const rendered = render(() => (+ <StaticMarkdownContext>+ <StaticMarkdown+ markdown={`${pending}\n\nAlso <m-await>{"awaitId":"db","text":"Creating database…","inline":true}</m-await>`}+ />+ </StaticMarkdownContext>+ ));+ expect(rendered.getByRole('status').textContent).toContain('Thinking');+ expect(rendered.queryByText(PENDING_REPLY_TEXT)).toBeNull();+ expect(rendered.getByText('Creating database…')).toBeTruthy();+ rendered.unmount();+ });+});+describe('static pull request mentions', () => {it.each([[diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex fafc727441..34aa729796 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -396,7 +396,7 @@ const DocumentMention: TypedRenderableEntity<DocumentMentionNode> = {const shouldRenderLazy = options.lazy;return (- <span class={getTextClassName(props.node, props.theme)}>+ <span class={getTextClassName(props.node, props.theme)} data-mention>{shouldRenderLazy ? (<LazyDecoratorplaceholder={@@ -420,7 +420,7 @@ const AgentSessionMention: TypedRenderableEntity<AgentSessionMentionNode> = {guard: (node: LexicalNode): node is AgentSessionMentionNode =>node.__type === 'agent-session-mention',render: (props) => (- <span class={getTextClassName(props.node, props.theme)}>+ <span class={getTextClassName(props.node, props.theme)} data-mention><AgentSessionMentionDecorator{...props.node.exportComponentProps()}key={props.node.getKey()}@@ -434,7 +434,7 @@ const PullRequestMention: TypedRenderableEntity<PullRequestMentionNode> = {guard: (node: LexicalNode): node is PullRequestMentionNode =>node.__type === 'pr-mention',render: (props) => (- <span class={getTextClassName(props.node, props.theme)}>+ <span class={getTextClassName(props.node, props.theme)} data-mention><PullRequestMentionDecorator{...props.node.exportComponentProps()}key={props.node.getKey()}@@ -530,7 +530,7 @@ const ContactMention: TypedRenderableEntity<ContactMentionNode> = {guard: (node: LexicalNode): node is ContactMentionNode =>node.__type === 'contact-mention',render: (props) => (- <span class={getTextClassName(props.node, props.theme)}>+ <span class={getTextClassName(props.node, props.theme)} data-mention>{ContactMentionDecorator({...props.node.exportComponentProps(),key: props.node.getKey(),diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/Await.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/Await.tsxindex b2518501cf..e6913c48cf 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/Await.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/Await.tsx@@ -1,14 +1,21 @@-import type { AwaitDecoratorProps } from '@macro-inc/lexical-core';-import type { Component } from 'solid-js';+import { AgentThinking } from '@app/features/agent-activity/agent-activity';+import {+ type AwaitDecoratorProps,+ PENDING_REPLY_TEXT,+} from '@macro-inc/lexical-core';+import { type Component, Show } from 'solid-js';export const Await: Component<AwaitDecoratorProps> = (props) => {return (- <span- class="animate-pulse text-current/50 select-none bg-current/5 rounded-xs"- inert- data-await-id={props.awaitId}- >- {props.text ?? 'Waiting…'}- </span>+ // A chat agent's running reply reads as the working line its runs use.+ <Show when={props.text !== PENDING_REPLY_TEXT} fallback={<AgentThinking />}>+ <span+ class="animate-pulse text-current/50 select-none bg-current/5 rounded-xs"+ inert+ data-await-id={props.awaitId}+ >+ {props.text ?? 'Waiting…'}+ </span>+ </Show>);};diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.tsindex 8a8f54a0e3..7e9378749a 100644--- a/apps/web/src/routes/routes.ts+++ b/apps/web/src/routes/routes.ts@@ -742,6 +742,7 @@ const debugComponentIds = ['dynamic-ui','agent-ui','agent-replay',+ 'agent-progress','agent-changes-ui','diff-view-ui',]diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex d47fb775c6..3dd8bd42fc 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -441,13 +441,14 @@ impl ReplyPlacement {/// takes. A thread carries one reply per mention, so the reply is one message/// that grows. A private conversation reads like talking to a teammate, so/// each passage the agent writes is its own message as soon as it is-/// finished, with the steps it took after it attached.+/// finished, with the steps it took to get there; while it works, its typing+/// row says what it is doing.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum VoiceStyle {/// One message per turn, posted when the turn starts and updated in place.Turn,/// One message per passage, posted when the passage is finished; nothing- /// is posted until the agent has something to say or do.+ /// is posted until the agent has something to say.Segments,}diff --git a/crates/agent_harness/src/domain/presenter.rs b/crates/agent_harness/src/domain/presenter.rsindex 3a7d0516cd..bb1b3ac0f7 100644--- a/crates/agent_harness/src/domain/presenter.rs+++ b/crates/agent_harness/src/domain/presenter.rs@@ -13,44 +13,51 @@ mod test;/// One message of a reply shown in/// [`VoiceStyle::Segments`](crate::domain::model::VoiceStyle::Segments): a-/// passage and the steps the agent took after it, or steps alone when the-/// agent got to work before writing anything.+/// passage and the steps the agent took to get to it, or steps alone when the+/// turn ended on them.#[derive(Debug, Clone, PartialEq, Eq)]pub struct PlannedMessage {/// The segments the message shows, in order.pub segments: Vec<ProjectedSegment>,- /// Whether the message can be posted. One that leads with a passage- /// waits until the agent has finished writing it - an unfinished passage- /// streams live instead; one that leads with steps is ready at once.+ /// Whether the message can be posted: once the agent has finished+ /// writing its passage. Until then the conversation's typing row shows+ /// what the agent is doing, so no posted message shows a step running.pub ready: bool,}/// Split a reply into the messages it is shown through.///-/// A message starts at each passage, so boundaries only ever appear at the-/// end as a reply grows: a reply's n-th message stays its n-th message,-/// which is what lets its id be allocated once and reused. Requests for the-/// user are not part of any message: a pending one is answered live, and an-/// answered one is history the agent's next passage takes up.+/// A message ends at each passage, so boundaries only ever appear at the end+/// as a reply grows: a reply's n-th message stays its n-th message, which is+/// what lets its id be allocated once and reused. Steps the turn ends on,+/// with no passage after them, are a message of their own that is posted+/// only once the turn is over. Requests for the user are not part of any+/// message: a pending one is answered live, and an answered one is history+/// the agent's next passage takes up.#[must_use]pub fn plan_messages(segments: &[ProjectedSegment]) -> Vec<PlannedMessage> {let mut planned: Vec<PlannedMessage> = Vec::new();+ let mut steps: Vec<ProjectedSegment> = Vec::new();for segment in segments {match segment.segment.kind {SegmentKind::Interaction => {}- SegmentKind::Prose => planned.push(PlannedMessage {- segments: vec![segment.clone()],- ready: segment.text.is_some(),- }),- SegmentKind::Activity => match planned.last_mut() {- Some(message) => message.segments.push(segment.clone()),- None => planned.push(PlannedMessage {- segments: vec![segment.clone()],- ready: true,- }),- },+ SegmentKind::Activity => steps.push(segment.clone()),+ SegmentKind::Prose => {+ let mut shown = std::mem::take(&mut steps);+ shown.push(segment.clone());+ planned.push(PlannedMessage {+ segments: shown,+ ready: segment.text.is_some(),+ });+ }}}+ if !steps.is_empty() {+ planned.push(PlannedMessage {+ segments: steps,+ ready: false,+ });+ }planned}diff --git a/crates/agent_harness/src/domain/presenter/test.rs b/crates/agent_harness/src/domain/presenter/test.rsindex 5482e2b9de..1db6dbe9f7 100644--- a/crates/agent_harness/src/domain/presenter/test.rs+++ b/crates/agent_harness/src/domain/presenter/test.rs@@ -56,12 +56,12 @@ fn indices(message: &PlannedMessage) -> Vec<u32> {}#[test]-fn each_passage_opens_a_message_that_carries_the_steps_after_it() {+fn each_passage_closes_a_message_that_carries_the_steps_before_it() {let planned = plan_messages(&[- prose(0, Some("Checking first.")),- activity(1, true, 2),- prose(2, Some("Found it.")),- activity(3, false, 1),+ activity(0, true, 2),+ prose(1, Some("Checking first.")),+ activity(2, true, 1),+ prose(3, Some("Found it.")),]);assert_eq!(planned.len(), 2);assert_eq!(indices(&planned[0]), [0, 1]);@@ -70,47 +70,52 @@ fn each_passage_opens_a_message_that_carries_the_steps_after_it() {}#[test]-fn steps_before_any_passage_are_a_message_of_their_own_ready_at_once() {- let planned = plan_messages(&[activity(0, false, 1)]);- assert_eq!(planned.len(), 1);- assert!(planned[0].ready);+fn steps_wait_for_the_passage_they_lead_to() {+ let working = plan_messages(&[prose(0, Some("Narration.")), activity(1, false, 1)]);+ assert_eq!(working.len(), 2);+ assert!(working[0].ready);+ assert!(!working[1].ready, "the typing row shows a run in progress");++ let writing = plan_messages(&[activity(0, true, 1), prose(1, None)]);+ assert_eq!(writing.len(), 1);+ assert!(!writing[0].ready, "an unfinished passage is not posted");}#[test]-fn a_passage_still_being_written_waits_but_keeps_its_place() {- let planned = plan_messages(&[- prose(0, Some("Narration.")),- activity(1, true, 1),- prose(2, None),- ]);+fn steps_the_turn_ends_on_are_a_message_of_their_own() {+ let planned = plan_messages(&closed(vec![+ prose(0, Some("Checking.")),+ activity(1, false, 2),+ ]));assert_eq!(planned.len(), 2);- assert!(planned[0].ready);- assert!(- !planned[1].ready,- "an unfinished passage streams live instead"- );+ assert_eq!(indices(&planned[1]), [1]);}#[test]fn requests_for_the_user_belong_to_no_message() {let planned = plan_messages(&[- prose(0, Some("May I?")),+ activity(0, true, 1),interaction(1),activity(2, true, 1),+ prose(3, Some("Done.")),]);assert_eq!(planned.len(), 1);- assert_eq!(indices(&planned[0]), [0, 2]);+ assert_eq!(indices(&planned[0]), [0, 2, 3]);}#[test]fn a_growing_reply_never_renumbers_its_earlier_messages() {- let early = plan_messages(&[prose(0, Some("A.")), activity(1, false, 1)]);+ let early = plan_messages(&[activity(0, false, 1)]);+ let writing = plan_messages(&[activity(0, true, 1), prose(1, None)]);let later = plan_messages(&[- prose(0, Some("A.")),- activity(1, true, 3),- prose(2, Some("B.")),+ activity(0, true, 1),+ prose(1, Some("A.")),+ activity(2, false, 1),]);- assert_eq!(indices(&early[0]), indices(&later[0]));+ assert_eq!(indices(&early[0]), [0]);+ assert_eq!(indices(&writing[0]), [0, 1]);+ assert_eq!(indices(&later[0]), [0, 1]);+ assert_eq!(indices(&later[1]), [2]);}#[test]diff --git a/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs b/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rsindex e54f7553e4..2a9c022c36 100644--- a/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs+++ b/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs@@ -271,7 +271,7 @@ fn answers(announcer: &AnnouncerMock) -> Vec<String> {}#[tokio::test]-async fn a_private_reply_posts_each_passage_with_its_steps_and_only_the_answer_is_news() {+async fn a_private_reply_posts_each_passage_with_the_steps_before_it_and_only_the_answer_is_news() {use agent_fold::domain::model::{SegmentKind, TurnPhase};let ((service, _, containers, announcer, _), turns) =harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());@@ -289,11 +289,11 @@ async fn a_private_reply_posts_each_passage_with_its_steps_and_only_the_answer_i.await;assert!(announcer.presented().is_empty(),- "an unfinished passage streams live and is not posted"+ "an unfinished passage is not posted");runs(&agent, "t1", "in_progress", "cargo test");- eventually("the narration is posted with its open steps", || {+ eventually("the narration is posted once finished", || {!announcer.presented().is_empty()}).await;@@ -305,7 +305,8 @@ async fn a_private_reply_posts_each_passage_with_its_steps_and_only_the_answer_i.iter().map(|segment| (segment.segment.kind, segment.segment.sealed)).collect::<Vec<_>>(),- [(SegmentKind::Prose, true), (SegmentKind::Activity, false)]+ [(SegmentKind::Prose, true)],+ "the running step shows in the typing row, not the message");assert_eq!(narration.segments[0].text.as_deref(),@@ -330,26 +331,25 @@ async fn a_private_reply_posts_each_passage_with_its_steps_and_only_the_answer_iassert_eq!(finals[0].segments- .last()- .and_then(|segment| segment.text.as_deref()),- Some("All green.")+ .iter()+ .map(|segment| (segment.segment.kind, segment.text.as_deref()))+ .collect::<Vec<_>>(),+ [+ (SegmentKind::Activity, None),+ (SegmentKind::Prose, Some("All green."))+ ],+ "the answer carries the steps that led to it");assert_ne!(finals[0].message_id, narration.message_id,"the answer is a message of its own");- // The narration's message is rewritten once its steps sealed, never posted twice.- let narration_updates: Vec<_> = presented- .iter()- .filter(|reply| reply.message_id == narration.message_id)- .collect();assert!(- narration_updates- .last()- .unwrap()- .segments+ presented.iter()- .all(|segment| segment.segment.sealed)+ .flat_map(|reply| &reply.segments)+ .all(|segment| segment.segment.sealed),+ "no message ever shows a step running: {presented:#?}");assert!(matches!(announcer.typed().last(), Some(typing) if !typing.active),@@ -1124,20 +1124,20 @@ async fn an_open_conversation_answers_while_another_one_bootstraps(pool: sqlx::Passert!(prompt_text(&container.agent(), 1).contains("Asked during the bootstrap"));}-/// A replica that dies mid-turn leaves the messages it posted showing their-/// steps running. Recovery shows each of them closed, the last one with how-/// the turn ended.+/// A replica that dies mid-run has posted its finished passages but not the+/// steps it was running. Recovery posts those steps closed, after the+/// passages, with how the turn ended.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn recovery_closes_the_messages_a_lost_replica_posted(pool: sqlx::PgPool) {+async fn recovery_posts_the_steps_a_lost_replica_left_running(pool: sqlx::PgPool) {use crate::domain::conversation_turns::{ConversationTurnState, ConversationTurnStore};- use agent_fold::domain::model::ActivityStatus;+ use agent_fold::domain::model::{ActivityStatus, SegmentKind};let journal = pg_journal(&pool);let (service, announcer, _signals, container, command) =journaled_conversation(pool, journal.clone()).await;let agent = container.agent();says(&agent, "Checking the tests first.");runs(&agent, "t1", "in_progress", "cargo test");- eventually("the narration is posted with its step running", || {+ eventually("the narration is posted once its step starts", || {!announcer.presented().is_empty()}).await;@@ -1164,7 +1164,23 @@ async fn recovery_closes_the_messages_a_lost_replica_posted(pool: sqlx::PgPool)let presented = announcer.presented();let closed = presented.last().unwrap();- assert_eq!(closed.message_id, narration, "{presented:#?}");+ assert_ne!(closed.message_id, narration, "{presented:#?}");+ assert!(+ presented+ .iter()+ .filter(|reply| reply.message_id == narration)+ .flat_map(|reply| &reply.segments)+ .all(|segment| segment.segment.kind == SegmentKind::Prose),+ "the narration never shows the steps after it: {presented:#?}"+ );+ assert_eq!(+ closed+ .segments+ .iter()+ .map(|segment| segment.segment.kind)+ .collect::<Vec<_>>(),+ [SegmentKind::Activity]+ );assert_eq!(closed.outcome, Some(ReplyOutcome::Failed));assert!(closed.notify);assert!(closed.segments.iter().all(|segment| segment.segment.sealed));diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex a1a6f61b78..ab9ea55673 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -1498,21 +1498,28 @@ chip is a GitHub link instead. The icon and status word follow open /merged / closed. Merging happens from the PR entity's top bar or from a channelMagic Chip's PR row, not from this header chip.+Agent prose sets the documents, sessions, pull requests, and contacts it+mentions in the accent color, as people mentions already are.+Tool rows show the tool's own name without an MCP server or workspace prefix.-Chat MCP rows retain their service icon.-Individual tools appear as bare rows with an icon, tool name, optional detail,-and a right-aligned result summary. The caret on the right opens the results;-it points right when collapsed and down when expanded. Individual results start-collapsed. Existing rich result views retain their own content and controls;+Individual tools appear as bare rows with no icon or indent, in the group+header's tone: the tool name, then any detail and result summary in a dimmer+tone. A successful call shows no outcome. The caret after them appears on hover+or keyboard focus, and always on touch, and the whole row opens the results; it+points right when collapsed and down when expanded. Macro tools such as+**Search** read the same way: the query in the detail tone, the result count+right after it, and found items listed flush below in the row's tone, without+icons. Code search output and read paths open as plain text, not a boxed block.+Individual results start collapsed. Existing rich result views retain their own content and controls;when a result view provides its own disclosure, use that control rather thanadding a second nested disclosure. Counts come from structured responses,edits show additions/deletions, and other tools show their outcome. A Macro-tool call keeps the same label and icon as its successful row in every state,+tool call keeps the same label as its successful row in every state,never the tool's code name: while it runs its text shimmers; a call cut off when-its turn ends reads **Stopped**; a failed call is faded with **Failed** on the-right (for example **Add to calendar · Failed**), and when the tool gave a-reason, **Failed** carries a caret that opens it. Only a call whose arguments do+its turn ends reads **Stopped**; a failed call is faded with **Failed** in the failure+color after its label (for example **Add to calendar Failed**), and when the+tool gave a reason, the row's caret opens it. Only a call whose arguments donot fit the tool (still arriving, or malformed) keeps the summary row with thetool's name. Labels stay in the present tense (**Fetch**, **Load tools**) untila result arrives.@@ -1535,8 +1542,8 @@ and tools requiring user input remain outside these groups so they stay visibleduring other tool bursts. Nested agent activity and code-mode SDK operations eachuse the same peek 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+The group and thought carets sit immediately after their labels and appear on+hover or keyboard focus, and always on touch. Expand an edit row to view its diffs. Result bodies load only when theirrow opens; syntax highlighting may appear after the diff text. Opening a sessionor expanding a group should leave the app responsive, even when the sessioncontains many file edits.@@ -1560,7 +1567,9 @@ Its carets should still expand the results, and reduced motion disables animatioCheck that rich result controls still work and `DisplayResults` stays visiblebetween surrounding groups. In **AgentMessage (end-to-end)**, expand the groupand confirm unknown tools have no individual disclosure or JSON payload. Repeat-at a narrow viewport width.+at a narrow viewport width. `/app/debug/agent-progress` renders the same replies+in a DM, as a channel mention, and in the session, one tab each; **Expand all**+opens every group and tool result at once.A thought row reads **Thinking** and shimmers only while it is the last partof the turn the session is working on. Earlier thoughts settle to **Thought**@@ -1573,9 +1582,13 @@ tool title, and working row settles — earlier turns never shimmer, even onesthe runtime cut off mid-call. Shimmer identifies current activity: an activetool and its containing group can shimmer together; completed rows stay still.Working and Thinking use the same text shimmer and keep its phase when the-status changes. Check both labels in light and dark themes at desktop and phone-widths: one highlight should sweep evenly across the whole label, with no-highlight returning at the opposite edge. With reduced motion, labels stay still.+status changes; both lead with the working dots, a small plus of five dots+that turns to an × and back in 45° steps while its dots brighten one at a time+in a scattered order, so the label stays put when Working becomes Thinking. Check both+labels in light and dark themes at desktop and phone widths: each pass should+lift the whole label quickly from dim, fade it back, and rest dim before the+next, with no highlight returning at the opposite edge. With reduced motion,+labels and dots stay still.### Sharing a sessiondiff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 91874e036f..5c7e16a1c6 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -127,25 +127,38 @@ state, and exclude conversation reservations; genuinespeculative sessions still expire normally.Send normally: no `@` mention is needed. Attachments, references, and quoted-messages use the channel composer. While the agent works, a typing row with its-avatar sits under the newest message: `<name> is thinking`, `is typing`,-`is working`, or `is waiting for an answer`. Below that row, the owner sees the-passage being written as it streams. They also see any live question or-permission request and **Stop**, which cancels the active turn. Answer those-controls to continue. If **Stop** fails, a failure toast appears and the control-becomes available again so you can retry.+messages use the channel composer. While the agent works, a typing row sits+under the newest message: the agent's avatar beside the working line, which+names the step the agent is on, or says what the turn is doing (`Thinking`,+`Writing`, `Working`, or `Waiting for an answer`) between steps and to anyone+who cannot read the session. The owner also gets **Stop** on that row, which+cancels the active turn, and any live question or permission request beneath+it. Answer those controls to continue. If **Stop** fails, a failure toast+appears and the control becomes available again so you can retry.The reply is posted as ordinary messages while the turn runs. Each finished-passage becomes a message. The steps taken between passages show inside the-message as compact rows: a status icon (spinner, check, cross, or warning for-interrupted), a label such as `Ran`, `Read`, `Edited`, or `Searching`, and a-short detail like the command or file name for readers with session access.+passage becomes a message, led by the steps the agent took to get to it, so+nothing is posted until the agent has written something and no message shows+a step running. Steps a turn ends on, with no passage after them (Stop, a+failure), are posted with how it ended. The working line is one shimmering+line, led by the working dots, naming the step in progress by its label alone,+such as `Ran`, `Read`, `Edited`, or `Searching`; the command, query, or file+stays in the session. The next step slides in as it starts, and steps running+at the same time take turns every two seconds. In a DM it is the typing row.+A channel mention's reply in its thread is one message, so the line sits in+it, and reads `Thinking` whenever the turn is running with no open run, before+the first step or while the agent writes after one.+Once a run closes, it folds to a `Used N tools` summary (with+`· N failed` when a step failed), with a caret after it on hover, that opens+to compact rows like the session's tool rows: the label, and **Failed** or+**Interrupted** when a step did not finish.+Documents, sessions, pull requests, and contacts an agent's reply mentions are+set in the accent color.Stored activity snapshots keep the status and label but omit commands and tool-input details, in both shared threads and DMs. A long run shows its latest six-steps behind an `N earlier steps` control. Rows tick live while the run is-open, then freeze-into the snapshot saved in the message. Readers without session access always-see that snapshot. Only the turn's last message notifies. Previews and search+input details, in both shared threads and DMs. The line follows the session+live while the run is open; the summary shows the snapshot saved in the+message. Readers without session access always see that snapshot. Only the+turn's last message notifies. Previews and searchquote the passages, not the steps. Typing refreshes every 3 seconds and clearson its own if the agent's replica dies. Follow-up messages queue in order, andthe bar above the composer counts them (`1 queued`). Editing a sent message@@ -153,6 +166,11 @@ does not invoke the agent again. A reply inside a thread is not part of theconversation: the agent answers it only when mentioned there, in the thread,as in any channel.+The local playground at `/app/debug/agent-progress` shows each of these states+in three tabs: **DM**, **Channel mention** (the reply in its thread), and+**Agent session**, with theme, viewer, and phone-width toggles and a looping+replay of one turn.+Each failed, stopped, or interrupted source message has its own **Retry message**action in the current context. Retry is explicit because an interrupted attemptmay already have performed an external action. Refreshing or reopening thediff --git a/packages/lexical-core/constants.ts b/packages/lexical-core/constants.tsindex 748d098a04..539bb9bd78 100644--- a/packages/lexical-core/constants.ts+++ b/packages/lexical-core/constants.ts@@ -80,3 +80,9 @@ export const SKIP_DOM_SELECTION_TAG = 'skip-dom-selection';* The update was triggered by editor.focus()*/export const FOCUS_TAG = 'focus';++/**+ * The marker a chat agent's reply carries while its turn runs, read as text+ * in notification excerpts, search, and plain-text previews.+ */+export const PENDING_REPLY_TEXT = 'Thinking…';diff --git a/packages/lexical-core/tests/agent-chat-reply.test.ts b/packages/lexical-core/tests/agent-chat-reply.test.tsindex ea1a9291f4..bbbc2d4d00 100644--- a/packages/lexical-core/tests/agent-chat-reply.test.ts+++ b/packages/lexical-core/tests/agent-chat-reply.test.ts@@ -1,6 +1,8 @@+import type { SerializedElementNode } from 'lexical';import { describe, expect, it } from 'vitest';import {AGENT_SESSION_LINK_LABEL,+ type AgentReplySegment,composeAgentChatReply,PENDING_REPLY_TEXT,} from '../utils/agent-chat-reply';@@ -123,25 +125,39 @@ describe('composeAgentChatReply with segments', () => {expect(markdownToPlainText(markdown)).toBe('All tests pass.');});- it('keeps the session link and spinner for a thread reply still running', () => {- const markdown = composeAgentChatReply({- sessionId: SESSION,- body: {- kind: 'segments',- segments: [- { kind: 'activity', turn: 0, segment: 0, rows, sealed: false },- ],- pending: true,- },- });- const state = markdownToSerializedEditorStateWithIds(markdown);- expect(- state.root.children.map((child) =>- child.type === 'paragraph'- ? (child as { children: { type: string }[] }).children[0]?.type- : child.type- )- ).toEqual(['agent-session-mention', 'agent-activity', 'await']);+ it('shows a running thread reply working once: by its open steps, or else the spinner', () => {+ const check = (segments: AgentReplySegment[], expected: string[]) => {+ const markdown = composeAgentChatReply({+ sessionId: SESSION,+ body: { kind: 'segments', segments, pending: true },+ });+ const state = markdownToSerializedEditorStateWithIds(markdown);+ expect(+ state.root.children.map((child) =>+ child.type === 'paragraph'+ ? (child as SerializedElementNode).children[0]?.type+ : child.type+ )+ ).toEqual(expected);+ };+ check(+ [{ kind: 'activity', turn: 0, segment: 0, rows, sealed: false }],+ ['agent-session-mention', 'agent-activity']+ );+ check(+ [+ { kind: 'activity', turn: 0, segment: 0, rows, sealed: true },+ { kind: 'prose', markdown: 'On it.' },+ ],+ ['agent-session-mention', 'agent-activity', 'text', 'await']+ );+ check(+ [+ { kind: 'prose', markdown: 'On it.' },+ { kind: 'activity', turn: 0, segment: 1, rows, sealed: true },+ ],+ ['agent-session-mention', 'text', 'agent-activity', 'await']+ );});it('closes with the footer the harness wrote', () => {diff --git a/packages/lexical-core/utils/agent-chat-reply.ts b/packages/lexical-core/utils/agent-chat-reply.tsindex 2657c90ca0..d115c4c54a 100644--- a/packages/lexical-core/utils/agent-chat-reply.ts+++ b/packages/lexical-core/utils/agent-chat-reply.ts@@ -1,6 +1,7 @@import { createHeadlessEditor } from '@lexical/headless';import { $convertToMarkdownString } from '@lexical/markdown';import { $createParagraphNode, $getRoot } from 'lexical';+import { PENDING_REPLY_TEXT } from '../constants';import { NodeReplacements, SupportedNodeTypes } from '../node-list';import {$createAgentActivityNode,@@ -16,8 +17,7 @@ import { ALL_TRANSFORMERS } from '../transformers';*/export const AGENT_SESSION_LINK_LABEL = 'Agent session';-/** The spinner's caption while a chat agent's turn runs. */-export const PENDING_REPLY_TEXT = 'Thinking…';+export { PENDING_REPLY_TEXT };/*** One segment of an agent's reply, as a message shows it: a passage as the@@ -45,7 +45,10 @@ export type AgentChatReplyBody =| {kind: 'segments';segments: AgentReplySegment[];- /** Show the spinner after the segments: the turn is still running. */+ /**+ * The turn is still running: the spinner follows the segments, unless+ * they end in an open run of steps, which shows the turn working itself.+ */pending?: boolean;/** A closing line the harness wrote: stopped, failed, said nothing. */footer?: string;@@ -145,7 +148,10 @@ export function composeAgentChatReply(reply: AgentChatReply): string {return [head, body.markdown].filter(Boolean).join('\n\n');}const head = chrome(reply, false);- const tail = body.pending ? chrome({ ...reply, link: false }, true) : '';+ const last = body.segments.at(-1);+ const working = last?.kind === 'activity' && !last.sealed;+ const tail =+ body.pending && !working ? chrome({ ...reply, link: false }, true) : '';return [head,...body.segments.map((segment) =>