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(agents): show coding agent updates on the Agents home (#9246)
Eric Hayes0282b7c4fdca
diff --git a/.sqlx/query-c416637508bd8cb0ca1b654c04e7778b05de47a979b9879f62d546232b9cec6e.json b/.sqlx/query-c416637508bd8cb0ca1b654c04e7778b05de47a979b9879f62d546232b9cec6e.jsonnew file mode 100644index 0000000000..93466422f3--- /dev/null+++ b/.sqlx/query-c416637508bd8cb0ca1b654c04e7778b05de47a979b9879f62d546232b9cec6e.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT s.id, s.name, s.harness, s.pull_request_url, s.turn_state,\n s.is_archived, GREATEST(s.modified_at, recent.created_at) AS \"last_activity!\"\n FROM agent_session s\n LEFT JOIN agent_configs config ON config.bot_id = s.bot_id\n LEFT JOIN LATERAL (\n SELECT created_at FROM agent_session_log\n WHERE agent_session_id = s.id ORDER BY created_at DESC LIMIT 1\n ) recent ON true\n WHERE s.owner_id = $1 AND NOT s.is_archived\n AND COALESCE(config.is_coding, s.harness NOT IN ('in-memory', 'macro-inmem'))\n AND (s.turn_state = 'blocked' OR\n (s.turn_state = 'running' AND GREATEST(s.modified_at, recent.created_at) <= now() - interval '20 minutes'))\n ORDER BY GREATEST(s.modified_at, recent.created_at) DESC, s.id DESC\n LIMIT 26\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "harness",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "pull_request_url",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "turn_state",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "is_archived",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "last_activity!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ false,+ null+ ]+ },+ "hash": "c416637508bd8cb0ca1b654c04e7778b05de47a979b9879f62d546232b9cec6e"+}diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex ca9d8ec6c3..506de84fd9 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -82,6 +82,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ImportPipelineCsv](/AI/mcp/tools/import-pipeline-csv)- [IssueBotCredential](/AI/mcp/tools/issue-bot-credential)- [ListAgents](/AI/mcp/tools/list-agents)+- [ListAgentUpdates](/AI/mcp/tools/list-agent-updates)- [ListBookingLinks](/AI/mcp/tools/list-booking-links)- [ListBookings](/AI/mcp/tools/list-bookings)- [ListBots](/AI/mcp/tools/list-bots)diff --git a/apps/docs/AI/mcp/tools/list-agent-updates.mdx b/apps/docs/AI/mcp/tools/list-agent-updates.mdxnew file mode 100644index 0000000000..f6d3b1c79b--- /dev/null+++ b/apps/docs/AI/mcp/tools/list-agent-updates.mdx@@ -0,0 +1,10 @@+---+title: ListAgentUpdates+description: >-+ List the current user's coding-agent sessions waiting for an answer or stalled+ for over 20 minutes.+---++# ListAgentUpdates++List the current user's coding-agent sessions waiting for an answer or stalled for over 20 minutes. The user answers permissions and questions through the cards Macro renders from this tool's result. To send a coding agent instructions, use ManageAgentSession with a prompt. To recall the user's earlier decisions about these agents, search earlier agent conversations with ContentSearch (entity_types agent_sessions) and read them with ReadAgentSession.diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex ac516e9cac..80ffaa2db5 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -73,6 +73,7 @@"AI/mcp/tools/import-pipeline-csv","AI/mcp/tools/issue-bot-credential","AI/mcp/tools/list-agents",+ "AI/mcp/tools/list-agent-updates","AI/mcp/tools/list-booking-links","AI/mcp/tools/list-bookings","AI/mcp/tools/list-bots",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 077c9e3231..89e4270e9c 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -177,6 +177,7 @@"AI/mcp/tools/import-pipeline-csv","AI/mcp/tools/issue-bot-credential","AI/mcp/tools/list-agents",+ "AI/mcp/tools/list-agent-updates","AI/mcp/tools/list-booking-links","AI/mcp/tools/list-bookings","AI/mcp/tools/list-bots",diff --git a/apps/web/src/components/ui/components/NotificationStack.docs.tsx b/apps/web/src/components/ui/components/NotificationStack.docs.tsxnew file mode 100644index 0000000000..6ecb904ce8--- /dev/null+++ b/apps/web/src/components/ui/components/NotificationStack.docs.tsx@@ -0,0 +1,94 @@+import { defineDoc } from '@app/features/ui-gallery/types';+import { createSignal, Show } from 'solid-js';+import { Button } from './Button';+import { NotificationStack } from './NotificationStack';++// #region demo:updates+function UpdatesDemo() {+ const [updates, setUpdates] = createSignal([+ {+ id: 'approval',+ agent: 'desktop-cef',+ message: 'Needs approval to sign the app bundle.',+ age: '2m',+ },+ {+ id: 'question',+ agent: 'sdk-soup-endpoint',+ message: 'Asked whether refreshSoup should be public.',+ age: '4m',+ },+ {+ id: 'stalled',+ agent: 'pdf-overlay-zoom',+ message: 'The build has been stalled for 23 minutes.',+ age: '23m',+ },+ {+ id: 'review',+ agent: 'granola-refresh',+ message: 'The fix is green and ready for review.',+ age: '6m',+ },+ ]);+ return (+ <div class="w-full max-w-xl">+ <NotificationStack+ label="Coding agent updates"+ title={+ <span class="font-semibold">+ {updates().length} updates from coding agents+ </span>+ }+ items={updates()}+ itemKey={(item) => item.id}+ >+ {(item) => (+ <div class="flex items-start gap-3 p-3 text-sm">+ <div class="min-w-0 flex-1">+ <div class="font-semibold text-ink">{item.agent}</div>+ <div class="text-ink-muted">{item.message}</div>+ <div class="mt-1 text-xs text-ink-extra-muted">+ {item.age} ago+ </div>+ </div>+ <Button+ size="sm"+ variant="ghost"+ onClick={() =>+ setUpdates((current) =>+ current.filter((update) => update.id !== item.id)+ )+ }+ >+ Dismiss+ </Button>+ </div>+ )}+ </NotificationStack>+ <Show when={updates().length === 0}>+ <p class="px-2 text-sm text-ink-muted">All updates dismissed</p>+ </Show>+ </div>+ );+}+// #endregion++export default defineDoc({+ name: 'NotificationStack',+ category: 'Data Display',+ status: 'beta',+ exports: ['NotificationStack'],+ import: "import { NotificationStack } from '@ui';",+ description:+ 'Groups a short queue of independent updates into a compact stack. The front card stays actionable; Show all reveals every card. Cards use stable keys so removals can animate.',+ demos: [+ {+ id: 'updates',+ title: 'Coding agent updates',+ description: 'Expand the stack or dismiss individual updates.',+ render: UpdatesDemo,+ fill: true,+ },+ ],+});diff --git a/apps/web/src/components/ui/components/NotificationStack.test.tsx b/apps/web/src/components/ui/components/NotificationStack.test.tsxnew file mode 100644index 0000000000..845b7b9436--- /dev/null+++ b/apps/web/src/components/ui/components/NotificationStack.test.tsx@@ -0,0 +1,128 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { NotificationStack } from './NotificationStack';++beforeEach(() => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++it('keeps only the front card interactive until Show all is pressed', () => {+ const first = vi.fn();+ const second = vi.fn();+ render(() => (+ <NotificationStack+ label="Agent updates"+ title="2 updates"+ items={[{ id: 'first' }, { id: 'second' }]}+ itemKey={(item) => item.id}+ >+ {(item) => (+ <button onClick={item.id === 'first' ? first : second}>+ {item.id}+ </button>+ )}+ </NotificationStack>+ ));+ const region = screen.getByRole('region', { name: 'Agent updates' });+ const toggle = screen.getByRole('button', { name: 'Show all' });+ expect(toggle.getAttribute('aria-expanded')).toBe('false');+ expect(toggle.getAttribute('aria-controls')).toBe(+ region.querySelector('div[id]')?.id+ );+ expect(screen.getAllByRole('article')).toHaveLength(1);+ expect(region.querySelectorAll('article')[1]?.inert).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'first' }));+ expect(first).toHaveBeenCalledOnce();+ expect(toggle.getAttribute('aria-expanded')).toBe('false');++ fireEvent.click(toggle);+ expect(+ screen+ .getByRole('button', { name: 'Show less' })+ .getAttribute('aria-expanded')+ ).toBe('true');+ expect(screen.getAllByRole('article')).toHaveLength(2);+ expect(region.querySelectorAll('article')[1]?.inert).toBe(false);+ fireEvent.click(screen.getByRole('button', { name: 'second' }));+ expect(second).toHaveBeenCalledOnce();+ fireEvent.click(screen.getByRole('button', { name: 'Show less' }));+ expect(+ screen+ .getByRole('button', { name: 'Show all' })+ .getAttribute('aria-expanded')+ ).toBe('false');+});++it('expands from the stack body but not from an action inside the front card', () => {+ const action = vi.fn();+ render(() => (+ <NotificationStack+ label="Agent updates"+ title="2 updates"+ items={[1, 2]}+ itemKey={String}+ >+ {(item) => (+ <div>+ <span>Update {item}</span>+ <button onClick={action}>Act</button>+ </div>+ )}+ </NotificationStack>+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Act' }));+ expect(action).toHaveBeenCalledOnce();+ expect(screen.getByRole('button', { name: 'Show all' })).toBeTruthy();+ fireEvent.click(screen.getByText('Update 1'));+ expect(screen.getByRole('button', { name: 'Show less' })).toBeTruthy();+});++it('closes and hides the toggle when one item remains', () => {+ const [items, setItems] = createSignal([1, 2]);+ render(() => (+ <NotificationStack+ label="Agent updates"+ title="Updates"+ items={items()}+ itemKey={String}+ >+ {(item) => <span>Update {item}</span>}+ </NotificationStack>+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Show all' }));+ setItems([1]);+ expect(screen.queryByRole('button', { name: 'Show less' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Show all' })).toBeNull();+ expect(screen.getAllByRole('article')).toHaveLength(1);+});++it('renders nothing for an empty list', () => {+ const [items, setItems] = createSignal<number[]>([]);+ const { container } = render(() => (+ <NotificationStack+ label="Agent updates"+ title="Updates"+ items={items()}+ itemKey={String}+ >+ {(item) => <span>{item}</span>}+ </NotificationStack>+ ));+ expect(container.querySelector('section')).toBeNull();+ setItems([1]);+ expect(screen.getByRole('region', { name: 'Agent updates' })).toBeTruthy();+ setItems([]);+ expect(container.querySelector('section')).toBeNull();+});diff --git a/apps/web/src/components/ui/components/NotificationStack.tsx b/apps/web/src/components/ui/components/NotificationStack.tsxnew file mode 100644index 0000000000..6b25e61375--- /dev/null+++ b/apps/web/src/components/ui/components/NotificationStack.tsx@@ -0,0 +1,240 @@+import { createResizeObserver } from '@solid-primitives/resize-observer';+import {+ createEffect,+ createSignal,+ createUniqueId,+ For,+ type JSX,+ on,+ onCleanup,+ onMount,+ Show,+ untrack,+} from 'solid-js';+import { Button } from './Button';++const GAP = 8;+const PEEK = 9;+const EXIT_DURATION = 250;++type StackEntry<T> = {+ key: string;+ item: () => T;+ setItem: (item: T) => void;+ leaving: () => boolean;+ setLeaving: (leaving: boolean) => void;+};++export type NotificationStackProps<T> = {+ /** Accessible name for the stack region. */+ label: string;+ /** Header content shown above the stack, e.g. a count of pending items. */+ title: JSX.Element;+ items: readonly T[];+ /** Stable identity; keys the card across reorders and removals. */+ itemKey: (item: T) => string;+ /**+ * Renders one card's content, once per key like `For`. The stack draws the+ * card surface; read live data inside the card, not from a new item object.+ */+ children: (item: T) => JSX.Element;+ /** Controlled disclosure state. A stack with fewer than two items always closes. */+ expanded?: boolean;+ onExpandedChange?: (expanded: boolean) => void;+};++/**+ * Cards that rest as a stack, the newest in front, and unstack into a list.+ * @do Use for a short queue of independent items that each need attention.+ * @do Keep each card self-contained: its actions act on that item only.+ */+export function NotificationStack<T>(props: NotificationStackProps<T>) {+ const cardsId = createUniqueId();+ const [localExpanded, setLocalExpanded] = createSignal(false);+ const [entries, setEntries] = createSignal<StackEntry<T>[]>([]);+ const [heights, setHeights] = createSignal<Record<string, number>>({});+ const exitTimers = new Map<string, ReturnType<typeof setTimeout>>();+ const expanded = () =>+ props.items.length > 1 && (props.expanded ?? localExpanded());+ const heightOf = (entry: StackEntry<T>) => heights()[entry.key] ?? 2;+ const frontHeight = () => (entries()[0] ? heightOf(entries()[0]) : 0);+ const cardTop = (index: number) =>+ expanded()+ ? entries()+ .slice(0, index)+ .reduce((top, entry) => top + heightOf(entry) + GAP, 0)+ : Math.min(index, 2) * PEEK;+ const stackHeight = () =>+ expanded()+ ? entries().reduce(+ (height, entry) => height + heightOf(entry) + GAP,+ -GAP+ )+ : frontHeight() + Math.min(entries().length - 1, 2) * PEEK;++ const setExpanded = (value: boolean) => {+ if (props.expanded === undefined) setLocalExpanded(value);+ props.onExpandedChange?.(value);+ };++ // Presence is stateful so a removed card can finish its exit before the gap closes.+ createEffect(+ on(+ () => props.items,+ (items) => {+ const previous = entries();+ const byKey = new Map(previous.map((entry) => [entry.key, entry]));+ const next = items.map((item) => {+ const key = props.itemKey(item);+ const existing = byKey.get(key);+ if (existing) {+ const timer = exitTimers.get(key);+ if (timer) clearTimeout(timer);+ exitTimers.delete(key);+ existing.setItem(item);+ existing.setLeaving(false);+ return existing;+ }+ const [currentItem, setItem] = createSignal(item);+ const [leaving, setLeaving] = createSignal(false);+ return { key, item: currentItem, setItem, leaving, setLeaving };+ });+ const currentKeys = new Set(items.map(props.itemKey));+ for (const [index, entry] of previous.entries()) {+ if (currentKeys.has(entry.key)) continue;+ if (!entry.leaving()) {+ entry.setLeaving(true);+ if (+ typeof window !== 'undefined' &&+ window.matchMedia?.('(prefers-reduced-motion: reduce)').matches+ )+ continue;+ const timer = setTimeout(() => {+ exitTimers.delete(entry.key);+ setEntries((current) => current.filter((card) => card !== entry));+ }, EXIT_DURATION);+ exitTimers.set(entry.key, timer);+ }+ if (exitTimers.has(entry.key))+ next.splice(Math.min(index, next.length), 0, entry);+ }+ setEntries(next);+ if (items.length < 2 && (props.expanded ?? localExpanded()))+ setExpanded(false);+ }+ )+ );+ onCleanup(() => {+ for (const timer of exitTimers.values()) clearTimeout(timer);+ });++ const measure = (key: string, element: HTMLElement) => {+ const height = element.getBoundingClientRect().height + 2;+ setHeights((current) =>+ current[key] === height ? current : { ...current, [key]: height }+ );+ };++ return (+ <Show when={props.items.length > 0}>+ <section aria-label={props.label} class="flex flex-col gap-2">+ <div class="flex min-h-7 items-center gap-2 px-2 text-sm">+ {props.title}+ <Show when={props.items.length > 1}>+ <Button+ size="sm"+ variant="ghost"+ class="ml-auto"+ aria-expanded={expanded()}+ aria-controls={cardsId}+ onClick={() => setExpanded(!expanded())}+ >+ {expanded() ? 'Show less' : 'Show all'}+ </Button>+ </Show>+ </div>+ <div+ id={cardsId}+ class="relative motion-safe:transition-[height] motion-safe:duration-[420ms] motion-safe:ease-[cubic-bezier(0.22,1,0.36,1)]"+ style={{ height: `${Math.max(0, stackHeight())}px` }}+ onClick={(event) => {+ if (expanded() || props.items.length < 2) return;+ if (+ event.target instanceof Element &&+ event.target.closest(+ 'button, a, input, textarea, select, [role="button"]'+ )+ )+ return;+ setExpanded(true);+ }}+ >+ <For each={entries()}>+ {(entry, index) => {+ let content: HTMLDivElement | undefined;+ const [entering, setEntering] = createSignal(true);+ const behind = () => !expanded() && index() > 0;+ const hidden = () => entry.leaving() || behind();+ const cardHeight = () =>+ expanded() ? heightOf(entry) : frontHeight();+ createResizeObserver(+ () => content,+ (_rect, element) => measure(entry.key, element)+ );+ onMount(() => {+ if (content) measure(entry.key, content);+ const frame = requestAnimationFrame(() => setEntering(false));+ onCleanup(() => cancelAnimationFrame(frame));+ });+ return (+ <article+ data-notification-key={entry.key}+ aria-hidden={hidden()}+ inert={hidden()}+ class="absolute inset-x-0 top-0 box-border overflow-hidden rounded-2xl border border-edge-frame shadow-sm motion-safe:transition-[top,height,transform,opacity,background-color,box-shadow] motion-safe:[transition-duration:420ms,420ms,420ms,250ms,200ms,200ms] motion-safe:ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none"+ classList={{+ 'bg-panel': !behind(),+ 'bg-surface-3': behind(),+ 'pointer-events-none': hidden(),+ 'not-touch:hover:shadow-md': !expanded() && index() === 0,+ }}+ style={{+ top: `${cardTop(index())}px`,+ height: `${cardHeight()}px`,+ transform:+ entry.leaving() || entering()+ ? 'scale(0.96)'+ : expanded()+ ? 'scale(1)'+ : `scale(${1 - Math.min(index(), 2) * 0.045})`,+ opacity:+ entry.leaving() || entering() || (behind() && index() > 2)+ ? 0+ : 1,+ // Behind cards shrink toward their bottom edge so the whole offset peeks out.+ 'transform-origin': behind()+ ? 'center bottom'+ : 'center top',+ 'z-index': entries().length - index(),+ 'transition-delay':+ expanded() && !entry.leaving()+ ? `${index() * 30}ms`+ : '0ms',+ }}+ >+ <div+ ref={content}+ class="flow-root motion-safe:transition-opacity motion-safe:duration-200 motion-reduce:transition-none"+ classList={{ 'opacity-0': behind() }}+ >+ {untrack(() => props.children(entry.item()))}+ </div>+ </article>+ );+ }}+ </For>+ </div>+ </section>+ </Show>+ );+}diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.tsindex bcf578b867..df71b721ab 100644--- a/apps/web/src/components/ui/index.ts+++ b/apps/web/src/components/ui/index.ts@@ -140,6 +140,10 @@ export { Layer } from './components/Layer';export { LogoProgress } from './components/LogoProgress';export type { NavRowProps } from './components/NavRow';export { NavRow } from './components/NavRow';+export {+ NotificationStack,+ type NotificationStackProps,+} from './components/NotificationStack';export type {NumberUnitInputDecrementProps,NumberUnitInputIncrementProps,diff --git a/apps/web/src/features/agent-updates/components/AgentUpdateCard.tsx b/apps/web/src/features/agent-updates/components/AgentUpdateCard.tsxnew file mode 100644index 0000000000..03b0449682--- /dev/null+++ b/apps/web/src/features/agent-updates/components/AgentUpdateCard.tsx@@ -0,0 +1,156 @@+import { LiveQuestionCard } from '@app/features/agent-interactions/components/LiveElicitation';+import { fireAndForget } from '@core/util/fireAndForget';+import type { PendingInteraction } from '@service-agent-fold/generated/types';+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';+import { Button } from '@ui';+import { For, Show } from 'solid-js';+import { match } from 'ts-pattern';+import { compactAge } from '../../agents-view/core/format-age';+import type { AgentUpdate } from '../core/agent-update';++export type UpdateAnswer = {+ optionId?: string;+ elicitation?: ElicitationAnswer;+ approval?: 'approve' | 'approve_and_remember' | 'deny';+};++function RequestActions(props: {+ request: PendingInteraction;+ answering: boolean;+ onAnswer: (answer: UpdateAnswer) => Promise<boolean>;+}) {+ const send = (answer: UpdateAnswer) =>+ fireAndForget(props.onAnswer(answer), 'agent-updates');+ return (+ <div class="mt-2 flex flex-wrap items-center gap-1 pl-4">+ {match(props.request)+ .with({ kind: 'permission' }, (permission) => (+ <For each={permission.options}>+ {(option) => (+ <Button+ type="button"+ variant="outline"+ size="sm"+ class="touch:min-h-11"+ disabled={props.answering}+ onClick={() => send({ optionId: option.id })}+ >+ {option.name}+ </Button>+ )}+ </For>+ ))+ .with({ kind: 'tool_approval' }, () => (+ <>+ <Button+ type="button"+ variant="outline"+ size="sm"+ class="touch:min-h-11"+ disabled={props.answering}+ onClick={() => send({ approval: 'approve' })}+ >+ Approve+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ class="touch:min-h-11"+ disabled={props.answering}+ onClick={() => send({ approval: 'approve_and_remember' })}+ >+ Always allow+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ class="touch:min-h-11"+ disabled={props.answering}+ onClick={() => send({ approval: 'deny' })}+ >+ Deny+ </Button>+ </>+ ))+ .with({ kind: 'elicitation' }, (elicitation) => (+ <div class="w-full">+ <LiveQuestionCard+ request={+ elicitation.request.kind === 'user_tool'+ ? { kind: 'form', schema: elicitation.request.schema }+ : elicitation.request+ }+ locked={props.answering}+ onRespond={(answer) => props.onAnswer({ elicitation: answer })}+ />+ </div>+ ))+ .exhaustive()}+ </div>+ );+}++/** A card renders one update and delegates every action to its host. */+export function AgentUpdateCard(props: {+ update: AgentUpdate;+ answering: boolean;+ onAnswer: (answer: UpdateAnswer) => Promise<boolean>;+ /** Omitted where there is no composer to attach the update to. */+ onChatAbout?: () => void;+ onOpenSession: () => void;+}) {+ const request = () =>+ props.update.kind === 'interaction' ? props.update.request : undefined;+ return (+ <div class="min-w-0 p-3 text-sm text-ink">+ <div class="flex min-w-0 items-start gap-2">+ <span+ class="mt-1.5 size-2 shrink-0 rounded-full bg-warning"+ aria-hidden="true"+ />+ <div class="min-w-0 flex-1">+ <div class="font-semibold truncate">{props.update.sessionName}</div>+ <p class="text-ink-muted truncate">{props.update.summary}</p>+ </div>+ <span class="shrink-0 text-xs text-ink-extra-muted">+ {compactAge(props.update.updatedAt)}+ </span>+ </div>+ <Show when={request()}>+ {(value) => (+ <RequestActions+ request={value()}+ answering={props.answering}+ onAnswer={props.onAnswer}+ />+ )}+ </Show>+ <div class="mt-2 flex flex-wrap gap-1 pl-4">+ <Show when={props.onChatAbout}>+ {(onChatAbout) => (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ class="touch:min-h-11"+ onClick={() => onChatAbout()()}+ >+ Chat about this+ </Button>+ )}+ </Show>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ class="touch:min-h-11"+ onClick={props.onOpenSession}+ >+ Open session+ </Button>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/agent-updates/core/agent-update.test.ts b/apps/web/src/features/agent-updates/core/agent-update.test.tsnew file mode 100644index 0000000000..dd88c781a5--- /dev/null+++ b/apps/web/src/features/agent-updates/core/agent-update.test.ts@@ -0,0 +1,143 @@+import type { PendingInteraction } from '@service-agent-fold/generated/types';+import { describe, expect, it } from 'vitest';+import {+ blockedSessions,+ eligibleSessions,+ selectAgentUpdates,+ type UpdateSession,+} from './agent-update';++const now = new Date('2026-10-30T12:00:00Z').getTime();+const mine: UpdateSession = {+ id: 'mine',+ name: 'Fix build',+ ownerId: 'me',+ botId: 'bot',+ harness: 'cursor',+ turnState: 'blocked',+ updatedAt: new Date(now - 3 * 60_000).toISOString(),+};++describe('agent updates selection', () => {+ it('keeps only owned, live coding sessions and acquires only blocked ones', () => {+ const eligible = eligibleSessions(+ [+ mine,+ { ...mine, id: 'other', ownerId: 'someone' },+ { ...mine, id: 'archived', isArchived: true },+ { ...mine, id: 'chat', harness: 'in-memory' },+ { ...mine, id: 'running', turnState: 'running' },+ ],+ 'me'+ );+ expect(eligible.map((session) => session.id)).toEqual(['mine', 'running']);+ expect(blockedSessions(eligible).map((session) => session.id)).toEqual([+ 'mine',+ ]);+ });++ it('makes one card per pending request and sorts newer sessions first', () => {+ const pending: PendingInteraction[] = [+ {+ kind: 'permission',+ requestId: 1,+ turn: 2,+ toolCall: 'tool',+ options: [{ id: 'yes', name: 'Allow', kind: 'allow_once' }],+ },+ {+ kind: 'elicitation',+ requestId: 2,+ turn: 2,+ toolCall: null,+ message: 'Which branch?',+ request: { kind: 'unrecognized', mode: 'test', raw: null },+ },+ {+ kind: 'tool_approval',+ approvalId: 'approval',+ turn: 2,+ serverSlug: 'linear',+ serverName: 'Linear',+ toolName: 'search',+ requestedBy: null,+ },+ ];+ const updates = selectAgentUpdates(+ [+ mine,+ {+ ...mine,+ id: 'newer',+ updatedAt: new Date(now - 60_000).toISOString(),+ },+ ],+ new Map([+ ['mine', pending],+ ['newer', pending.slice(0, 1)],+ ]),+ new Map(),+ now+ );+ expect(updates).toHaveLength(4);+ expect(updates[0]?.sessionId).toBe('newer');+ expect(updates.map((update) => update.summary)).toContain('Has a question');+ expect(updates.map((update) => update.summary)).toContain(+ 'Wants to use search from Linear'+ );+ });++ it('shows a running session only after twenty minutes of inactivity', () => {+ const updates = selectAgentUpdates(+ [+ {+ ...mine,+ id: 'fresh',+ turnState: 'running',+ updatedAt: new Date(now - 20 * 60_000).toISOString(),+ },+ {+ ...mine,+ id: 'stalled',+ turnState: 'running',+ updatedAt: new Date(now - 23 * 60_000).toISOString(),+ },+ ],+ new Map(),+ new Map(),+ now+ );+ expect(updates.map((update) => update.sessionId)).toEqual(['stalled']);+ expect(updates[0]?.summary).toBe('No activity for 23 minutes');+ });++ it('keeps requests with a reused request id distinct across turns', () => {+ const updates = selectAgentUpdates(+ [mine],+ new Map([+ [+ 'mine',+ [+ {+ kind: 'permission',+ requestId: 1,+ turn: 1,+ toolCall: 'first',+ options: [],+ },+ {+ kind: 'permission',+ requestId: 1,+ turn: 2,+ toolCall: 'second',+ options: [],+ },+ ],+ ],+ ]),+ new Map(),+ now+ );+ expect(new Set(updates.map((update) => update.id)).size).toBe(2);+ });+});diff --git a/apps/web/src/features/agent-updates/core/agent-update.ts b/apps/web/src/features/agent-updates/core/agent-update.tsnew file mode 100644index 0000000000..332442dfb4--- /dev/null+++ b/apps/web/src/features/agent-updates/core/agent-update.ts@@ -0,0 +1,132 @@+import type { AgentSessionEntity } from '@entity';+import type {+ FoldedMessage,+ PendingInteraction,+} from '@service-agent-fold/generated/types';+import { match } from 'ts-pattern';+import {+ isCoderHarness,+ systemBotKind,+} from '../../agents-view/core/agent-kind';++export type AgentUpdate = {+ id: string;+ sessionId: string;+ sessionName: string;+ updatedAt: number;+ summary: string;+} & (+ | { kind: 'stalled' }+ | { kind: 'interaction'; request: PendingInteraction }+);++export type UpdateSession = Pick<+ AgentSessionEntity,+ | 'id'+ | 'name'+ | 'ownerId'+ | 'isArchived'+ | 'harness'+ | 'botId'+ | 'turnState'+ | 'updatedAt'+>;++export function eligibleSessions(+ sessions: readonly UpdateSession[],+ ownerId: string | undefined+): UpdateSession[] {+ if (!ownerId) return [];+ return sessions.filter(+ (session) =>+ session.ownerId === ownerId &&+ !session.isArchived &&+ (isCoderHarness(session.harness) ||+ (!session.harness && systemBotKind(session.botId) === 'coder'))+ );+}++export function blockedSessions(+ sessions: readonly UpdateSession[]+): UpdateSession[] {+ return sessions.filter((session) => session.turnState === 'blocked');+}++function timestamp(session: UpdateSession): number {+ const value = session.updatedAt ? new Date(session.updatedAt).getTime() : 0;+ return Number.isFinite(value) ? value : 0;+}++function summary(+ request: PendingInteraction,+ messages: readonly FoldedMessage[]+): string {+ return match(request)+ .with({ kind: 'permission' }, (permission) => {+ const tool = messages+ .find(+ (message) =>+ message.author.kind === 'agent' && message.turn === permission.turn+ )+ ?.parts.find(+ (part) => part.kind === 'tool_use' && part.id === permission.toolCall+ );+ if (tool?.kind !== 'tool_use') return 'Wants permission to run a tool';+ const label =+ tool.detail.kind === 'terminal'+ ? (tool.detail.command ?? 'a command')+ : tool.name.kind === 'mcp'+ ? tool.name.tool+ : tool.name.name;+ return `Wants to run ${label.replace(/\s+/g, ' ')}`;+ })+ .with({ kind: 'elicitation' }, () => 'Has a question')+ .with(+ { kind: 'tool_approval' },+ (approval) =>+ `Wants to use ${approval.toolName} from ${approval.serverName}`+ )+ .exhaustive();+}++export function selectAgentUpdates(+ sessions: readonly UpdateSession[],+ pendingBySession: ReadonlyMap<string, readonly PendingInteraction[]>,+ messagesBySession: ReadonlyMap<string, readonly FoldedMessage[]>,+ now = Date.now()+): AgentUpdate[] {+ return sessions+ .flatMap((session): AgentUpdate[] => {+ const updatedAt = timestamp(session);+ const sessionName = session.name || 'Untitled conversation';+ if (+ session.turnState === 'running' &&+ updatedAt > 0 &&+ now - updatedAt > 20 * 60_000+ ) {+ return [+ {+ kind: 'stalled',+ id: `${session.id}:stalled`,+ sessionId: session.id,+ sessionName,+ updatedAt,+ summary: `No activity for ${Math.floor((now - updatedAt) / 60_000)} minutes`,+ },+ ];+ }+ if (session.turnState !== 'blocked') return [];+ return (pendingBySession.get(session.id) ?? []).toReversed().map(+ (request): AgentUpdate => ({+ kind: 'interaction',+ id: `${session.id}:${request.turn}:${request.kind}:${request.kind === 'tool_approval' ? request.approvalId : request.requestId}`,+ sessionId: session.id,+ sessionName,+ updatedAt,+ summary: summary(request, messagesBySession.get(session.id) ?? []),+ request,+ })+ );+ })+ .toSorted((left, right) => right.updatedAt - left.updatedAt);+}diff --git a/apps/web/src/features/agent-updates/primitives/create-agent-updates.test.ts b/apps/web/src/features/agent-updates/primitives/create-agent-updates.test.tsnew file mode 100644index 0000000000..3507d83657--- /dev/null+++ b/apps/web/src/features/agent-updates/primitives/create-agent-updates.test.ts@@ -0,0 +1,121 @@+import { createRoot, createSignal, type Setter } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { UpdateSession } from '../core/agent-update';++const fake = vi.hoisted(() => ({+ acquired: vi.fn(),+ released: vi.fn(),+ issued: vi.fn(async (_action: unknown) => ({ isErr: () => false })),+ listeners: new Set<(events: unknown[]) => void>(),+ load: vi.fn(async () => {}),+ snapshot: vi.fn(async () => ({+ messages: [],+ metadata: { pendingInteractions: [] },+ })),+}));+vi.mock('@core/agent-session/AgentSession', () => ({+ AgentSession: {+ acquire: (id: string) => {+ fake.acquired(id);+ return {+ load: fake.load,+ snapshot: fake.snapshot,+ subscribe: (listener: (events: unknown[]) => void) => {+ fake.listeners.add(listener);+ return () => {+ fake.listeners.delete(listener);+ };+ },+ release: fake.released,+ issue: fake.issued,+ };+ },+ },+}));+vi.mock('@app/features/block-agent/queries/issue-session-action', () => ({+ issueSessionAction: (_session: unknown, action: unknown) =>+ fake.issued(action),+}));+vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure: vi.fn() } }));++import { createAgentUpdates } from './create-agent-updates';++const blocked: UpdateSession = {+ id: 'blocked',+ name: 'Build',+ ownerId: 'me',+ botId: 'bot',+ harness: 'cursor',+ turnState: 'blocked',+ updatedAt: '2026-10-30T12:00:00Z',+};++afterEach(() => {+ fake.acquired.mockClear();+ fake.released.mockClear();+ fake.issued.mockClear();+ fake.listeners.clear();+ fake.snapshot.mockClear();+});++describe('createAgentUpdates', () => {+ it('acquires only blocked sessions and releases them on state change and cleanup', async () => {+ let dispose = () => {};+ let changeSessions: Setter<UpdateSession[]> = () => [];+ createRoot((close) => {+ dispose = close;+ const [sessions, setSessions] = createSignal<UpdateSession[]>([+ blocked,+ { ...blocked, id: 'running', turnState: 'running' },+ ]);+ changeSessions = setSessions;+ createAgentUpdates(sessions, () => 'me');+ });+ expect(fake.acquired.mock.calls.map(([id]) => id)).toEqual(['blocked']);+ changeSessions([{ ...blocked, turnState: 'running' }]);+ expect(fake.released).toHaveBeenCalledTimes(1);+ changeSessions([blocked]);+ expect(fake.acquired).toHaveBeenCalledTimes(2);+ dispose();+ expect(fake.released).toHaveBeenCalledTimes(2);+ });++ it('answers a live permission through the interaction controller', async () => {+ let dispose = () => {};+ let answerPromise: Promise<boolean> | undefined;+ createRoot((close) => {+ dispose = close;+ const model = createAgentUpdates(+ () => [blocked],+ () => 'me'+ );+ for (const listener of fake.listeners)+ listener([+ {+ kind: 'metadata',+ metadata: {+ pendingInteractions: [+ {+ kind: 'permission',+ requestId: 7,+ turn: 1,+ toolCall: 'tool',+ options: [{ id: 'allow', name: 'Allow', kind: 'allow_once' }],+ },+ ],+ },+ },+ ]);+ const update = model.updates()[0];+ if (!update) throw new Error('Missing update');+ answerPromise = model.answer(update, { optionId: 'allow' });+ });+ await answerPromise;+ expect(fake.issued).toHaveBeenCalledWith({+ type: 'respondToPermission',+ requestId: 7,+ answer: { kind: 'selected', optionId: 'allow' },+ });+ dispose();+ });+});diff --git a/apps/web/src/features/agent-updates/primitives/create-agent-updates.ts b/apps/web/src/features/agent-updates/primitives/create-agent-updates.tsnew file mode 100644index 0000000000..cb3e09143b--- /dev/null+++ b/apps/web/src/features/agent-updates/primitives/create-agent-updates.ts@@ -0,0 +1,222 @@+import { createInteractionController } from '@app/features/agent-interactions/primitives/create-interaction-controller';+import { createToolApprovalController } from '@app/features/block-agent/primitives/create-tool-approval-controller';+import { issueSessionAction } from '@app/features/block-agent/queries/issue-session-action';+import { AgentSession } from '@core/agent-session/AgentSession';+import { toast } from '@core/component/Toast/Toast';+import { fireAndForget } from '@core/util/fireAndForget';+import { Telemetry } from '@macro-inc/observability';+import { answerAgentSessionToolApproval } from '@queries/agent-session/tool-approvals';+import type {+ FoldedMessage,+ PendingInteraction,+ SessionMetadata,+} from '@service-agent-fold/generated/types';+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';+import {+ type Accessor,+ createRenderEffect,+ createSignal,+ on,+ onCleanup,+} from 'solid-js';+import {+ blockedSessions,+ eligibleSessions,+ selectAgentUpdates,+ type UpdateSession,+} from '../core/agent-update';++type LiveSession = Pick<+ AgentSession,+ 'load' | 'snapshot' | 'subscribe' | 'release' | 'issue'+>;++type Source = {+ acquire: (id: string) => LiveSession;+ answerToolApproval: typeof answerAgentSessionToolApproval;+ onFailure: (message: string) => void;+};++type SessionState = {+ live: LiveSession;+ unsubscribe: () => void;+ released: boolean;+ pending: Accessor<PendingInteraction[]>;+ messages: Accessor<FoldedMessage[]>;+ interactions: ReturnType<typeof createInteractionController>;+ approvals: ReturnType<typeof createToolApprovalController>;+ release: () => void;+};++/** Owns headless folds only while matching sessions remain blocked. */+export function createAgentUpdates(+ sessions: Accessor<readonly UpdateSession[]>,+ ownerId: Accessor<string | undefined>,+ source: Source = {+ acquire: AgentSession.acquire,+ answerToolApproval: answerAgentSessionToolApproval,+ onFailure: toast.failure,+ }+) {+ const [revision, setRevision] = createSignal(0);+ const [now, setNow] = createSignal(Date.now());+ const opened = new Map<string, SessionState>();+ const selected = () => eligibleSessions(sessions(), ownerId());+ const tick = setInterval(() => setNow(Date.now()), 60_000);+ onCleanup(() => clearInterval(tick));++ function acquire(id: string): SessionState {+ const live = source.acquire(id);+ const [pending, setPending] = createSignal<PendingInteraction[]>([]);+ const [messages, setMessages] = createSignal<FoldedMessage[]>([]);+ const applyMetadata = (metadata: SessionMetadata) => {+ setPending(metadata.pendingInteractions);+ setRevision((value) => value + 1);+ };+ const unsubscribe = live.subscribe((events) => {+ for (const event of events) {+ if (event.kind === 'metadata') applyMetadata(event.metadata);+ else if (event.kind === 'replace') setMessages(event.messages);+ else+ setMessages((current) => {+ const index = current.findIndex(+ (message) =>+ message.turn === event.message.turn &&+ message.author.kind === event.message.author.kind+ );+ return index < 0+ ? [...current, event.message]+ : current.map((message, i) =>+ i === index ? event.message : message+ );+ });+ }+ setRevision((value) => value + 1);+ });+ const interactions = createInteractionController({+ sessionId: () => id,+ pending,+ canEdit: () => Boolean(ownerId()),+ issue: (action) => issueSessionAction(live, action),+ onFailure: source.onFailure,+ });+ const approvals = createToolApprovalController({+ sessionId: () => id,+ pending,+ ownerId,+ userId: ownerId,+ canEdit: () => Boolean(ownerId()),+ answer: source.answerToolApproval,+ onFailure: source.onFailure,+ });+ const state: SessionState = {+ live,+ unsubscribe,+ released: false,+ pending,+ messages,+ interactions,+ approvals,+ release: () => {+ state.released = true;+ unsubscribe();+ live.release();+ },+ };+ async function load() {+ try {+ await live.load();+ if (state.released) return;+ const snapshot = await live.snapshot();+ if (state.released) return;+ setMessages(snapshot.messages);+ applyMetadata(snapshot.metadata);+ } catch {+ if (!state.released) source.onFailure("Couldn't load agent updates");+ }+ }+ fireAndForget(load(), 'agent-updates');+ return state;+ }++ createRenderEffect(+ on(+ () => blockedSessions(selected()).map((session) => session.id),+ (ids) => {+ const wanted = new Set(ids);+ for (const [id, state] of opened) {+ if (!wanted.has(id)) {+ state.release();+ opened.delete(id);+ }+ }+ for (const id of ids) {+ if (!opened.has(id)) opened.set(id, acquire(id));+ }+ setRevision((value) => value + 1);+ }+ )+ );+ onCleanup(() => {+ for (const state of opened.values()) state.release();+ opened.clear();+ });++ const updates = () => {+ revision();+ return selectAgentUpdates(+ selected(),+ new Map([...opened].map(([id, state]) => [id, state.pending()])),+ new Map([...opened].map(([id, state]) => [id, state.messages()])),+ now()+ );+ };+ const answer = async (+ update: ReturnType<typeof updates>[number],+ response: {+ optionId?: string;+ elicitation?: ElicitationAnswer;+ approval?: 'approve' | 'approve_and_remember' | 'deny';+ }+ ): Promise<boolean> => {+ if (update.kind !== 'interaction') return false;+ const state = opened.get(update.sessionId);+ if (!state) return false;+ return Telemetry.span('agent.updates.answer', async (span) => {+ span.setAttr('agent.session.id', update.sessionId);+ const request = update.request;+ const succeeded =+ request.kind === 'permission' && response.optionId+ ? await state.interactions.respond({+ kind: 'permission',+ turn: request.turn,+ requestId: request.requestId,+ answer: { kind: 'selected', optionId: response.optionId },+ })+ : request.kind === 'elicitation' && response.elicitation+ ? await state.interactions.respond({+ kind: 'elicitation',+ turn: request.turn,+ requestId: request.requestId,+ answer: response.elicitation,+ })+ : request.kind === 'tool_approval' && response.approval+ ? await state.approvals.answer(+ request.approvalId,+ response.approval+ )+ : false;+ if (!succeeded) span.error('Agent update answer failed');+ return succeeded;+ });+ };+ const answering = (update: ReturnType<typeof updates>[number]) => {+ if (update.kind !== 'interaction') return false;+ const state = opened.get(update.sessionId);+ if (!state) return false;+ return update.request.kind === 'tool_approval'+ ? state.approvals.answering(update.request.approvalId)+ : state.interactions.answering(update.request);+ };+ return { updates, answer, answering };+}diff --git a/apps/web/src/features/agent-updates/views/AgentUpdatesStack.test.tsx b/apps/web/src/features/agent-updates/views/AgentUpdatesStack.test.tsxnew file mode 100644index 0000000000..b94ea2de83--- /dev/null+++ b/apps/web/src/features/agent-updates/views/AgentUpdatesStack.test.tsx@@ -0,0 +1,70 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const fake = vi.hoisted(() => ({ answer: vi.fn(async () => true) }));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'me' }));+vi.mock('../primitives/create-agent-updates', () => ({+ createAgentUpdates: () => ({+ updates: () => [+ {+ kind: 'interaction',+ id: 'session:permission:7',+ sessionId: 'session',+ sessionName: 'Build app',+ updatedAt: Date.now(),+ summary: 'Wants to run tests',+ request: {+ kind: 'permission',+ requestId: 7,+ turn: 1,+ toolCall: 'tool',+ options: [{ id: 'allow', name: 'Allow', kind: 'allow_once' }],+ },+ },+ ],+ answer: fake.answer,+ answering: () => false,+ }),+}));++import { AgentUpdatesStack } from './AgentUpdatesStack';++beforeEach(() => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+});++afterEach(() => {+ cleanup();+ fake.answer.mockClear();+ vi.unstubAllGlobals();+});++describe('AgentUpdatesStack', () => {+ it('answers an option and delegates chat and session navigation', () => {+ const onChatAbout = vi.fn();+ const onOpenSession = vi.fn();+ render(() => (+ <AgentUpdatesStack+ sessions={[]}+ onChatAbout={onChatAbout}+ onOpenSession={onOpenSession}+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Allow' }));+ fireEvent.click(screen.getByRole('button', { name: 'Chat about this' }));+ fireEvent.click(screen.getByRole('button', { name: 'Open session' }));+ expect(fake.answer).toHaveBeenCalledWith(+ expect.objectContaining({ sessionId: 'session' }),+ { optionId: 'allow' }+ );+ expect(onChatAbout).toHaveBeenCalledWith('session', 'Build app');+ expect(onOpenSession).toHaveBeenCalledWith('session');+ });+});diff --git a/apps/web/src/features/agent-updates/views/AgentUpdatesStack.tsx b/apps/web/src/features/agent-updates/views/AgentUpdatesStack.tsxnew file mode 100644index 0000000000..27a84371f4--- /dev/null+++ b/apps/web/src/features/agent-updates/views/AgentUpdatesStack.tsx@@ -0,0 +1,64 @@+import { useUserId } from '@core/context/user';+import { NotificationStack } from '@ui';+import { Show } from 'solid-js';+import { AgentUpdateCard } from '../components/AgentUpdateCard';+import type { AgentUpdate, UpdateSession } from '../core/agent-update';+import { createAgentUpdates } from '../primitives/create-agent-updates';++/**+ * Live updates for the given sessions as a notification stack. Hosts supply+ * the sessions (the Agents list, or an AI tool result) and navigation.+ */+export function AgentUpdatesStack(props: {+ sessions: readonly UpdateSession[];+ onOpenSession: (sessionId: string) => void;+ /** Omitted where there is no composer to attach an update to. */+ onChatAbout?: (sessionId: string, sessionName: string) => void;+ /** Leave room for the floating composer on the touch home page. */+ home?: boolean;+}) {+ const ownerId = useUserId();+ const model = createAgentUpdates(() => props.sessions, ownerId);+ return (+ <Show when={model.updates().length > 0}>+ <div+ class="w-full"+ classList={{+ 'touch:pb-[calc(var(--mobile-content-inset-bottom,0px)+1rem)]':+ props.home,+ }}+ >+ <NotificationStack+ label="Updates from coding agents"+ title={+ <>+ <span class="size-2 rounded-full bg-warning" aria-hidden="true" />+ <strong>+ {model.updates().length === 1+ ? '1 update from a coding agent'+ : `${model.updates().length} updates from coding agents`}+ </strong>+ </>+ }+ items={model.updates()}+ itemKey={(update) => update.id}+ >+ {(update: AgentUpdate) => (+ <AgentUpdateCard+ update={update}+ answering={model.answering(update)}+ onAnswer={(answer) => model.answer(update, answer)}+ onChatAbout={+ props.onChatAbout+ ? () =>+ props.onChatAbout?.(update.sessionId, update.sessionName)+ : undefined+ }+ onOpenSession={() => props.onOpenSession(update.sessionId)}+ />+ )}+ </NotificationStack>+ </div>+ </Show>+ );+}diff --git a/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx b/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsxindex 35e2d9881a..2defe7b5e3 100644--- a/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx+++ b/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx@@ -15,12 +15,21 @@ import {} from '../core/conversation-filters';import {type AgentConversationEntity,+ conversationMode,partitionArchived,} from '../core/recent-conversations';import { AgentsSidebar } from './AgentsSidebar';const openWithSplit = vi.fn();const unreadFilter = vi.hoisted(() => vi.fn(() => false));+const sidebarState = vi.hoisted(() => ({ agentUpdates: false, touch: false }));+vi.mock('@app/lib/analytics/posthog', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/analytics/posthog')>()),+ useFeatureFlag: () => () => ({ enabled: sidebarState.agentUpdates }),+}));+vi.mock('@core/mobile/isTouchDevice', () => ({+ isTouchDevice: () => sidebarState.touch,+}));vi.mock('@components/app/split-layout/layout', () => ({useSplitLayout: () => ({ openWithSplit }),}));@@ -63,6 +72,8 @@ beforeEach(() => {afterEach(() => {cleanup();unreadFilter.mockReturnValue(false);+ sidebarState.agentUpdates = false;+ sidebarState.touch = false;});vi.mock('@solid-primitives/resize-observer', () => ({@@ -75,8 +86,16 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({}),}));vi.mock('@app/features/next-soup/actions', () => ({- toEntityActionListState: () => ({- focus: { set: vi.fn() },+ toEntityActionListState: (options: {+ controller: { items: { all: () => { id: string }[] } };+ }) => ({+ focus: {+ set: (id: string) => {+ if (!options.controller.items.all().some((item) => item.id === id)) {+ throw new Error(`Missing action row: ${id}`);+ }+ },+ },}),}));vi.mock('@app/features/soup', () => ({@@ -86,6 +105,7 @@ vi.mock('@app/features/soup', () => ({children: JSX.Element;entity: { id: string };extraItems?: JSX.Element;+ onOpenChange?: (open: boolean) => void;}) => {const [open, setOpen] = createSignal(false);return (@@ -94,6 +114,7 @@ vi.mock('@app/features/soup', () => ({onContextMenu={(event) => {event.preventDefault();setOpen(true);+ props.onOpenChange?.(true);}}>{props.children}@@ -406,6 +427,165 @@ describe('mixed Agents sidebar', () => {});});+describe('Open PRs sidebar section', () => {+ const open: AgentConversationEntity = {+ type: 'agent_session',+ id: 'open-pr',+ name: 'Fix build',+ ownerId: 'me',+ botId: 'cursor',+ harness: 'cursor',+ status: 'acp_ready',+ turnState: 'running',+ updatedAt: '2026-10-29T10:00:00Z',+ pullRequestState: 'open',+ pullRequestUrl: 'https://github.com/macro-inc/macro/pull/42',+ repoUrl: 'https://github.com/macro-inc/macro.git',+ workingBranch: 'fix/build',+ };+ const draft: AgentConversationEntity = {+ ...open,+ id: 'draft-pr',+ name: 'Add tests',+ updatedAt: '2026-10-30T10:00:00Z',+ pullRequestState: 'draft',+ pullRequestUrl: 'https://github.com/macro-inc/macro/pull/43',+ };+ const conversations: AgentConversationEntity[] = [+ open,+ { ...open, id: 'merged-pr', name: 'Merged PR', pullRequestState: 'merged' },+ { ...open, id: 'closed-pr', name: 'Closed PR', pullRequestState: 'closed' },+ { ...open, id: 'archived-pr', name: 'Archived PR', isArchived: true },+ {+ ...open,+ id: 'chat-mode-pr',+ name: 'Chat mode PR',+ harness: 'in-memory',+ },+ { type: 'chat', id: 'chat', name: 'Plain chat', ownerId: 'me' },+ draft,+ ];++ function renderSidebar(+ items: AgentConversationEntity[],+ filters: ConversationFilters = EMPTY_CONVERSATION_FILTERS+ ) {+ const onOpenConversation = vi.fn();+ render(() => (+ <AgentsSidebar+ filters={filters}+ grouping="none"+ onFilterChange={vi.fn()}+ onClearFilters={vi.fn()}+ onGroupingChange={vi.fn()}+ activePage="new"+ onOpenPage={vi.fn()}+ conversations={items}+ archived={[]}+ modeForConversation={(conversation) =>+ conversationMode(conversation, () => 'agent')+ }+ activeConversationId="open-pr"+ search=""+ loading={false}+ error={false}+ hasNextPage={false}+ loadingNextPage={false}+ onSearchChange={vi.fn()}+ onOpenConversation={onOpenConversation}+ onRetry={vi.fn()}+ onLoadMore={vi.fn()}+ onCreateAgent={vi.fn()}+ onCreateRoutine={vi.fn()}+ showUnlistedRuns={false}+ onShowUnlistedRunsChange={vi.fn()}+ />+ ));+ return onOpenConversation;+ }++ it('shows open and draft coding PRs in update order with the existing rows and navigation', () => {+ sidebarState.agentUpdates = true;+ const onOpenConversation = renderSidebar(conversations);+ const section = screen.getByRole('navigation', {+ name: 'Open pull requests',+ });+ expect(screen.getByRole('button', { name: 'Open PRs 2' })).toBeTruthy();+ expect(+ within(section)+ .getAllByRole('button')+ .map((row) => row.getAttribute('aria-label'))+ ).toEqual(['Add tests', 'Fix build']);+ expect(within(section).getByText('#42')).toBeTruthy();+ expect(+ within(section).getAllByText('macro-inc/macro · fix/build')+ ).toHaveLength(2);+ expect(+ section.querySelectorAll('[data-agent-status-indicator]')+ ).toHaveLength(2);+ expect(+ within(section)+ .getByRole('button', { name: 'Fix build' })+ .getAttribute('aria-current')+ ).toBe('page');+ for (const name of [+ 'Merged PR',+ 'Closed PR',+ 'Archived PR',+ 'Chat mode PR',+ 'Plain chat',+ ]) {+ expect(within(section).queryByRole('button', { name })).toBeNull();+ }+ expect(+ within(+ screen.getByRole('navigation', { name: 'Recent conversations' })+ ).getByRole('button', { name: 'Fix build' })+ ).toBeTruthy();++ const draftRow = within(section).getByRole('button', { name: 'Add tests' });+ expect(draftRow.closest('[data-entity-context-menu]')).not.toBeNull();+ fireEvent.click(draftRow);+ expect(onOpenConversation).toHaveBeenCalledWith(draft, expect.anything());+ });++ it('hides the section when the flag is off or there are no matching sessions', () => {+ renderSidebar(conversations);+ expect(screen.queryByText('Open PRs')).toBeNull();+ cleanup();++ sidebarState.agentUpdates = true;+ renderSidebar(+ conversations.filter(+ (conversation) =>+ conversation.id !== 'open-pr' && conversation.id !== 'draft-pr'+ )+ );+ expect(screen.queryByText('Open PRs')).toBeNull();+ });++ it('keeps PR context actions available when conversation filters exclude the row', () => {+ sidebarState.agentUpdates = true;+ renderSidebar([open], { ...EMPTY_CONVERSATION_FILTERS, type: ['chat'] });+ const section = screen.getByRole('navigation', {+ name: 'Open pull requests',+ });+ const row = within(section).getByRole('button', { name: 'Fix build' });+ expect(row.closest('[data-entity-context-menu]')).not.toBeNull();+ });++ it('uses the same PR rows in the touch list view', () => {+ sidebarState.agentUpdates = true;+ sidebarState.touch = true;+ const onOpenConversation = renderSidebar([open]);+ const section = screen.getByRole('navigation', {+ name: 'Open pull requests',+ });+ fireEvent.click(within(section).getByRole('button', { name: 'Fix build' }));+ expect(onOpenConversation).toHaveBeenCalledWith(open, expect.anything());+ });+});+describe.each(['home', 'sidebar'] as const)('%s agent rows', (surface) => {const conversation: AgentConversationEntity = {type: 'agent_session',diff --git a/apps/web/src/features/agents-view/components/AgentsSidebar.tsx b/apps/web/src/features/agents-view/components/AgentsSidebar.tsxindex d13a8226ce..50d112addc 100644--- a/apps/web/src/features/agents-view/components/AgentsSidebar.tsx+++ b/apps/web/src/features/agents-view/components/AgentsSidebar.tsx@@ -16,8 +16,11 @@ import {MaybeSoupEntityActionDrawerManager,SoupEntityContextMenu,} from '@app/features/soup';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { t } from '@app/lib/i18n';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { enableAgentUpdates } from '@core/constant/featureFlags';+import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { unreadFilterFn } from '@entity/utils/filter';import RoutineIcon from '@icon/system/regular/clock-clockwise.svg';@@ -40,6 +43,7 @@ import {} from '../core/conversation-filters';import { compactAge } from '../core/format-age';import type { AgentsMode } from '../core/mode';+import { selectOpenPullRequests } from '../core/open-pull-requests';import type { AgentsPage } from '../core/pages';import {type AgentConversationEntity,@@ -160,7 +164,10 @@ function Row(props: {export function AgentsSidebar(props: AgentsSidebarProps) {const panel = useSplitPanelOrThrow();+ const userId = useUserId();+ const agentUpdates = useFeatureFlag(enableAgentUpdates);const [searchOpen, setSearchOpen] = createSignal(false);+ const [openPullRequestsOpen, setOpenPullRequestsOpen] = createSignal(true);const [conversationsOpen, setConversationsOpen] = createSignal(true);let searchInput: HTMLInputElement | undefined;const factsOf = (conversation: AgentConversationEntity) =>@@ -174,12 +181,26 @@ export function AgentsSidebar(props: AgentsSidebarProps) {conversationMatchesFilters(factsOf(conversation), props.filters));const conversations = () => matching(props.conversations);+ const openPullRequests = () =>+ selectOpenPullRequests(+ props.conversations,+ userId(),+ props.modeForConversation+ );const archived = () => matching(props.archived);const groups = () =>groupConversations(conversations(), factsOf, props.grouping);const filtering = () => activeFilterCount(props.filters) > 0;const actionController = createListController({- items: () => [...conversations(), ...archived()],+ items: () => [+ ...new Map(+ [+ ...(agentUpdates().enabled ? openPullRequests() : []),+ ...conversations(),+ ...archived(),+ ].map((conversation) => [conversation.id, conversation])+ ).values(),+ ],getKey: (conversation) => conversation.id,isSelectable: () => false,});@@ -320,6 +341,34 @@ export function AgentsSidebar(props: AgentsSidebarProps) {</ViewSidebar.Item></ViewSidebar.Nav></Show>+ <Show when={agentUpdates().enabled && openPullRequests().length > 0}>+ <CollapsibleSection.Root+ open={openPullRequestsOpen()}+ onOpenChange={setOpenPullRequestsOpen}+ class={cn(+ 'flex min-h-0 flex-col',+ openPullRequestsOpen() ? 'max-h-[40%]' : 'shrink-0'+ )}+ >+ <CollapsibleSection.Header>+ <CollapsibleSection.Trigger>+ <span class="min-w-0 truncate">Open PRs</span>+ <span class="text-ink-extra-muted tabular-nums">+ {openPullRequests().length}+ </span>+ <CollapsibleSection.Indicator />+ </CollapsibleSection.Trigger>+ </CollapsibleSection.Header>+ <CollapsibleSection.Content class="flex min-h-0 flex-col">+ <ViewSidebar.Nav+ class="min-h-0 shrink overflow-auto"+ aria-label="Open pull requests"+ >+ {rows(openPullRequests)}+ </ViewSidebar.Nav>+ </CollapsibleSection.Content>+ </CollapsibleSection.Root>+ </Show><CollapsibleSection.Rootopen={conversationsOpen()}onOpenChange={setConversationsOpen}diff --git a/apps/web/src/features/agents-view/core/open-pull-requests.test.ts b/apps/web/src/features/agents-view/core/open-pull-requests.test.tsnew file mode 100644index 0000000000..c957a005ba--- /dev/null+++ b/apps/web/src/features/agents-view/core/open-pull-requests.test.ts@@ -0,0 +1,80 @@+import type { AgentSessionEntity, ChatEntity } from '@entity';+import { describe, expect, it } from 'vitest';+import { selectOpenPullRequests } from './open-pull-requests';+import { conversationMode } from './recent-conversations';++const ownerId = 'macro|[email protected]';++describe('selectOpenPullRequests', () => {+ it('keeps only the owner’s active coding sessions with open or draft PRs, newest first', () => {+ const session: AgentSessionEntity = {+ type: 'agent_session',+ id: 'open',+ name: 'Open PR',+ ownerId,+ botId: 'cursor',+ harness: 'cursor',+ status: 'acp_ready',+ updatedAt: '2026-10-29T10:00:00Z',+ pullRequestState: 'open',+ };+ const draft: AgentSessionEntity = {+ ...session,+ id: 'draft',+ updatedAt: '2026-10-30T10:00:00Z',+ pullRequestState: 'draft',+ };+ const merged: AgentSessionEntity = {+ ...session,+ id: 'merged',+ pullRequestState: 'merged',+ };+ const closed: AgentSessionEntity = {+ ...session,+ id: 'closed',+ pullRequestState: 'closed',+ };+ const archived: AgentSessionEntity = {+ ...session,+ id: 'archived',+ isArchived: true,+ };+ const chatMode: AgentSessionEntity = {+ ...session,+ id: 'chat-mode',+ harness: 'in-memory',+ };+ const otherOwner: AgentSessionEntity = {+ ...session,+ id: 'other-owner',+ ownerId: 'macro|[email protected]',+ };+ const chat: ChatEntity = {+ type: 'chat',+ id: 'chat',+ name: 'Chat',+ ownerId,+ };+ const conversations = [+ session,+ merged,+ chat,+ archived,+ chatMode,+ draft,+ closed,+ otherOwner,+ ];+ const modeForConversation = (+ conversation: (typeof conversations)[number]+ ) => conversationMode(conversation, () => 'agent');++ expect(+ selectOpenPullRequests(conversations, ownerId, modeForConversation)+ ).toEqual([draft, session]);+ expect(conversations[0]).toBe(session);+ expect(+ selectOpenPullRequests(conversations, undefined, modeForConversation)+ ).toEqual([]);+ });+});diff --git a/apps/web/src/features/agents-view/core/open-pull-requests.ts b/apps/web/src/features/agents-view/core/open-pull-requests.tsnew file mode 100644index 0000000000..a24cc21b86--- /dev/null+++ b/apps/web/src/features/agents-view/core/open-pull-requests.ts@@ -0,0 +1,29 @@+import type { AgentsMode } from './mode';+import {+ type AgentConversationEntity,+ conversationTimestamp,+} from './recent-conversations';++/** Select the current user's active coding sessions with open pull requests. */+export function selectOpenPullRequests(+ conversations: readonly AgentConversationEntity[],+ ownerId: string | undefined,+ modeForConversation: (conversation: AgentConversationEntity) => AgentsMode+): AgentConversationEntity[] {+ if (!ownerId) return [];++ return conversations+ .filter(+ (conversation) =>+ conversation.type === 'agent_session' &&+ conversation.ownerId === ownerId &&+ !conversation.isArchived &&+ modeForConversation(conversation) === 'code' &&+ (conversation.pullRequestState === 'open' ||+ conversation.pullRequestState === 'draft')+ )+ .toSorted(+ (left, right) =>+ conversationTimestamp(right) - conversationTimestamp(left)+ );+}diff --git a/apps/web/src/features/agents-view/views/AgentsView.tsx b/apps/web/src/features/agents-view/views/AgentsView.tsxindex 54c3237d6c..2f0df41920 100644--- a/apps/web/src/features/agents-view/views/AgentsView.tsx+++ b/apps/web/src/features/agents-view/views/AgentsView.tsx@@ -39,8 +39,11 @@ import {import { routineContent } from '../../routines/routine-navigation';import { RoutinesPage } from '../../routines/routines-page';import '../agents-view.css';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { ComposerGreeting } from '@core/component/ComposerGreeting';+import { enableAgentUpdates } from '@core/constant/featureFlags';import { fireAndForget } from '@core/util/fireAndForget';+import type { AgentSessionEntity } from '@entity';import { AgentSessionPane } from '../components/AgentSessionPane';import { AgentsSidebar } from '../components/AgentsSidebar';import { Topbar } from '../components/Topbar';@@ -86,6 +89,7 @@ function AgentsWorkspace(props: { route?: AgentsRoute }) {const layout = useSplitLayout();const orchestrator = useGlobalBlockOrchestrator();const userId = useUserId();+ const updatesFlag = useFeatureFlag(enableAgentUpdates);useWarmAgentSessionQuery(userId);const notifications = useGlobalNotificationSource();const mode = (): AgentsMode => props.route?.mode ?? 'chat';@@ -168,6 +172,10 @@ function AgentsWorkspace(props: { route?: AgentsRoute }) {));const partitioned = createMemo(() => partitionArchived(conversations()));+ const updateSessions = () =>+ (query.isPending ? [] : (query.data?.entities ?? [])).filter(+ (entity): entity is AgentSessionEntity => entity.type === 'agent_session'+ );const modeForConversation = (conversation: AgentConversationEntity) =>conversationMode(conversation, (botId) =>kindForBot(botId, rosterSource.roster())@@ -452,6 +460,21 @@ function AgentsWorkspace(props: { route?: AgentsRoute }) {classList={{ hidden: page() !== 'new' }}><NewChatPage+ showUpdates={+ updatesFlag().enabled && page() === 'new'+ }+ updateSessions={updateSessions()}+ onOpenUpdateSession={(id) => {+ const session = updateSessions().find(+ (item) => item.id === id+ );+ if (session)+ openConversation(+ session,+ undefined,+ modeForConversation(session)+ );+ }}mode={workspace.mode()}onModeChange={workspace.setMode}active={diff --git a/apps/web/src/features/agents-view/views/NewChatPage.tsx b/apps/web/src/features/agents-view/views/NewChatPage.tsxindex 236a61916b..4ab0d0c425 100644--- a/apps/web/src/features/agents-view/views/NewChatPage.tsx+++ b/apps/web/src/features/agents-view/views/NewChatPage.tsx@@ -13,12 +13,14 @@ import {speedForModel,} from '@core/component/AI/constant/speed';import { fastModeEnabled } from '@core/component/AI/signal/speed';+import { chatAttachmentMentionToMarkdown } from '@core/component/AI/util/chatAttachmentMention';import { ComposerGreeting } from '@core/component/ComposerGreeting';import { useSettingsState } from '@core/constant/SettingsState';import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { fireAndForget } from '@core/util/fireAndForget';import { uploadFile } from '@core/util/upload';+import type { AgentSessionEntity } from '@entity';import ChatIcon from '@icon/system/regular/chat-circle.svg';import CodeIcon from '@icon/system/regular/code.svg';import AutoIcon from '@icon/system/regular/sparkle.svg';@@ -29,6 +31,7 @@ import type { PromptAttachment } from '@service-agent-harness/generated/schemas'import { Tabs } from '@ui';import { tourTarget } from '@ui/components/Tour';import { createMemo, createSignal, Show } from 'solid-js';+import { AgentUpdatesStack } from '../../agent-updates/views/AgentUpdatesStack';import { EffortSelector } from '../../block-agent/component/EffortSelector';import {type EffortChoice,@@ -98,6 +101,9 @@ export function NewChatPage(props: {onStart: (start: StartConversation) => void;/** Opens the roster page on the given kind's tab. */onOpenRoster: (kind: AgentKind) => void;+ updateSessions?: readonly AgentSessionEntity[];+ onOpenUpdateSession?: (sessionId: string) => void;+ showUpdates?: boolean;}) {const userId = useUserId();const billing = useAiBillingSummaryQuery();@@ -410,6 +416,17 @@ export function NewChatPage(props: {};let focusInput: (() => void) | undefined;+ const chatAboutUpdate = (sessionId: string, sessionName: string) => {+ const mention = chatAttachmentMentionToMarkdown({+ documentId: sessionId,+ documentName: sessionName,+ blockName: 'agent',+ });+ setDraft(+ `${draft().trim()}${draft().trim() ? '\n\n' : ''}${mention}\nAbout this update: `+ );+ focusInput?.();+ };const restoreInputFocus = (event: Event) => {event.preventDefault();focusInput?.();@@ -587,6 +604,20 @@ export function NewChatPage(props: {{composer()}</div></FloatRegionOrInline>+ <Show+ when={+ props.showUpdates &&+ props.updateSessions &&+ props.onOpenUpdateSession+ }+ >+ <AgentUpdatesStack+ home+ sessions={props.updateSessions ?? []}+ onOpenSession={(id) => props.onOpenUpdateSession?.(id)}+ onChatAbout={chatAboutUpdate}+ />+ </Show></div></section></Show>diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.tsindex 96e5a60b29..b148fb1b35 100644--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts@@ -101,6 +101,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {ListCalendarEvents: (whose) => `read ${whose} calendar`,ListCalendars: (whose) => `read ${whose} calendar`,ListCodingAgents: (whose) => `list ${whose} coding agents`,+ ListAgentUpdates: (whose) => `read ${whose} coding agent updates`,ListCompanies: (whose) => `look up companies in ${whose} workspace`,ListDatabases: (whose) => `list ${whose} databases`,ListEntities: (whose) => `list ${whose} files and tasks`,diff --git a/apps/web/src/lib/core/component/AI/component/tool/ListAgentUpdates.test.ts b/apps/web/src/lib/core/component/AI/component/tool/ListAgentUpdates.test.tsnew file mode 100644index 0000000000..090f533c91--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/ListAgentUpdates.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('@app/features/agent-updates/views/AgentUpdatesStack', () => ({+ AgentUpdatesStack: () => null,+}));+vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit: vi.fn() }),+}));++import { sessionsOf } from './ListAgentUpdates';++describe('sessionsOf', () => {+ it('opens each waiting session once and keeps stalled sessions static', () => {+ const sessions = sessionsOf(+ {+ truncated: false,+ items: [+ {+ sessionId: 'a',+ sessionName: 'Signing',+ harness: 'opencode',+ kind: 'permission',+ summary: 'Signing wants to run codesign',+ since: '2026-10-30T20:00:00Z',+ options: ['Allow'],+ },+ {+ sessionId: 'a',+ sessionName: 'Signing',+ harness: 'opencode',+ kind: 'elicitation',+ summary: 'Signing asks which certificate',+ since: '2026-10-30T20:01:00Z',+ options: [],+ },+ {+ sessionId: 'b',+ sessionName: 'PDF zoom',+ harness: 'cursor',+ kind: 'stalled',+ summary: 'No activity for 23 minutes',+ since: '2026-10-30T19:40:00Z',+ options: [],+ },+ ],+ },+ 'me'+ );+ expect(sessions.map((session) => [session.id, session.turnState])).toEqual([+ ['a', 'blocked'],+ ['b', 'running'],+ ]);+ expect(sessions.every((session) => session.ownerId === 'me')).toBe(true);+ });++ it('shows nothing before the user is known', () => {+ expect(sessionsOf({ truncated: false, items: [] }, undefined)).toEqual([]);+ });+});diff --git a/apps/web/src/lib/core/component/AI/component/tool/ListAgentUpdates.tsx b/apps/web/src/lib/core/component/AI/component/tool/ListAgentUpdates.tsxnew file mode 100644index 0000000000..f59d16822a--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/ListAgentUpdates.tsx@@ -0,0 +1,102 @@+import type { UpdateSession } from '@app/features/agent-updates/core/agent-update';+import { AgentUpdatesStack } from '@app/features/agent-updates/views/AgentUpdatesStack';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useUserId } from '@core/context/user';+import List from '@phosphor-icons/core/regular/list.svg';+import type { AgentUpdates } from '@service-cognition/generated/tools/types';+import { createSignal, For, Show } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++/**+ * One entry per session in the tool result. Waiting sessions are opened live,+ * so their cards show the current request and leave once it is answered.+ */+export function sessionsOf(+ updates: AgentUpdates,+ ownerId: string | undefined+): UpdateSession[] {+ if (!ownerId) return [];+ const sessions = new Map<string, UpdateSession>();+ for (const item of updates.items) {+ if (sessions.has(item.sessionId)) continue;+ sessions.set(item.sessionId, {+ id: item.sessionId,+ name: item.sessionName,+ ownerId,+ isArchived: false,+ harness: item.harness,+ botId: '',+ turnState: item.kind === 'stalled' ? 'running' : 'blocked',+ updatedAt: item.since,+ });+ }+ return [...sessions.values()];+}++export const listAgentUpdatesHandler = createToolRenderer({+ name: 'ListAgentUpdates',+ render: (ctx) => {+ const [expanded, setExpanded] = createSignal(false);+ const userId = useUserId();+ const { openWithSplit } = useSplitLayout();+ const items = () => ctx.response?.data.items ?? [];+ const status = () => {+ if (!ctx.response) return undefined;+ const count = items().length;+ return count === 0+ ? 'No updates'+ : `${count} update${count === 1 ? '' : 's'}`;+ };++ return (+ <div class="flex min-w-0 flex-col gap-2">+ <BaseTool+ icon={List}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response && expanded() ? (+ <div class="space-y-2 px-3 py-2">+ <For each={items()}>+ {(item) => (+ <div class="min-w-0">+ <div class="truncate text-ink">{item.sessionName}</div>+ <div class="text-ink-muted">{item.summary}</div>+ </div>+ )}+ </For>+ <Show when={ctx.response?.data.truncated}>+ <div class="text-ink-muted">+ {ctx.response?.data.truncationNotice}+ </div>+ </Show>+ </div>+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span>Read agent updates</span>+ <Tool.ResultToggle+ expanded={expanded()}+ onToggle={() => setExpanded((value) => !value)}+ showToggle={!!ctx.response}+ status={status()}+ />+ </div>+ </BaseTool>+ <Show when={ctx.response?.data}>+ {(data) => (+ <AgentUpdatesStack+ sessions={sessionsOf(data(), userId())}+ onOpenSession={(id) =>+ openWithSplit({ type: 'agent', id }, { activate: true })+ }+ />+ )}+ </Show>+ </div>+ );+ },+});diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex 478fbcfee8..7dc765ac11 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -134,6 +134,7 @@ import {} from './ImportTools';import { initiativeToolHandlers } from './Initiatives';import { LegacyGeneratedImage } from './LegacyGeneratedImage';+import { listAgentUpdatesHandler } from './ListAgentUpdates';import { listEntitiesHandler } from './ListEntities';import { listInboxesHandler } from './ListInboxes';import { listLabelsHandler } from './ListLabels';@@ -220,6 +221,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ReadCodeDocs: readCodeDocsHandler,DispatchCodingAgent: dispatchCodingAgentHandler,ListCodingAgents: listCodingAgentsHandler,+ ListAgentUpdates: listAgentUpdatesHandler,ReadSpreadsheet: readSpreadsheetHandler,CalculateSpreadsheet: calculateSpreadsheetHandler,EditSpreadsheet: editSpreadsheetHandler,diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 7876e96cb6..b0a7bc8296 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -831,6 +831,15 @@ export const enableActivityFeed = defineFlag({default: onInDev,});+// Agents home: pending updates from coding agents shown as a stack under the+// new-chat composer, and the Open PRs section in the Agents sidebar.+// Override with VITE_ENABLE_AGENT_UPDATES.+export const enableAgentUpdates = defineFlag({+ key: 'enable-agent-updates',+ env: 'ENABLE_AGENT_UPDATES',+ default: onInDev,+});+// AI agents: the folded agent-session view in channels, and which bot the// single `@macro` mention targets — the agent session when on, the classic// in-channel reply when off.diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex c30c39e247..6152fd7d0c 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -9952,6 +9952,25 @@ export const IssueBotCredentialResponse = z.object({summary: z.string(),});+export const ListAgentUpdates = z.record(z.never());++export const AgentUpdates = z.object({+ items: z.array(+ z.object({+ sessionId: z.string().uuid(),+ sessionName: z.string(),+ harness: z.string(),+ pullRequestUrl: z.union([z.string(), z.null()]).optional(),+ kind: z.enum(['permission', 'elicitation', 'tool_approval', 'stalled']),+ summary: z.string(),+ since: z.string().datetime({ offset: true }),+ options: z.array(z.string()),+ })+ ),+ truncated: z.boolean(),+ truncationNotice: z.union([z.string(), z.null()]).optional(),+});+export const ListAgents = z.record(z.any());export const ListAgentsResponse = z.object({diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex ba7a67c3ec..1312b37910 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -264,6 +264,10 @@ type ToolParserMap = {response: types.IssueBotCredentialResponse;};ListAgents: { call: types.ListAgents; response: types.ListAgentsResponse };+ ListAgentUpdates: {+ call: types.ListAgentUpdates;+ response: types.AgentUpdates;+ };ListBookingLinks: {call: types.ListBookingLinks;response: types.ListBookingLinksResult;@@ -828,6 +832,10 @@ const toolParserMap = {call: schemas.ListAgents,response: schemas.ListAgentsResponse,},+ ListAgentUpdates: {+ call: schemas.ListAgentUpdates,+ response: schemas.AgentUpdates,+ },ListBookingLinks: {call: schemas.ListBookingLinks,response: schemas.ListBookingLinksResult,@@ -1427,6 +1435,10 @@ type ToolDataMap = {response: types.IssueBotCredentialResponse;};ListAgents: { call: types.ListAgents; response: types.ListAgentsResponse };+ ListAgentUpdates: {+ call: types.ListAgentUpdates;+ response: types.AgentUpdates;+ };ListBookingLinks: {call: types.ListBookingLinks;response: types.ListBookingLinksResult;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex f90ecb274b..2b49b49616 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -3667,6 +3667,14 @@ export type ImportKind =| 'jira_project'| 'jira_epic'| 'channel';+/**+ * A kind of action or inactivity the user should see.+ */+export type AgentUpdateKind =+ | 'permission'+ | 'elicitation'+ | 'tool_approval'+ | 'stalled';/*** Provider selected from the persisted calendar account and email binding.*/@@ -11310,6 +11318,31 @@ export interface IssueBotCredentialResponse {*/summary: string;}+/**+ * List the current user's coding-agent sessions waiting for an answer or stalled for over 20 minutes. The user answers permissions and questions through the cards Macro renders from this tool's result. To send a coding agent instructions, use ManageAgentSession with a prompt. To recall the user's earlier decisions about these agents, search earlier agent conversations with ContentSearch (entity_types agent_sessions) and read them with ReadAgentSession.+ */+export type ListAgentUpdates = {};+/**+ * Bounded results; truncation means older qualifying sessions were not folded.+ */+export interface AgentUpdates {+ items: AgentUpdate[];+ truncated: boolean;+ truncationNotice?: string | null;+}+/**+ * One pending interaction, or one stalled session.+ */+export interface AgentUpdate {+ sessionId: string;+ sessionName: string;+ harness: string;+ pullRequestUrl?: string | null;+ kind: AgentUpdateKind;+ summary: string;+ since: string;+ options: string[];+}/*** List every AI agent the current user can manage - their own, their teams', and channel agents they can mention - with each agent's current instructions and settings: harness, model, channel availability, connected apps, permission behavior, and whether it is a coding or chat agent. Use this to find an agent's botId and read its current configuration before changing it with ConfigureAgent. ListBots covers plain webhook bots instead.*/diff --git a/crates/agent_session/AGENTS.md b/crates/agent_session/AGENTS.mdindex 89a3d6fa0d..fb264524fd 100644--- a/crates/agent_session/AGENTS.md+++ b/crates/agent_session/AGENTS.md@@ -19,6 +19,8 @@ consumer talks to.same fold run server-side for the SDK and agents.- `src/domain/read.rs` and `src/inbound/toolset/read_agent_session.rs`: bounded,view-authorized conversation reads using the shared transcript fold.+- `src/domain/updates.rs`: owner-scoped blocked and stalled coding-session updates,+ capped to 25 sessions before folding their logs.- `src/outbound/postgres.rs`: the session repository.- `src/outbound/broker_lifecycle_publisher.rs` /`broker_log_realtime.rs`: Kafka publication of lifecycle and log events.diff --git a/crates/agent_session/src/domain/coding_agents.rs b/crates/agent_session/src/domain/coding_agents.rsindex 1be92b65c9..c35323ef7c 100644--- a/crates/agent_session/src/domain/coding_agents.rs+++ b/crates/agent_session/src/domain/coding_agents.rs@@ -13,6 +13,7 @@ use super::routines::{PrepareRoutineSession, PromptRoutineSession, RoutineSessionAction, RoutineSessionError,RoutineSessions, ValidateRoutineSession,};+use super::updates::{AgentUpdates, CodingAgentUpdatesRepo, list_updates};#[cfg(test)]mod test;@@ -114,6 +115,11 @@ pub enum CodingAgentError {/// Owner-authorized coding delegation shared by tool and transport adapters.pub trait CodingAgentService: Send + Sync + 'static {+ /// List the caller's pending coding-session updates.+ fn list_updates(+ &self,+ user_id: MacroUserIdStr<'static>,+ ) -> Pin<Box<dyn Future<Output = Result<AgentUpdates, CodingAgentError>> + Send + '_>>;/// List the caller's configured, available coding personas.fn list(&self,@@ -134,26 +140,38 @@ pub trait CodingAgentService: Send + Sync + 'static {}/// Delegation policy over the existing persona directory and session lifecycle.-pub struct CodingAgentServiceImpl<Directory, Sessions> {+pub struct CodingAgentServiceImpl<Directory, Sessions, Updates> {directory: Directory,sessions: Sessions,+ updates: Updates,}-impl<Directory, Sessions> CodingAgentServiceImpl<Directory, Sessions> {+impl<Directory, Sessions, Updates: CodingAgentUpdatesRepo>+ CodingAgentServiceImpl<Directory, Sessions, Updates>+{/// Compose persona visibility with the normal session preparation and control path.- pub fn new(directory: Directory, sessions: Sessions) -> Self {+ pub fn new(directory: Directory, sessions: Sessions, updates: Updates) -> Self {Self {directory,sessions,+ updates,}}}-impl<Directory, Sessions> CodingAgentService for CodingAgentServiceImpl<Directory, Sessions>+impl<Directory, Sessions, Updates> CodingAgentService+ for CodingAgentServiceImpl<Directory, Sessions, Updates>whereDirectory: CodingAgentDirectory,Sessions: RoutineSessions,+ Updates: CodingAgentUpdatesRepo,{+ fn list_updates(+ &self,+ user_id: MacroUserIdStr<'static>,+ ) -> Pin<Box<dyn Future<Output = Result<AgentUpdates, CodingAgentError>> + Send + '_>> {+ Box::pin(list_updates(&self.updates, user_id))+ }fn list(&self,user_id: MacroUserIdStr<'static>,@@ -186,8 +204,8 @@ where}}-impl<Directory: CodingAgentDirectory, Sessions: RoutineSessions>- CodingAgentServiceImpl<Directory, Sessions>+impl<Directory: CodingAgentDirectory, Sessions: RoutineSessions, Updates: CodingAgentUpdatesRepo>+ CodingAgentServiceImpl<Directory, Sessions, Updates>{fn dispatch_selected(&self,diff --git a/crates/agent_session/src/domain/coding_agents/test.rs b/crates/agent_session/src/domain/coding_agents/test.rsindex c1eb48e4d2..d4b64de770 100644--- a/crates/agent_session/src/domain/coding_agents/test.rs+++ b/crates/agent_session/src/domain/coding_agents/test.rs@@ -108,7 +108,7 @@ fn candidate(is_coding: bool, available: bool) -> CodingAgentCandidate {}fn fixture() -> (- CodingAgentServiceImpl<Directory, Sessions>,+ CodingAgentServiceImpl<Directory, Sessions, ()>,Directory,Sessions,CodingAgentCandidate,@@ -118,7 +118,7 @@ fn fixture() -> (directory.candidates.lock().unwrap().push(agent.clone());let sessions = Sessions::default();(- CodingAgentServiceImpl::new(directory.clone(), sessions.clone()),+ CodingAgentServiceImpl::new(directory.clone(), sessions.clone(), ()),directory,sessions,agent,diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rsindex ac48195631..0f804be5d7 100644--- a/crates/agent_session/src/domain/mod.rs+++ b/crates/agent_session/src/domain/mod.rs@@ -26,6 +26,7 @@ pub mod session;pub mod session_task;/// Session link, channel, and team sharing.pub mod sharing;+pub mod updates;pub mod credentials;diff --git a/crates/agent_session/src/domain/updates.rs b/crates/agent_session/src/domain/updates.rsnew file mode 100644index 0000000000..6900a4f625--- /dev/null+++ b/crates/agent_session/src/domain/updates.rs@@ -0,0 +1,253 @@+//! Read-only view of coding sessions awaiting their owner.++use agent_fold::domain::model::FoldedMessage;+use agent_fold::domain::{+ lifecycle::LifecycleFold,+ model::{MessagePart, PendingInteraction, ToolDetail},+};+use chrono::{DateTime, Duration, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{+ coding_agents::CodingAgentError,+ model::{AgentSessionId, StoredAgentSessionLog},+};++#[cfg(test)]+mod test;++const MAX_SESSIONS: usize = 25;++/// Session facts selected by the persistence port, newest activity first.+#[derive(Debug, Clone)]+pub struct UpdateCandidate {+ pub id: AgentSessionId,+ pub name: String,+ pub harness: String,+ pub pull_request_url: Option<String>,+ pub turn_state: UpdateTurnState,+ pub is_archived: bool,+ pub last_activity: DateTime<Utc>,+}++/// States eligible for the updates query.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum UpdateTurnState {+ /// A pending interaction may need the owner.+ Blocked,+ /// An active turn may have stopped making progress.+ Running,+}++/// Owner-scoped listing and effective log reads.+pub trait CodingAgentUpdatesRepo: Send + Sync + 'static {+ fn candidates(+ &self,+ owner: MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<Vec<UpdateCandidate>, CodingAgentError>> + Send;+ fn log(+ &self,+ id: AgentSessionId,+ ) -> impl Future<Output = Result<Vec<StoredAgentSessionLog>, CodingAgentError>> + Send;+}++impl CodingAgentUpdatesRepo for () {+ async fn candidates(+ &self,+ _: MacroUserIdStr<'static>,+ ) -> Result<Vec<UpdateCandidate>, CodingAgentError> {+ Ok(Vec::new())+ }+ async fn log(&self, _: AgentSessionId) -> Result<Vec<StoredAgentSessionLog>, CodingAgentError> {+ Ok(Vec::new())+ }+}++/// A kind of action or inactivity the user should see.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "snake_case")]+pub enum AgentUpdateKind {+ Permission,+ Elicitation,+ ToolApproval,+ Stalled,+}++/// One pending interaction, or one stalled session.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "camelCase")]+pub struct AgentUpdate {+ pub session_id: Uuid,+ pub session_name: String,+ pub harness: String,+ pub pull_request_url: Option<String>,+ pub kind: AgentUpdateKind,+ pub summary: String,+ pub since: DateTime<Utc>,+ pub options: Vec<String>,+}++/// Bounded results; truncation means older qualifying sessions were not folded.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "camelCase")]+pub struct AgentUpdates {+ pub items: Vec<AgentUpdate>,+ pub truncated: bool,+ pub truncation_notice: Option<String>,+}++/// Read the owner's recent blocked or stalled sessions and fold only blocked logs.+#[tracing::instrument(+ name = "agent_session.list_updates",+ skip(repo, owner),+ fields(owner_count = 1, session_count, update_count, truncated),+ err+)]+pub async fn list_updates<R: CodingAgentUpdatesRepo>(+ repo: &R,+ owner: MacroUserIdStr<'static>,+) -> Result<AgentUpdates, CodingAgentError> {+ let mut candidates = repo.candidates(owner).await?;+ let truncated = candidates.len() > MAX_SESSIONS;+ candidates.truncate(MAX_SESSIONS);+ let span = tracing::Span::current();+ span.record("session_count", candidates.len());+ span.record("truncated", truncated);+ let now = Utc::now();+ let mut items = Vec::new();+ for candidate in candidates {+ if candidate.is_archived+ || matches!(candidate.harness.as_str(), "in-memory" | "macro-inmem")+ {+ continue;+ }+ match candidate.turn_state {+ UpdateTurnState::Running => {+ if candidate.last_activity <= now - Duration::minutes(20) {+ items.push(item(+ &candidate,+ AgentUpdateKind::Stalled,+ "No activity for over 20 minutes".into(),+ Vec::new(),+ ));+ }+ }+ UpdateTurnState::Blocked => {+ let mut fold = LifecycleFold::new();+ let mut pending_since: Vec<(PendingInteraction, DateTime<Utc>)> = Vec::new();+ for entry in repo.log(candidate.id).await? {+ let _ = fold.push(entry.entry);+ let pending = &fold.inner().metadata().pending_interactions;+ pending_since.retain(|(interaction, _)| pending.contains(interaction));+ for interaction in pending {+ if !pending_since.iter().any(|(seen, _)| seen == interaction) {+ pending_since.push((interaction.clone(), entry.created_at));+ }+ }+ }+ for pending in &fold.inner().metadata().pending_interactions {+ let since = pending_since+ .iter()+ .find_map(|(seen, since)| (seen == pending).then_some(*since))+ .unwrap_or(candidate.last_activity);+ items.push(pending_item(+ &candidate,+ pending,+ fold.inner().messages(),+ since,+ ));+ }+ }+ }+ }+ span.record("update_count", items.len());+ Ok(AgentUpdates {+ items,+ truncated,+ truncation_notice: truncated.then(|| "Only the 25 most recent qualifying sessions were inspected; older sessions may also need attention.".into()),+ })+}++fn pending_item(+ candidate: &UpdateCandidate,+ pending: &PendingInteraction,+ messages: &[FoldedMessage],+ since: DateTime<Utc>,+) -> AgentUpdate {+ let (kind, summary, options) = match pending {+ PendingInteraction::Permission(permission) => {+ let label = messages+ .iter()+ .filter(|message| message.id.0 == permission.turn)+ .flat_map(|message| message.parts.iter())+ .find_map(|part| match part {+ MessagePart::ToolUse {+ id, name, detail, ..+ } if id == &permission.tool_call => {+ let command = match detail {+ ToolDetail::Terminal {+ command: Some(command),+ ..+ } => Some(command.as_str()),+ _ => None,+ };+ Some(command.unwrap_or_else(|| name.display()).to_owned())+ }+ _ => None,+ })+ .unwrap_or_else(|| "a tool call".into());+ (+ AgentUpdateKind::Permission,+ format!("Approve {label}"),+ permission+ .options+ .iter()+ .map(|option| option.name.clone())+ .collect(),+ )+ }+ PendingInteraction::Elicitation(question) => (+ AgentUpdateKind::Elicitation,+ question.message.clone(),+ Vec::new(),+ ),+ PendingInteraction::ToolApproval(approval) => (+ AgentUpdateKind::ToolApproval,+ format!("Approve {} on {}", approval.tool_name, approval.server_name),+ Vec::new(),+ ),+ };+ let summary: String = summary+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+ .chars()+ .take(240)+ .collect();+ let mut update = item(candidate, kind, summary, options);+ update.since = since;+ update+}++fn item(+ candidate: &UpdateCandidate,+ kind: AgentUpdateKind,+ summary: String,+ options: Vec<String>,+) -> AgentUpdate {+ AgentUpdate {+ session_id: candidate.id.as_uuid(),+ session_name: candidate.name.clone(),+ harness: candidate.harness.clone(),+ pull_request_url: candidate.pull_request_url.clone(),+ kind,+ summary,+ since: candidate.last_activity,+ options,+ }+}diff --git a/crates/agent_session/src/domain/updates/test.rs b/crates/agent_session/src/domain/updates/test.rsnew file mode 100644index 0000000000..79fa77dc7c--- /dev/null+++ b/crates/agent_session/src/domain/updates/test.rs@@ -0,0 +1,155 @@+use super::*;+use agent_fold::domain::model::{+ AgentRequestId, ElicitationRequest, ElicitationRequestId, PendingElicitation,+ PendingPermission, PendingToolApproval, PermissionOption, PermissionOptionKind, ToolUseId,+};+use agent_fold::domain::model::{Author, FoldedMessage, MessagePart, ToolName, ToolStatus, TurnId};+use non_empty::NonEmpty;++fn candidate(state: UpdateTurnState, harness: &str, archived: bool) -> UpdateCandidate {+ UpdateCandidate {+ id: AgentSessionId::new(),+ name: "Fix login".into(),+ harness: harness.into(),+ pull_request_url: Some("https://github.com/example/repo/pull/1".into()),+ turn_state: state,+ is_archived: archived,+ last_activity: Utc::now() - Duration::minutes(21),+ }+}++struct Repo(Vec<UpdateCandidate>);++impl CodingAgentUpdatesRepo for Repo {+ async fn candidates(+ &self,+ _: MacroUserIdStr<'static>,+ ) -> Result<Vec<UpdateCandidate>, CodingAgentError> {+ Ok(self.0.clone())+ }+ async fn log(&self, _: AgentSessionId) -> Result<Vec<StoredAgentSessionLog>, CodingAgentError> {+ Ok(Vec::new())+ }+}++#[tokio::test]+async fn stalled_excludes_archived_and_non_coding_sessions() {+ let owner = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();+ let result = list_updates(+ &Repo(vec![+ candidate(UpdateTurnState::Running, "cursor", false),+ candidate(UpdateTurnState::Running, "cursor", true),+ candidate(UpdateTurnState::Running, "in-memory", false),+ ]),+ owner,+ )+ .await+ .unwrap();+ assert_eq!(result.items.len(), 1);+ assert_eq!(result.items[0].kind, AgentUpdateKind::Stalled);+ assert_eq!(result.items[0].session_name, "Fix login");+ assert_eq!(+ result.items[0].pull_request_url.as_deref(),+ Some("https://github.com/example/repo/pull/1")+ );+}++#[tokio::test]+async fn limits_session_work_and_explains_truncation() {+ let owner = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();+ let result = list_updates(+ &Repo(+ (0..26)+ .map(|_| candidate(UpdateTurnState::Running, "cursor", false))+ .collect(),+ ),+ owner,+ )+ .await+ .unwrap();+ assert_eq!(result.items.len(), 25);+ assert!(result.truncated);+ assert!(+ result+ .truncation_notice+ .as_deref()+ .unwrap()+ .contains("25 most recent")+ );+}++#[test]+fn pending_interaction_variants_keep_their_user_facing_details() {+ let session = candidate(UpdateTurnState::Blocked, "cursor", false);+ let transcript = FoldedMessage {+ id: TurnId(1),+ author: Author::Agent,+ request_id: None,+ parts: NonEmpty::new(vec![MessagePart::ToolUse {+ id: ToolUseId("tool-1".into()),+ name: ToolName::native("Bash"),+ status: ToolStatus::Pending,+ detail: ToolDetail::Terminal {+ command: Some("cargo test".into()),+ output: None,+ exit_code: None,+ },+ }])+ .unwrap(),+ stop: None,+ pending: false,+ posted_at: None,+ };+ let permission = pending_item(+ &session,+ &PendingInteraction::Permission(PendingPermission {+ request_id: AgentRequestId::Number(1),+ turn: 1,+ tool_call: ToolUseId("tool-1".into()),+ options: vec![PermissionOption {+ id: "allow".into(),+ name: "Allow once".into(),+ kind: PermissionOptionKind::AllowOnce,+ }],+ }),+ &[transcript],+ session.last_activity,+ );+ assert_eq!(permission.kind, AgentUpdateKind::Permission);+ assert_eq!(permission.summary, "Approve cargo test");+ assert_eq!(permission.options, ["Allow once"]);++ let elicitation = pending_item(+ &session,+ &PendingInteraction::Elicitation(PendingElicitation {+ request_id: ElicitationRequestId::Number(2),+ turn: 1,+ tool_call: None,+ message: "Which branch?".into(),+ request: ElicitationRequest::Unrecognized {+ mode: "other".into(),+ raw: serde_json::Value::Null,+ },+ }),+ &[],+ session.last_activity,+ );+ assert_eq!(elicitation.kind, AgentUpdateKind::Elicitation);+ assert_eq!(elicitation.summary, "Which branch?");++ let approval = pending_item(+ &session,+ &PendingInteraction::ToolApproval(PendingToolApproval {+ approval_id: "approval-1".into(),+ turn: 1,+ server_slug: "github".into(),+ server_name: "GitHub".into(),+ tool_name: "merge_pr".into(),+ requested_by: None,+ }),+ &[],+ session.last_activity,+ );+ assert_eq!(approval.kind, AgentUpdateKind::ToolApproval);+ assert_eq!(approval.summary, "Approve merge_pr on GitHub");+}diff --git a/crates/agent_session/src/inbound/coding_agents.rs b/crates/agent_session/src/inbound/coding_agents.rsindex 74a88ebe4f..87e745047b 100644--- a/crates/agent_session/src/inbound/coding_agents.rs+++ b/crates/agent_session/src/inbound/coding_agents.rs@@ -8,10 +8,11 @@ use axum::{http::StatusCode,middleware::{self, Next},response::{IntoResponse, Response},- routing::post,+ routing::{get, post},};use macro_authorization::{InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,+ UserOrInternal,};use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};@@ -20,9 +21,11 @@ use crate::domain::coding_agents::{CodingAgent, CodingAgentError, CodingAgentService, DispatchCodingAgentRequest,DispatchedCodingAgent,};+use crate::domain::updates::AgentUpdates;const DISPATCH_TIMEOUT: Duration = Duration::from_secs(120);const LIST_TIMEOUT: Duration = Duration::from_secs(10);+const UPDATES_TIMEOUT: Duration = Duration::from_secs(30);const MAX_COMMAND_BYTES: usize = 1024 * 1024;/// Independent state for the internal coding agent capability.@@ -64,6 +67,7 @@ pub fn coding_agents_router<Service: CodingAgentService, Auth: MacroAuthorizatio"/internal/coding-agents",Router::new().route("/list", post(list::<Service, Auth>))+ .route("/updates", get(updates::<Service, Auth>)).route("/dispatch", post(dispatch::<Service, Auth>)).route("/create-session", post(create::<Service, Auth>)).layer(DefaultBodyLimit::max(MAX_COMMAND_BYTES))@@ -114,8 +118,11 @@ impl IntoResponse for ApiError {}async fn bound_request(request: Request, next: Next) -> Response {- let is_dispatch = !request.uri().path().ends_with("/list");- let timeout = if is_dispatch {+ let path = request.uri().path();+ let is_dispatch = !path.ends_with("/list") && !path.ends_with("/updates");+ let timeout = if path.ends_with("/updates") {+ UPDATES_TIMEOUT+ } else if is_dispatch {DISPATCH_TIMEOUT} else {LIST_TIMEOUT@@ -152,6 +159,19 @@ async fn list<Service: CodingAgentService, Auth: MacroAuthorizationService>(}))}+async fn updates<Service: CodingAgentService, Auth: MacroAuthorizationService>(+ State(state): State<CodingAgentsState<Service, Auth>>,+ _internal: MacroAuthorizationExtractor<Auth, InternalOnly>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+) -> Result<Json<AgentUpdates>, ApiError> {+ Ok(Json(+ state+ .service+ .list_updates(user.authorization.user.macro_user_id)+ .await?,+ ))+}+async fn dispatch<Service: CodingAgentService, Auth: MacroAuthorizationService>(State(state): State<CodingAgentsState<Service, Auth>>,_internal: MacroAuthorizationExtractor<Auth, InternalOnly>,diff --git a/crates/agent_session/src/inbound/coding_agents/test.rs b/crates/agent_session/src/inbound/coding_agents/test.rsindex c84464e978..c3f1bef08f 100644--- a/crates/agent_session/src/inbound/coding_agents/test.rs+++ b/crates/agent_session/src/inbound/coding_agents/test.rs@@ -1,8 +1,9 @@use super::*;use axum::body::{Body, to_bytes};use macro_authorization::{- INTERNAL_API_KEY_HEADER, InternalAuthConfig, JwtValidator, MacroAuthorizationError,- MacroAuthorizationServiceImpl, NoBotAuthorizer, NoUserApiKeyAuthorizer, ValidatedIdentity,+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalAuthConfig, JwtValidator,+ MacroAuthorizationError, MacroAuthorizationServiceImpl, NoBotAuthorizer,+ NoUserApiKeyAuthorizer, ValidatedIdentity,};use rootcause::Report;use serde_json::{Value, json};@@ -34,6 +35,46 @@ impl JwtValidator for UserCredentials {}}+#[tokio::test]+async fn updates_use_the_authenticated_internal_acting_user() {+ let service = Arc::new(ServiceSpy::default());+ let response = app(service.clone())+ .oneshot(+ Request::builder()+ .method("GET")+ .uri("/internal/coding-agents/updates")+ .header(INTERNAL_API_KEY_HEADER, KEY)+ .header(INTERNAL_MACRO_USER_ID_HEADER, USER)+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ body(response).await,+ json!({"items":[],"truncated":false,"truncationNotice":null})+ );+ assert_eq!(+ service.seen.lock().unwrap().as_slice(),+ &[json!({"updates_user_id":USER})]+ );++ let denied = app(service.clone())+ .oneshot(+ Request::builder()+ .method("GET")+ .uri("/internal/coding-agents/updates")+ .header(INTERNAL_API_KEY_HEADER, KEY)+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_ne!(denied.status(), StatusCode::OK);+ assert_eq!(service.seen.lock().unwrap().len(), 1);+}+#[derive(Default)]struct ServiceSpy {seen: Mutex<Vec<Value>>,@@ -41,6 +82,28 @@ struct ServiceSpy {}impl CodingAgentService for ServiceSpy {+ fn list_updates(+ &self,+ user_id: MacroUserIdStr<'static>,+ ) -> Pin<+ Box<+ dyn Future<Output = Result<crate::domain::updates::AgentUpdates, CodingAgentError>>+ + Send+ + '_,+ >,+ > {+ Box::pin(async move {+ self.seen+ .lock()+ .unwrap()+ .push(json!({"updates_user_id": user_id}));+ Ok(crate::domain::updates::AgentUpdates {+ items: Vec::new(),+ truncated: false,+ truncation_notice: None,+ })+ })+ }fn create(&self,command: DispatchCodingAgentRequest,diff --git a/crates/agent_session/src/inbound/toolset/coding_agents.rs b/crates/agent_session/src/inbound/toolset/coding_agents.rsindex 63bf8a1d9e..64f26d766e 100644--- a/crates/agent_session/src/inbound/toolset/coding_agents.rs+++ b/crates/agent_session/src/inbound/toolset/coding_agents.rs@@ -15,6 +15,7 @@ use crate::domain::coding_agents::{CodingAgent, CodingAgentError, CodingAgentService, DispatchCodingAgentRequest,DispatchedCodingAgent,};+use crate::domain::updates::AgentUpdates;#[cfg(test)]mod test;@@ -44,6 +45,36 @@ pub struct ListCodingAgentsResponse {pub agents: Vec<CodingAgent>,}+/// Read the current user's coding sessions that need attention.+#[derive(Debug, Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+#[schemars(+ title = "ListAgentUpdates",+ description = "List the current user's coding-agent sessions waiting for an answer or stalled for over 20 minutes. The user answers permissions and questions through the cards Macro renders from this tool's result. To send a coding agent instructions, use ManageAgentSession with a prompt. To recall the user's earlier decisions about these agents, search earlier agent conversations with ContentSearch (entity_types agent_sessions) and read them with ReadAgentSession."+)]+pub struct ListAgentUpdates {}++impl ToolAnnotated for ListAgentUpdates {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read agent updates");+}++#[async_trait]+impl AsyncTool<CodingAgentToolContext> for ListAgentUpdates {+ type Output = AgentUpdates;++ async fn call(+ &self,+ context: ServiceContext<CodingAgentToolContext>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ context+ .service+ .list_updates(request.user_id)+ .await+ .map_err(tool_error)+ }+}+impl ToolAnnotated for ListCodingAgents {const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List coding agents");}@@ -126,6 +157,7 @@ pub fn coding_agent_toolset() -> AsyncToolCollection<CodingAgentToolContext> {.add_tool::<super::manage_agent_session::ManageAgentSession, CodingAgentToolContext>().add_tool::<CreateAgentSession, CodingAgentToolContext>().add_tool::<ListCodingAgents, CodingAgentToolContext>()+ .add_tool::<ListAgentUpdates, CodingAgentToolContext>().add_tool::<DispatchCodingAgent, CodingAgentToolContext>()}diff --git a/crates/agent_session/src/inbound/toolset/coding_agents/test.rs b/crates/agent_session/src/inbound/toolset/coding_agents/test.rsindex 16ad723d8c..307deb2271 100644--- a/crates/agent_session/src/inbound/toolset/coding_agents/test.rs+++ b/crates/agent_session/src/inbound/toolset/coding_agents/test.rs@@ -12,6 +12,25 @@ struct Service {}impl CodingAgentService for Service {+ fn list_updates(+ &self,+ user_id: MacroUserIdStr<'static>,+ ) -> Pin<+ Box<+ dyn Future<Output = Result<crate::domain::updates::AgentUpdates, CodingAgentError>>+ + Send+ + '_,+ >,+ > {+ Box::pin(async move {+ self.list_callers.lock().unwrap().push(user_id);+ Ok(crate::domain::updates::AgentUpdates {+ items: Vec::new(),+ truncated: false,+ truncation_notice: None,+ })+ })+ }fn create(&self,command: DispatchCodingAgentRequest,@@ -63,6 +82,16 @@ async fn tools_always_use_the_authenticated_request_identity() {assert!(listed.agents.is_empty());assert_eq!(*service.list_callers.lock().unwrap(), vec![caller.clone()]);+ let updates = ListAgentUpdates {}+ .call(context.clone(), request.clone())+ .await+ .unwrap();+ assert!(updates.items.is_empty());+ assert_eq!(+ *service.list_callers.lock().unwrap(),+ vec![caller.clone(), caller.clone()]+ );+let tool = DispatchCodingAgent {agent_id: macro_uuid::generate_uuid_v7(),prompt: "Implement repository issue 123".into(),@@ -84,6 +113,12 @@ fn tools_reject_an_ai_supplied_user_identity() {})).is_err());+ assert!(+ serde_json::from_value::<ListAgentUpdates>(+ serde_json::json!({"user_id": "macro|[email protected]"})+ )+ .is_err()+ );assert!(serde_json::from_value::<DispatchCodingAgent>(serde_json::json!({"agent_id": macro_uuid::generate_uuid_v7(),diff --git a/crates/agent_session/src/outbound/coding_agents_client.rs b/crates/agent_session/src/outbound/coding_agents_client.rsindex ea07d34f91..ab8b8f62f1 100644--- a/crates/agent_session/src/outbound/coding_agents_client.rs+++ b/crates/agent_session/src/outbound/coding_agents_client.rs@@ -2,7 +2,7 @@use std::{future::Future, pin::Pin, time::Duration};-use macro_authorization::INTERNAL_API_KEY_HEADER;+use macro_authorization::{INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER};use macro_user_id::user_id::MacroUserIdStr;use reqwest::{Client, Response, StatusCode, Url, header::HeaderValue};use serde::{Deserialize, Serialize, de::DeserializeOwned};@@ -11,15 +11,18 @@ use crate::domain::coding_agents::{CodingAgent, CodingAgentError, CodingAgentService, DispatchCodingAgentRequest,DispatchedCodingAgent,};+use crate::domain::updates::AgentUpdates;const DISPATCH_TIMEOUT: Duration = Duration::from_secs(120);const LIST_TIMEOUT: Duration = Duration::from_secs(10);+const UPDATES_TIMEOUT: Duration = Duration::from_secs(30);const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);const MAX_RESPONSE_BYTES: usize = 1024 * 1024;#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Operation {List,+ Updates,Dispatch,Create,}@@ -28,6 +31,7 @@ impl Operation {fn path(self) -> &'static str {match self {Self::List => "internal/coding-agents/list",+ Self::Updates => "internal/coding-agents/updates",Self::Create => "internal/coding-agents/create-session",Self::Dispatch => "internal/coding-agents/dispatch",}@@ -36,13 +40,14 @@ impl Operation {fn timeout(self) -> Duration {match self {Self::List => LIST_TIMEOUT,+ Self::Updates => UPDATES_TIMEOUT,Self::Dispatch | Self::Create => DISPATCH_TIMEOUT,}}fn uncertain_error(self) -> CodingAgentError {match self {- Self::List => CodingAgentError::OperationFailed,+ Self::List | Self::Updates => CodingAgentError::OperationFailed,Self::Dispatch | Self::Create => CodingAgentError::DispatchDeliveryUnknown,}}@@ -92,6 +97,7 @@ impl CodingAgentsClient {&self,operation: Operation,command: &impl Serialize,+ acting_user: Option<&MacroUserIdStr<'static>>,) -> Result<T, CodingAgentError> {let url = self.base_url@@ -99,13 +105,20 @@ impl CodingAgentsClient {.map_err(|_| CodingAgentError::OperationFailed)?;let mut headers = reqwest::header::HeaderMap::new();macro_tower_layers::inject_trace_headers(&mut headers);- let response = self- .client- .post(url)+ let builder = if operation == Operation::Updates {+ self.client.get(url).header(+ INTERNAL_MACRO_USER_ID_HEADER,+ acting_user+ .ok_or(CodingAgentError::InvalidCommand)?+ .as_ref(),+ )+ } else {+ self.client.post(url).json(command)+ };+ let response = builder.headers(headers).header(INTERNAL_API_KEY_HEADER, self.internal_key.clone()).timeout(operation.timeout())- .json(command).send().await.map_err(|_| operation.uncertain_error())?;@@ -125,12 +138,14 @@ impl CodingAgentsClient {CodingAgentError::Unavailable => status == StatusCode::NOT_FOUND,CodingAgentError::OperationFailed => {status == StatusCode::INTERNAL_SERVER_ERROR- || (operation == Operation::List && status == StatusCode::GATEWAY_TIMEOUT)+ || (matches!(operation, Operation::List | Operation::Updates)+ && status == StatusCode::GATEWAY_TIMEOUT)}CodingAgentError::DispatchFailed { .. } => status == StatusCode::BAD_GATEWAY,CodingAgentError::DispatchDeliveryUnknown => {status == StatusCode::BAD_GATEWAY- || (operation != Operation::List && status == StatusCode::GATEWAY_TIMEOUT)+ || (matches!(operation, Operation::Dispatch | Operation::Create)+ && status == StatusCode::GATEWAY_TIMEOUT)}};// A contradictory envelope is not evidence that dispatch was refused.@@ -177,12 +192,18 @@ async fn bounded_body(mut response: Response) -> Result<Vec<u8>, CodingAgentErro}impl CodingAgentService for CodingAgentsClient {+ fn list_updates(+ &self,+ user_id: MacroUserIdStr<'static>,+ ) -> Pin<Box<dyn Future<Output = Result<AgentUpdates, CodingAgentError>> + Send + '_>> {+ Box::pin(async move { self.command(Operation::Updates, &(), Some(&user_id)).await })+ }fn create(&self,command: DispatchCodingAgentRequest,) -> Pin<Box<dyn Future<Output = Result<DispatchedCodingAgent, CodingAgentError>> + Send + '_>>{- Box::pin(async move { self.command(Operation::Create, &command).await })+ Box::pin(async move { self.command(Operation::Create, &command, None).await })}fn list(@@ -191,7 +212,7 @@ impl CodingAgentService for CodingAgentsClient {) -> Pin<Box<dyn Future<Output = Result<Vec<CodingAgent>, CodingAgentError>> + Send + '_>> {Box::pin(async move {let response: ListResponse = self- .command(Operation::List, &ListRequest { user_id })+ .command(Operation::List, &ListRequest { user_id }, None).await?;Ok(response.agents)})@@ -202,7 +223,7 @@ impl CodingAgentService for CodingAgentsClient {command: DispatchCodingAgentRequest,) -> Pin<Box<dyn Future<Output = Result<DispatchedCodingAgent, CodingAgentError>> + Send + '_>>{- Box::pin(async move { self.command(Operation::Dispatch, &command).await })+ Box::pin(async move { self.command(Operation::Dispatch, &command, None).await })}}diff --git a/crates/agent_session/src/outbound/coding_agents_client/test.rs b/crates/agent_session/src/outbound/coding_agents_client/test.rsindex a175513607..a2d5456a2c 100644--- a/crates/agent_session/src/outbound/coding_agents_client/test.rs+++ b/crates/agent_session/src/outbound/coding_agents_client/test.rs@@ -11,6 +11,35 @@ use tokio::{};use uuid::Uuid;+#[tokio::test]+async fn updates_send_acting_user_only_in_authenticated_header() {+ let server = server(vec![Reply::json(+ 200,+ json!({"items": [], "truncated": false, "truncationNotice": null}),+ )])+ .await;+ let client = CodingAgentsClient::new(&server.url, KEY).unwrap();+ let updates = client+ .list_updates(MacroUserIdStr::try_from(USER).unwrap())+ .await+ .unwrap();+ assert!(updates.items.is_empty());+ let requests = server.requests.lock().unwrap();+ assert_eq!(requests.len(), 1);+ assert!(+ requests[0]+ .head+ .contains("GET /internal/coding-agents/updates")+ );+ assert!(+ requests[0]+ .head+ .to_lowercase()+ .contains(&format!("{}: {USER}", INTERNAL_MACRO_USER_ID_HEADER))+ );+ assert_eq!(requests[0].body, Value::Null);+}+const KEY: &str = "test-internal-key";const USER: &str = "macro|[email protected]";@@ -72,7 +101,7 @@ async fn server(replies: Vec<Reply>) -> Server {let len = head.lines().find_map(|line| line.strip_prefix("content-length: "))- .unwrap()+ .unwrap_or("0").parse::<usize>().unwrap();break (end + 4, len);@@ -86,8 +115,11 @@ async fn server(replies: Vec<Reply>) -> Server {}captured.lock().unwrap().push(Request {head: String::from_utf8(bytes[..header_end].to_vec()).unwrap(),- body: serde_json::from_slice(&bytes[header_end..header_end + content_length])- .unwrap(),+ body: if content_length == 0 {+ Value::Null+ } else {+ serde_json::from_slice(&bytes[header_end..header_end + content_length]).unwrap()+ },});tokio::time::sleep(reply.delay).await;let response = format!(diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex fdae3816b2..cee7806018 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -34,6 +34,7 @@ use crate::domain::ports::{};use crate::domain::sharing::{SessionBotOwnership, originating_channel_access};use crate::domain::turn_state::moves_session_list;+use crate::domain::updates::{CodingAgentUpdatesRepo, UpdateCandidate, UpdateTurnState};use crate::outbound::connection_gateway_realtime::SessionAudience;use agent_client_protocol::schema::v1::SessionId;use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};@@ -64,6 +65,64 @@ pub struct PgAgentSessionRepo<B> {list_policy: crate::domain::list_visibility::SessionListPolicy,}+impl<B: BotFacts + 'static> CodingAgentUpdatesRepo for PgAgentSessionRepo<B> {+ async fn candidates(+ &self,+ owner: MacroUserIdStr<'static>,+ ) -> std::result::Result<Vec<UpdateCandidate>, crate::domain::coding_agents::CodingAgentError>+ {+ let rows = sqlx::query!(+ r#"+ SELECT s.id, s.name, s.harness, s.pull_request_url, s.turn_state,+ s.is_archived, GREATEST(s.modified_at, recent.created_at) AS "last_activity!"+ FROM agent_session s+ LEFT JOIN agent_configs config ON config.bot_id = s.bot_id+ LEFT JOIN LATERAL (+ SELECT created_at FROM agent_session_log+ WHERE agent_session_id = s.id ORDER BY created_at DESC LIMIT 1+ ) recent ON true+ WHERE s.owner_id = $1 AND NOT s.is_archived+ AND COALESCE(config.is_coding, s.harness NOT IN ('in-memory', 'macro-inmem'))+ AND (s.turn_state = 'blocked' OR+ (s.turn_state = 'running' AND GREATEST(s.modified_at, recent.created_at) <= now() - interval '20 minutes'))+ ORDER BY GREATEST(s.modified_at, recent.created_at) DESC, s.id DESC+ LIMIT 26+ "#,+ owner.as_ref(),+ ).fetch_all(&self.pool).await.map_err(|_| crate::domain::coding_agents::CodingAgentError::OperationFailed)?;+ Ok(rows+ .into_iter()+ .filter_map(|row| {+ Some(UpdateCandidate {+ id: AgentSessionId::new_from_uuid(row.id),+ name: row.name,+ harness: row.harness,+ pull_request_url: row.pull_request_url,+ turn_state: match row.turn_state.as_deref()? {+ "blocked" => UpdateTurnState::Blocked,+ "running" => UpdateTurnState::Running,+ _ => return None,+ },+ is_archived: row.is_archived,+ last_activity: row.last_activity,+ })+ })+ .collect())+ }++ async fn log(+ &self,+ id: AgentSessionId,+ ) -> std::result::Result<+ Vec<StoredAgentSessionLog>,+ crate::domain::coding_agents::CodingAgentError,+ > {+ AgentSessionLogRepo::list_by_session(self, id)+ .await+ .map_err(|_| crate::domain::coding_agents::CodingAgentError::OperationFailed)+ }+}+impl<B> std::fmt::Debug for PgAgentSessionRepo<B> {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {formatterdiff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rsindex 8bd64e7193..0a827942f4 100644--- a/crates/ai_tools/src/test.rs+++ b/crates/ai_tools/src/test.rs@@ -100,13 +100,23 @@ fn coding_dispatch_is_available_to_every_host_but_not_internal_subagents() {AiHost::Mcp,] {let tools = tools_for(host);- for name in ["ListCodingAgents", "DispatchCodingAgent"] {+ for name in [+ "ListCodingAgents",+ "ListAgentUpdates",+ "DispatchCodingAgent",+ ] {assert!(tools.toolset.tools.contains_key(name), "{host:?}: {name}");+ }+ for name in ["ListCodingAgents", "DispatchCodingAgent"] {assert!(tools.prompt.to_string().contains(name), "{host:?}: {name}");}}let subagent = subagent_toolset();- for name in ["ListCodingAgents", "DispatchCodingAgent"] {+ for name in [+ "ListCodingAgents",+ "ListAgentUpdates",+ "DispatchCodingAgent",+ ] {assert!(!subagent.tools.contains_key(name));}}diff --git a/crates/macro_db_client/migrations/20261030203640_index_agent_session_owner_turn_state.sql b/crates/macro_db_client/migrations/20261030203640_index_agent_session_owner_turn_state.sqlnew file mode 100644index 0000000000..5802a2eacf--- /dev/null+++ b/crates/macro_db_client/migrations/20261030203640_index_agent_session_owner_turn_state.sql@@ -0,0 +1,4 @@+-- no-transaction+CREATE INDEX CONCURRENTLY agent_session_owner_active_turn_state_idx+ON agent_session (owner_id, turn_state, modified_at DESC)+WHERE NOT is_archived AND turn_state IN ('blocked', 'running');diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex 1fde4fc132..5e86b27b17 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -333,6 +333,15 @@ you can follow up there. Reloading the chat restores the same session card.Failed dispatches do not show a successful session card. If no coding agents areavailable, configure one in Agents before retrying.+Ask a chat agent what your coding agents need from you and it calls+`ListAgentUpdates`: your non-archived coding sessions waiting on a permission,+question, or tool approval, plus sessions running with no activity for 20+minutes (at most 25 sessions; the result says when it was truncated). The+result shows the same live cards as the Agents home, so you answer in place;+agents cannot answer for you. To send a coding agent instructions the chat uses+`ManageAgentSession`, and to recall earlier decisions it searches past agent+conversations with `ContentSearch` and reads them with `ReadAgentSession`.+## Where chats liveThe Agents conversation list shows row skeletons after a short delay on first@@ -399,6 +408,10 @@ the shimmer.Pull request filters; choices within a category are ORed and categories areANDed. Grouping and filters are remembered per user. Clear filters from the menuor an empty filtered list.+ With the `enable-agent-updates` flag, an **Open PRs** section sits above+ Conversations: your non-archived coding sessions whose pull request is open or+ draft, newest first, using the same rows (they stay in Conversations too). It+ is hidden when empty.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. A session that is starting or@@ -538,6 +551,15 @@ the shimmer.including when it is the agent’s configured default; there is no separate default row.Disconnected Cursor offers **Connect Cursor**, opening Settings → Agents → Runtimes.The built-in sandbox and paired macrod runtimes are not offered here.+- With the `enable-agent-updates` flag, the New conversation page shows a stack+ of pending updates from your coding sessions under the composer: one card per+ permission request, question, or tool approval of a blocked session, plus+ sessions running with no activity for 20 minutes. The stack rests collapsed+ (front card plus two peeking) so the page does not scroll; click it or **Show+ all** to unstack. Cards answer in place with the session's own options, and+ every card has **Chat about this** (adds a mention of that session to the+ composer draft) and **Open session**. Answered cards leave once the session+ stops waiting. Check with a coding session blocked on a permission prompt.- Selecting an agent changes the heading: **What should we work on?** for chatagents and **What should we build?** for coding agents. The draft stays intactwhen changing agents. Unsent New conversation text and attachments also comediff --git a/services/agent_harness_service/src/api/test.rs b/services/agent_harness_service/src/api/test.rsindex 75360884fc..641a32ba67 100644--- a/services/agent_harness_service/src/api/test.rs+++ b/services/agent_harness_service/src/api/test.rs@@ -330,6 +330,22 @@ async fn gateway_egress_keeps_authentication_and_git_basic_challenge() {}impl CodingAgentService for RoutineSessionsSpy {+ fn list_updates(+ &self,+ user_id: macro_user_id::user_id::MacroUserIdStr<'static>,+ ) -> Pin<+ Box<+ dyn Future<+ Output = Result<agent_session::domain::updates::AgentUpdates, CodingAgentError>,+ > + Send+ + '_,+ >,+ > {+ Box::pin(async move {+ self.0.lock().unwrap().push(user_id.to_string());+ Err(CodingAgentError::Forbidden)+ })+ }fn create(&self,command: DispatchCodingAgentRequest,diff --git a/services/agent_harness_service/src/coding_agents.rs b/services/agent_harness_service/src/coding_agents.rsindex 0e5e298032..5211974a79 100644--- a/services/agent_harness_service/src/coding_agents.rs+++ b/services/agent_harness_service/src/coding_agents.rs@@ -7,6 +7,7 @@ use agent_session::domain::coding_agents::{CodingAgentServiceImpl,};use agent_session::domain::routines::RoutineSessions;+use agent_session::domain::updates::CodingAgentUpdatesRepo;use agent_session::inbound::coding_agents::{CodingAgentsState, coding_agents_router};use axum::Router;use bots::domain::ports::BotService;@@ -171,18 +172,20 @@ impl RuntimeConnections {}/// Reuse authorized session preparation and the normal first-prompt pipeline.-pub fn router<Directory, Sessions, Auth>(+pub fn router<Directory, Sessions, Updates, Auth>(directory: Directory,sessions: Sessions,+ updates: Updates,authorization: MacroAuthorizationState<Auth>,) -> RouterwhereDirectory: CodingAgentDirectory,Sessions: RoutineSessions,+ Updates: CodingAgentUpdatesRepo,Auth: MacroAuthorizationService,{coding_agents_router(CodingAgentsState::new(- Arc::new(CodingAgentServiceImpl::new(directory, sessions)),+ Arc::new(CodingAgentServiceImpl::new(directory, sessions, updates)),authorization,))}diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 1f87a4fdf4..573e19b04c 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -1501,6 +1501,7 @@ async fn run() -> anyhow::Result<()> {(*harness).clone(),routine_sessions::PipedreamConnectedApps(PgConnectionRepo::new(pool.clone())),),+ session_repo.clone(),MacroAuthorizationState::new(Arc::new(authorization_service.clone())),);let gateway_state = RuntimeGatewayState::new(