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
chore(agents): show a loading spinner on Agents sidebar rows while a session is working (#6633)
Wolf Mermelsteinfb84e63c5eec
diff --git a/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx b/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsxindex 581ca6065d..71654bf466 100644--- a/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx+++ b/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx@@ -25,6 +25,9 @@ vi.mock('@queries/agent-session/session', () => ({},}),}));+vi.mock('@core/agent-session/use-session-turn', () => ({+ useSessionTurn: () => turn,+}));vi.mock('@queries/agents/agents', () => ({useAgentsQuery: () => ({ isSuccess: true, data: [] }),}));@@ -62,9 +65,11 @@ const [metadata, setMetadata] = createSignal<{harness: string;pullRequestUrl?: string;}>();+const [turn, setTurn] = createSignal<string | undefined>();afterEach(() => {cleanup();setMetadata(undefined);+ setTurn(undefined);});vi.mock('@solid-primitives/resize-observer', () => ({@@ -194,6 +199,9 @@ describe.each(['home', 'sidebar'] as const)('%s agent rows', (surface) => {expect(view.container.querySelector('[data-coding-icon]')).toBeNull();expect(screen.queryByText('@cursor')).toBeNull();expect(screen.queryByText('Ready')).toBeNull();+ expect(+ view.container.querySelector('[data-session-state="live"]')+ ).toBeTruthy();expect(pr.getAttribute('target')).toBe('_blank');fireEvent.mouseDown(pr, { button: 0, detail: 1 });fireEvent.click(pr);@@ -213,4 +221,17 @@ describe.each(['home', 'sidebar'] as const)('%s agent rows', (surface) => {expect(screen.queryByRole('link')).toBeNull();expect(screen.queryByText('Ready')).toBeNull();});++ it('spins the leading icon while the session turn is still running', () => {+ setTurn('running');+ const { view } = setup();+ expect(+ screen.getByRole('button', { name: 'Fix build, Working' })+ ).toBeTruthy();+ expect(+ view.container.querySelector('[data-session-state="working"]')+ ).toBeTruthy();+ expect(view.container.querySelector('[data-pr-icon]')).toBeNull();+ expect(view.container.querySelector('[data-coding-icon]')).toBeNull();+ });});diff --git a/apps/web/src/features/agents-view/core/conversation-state.test.ts b/apps/web/src/features/agents-view/core/conversation-state.test.tsindex 080933a3a8..e4bd2a9f2a 100644--- a/apps/web/src/features/agents-view/core/conversation-state.test.ts+++ b/apps/web/src/features/agents-view/core/conversation-state.test.ts@@ -18,6 +18,19 @@ describe('conversationState', () => {expect(conversationState('worktree_ready')).toBe('live');});+ it('reads an open fold turn as working, even when the runtime is ready', () => {+ expect(conversationState('acp_ready', 'running')).toBe('working');+ expect(conversationState('acp_ready', 'starting')).toBe('working');+ expect(conversationState('acp_ready', 'stopping')).toBe('working');+ expect(conversationState('no_messages', 'running')).toBe('working');+ });++ it('does not treat a blocked or idle turn as working', () => {+ expect(conversationState('acp_ready', 'blocked')).toBe('live');+ expect(conversationState('acp_ready', 'idle')).toBe('live');+ expect(conversationState('acp_ready', 'disconnected')).toBe('live');+ });+it('reads a dropped transport as ended', () => {expect(conversationState('disconnected')).toBe('ended');expect(conversationState('session/end')).toBe('ended');@@ -25,6 +38,7 @@ describe('conversationState', () => {it('labels each state', () => {expect(conversationStateLabel('starting')).toBe('Starting');+ expect(conversationStateLabel('working')).toBe('Working');expect(conversationStateLabel('live')).toBe('Ready');expect(conversationStateLabel('ended')).toBe('Ended');});diff --git a/apps/web/src/features/agents-view/core/conversation-state.ts b/apps/web/src/features/agents-view/core/conversation-state.tsindex b75a72bb0d..86ac931bdc 100644--- a/apps/web/src/features/agents-view/core/conversation-state.ts+++ b/apps/web/src/features/agents-view/core/conversation-state.ts@@ -1,13 +1,18 @@/**- * What a session's last known runtime status means for a list row.+ * What a session's last known runtime status, and its fold turn, mean for a+ * list row.** Soup carries the wire name of the latest system event (`no_messages`* before the first, `disconnected` when the transport dropped). That is- * coarse — it says whether a runtime is up, not whether a turn is running —- * so the list only distinguishes a session that is coming up, one whose- * runtime is alive, and one whose runtime has gone.+ * coarse — it says whether a runtime is up, not whether a turn is running.+ * The fold's `turn` fills that gap: an open turn is work in progress, even+ * when the last system event was just `acp_ready`.*/-export type ConversationState = 'starting' | 'live' | 'ended';++import { isWorkingTurn } from '@core/agent-session/session-turn';+import type { TurnState } from '@service-agent-fold/generated/types';++export type ConversationState = 'starting' | 'working' | 'live' | 'ended';const STARTING: ReadonlySet<string> = new Set(['no_messages', 'booting']);const ENDED: ReadonlySet<string> = new Set([@@ -17,8 +22,10 @@ const ENDED: ReadonlySet<string> = new Set([]);export function conversationState(- status: string | null | undefined+ status: string | null | undefined,+ turn?: TurnState | null): ConversationState {+ if (isWorkingTurn(turn)) return 'working';if (!status || STARTING.has(status)) return 'starting';if (ENDED.has(status)) return 'ended';return 'live';@@ -28,6 +35,8 @@ export function conversationStateLabel(state: ConversationState): string {switch (state) {case 'starting':return 'Starting';+ case 'working':+ return 'Working';case 'live':return 'Ready';case 'ended':diff --git a/apps/web/src/features/agents-view/views/AgentSessionListItem.tsx b/apps/web/src/features/agents-view/views/AgentSessionListItem.tsxindex 6ec5231704..e29cb8db47 100644--- a/apps/web/src/features/agents-view/views/AgentSessionListItem.tsx+++ b/apps/web/src/features/agents-view/views/AgentSessionListItem.tsx@@ -4,16 +4,19 @@ import {AgentPullRequestLink,} from '@app/features/block-agent/component/AgentPullRequestChip';import { parseGithubPrUrl, prHtmlUrl } from '@app/features/block-pr/util/prKey';+import { useSessionTurn } from '@core/agent-session/use-session-turn';import type { AgentSessionEntity } from '@entity';import ChatIcon from '@phosphor/chat-circle.svg';import CodeIcon from '@phosphor/code.svg';-import SpinnerIcon from '@phosphor/spinner.svg';import { useAgentSessionQuery } from '@queries/agent-session/session';import { useAgentsQuery } from '@queries/agents/agents';import { cn, pressHandlers } from '@ui';import { ErrorBoundary, Show, Suspense } from 'solid-js';import { kindForHarness, modeForKind, systemBotKind } from '../core/agent-kind';-import { conversationState } from '../core/conversation-state';+import {+ conversationState,+ conversationStateLabel,+} from '../core/conversation-state';import { compactAge } from '../core/format-age';import type { AgentsMode } from '../core/mode';import { conversationTimestamp } from '../core/recent-conversations';@@ -52,7 +55,11 @@ function SessionListItem(props: Props) {: (props.mode ?? modeForKind(systemBotKind(botId()) ?? 'agent'));};const title = () => props.entity.name || session()?.name || 'Untitled chat';- const state = () => conversationState(props.entity.status);+ const turn = useSessionTurn(() => props.entity.id);+ const state = () => conversationState(props.entity.status, turn());+ const busy = () => state() === 'starting' || state() === 'working';+ const label = () =>+ busy() ? `${title()}, ${conversationStateLabel(state())}` : title();const pullRequest = () => parseGithubPrUrl(session()?.pullRequestUrl ?? '');const pullRequestUrl = () => {const pr = pullRequest();@@ -69,18 +76,19 @@ function SessionListItem(props: Props) {)}data-agent-session-row={props.entity.id}data-kind={mode()}+ data-session-state={state()}><buttontype="button"class="absolute inset-0 rounded-lg outline-none focus-visible:outline-2 focus-visible:outline-accent"- aria-label={title()}+ aria-label={label()}aria-current={props.active ? 'page' : undefined}title={title()}{...pressHandlers((event) => props.onOpen?.(event))}/><ViewSidebar.Icon class="pointer-events-none relative"><Show- when={state() === 'starting'}+ when={busy()}fallback={<Show when={mode() === 'code'} fallback={<ChatIcon />}><Show when={pullRequestUrl()} fallback={<CodeIcon />}>@@ -95,7 +103,14 @@ function SessionListItem(props: Props) {</Show>}>- <SpinnerIcon class="motion-safe:animate-spin" />+ <span+ aria-hidden="true"+ class="agent-working-wave flex size-4 items-center justify-center gap-[2px] text-ink-muted"+ >+ <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></Show></ViewSidebar.Icon><span class="pointer-events-none relative min-w-0 flex-1">diff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.tsindex b2e2004f07..a7b304535c 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts@@ -41,6 +41,7 @@ vi.mock('@queries/agent-session/queue-sync', () => ({}));import { AgentSession } from './AgentSession';+import { resetSessionTurns, sessionTurn } from './session-turn';const SESSION = '01a0abed-279f-724c-9f49-60dbedc79b6e';@@ -77,6 +78,7 @@ function deferred<T>() {beforeEach(() => {vi.clearAllMocks();+ resetSessionTurns();socket.listeners.clear();// Instances are shared and refcounted, so a test that fails before its// `release()` would hand the next one a session that is already loaded.@@ -380,6 +382,18 @@ describe('AgentSession', () => {live.release();});+ it('publishes the fold turn so list rows can follow a working session', async () => {+ const live = await loadedWith('running');+ expect(sessionTurn(SESSION)).toBe('running');+ fold.pushSession.mockResolvedValueOnce([+ { kind: 'metadata', metadata: { turn: 'idle' } },+ ]);+ AgentSession.ingest({ agentSessionId: SESSION, ...row(2) });+ await settle();+ expect(sessionTurn(SESSION)).toBe('idle');+ live.release();+ });+it('retracts a speculation the server queued after all', async () => {harness.control.mockResolvedValue(ok({ actionId: 'server-id', status: 'queued' })diff --git a/apps/web/src/lib/core/agent-session/AgentSession.ts b/apps/web/src/lib/core/agent-session/AgentSession.tsindex c7b71bb790..ca10446c9f 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.ts@@ -37,6 +37,7 @@ import type {SessionBot,} from '@service-agent-harness/generated/schemas';import { v7 as uuidv7 } from 'uuid';+import { publishSessionTurn } from './session-turn';export type AgentSessionListener = (events: FoldedStreamEvent[]) => void;@@ -114,6 +115,12 @@ export class AgentSession {*/private turn: TurnState = 'idle';+ private setTurn(turn: TurnState | undefined): void {+ const next = turn ?? 'idle';+ this.turn = next;+ publishSessionTurn(this.id, next);+ }+private constructor(id: string) {this.id = id;// Subscribed before the fetch so no row between the two is lost: rows@@ -164,7 +171,7 @@ export class AgentSession {// moves when the worker answers, and two prompts sent inside that// window would both speculate - the second one showing a bubble the// server's `queued` then takes away again.- if (occupiesTurn(action)) this.turn = 'starting';+ if (occupiesTurn(action)) this.setTurn('starting');void this.enqueue({kind: 'speculated',actionId,@@ -220,7 +227,7 @@ export class AgentSession {action: AgentAction,options: { userId?: string } = {}): void {- if (occupiesTurn(action)) this.turn = 'starting';+ if (occupiesTurn(action)) this.setTurn('starting');void this.enqueue({kind: 'speculated',actionId,@@ -316,7 +323,7 @@ export class AgentSession {await this.apply(inputs);}this.ready = true;- this.turn = (await readSession(this.id)).metadata.turn;+ this.setTurn((await readSession(this.id)).metadata.turn);return { session: session.value, bot: log.value.bot };}@@ -346,7 +353,7 @@ export class AgentSession {const events = await pushSession(this.id, inputs);if (this.closed || events.length === 0) return;const metadata = events.findLast((event) => event.kind === 'metadata');- if (metadata) this.turn = metadata.metadata.turn;+ if (metadata) this.setTurn(metadata.metadata.turn);for (const listener of this.listeners) listener(events);});// A failed push must not poison the chain for every input after it.diff --git a/apps/web/src/lib/core/agent-session/session-turn.test.ts b/apps/web/src/lib/core/agent-session/session-turn.test.tsnew file mode 100644index 0000000000..247ef40d2f--- /dev/null+++ b/apps/web/src/lib/core/agent-session/session-turn.test.ts@@ -0,0 +1,48 @@+import { afterEach, describe, expect, it } from 'vitest';+import {+ hasSessionActivity,+ isWorkingTurn,+ noteSessionActivity,+ publishSessionTurn,+ resetSessionTurns,+ sessionTurn,+ subscribeSessionTurns,+} from './session-turn';++afterEach(() => {+ resetSessionTurns();+});++describe('isWorkingTurn', () => {+ it('treats an open or stopping turn as work', () => {+ expect(isWorkingTurn('starting')).toBe(true);+ expect(isWorkingTurn('running')).toBe(true);+ expect(isWorkingTurn('stopping')).toBe(true);+ });++ it('does not treat a settled or blocked turn as work', () => {+ expect(isWorkingTurn('idle')).toBe(false);+ expect(isWorkingTurn('blocked')).toBe(false);+ expect(isWorkingTurn('disconnected')).toBe(false);+ expect(isWorkingTurn(undefined)).toBe(false);+ });+});++describe('session turn store', () => {+ it('publishes a turn and notifies listeners only when it changes', () => {+ const seen: string[] = [];+ const stop = subscribeSessionTurns((id) => seen.push(id));+ publishSessionTurn('a', 'running');+ publishSessionTurn('a', 'running');+ publishSessionTurn('a', 'idle');+ expect(sessionTurn('a')).toBe('idle');+ expect(seen).toEqual(['a', 'a']);+ stop();+ });++ it('marks recent activity for a session nobody has open', () => {+ expect(hasSessionActivity('b')).toBe(false);+ noteSessionActivity('b');+ expect(hasSessionActivity('b')).toBe(true);+ });+});diff --git a/apps/web/src/lib/core/agent-session/session-turn.ts b/apps/web/src/lib/core/agent-session/session-turn.tsnew file mode 100644index 0000000000..b7e9c097f4--- /dev/null+++ b/apps/web/src/lib/core/agent-session/session-turn.ts@@ -0,0 +1,71 @@+/**+ * Last-known fold turn for each session, plus a short-lived "frames are+ * arriving" mark for sessions nobody has open yet.+ *+ * The fold's `turn` is the one answer to "is the agent working". Open+ * sessions publish it as they fold. Unopened sessions only appear here once+ * a live log frame lands — list rows then follow that session until the+ * turn settles.+ */++import type { TurnState } from '@service-agent-fold/generated/types';++/** How long a stray log frame keeps a list row interested in following. */+export const SESSION_ACTIVITY_WINDOW_MS = 120_000;++type Listener = (sessionId: string) => void;++const listeners = new Set<Listener>();+const turns = new Map<string, TurnState>();+const activityUntil = new Map<string, number>();++/** A turn the list should treat as still in motion. */+export function isWorkingTurn(turn: TurnState | null | undefined): boolean {+ return turn === 'starting' || turn === 'running' || turn === 'stopping';+}++/** The last published turn for `sessionId`, if any. */+export function sessionTurn(sessionId: string): TurnState | undefined {+ return turns.get(sessionId);+}++/** Record the fold's turn so list rows can follow without opening the block. */+export function publishSessionTurn(sessionId: string, turn: TurnState): void {+ if (turns.get(sessionId) === turn) return;+ turns.set(sessionId, turn);+ notify(sessionId);+}++/**+ * A live log frame arrived for a session nobody has acquired. List rows+ * treat this as a reason to follow until the fold names a settled turn.+ */+export function noteSessionActivity(sessionId: string): void {+ activityUntil.set(sessionId, Date.now() + SESSION_ACTIVITY_WINDOW_MS);+ notify(sessionId);+}++/** Whether a recent log frame said this session is moving. */+export function hasSessionActivity(sessionId: string): boolean {+ const until = activityUntil.get(sessionId);+ return until !== undefined && until > Date.now();+}++/** Follow turn and activity changes. */+export function subscribeSessionTurns(listener: Listener): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++function notify(sessionId: string): void {+ for (const listener of listeners) listener(sessionId);+}++/** Drop published state between tests. */+export function resetSessionTurns(): void {+ turns.clear();+ activityUntil.clear();+ listeners.clear();+}diff --git a/apps/web/src/lib/core/agent-session/use-session-turn.test.tsx b/apps/web/src/lib/core/agent-session/use-session-turn.test.tsxnew file mode 100644index 0000000000..9d1925824a--- /dev/null+++ b/apps/web/src/lib/core/agent-session/use-session-turn.test.tsx@@ -0,0 +1,53 @@+import { cleanup, render } from '@solidjs/testing-library';+import { afterEach, describe, expect, it, vi } from 'vitest';++const session = vi.hoisted(() => ({+ get: vi.fn(),+ acquire: vi.fn(),+}));++vi.mock('./AgentSession', () => ({+ AgentSession: {+ get: session.get,+ acquire: session.acquire,+ },+}));++import { noteSessionActivity, resetSessionTurns } from './session-turn';+import { useSessionTurn } from './use-session-turn';++afterEach(() => {+ cleanup();+ resetSessionTurns();+ session.get.mockReset();+ session.acquire.mockReset();+});++function Follow(props: { id: string }) {+ const turn = useSessionTurn(() => props.id);+ return <span data-testid="turn">{turn() ?? 'none'}</span>;+}++describe('useSessionTurn', () => {+ it('does not acquire a quiet session nobody has open', () => {+ session.get.mockReturnValue(undefined);+ render(() => <Follow id="quiet" />);+ expect(session.acquire).not.toHaveBeenCalled();+ expect(document.querySelector('[data-testid="turn"]')?.textContent).toBe(+ 'none'+ );+ });++ it('acquires a session that just produced a live frame', () => {+ const load = vi.fn();+ const release = vi.fn();+ session.get.mockReturnValue(undefined);+ session.acquire.mockReturnValue({ load, release });+ noteSessionActivity('live');+ const view = render(() => <Follow id="live" />);+ expect(session.acquire).toHaveBeenCalledWith('live');+ expect(load).toHaveBeenCalledOnce();+ view.unmount();+ expect(release).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/lib/core/agent-session/use-session-turn.ts b/apps/web/src/lib/core/agent-session/use-session-turn.tsnew file mode 100644index 0000000000..328e846bd5--- /dev/null+++ b/apps/web/src/lib/core/agent-session/use-session-turn.ts@@ -0,0 +1,48 @@+/**+ * The fold's turn for a list row: last published value, and a follow of the+ * shared session when one is already open or a live frame just arrived.+ */++import type { TurnState } from '@service-agent-fold/generated/types';+import { type Accessor, createMemo, createSignal, onCleanup } from 'solid-js';+import { AgentSession } from './AgentSession';+import {+ hasSessionActivity,+ isWorkingTurn,+ sessionTurn,+ subscribeSessionTurns,+} from './session-turn';++function shouldFollow(sessionId: string): boolean {+ return (+ AgentSession.get(sessionId) !== undefined ||+ hasSessionActivity(sessionId) ||+ isWorkingTurn(sessionTurn(sessionId))+ );+}++/** Latest fold turn for `sessionId`, followed while the row is mounted. */+export function useSessionTurn(+ sessionId: Accessor<string>+): Accessor<TurnState | undefined> {+ const [epoch, setEpoch] = createSignal(0);+ onCleanup(subscribeSessionTurns(() => setEpoch((current) => current + 1)));++ const follow = createMemo(() => {+ epoch();+ return shouldFollow(sessionId());+ });++ createMemo(() => {+ const id = sessionId();+ if (!follow()) return;+ const session = AgentSession.acquire(id);+ void session.load();+ onCleanup(() => session.release());+ });++ return () => {+ epoch();+ return sessionTurn(sessionId());+ };+}diff --git a/apps/web/src/lib/queries/sync/SyncProvider.tsx b/apps/web/src/lib/queries/sync/SyncProvider.tsxindex f4285f9bd2..4bb3fb6987 100644--- a/apps/web/src/lib/queries/sync/SyncProvider.tsx+++ b/apps/web/src/lib/queries/sync/SyncProvider.tsx@@ -1,4 +1,5 @@import { AgentSession } from '@core/agent-session/AgentSession';+import { noteSessionActivity } from '@core/agent-session/session-turn';import {enableGraphqlSoup,isFeatureEnabled,@@ -116,7 +117,12 @@ export function QuerySyncProvider(props: SyncProviderProps) {withParsedWebsocketPayload<AgentSessionLogEvent>(data.type,data.data,- (event) => AgentSession.ingest(event)+ (event) => {+ AgentSession.ingest(event);+ if (!AgentSession.get(event.agentSessionId)) {+ noteSessionActivity(event.agentSessionId);+ }+ });}).with({ type: AGENT_SESSION_UPDATED_EVENT }, () => {diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 2267052598..15945f5875 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -15,7 +15,11 @@of chats and coding sessions, newest first, with one search across both.Chat rows use a chat icon; coding rows use `</>` (the PR status icon when apull request is linked). Home and the Agents sidebar share these agent rows.- Rows have no agent or runtime-status subtext. Sessions with a linked PR show+ Rows have no agent or runtime-status subtext. A session that is starting or+ whose turn is still running (the agent is working, writing code, or stopping)+ shows the same three-dot working wave as the transcript in place of the+ leading icon; the row's accessible name appends `Starting` or `Working`.+ Sessions with a linked PR show**View PR #<number> in GitHub** beneath the title; clicking it opens the syncedGitHub PR entity in a split (the same destination as the session header chipand Magic Chip). Until GitHub has synced the entity it opens GitHub in a new