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
unchud(agent): agent composer modal (#6350)
Eric Hayes90a79168ee50
diff --git a/apps/web/src/components/app/split-layout/layoutUrlSync.ts b/apps/web/src/components/app/split-layout/layoutUrlSync.tsindex bd3773bcac..1e3a23dfbd 100644--- a/apps/web/src/components/app/split-layout/layoutUrlSync.ts+++ b/apps/web/src/components/app/split-layout/layoutUrlSync.ts@@ -122,14 +122,13 @@ export function createLayoutUrlSync(const nextState = managerUrlState();const pathChanged = nextState.segments.join('/') !== pairs().join('/');const currentQuery = new URLSearchParams(environment.search());- // On a direct macrod pairing link, the settings split initially serializes- // its default tab before the settings wrapper reads `settings/harness`.- // Let that wrapper select Harness instead of replacing the requested URL.+ // Action links can mount before settings has selected its requested tab.+ // Preserve their query until the wrapper has canonicalized that tab.if (pathChanged &&pairs()[0] === 'settings' &&- pairs()[1] === 'harness' &&- currentQuery.get('pair')+ ((pairs()[1] === 'harness' && currentQuery.get('pair')) ||+ (pairs()[1] === 'agents' && currentQuery.get('createAgent') === 'true'))) {return;}diff --git a/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts b/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.tsindex 1b52cb8681..758a3d7050 100644--- a/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts+++ b/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts@@ -282,4 +282,15 @@ describe('layout URL synchronization', () => {harness.dispose();});++ it('preserves agent creation links while settings canonicalizes its tab', async () => {+ const harness = createHarness({+ managerContent: [{ type: 'component', id: 'settings' }],+ urlSegments: ['settings', 'agents'],+ search: '?createAgent=true',+ });+ await flushUrlSync();+ expect(harness.navigate).not.toHaveBeenCalled();+ harness.dispose();+ });});diff --git a/apps/web/src/features/block-agent/component/AgentPicker.test.tsx b/apps/web/src/features/block-agent/component/AgentPicker.test.tsxnew file mode 100644index 0000000000..c2bedc40ac--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentPicker.test.tsx@@ -0,0 +1,141 @@+import { fireEvent, render, screen, within } from '@solidjs/testing-library';+import { createSignal, type JSX } from 'solid-js';+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { AgentPicker } from './AgentPicker';+import type { PersonaOption } from './compose-agent-session-options';++vi.mock('@ui', () => {+ const Container = (props: { children?: JSX.Element }) => props.children;+ return {+ Avatar: Object.assign(Container, {+ Fallback: Container,+ Image: () => null,+ }),+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+ };+});++beforeAll(() => {+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {+ configurable: true,+ value: vi.fn(),+ });+});+afterAll(() => {+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView');+});++const personas: PersonaOption[] = Array.from({ length: 8 }, (_, index) => ({+ id: `agent-${index}`,+ name: `Agent ${index}`,+ handle: `helper-${index}`,+ harness: 'in-memory',+ defaultModel: 'test-model',+ description: index === 7 ? 'Reviews pull requests' : undefined,+ unavailableReason: index === 1 ? 'Connect this agent first' : undefined,+}));++function mount(+ recentIds: string[] = [],+ selectedId = 'agent-0',+ disabled = false,+ onConnect?: (id: string) => void+) {+ const onSelect = vi.fn();+ render(() => {+ const [selected, setSelected] = createSignal(selectedId);+ return (+ <AgentPicker+ personas={personas.map((persona) => ({+ ...persona,+ connectLabel:+ onConnect && persona.id === 'agent-1' ? 'Connect agent' : undefined,+ }))}+ recentIds={recentIds}+ selected={personas.find((persona) => persona.id === selected())}+ disabled={disabled}+ loading={false}+ error={false}+ onConnect={onConnect ?? vi.fn()}+ onSelect={(id) => {+ setSelected(id);+ onSelect(id);+ }}+ />+ );+ });+ return onSelect;+}++const rows = () => screen.getAllByRole('radio');++describe('agent picker', () => {+ it('focuses setup actions with arrow keys without selecting or activating them', () => {+ const onConnect = vi.fn();+ const onSelect = mount([], 'agent-0', false, onConnect);+ const first = screen.getByRole('radio', { name: /Agent 0/ });+ const connect = screen.getByRole('button', { name: 'Connect agent' });+ fireEvent.keyDown(first, { key: 'ArrowRight' });+ expect(document.activeElement).toBe(connect);+ expect(onSelect).not.toHaveBeenCalled();+ expect(onConnect).not.toHaveBeenCalled();+ fireEvent.click(connect);+ expect(onConnect).toHaveBeenCalledWith('agent-1');+ expect(onSelect).not.toHaveBeenCalled();+ fireEvent.keyDown(connect, { key: 'ArrowRight' });+ expect(onSelect).toHaveBeenCalledWith('agent-2');+ });+ it('keeps every agent in the horizontal strip, with recent choices first', () => {+ const recent = ['agent-7', 'agent-5', 'agent-3', 'agent-2', 'agent-0'];+ mount(recent);+ expect(+ screen.getByRole('radiogroup').getAttribute('aria-orientation')+ ).toBe('horizontal');+ expect(rows().map((row) => row.dataset.personaId)).toEqual([+ ...recent,+ 'agent-1',+ 'agent-4',+ 'agent-6',+ ]);+ expect(screen.queryByRole('searchbox')).toBeNull();+ expect(screen.queryByRole('button', { name: /Browse all/ })).toBeNull();+ for (const row of rows()) {+ expect(within(row).getByText(/@helper-/)).toBeTruthy();+ expect(within(row).queryByText(/default/)).toBeNull();+ expect(within(row).queryByText('coding')).toBeNull();+ }+ });++ it('supports keyboard selection across the full list and skips unavailable agents', () => {+ const onSelect = mount();+ rows()[0].focus();+ fireEvent.keyDown(rows()[0], { key: 'ArrowRight' });+ expect(onSelect).toHaveBeenLastCalledWith('agent-2');+ expect(document.activeElement).toBe(rows()[2]);+ expect(rows()[2].scrollIntoView).toHaveBeenLastCalledWith({+ block: 'nearest',+ inline: 'nearest',+ });+ fireEvent.keyDown(rows()[2], { key: 'ArrowLeft' });+ expect(onSelect).toHaveBeenLastCalledWith('agent-0');+ expect(document.activeElement).toBe(rows()[0]);+ fireEvent.keyDown(rows()[0], { key: 'ArrowLeft' });+ expect(onSelect).toHaveBeenLastCalledWith('agent-7');+ fireEvent.keyDown(rows()[7], { key: 'ArrowRight' });+ expect(onSelect).toHaveBeenLastCalledWith('agent-0');+ fireEvent.keyDown(rows()[0], { key: 'End' });+ expect(onSelect).toHaveBeenLastCalledWith('agent-7');+ expect(document.activeElement).toBe(rows()[7]);+ fireEvent.keyDown(rows()[7], { key: 'Home' });+ expect(onSelect).toHaveBeenLastCalledWith('agent-0');+ fireEvent.click(rows()[1]);+ expect(onSelect).toHaveBeenLastCalledWith('agent-0');+ });++ it('does not change the agent during session creation', () => {+ const onSelect = mount([], 'agent-0', true);+ fireEvent.click(rows()[2]);+ fireEvent.keyDown(rows()[0], { key: 'ArrowRight' });+ expect(onSelect).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/block-agent/component/AgentPicker.tsx b/apps/web/src/features/block-agent/component/AgentPicker.tsxnew file mode 100644index 0000000000..296f7159c8--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentPicker.tsx@@ -0,0 +1,171 @@+import CheckIcon from '@phosphor/check.svg';+import RobotIcon from '@phosphor/robot.svg';+import { Avatar, cn } from '@ui';+import { createMemo, For, Show } from 'solid-js';+import type { PersonaOption } from './compose-agent-session-options';++/** Horizontally scrollable agent choices, with recent selections first. */+export function AgentPicker(props: {+ personas: PersonaOption[];+ recentIds: string[];+ selected: PersonaOption | undefined;+ loading: boolean;+ error: boolean;+ disabled: boolean;+ onSelect: (id: string) => void;+ onConnect: (id: string) => void;+}) {+ let listRef: HTMLDivElement | undefined;+ const sorted = createMemo(() => {+ const order = new Map(props.recentIds.map((id, index) => [id, index]));+ return [...props.personas].sort(+ (a, b) =>+ (order.get(a.id) ?? props.recentIds.length) -+ (order.get(b.id) ?? props.recentIds.length)+ );+ });+ const selectable = () => sorted().filter((item) => !item.unavailableReason);+ const navigable = () =>+ sorted().filter((item) => !item.unavailableReason || item.connectLabel);+ const tabStop = () =>+ selectable().find((item) => item.id === props.selected?.id)?.id ??+ selectable()[0]?.id;++ const focusAgent = (id: string) => {+ const row = Array.from(+ listRef?.querySelectorAll<HTMLElement>('[data-persona-id]') ?? []+ ).find((element) => element.dataset.personaId === id);+ row?.focus({ preventScroll: true });+ row?.scrollIntoView({ block: 'nearest', inline: 'nearest' });+ };+ const moveSelection = (event: KeyboardEvent) => {+ if (props.disabled) return;+ const choices = navigable();+ if (choices.length === 0) return;+ const focusedId =+ event.target instanceof HTMLElement+ ? event.target.closest<HTMLElement>('[data-persona-id]')?.dataset+ .personaId+ : undefined;+ const current = choices.findIndex(+ (item) => item.id === (focusedId ?? props.selected?.id)+ );+ let next: PersonaOption | undefined;+ if (event.key === 'ArrowRight') {+ next = choices[(current + 1) % choices.length];+ } else if (event.key === 'ArrowLeft') {+ next = choices[(current - 1 + choices.length) % choices.length];+ } else if (event.key === 'Home') {+ next = choices[0];+ } else if (event.key === 'End') {+ next = choices.at(-1);+ }+ if (!next) return;+ event.preventDefault();+ event.stopPropagation();+ if (!next.connectLabel) props.onSelect(next.id);+ focusAgent(next.id);+ };++ return (+ <section class="flex min-w-0 shrink-0 flex-col" aria-label="Agent">+ <Show when={props.loading}>+ <span role="status" class="px-2 pb-1 text-xs text-ink-muted">+ Loading agents…+ </span>+ </Show>+ <div+ ref={listRef}+ role="radiogroup"+ aria-label="Agent"+ aria-orientation="horizontal"+ class="flex min-w-0 gap-2 overflow-x-auto overscroll-x-contain"+ onKeyDown={moveSelection}+ >+ <For each={sorted()}>+ {(persona) => {+ const selected = () => persona.id === props.selected?.id;+ const disabled = () =>+ props.disabled ||+ (!!persona.unavailableReason && !persona.connectLabel);+ return (+ <button+ type="button"+ role={persona.connectLabel ? 'button' : 'radio'}+ aria-label={persona.connectLabel}+ aria-checked={persona.connectLabel ? undefined : selected()}+ aria-disabled={disabled()}+ data-persona-id={persona.id}+ tabIndex={+ persona.connectLabel || tabStop() === persona.id ? 0 : -1+ }+ title={[+ persona.name,+ `@${persona.handle}`,+ persona.unavailableReason ?? persona.description,+ ]+ .filter(Boolean)+ .join(' · ')}+ class={cn(+ 'flex h-14 w-48 max-w-full shrink-0 items-center gap-2 rounded-md px-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/40',+ selected()+ ? 'bg-accent/5 text-ink'+ : 'text-ink hover:bg-hover',+ disabled() && 'opacity-45'+ )}+ onClick={() => {+ if (disabled()) return;+ if (persona.connectLabel) props.onConnect(persona.id);+ else props.onSelect(persona.id);+ }}+ >+ <Avatar size="sm" class="shrink-0 bg-surface-2 text-ink-muted">+ <Show+ when={persona.avatarUrl}+ fallback={+ <Avatar.Fallback>+ <RobotIcon class="size-4" />+ </Avatar.Fallback>+ }+ >+ {(url) => <Avatar.Image src={url()} alt="" />}+ </Show>+ </Avatar>+ <span class="min-w-0 flex-1">+ <span class="flex min-w-0 items-baseline gap-2">+ <span class="truncate text-sm font-medium">+ {persona.name}+ </span>+ </span>+ <span class="block truncate text-xs text-ink-muted">+ @{persona.handle}+ <Show when={persona.unavailableReason}>+ {' · '}+ {persona.unavailableReason}+ </Show>+ </span>+ </span>+ <CheckIcon+ class={cn(+ 'size-4 shrink-0 text-accent',+ !selected() && 'invisible'+ )}+ />+ </button>+ );+ }}+ </For>+ </div>+ <Show when={sorted().length === 0 && !props.loading}>+ <p role="status" class="px-2 py-6 text-center text-sm text-ink-muted">+ No agents available.+ </p>+ </Show>+ <Show when={props.error}>+ <p role="alert" class="px-2 pt-2 text-xs text-negative">+ Your saved agents could not be loaded. Macro is still available.+ </p>+ </Show>+ </section>+ );+}diff --git a/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx b/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsxnew file mode 100644index 0000000000..ee4c55472e--- /dev/null+++ b/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx@@ -0,0 +1,459 @@+import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';+import { CURSOR_BOT_ID } from '@core/constant/cursorAgent';+import { agentHarnessServiceClient } from '@service-agent-harness/client';+import type { CreateAgentSessionResponse } from '@service-agent-harness/generated/schemas';+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ComposeAgentSession } from './ComposeAgentSession';++const navigation = vi.hoisted(() => ({+ close: vi.fn(),+ open: vi.fn(),+ settings: vi.fn(),+ navigate: vi.fn(),+}));+const cursorConnection = vi.hoisted(() => ({+ registered: true,+ isPlaceholderData: false,+}));+const hotkeys = vi.hoisted(() => ({ submit: (): boolean => false }));++vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'test-user',+}));+vi.mock('@solidjs/router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@solidjs/router')>()),+ useNavigate: () => navigation.navigate,+}));+vi.mock('@core/constant/SettingsState', () => ({+ useSettingsState: () => ({ openSettings: navigation.settings }),+}));++vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit: navigation.open }),+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({+ handle: { close: navigation.close, isPopover: () => true },+ }),+}));+vi.mock('@core/hotkey/hotkeys', () => ({+ useHotkeyDOMScope: () => [vi.fn(), 'test'],+ registerHotkey: (options: { keyDownHandler: () => boolean }) => {+ hotkeys.submit = options.keyDownHandler;+ },+}));+vi.mock('@queries/agents/agents', () => ({+ useAgentsQuery: () => ({+ isSuccess: true,+ data: [+ {+ bot: {+ id: 'reviewer',+ name: 'Reviewer',+ handle: 'reviewer',+ has_agent: false,+ },+ harness: 'in-memory',+ default_model: 'anthropic/claude-sonnet-5',+ },+ {+ bot: { id: 'coder', name: 'Coder', handle: 'coder', has_agent: true },+ harness: 'in-memory',+ default_model: 'anthropic/claude-opus-5',+ },+ ],+ }),+}));+vi.mock('@queries/agents/models', () => ({+ useAgentModelsQuery: () => ({+ isSuccess: true,+ data: {+ currentModel: 'anthropic/claude-sonnet-5',+ models: [{ id: 'anthropic/claude-sonnet-5', name: 'Sonnet 5' }],+ },+ }),+}));+vi.mock('@queries/auth/cursor-api-key', () => ({+ useCursorApiKeyStatusQuery: () => ({+ isSuccess: true,+ isPlaceholderData: cursorConnection.isPlaceholderData,+ data: { registered: cursorConnection.registered },+ }),+ useCursorModelsQuery: () => ({+ isSuccess: true,+ data: { models: [] },+ }),+}));+vi.mock('@service-agent-harness/client', () => ({+ agentHarnessServiceClient: { create: vi.fn(), control: vi.fn() },+}));++// Keep the real composer and mutations; replace shared visual chrome only.+vi.mock('@ui', () => {+ const Container = (props: { children?: import('solid-js').JSX.Element }) =>+ props.children;+ const Button = (+ props: import('solid-js').JSX.ButtonHTMLAttributes<HTMLButtonElement>+ ) => (+ <button disabled={props.disabled} onClick={props.onClick}>+ {props.children}+ </button>+ );+ return {+ Button,+ Surface: (+ props: import('solid-js').JSX.HTMLAttributes<HTMLDivElement> & {+ depth?: number;+ }+ ) => (+ <div+ role={props.role}+ aria-label={props['aria-label']}+ data-depth={props.depth}+ >+ {props.children}+ </div>+ ),+ SendButton: (+ props: import('solid-js').JSX.ButtonHTMLAttributes<HTMLButtonElement>+ ) => (+ <button+ aria-label={props['aria-label']}+ disabled={props.disabled}+ onClick={props.onClick}+ />+ ),+ Avatar: Object.assign(Container, {+ Fallback: Container,+ Image: () => null,+ }),+ Dropdown: Object.assign(Container, {+ Trigger: Button,+ Content: Container,+ Group: Container,+ GroupLabel: Container,+ Item: (props: {+ children?: import('solid-js').JSX.Element;+ onSelect: () => void;+ }) => <button onClick={props.onSelect}>{props.children}</button>,+ Sub: Container,+ SubTrigger: Container,+ SubContent: Container,+ }),+ badgeTriggerClasses: () => '',+ cn: () => '',+ };+});++const sessionId = '01991aae-f05b-7000-8000-000000000001';+const created = { session: { id: sessionId } } as CreateAgentSessionResponse;+const failure = err([+ { code: 'SERVER_ERROR' as const, message: 'Request failed' },+]);+let client: QueryClient;++beforeEach(() => {+ cursorConnection.registered = true;+ cursorConnection.isPlaceholderData = false;+ window.localStorage.clear();+ vi.clearAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ client = new QueryClient();+ vi.mocked(agentHarnessServiceClient.create).mockResolvedValue(ok(created));+ vi.mocked(agentHarnessServiceClient.control).mockResolvedValue(+ ok({ actionId: 'action-1', status: 'queued' })+ );+});++afterEach(() => {+ client.clear();+ vi.restoreAllMocks();+});++function mount(preferNewSplit = false) {+ render(() => (+ <QueryClientProvider client={client}>+ <ComposeAgentSession preferNewSplit={preferNewSplit} />+ </QueryClientProvider>+ ));+}++function enterPrompt() {+ fireEvent.input(screen.getByRole('textbox'), {+ target: { value: ' Fix the tests ' },+ });+}++describe('agent session creation', () => {+ it('keeps Create agent outside the slider and opens the new-agent form', () => {+ mount();+ const createAgent = screen.getByRole('button', { name: 'Create agent' });+ expect(+ within(screen.getByRole('radiogroup')).queryByRole('button', {+ name: 'Create agent',+ })+ ).toBeNull();+ fireEvent.click(createAgent);+ expect(navigation.close).toHaveBeenCalledOnce();+ expect(navigation.navigate).toHaveBeenCalledWith(+ '/settings/agents?createAgent=true'+ );+ expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();+ });++ it('opens Harness settings from disconnected Cursor without creating a session', () => {+ cursorConnection.registered = false;+ mount();+ const connect = screen.getByRole('button', { name: 'Connect Cursor' });+ expect(connect.getAttribute('aria-disabled')).toBe('false');+ expect(connect.tabIndex).toBe(0);+ fireEvent.click(connect);+ expect(navigation.close).toHaveBeenCalledOnce();+ expect(navigation.settings).toHaveBeenCalledWith('Harness');+ expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();+ expect(navigation.open).not.toHaveBeenCalled();+ });++ it('does not offer connection setup before the connection status is known', () => {+ cursorConnection.registered = false;+ cursorConnection.isPlaceholderData = true;+ mount();+ expect(screen.queryByRole('button', { name: 'Connect Cursor' })).toBeNull();+ fireEvent.click(screen.getByRole('radio', { name: /Cursor/ }));+ expect(navigation.settings).not.toHaveBeenCalled();+ });++ it('waits for creation and opens the real ID, preventing duplicate submissions', async () => {+ cursorConnection.registered = false;+ let finish!: (+ value: Awaited<ReturnType<typeof agentHarnessServiceClient.create>>+ ) => void;+ vi.mocked(agentHarnessServiceClient.create).mockReturnValue(+ new Promise((resolve) => {+ finish = resolve;+ })+ );+ mount(true);+ fireEvent.click(screen.getByRole('button', { name: 'Start session' }));+ hotkeys.submit();+ await waitFor(() =>+ expect(agentHarnessServiceClient.create).toHaveBeenCalledTimes(1)+ );+ expect(navigation.close).not.toHaveBeenCalled();+ expect(navigation.open).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Connect Cursor' }));+ expect(navigation.settings).not.toHaveBeenCalled();++ const createAgent = screen.getByRole('button', {+ name: 'Create agent',+ }) as HTMLButtonElement;+ expect(createAgent.disabled).toBe(true);+ fireEvent.click(createAgent);+ expect(navigation.navigate).not.toHaveBeenCalled();++ finish(ok(created));+ await waitFor(() =>+ expect(navigation.open).toHaveBeenCalledWith(+ { type: 'agent', id: sessionId },+ { referredFrom: 'launcher', preferNewSplit: true }+ )+ );+ expect(navigation.close).toHaveBeenCalledTimes(1);+ expect(agentHarnessServiceClient.control).not.toHaveBeenCalled();+ expect(+ JSON.parse(+ window.localStorage.getItem('agent-session-recent-v1:test-user') ?? '[]'+ )+ ).toEqual(['macro']);+ });++ it('keeps the prompt and offers retry when creation fails', async () => {+ vi.mocked(agentHarnessServiceClient.create).mockResolvedValueOnce(failure);+ mount();+ enterPrompt();+ fireEvent.click(screen.getByRole('button', { name: 'Start session' }));+ await screen.findByRole('alert');+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(+ ' Fix the tests '+ );+ expect(navigation.open).not.toHaveBeenCalled();+ expect(navigation.close).not.toHaveBeenCalled();+ expect(+ window.localStorage.getItem('agent-session-recent-v1:test-user')+ ).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(navigation.open).toHaveBeenCalled());+ expect(agentHarnessServiceClient.create).toHaveBeenCalledTimes(2);+ });++ it('sends the selected persona', async () => {+ mount();+ const prompt = screen.getByRole('textbox') as HTMLTextAreaElement;+ const promptBox = within(+ screen.getByRole('group', { name: 'New session prompt' })+ );+ expect(promptBox.getByRole('textbox')).toBe(prompt);+ expect(prompt.rows).toBe(3);+ expect(+ screen+ .getByRole('group', { name: 'New session prompt' })+ .getAttribute('data-depth')+ ).toBe('1');+ expect(+ screen+ .getByRole('radiogroup')+ .closest('[data-depth]')+ ?.getAttribute('data-depth')+ ).toBe('1');+ expect(+ screen.getByRole('heading', { name: 'Start a session' })+ ).toBeTruthy();+ expect(promptBox.queryByRole('radiogroup')).toBeNull();+ expect(+ promptBox.getByRole('button', { name: 'Start session' })+ ).toBeTruthy();+ expect(+ promptBox.getAllByRole('button', { name: 'default (Sonnet 5)' })+ ).toHaveLength(2);+ expect(prompt.placeholder).toBe('What would you like Macro to work on?');+ expect(+ screen.getByRole('radiogroup').compareDocumentPosition(prompt) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).not.toBe(0);+ expect(+ screen.getAllByRole('button', { name: 'default (Sonnet 5)' })+ ).toHaveLength(2);+ const macro = within(screen.getByRole('radio', { name: /Macro/ }));+ const cursor = within(screen.getByRole('radio', { name: /Cursor/ }));+ expect(macro.getByText('@macro')).toBeTruthy();+ expect(macro.queryByText(/default/)).toBeNull();+ expect(macro.queryByText('coding')).toBeNull();+ expect(cursor.getByText('@cursor')).toBeTruthy();+ expect(cursor.queryByText('coding')).toBeNull();+ const reviewer = within(screen.getByRole('radio', { name: /Reviewer/ }));+ const coder = within(screen.getByRole('radio', { name: /Coder/ }));+ expect(reviewer.getByText('@reviewer')).toBeTruthy();+ expect(reviewer.queryByText('coding')).toBeNull();+ expect(coder.getByText('@coder')).toBeTruthy();+ expect(coder.queryByText('coding')).toBeNull();+ expect(+ screen.getByText(+ 'Starts quickly and runs in-memory. Great for workspace tasks'+ )+ ).toBeTruthy();+ fireEvent.click(screen.getByRole('radio', { name: /Cursor/ }));+ expect(+ screen.getByText('Bring in Cursor for some heavier coding work')+ ).toBeTruthy();+ expect(+ screen.queryByText(+ 'Starts quickly and runs in-memory. Great for workspace tasks'+ )+ ).toBeNull();+ expect(prompt.placeholder).toBe('What would you like Cursor to work on?');+ hotkeys.submit();+ await waitFor(() => expect(navigation.open).toHaveBeenCalled());+ expect(agentHarnessServiceClient.create).toHaveBeenCalledWith({+ botId: CURSOR_BOT_ID,+ });+ });++ it('applies the model before the prompt and does not reapply it on prompt retry', async () => {+ vi.mocked(agentHarnessServiceClient.control)+ .mockResolvedValueOnce(ok({ actionId: 'model-action', status: 'queued' }))+ .mockResolvedValueOnce(failure);+ mount();+ enterPrompt();+ const model = Model.opus5;+ fireEvent.click(+ screen.getByRole('button', { name: MODEL_PRETTYNAME[model] })+ );+ hotkeys.submit();+ await screen.findByRole('alert');+ expect(navigation.open).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(navigation.open).toHaveBeenCalled());+ expect(agentHarnessServiceClient.control).toHaveBeenNthCalledWith(+ 1,+ sessionId,+ { type: 'setModel', model }+ );+ expect(agentHarnessServiceClient.control).toHaveBeenNthCalledWith(+ 2,+ sessionId,+ { type: 'prompt', prompt: 'Fix the tests' }+ );+ expect(agentHarnessServiceClient.control).toHaveBeenNthCalledWith(+ 3,+ sessionId,+ { type: 'prompt', prompt: 'Fix the tests' }+ );+ expect(agentHarnessServiceClient.create).toHaveBeenCalledTimes(1);+ });++ it('retries a failed prompt on the already-created session', async () => {+ vi.mocked(agentHarnessServiceClient.control).mockResolvedValueOnce(failure);+ mount();+ enterPrompt();+ fireEvent.click(screen.getByRole('button', { name: 'Start session' }));+ await screen.findByRole('alert');+ expect(screen.getByRole('button', { name: 'Open session' })).toBeDefined();+ expect(navigation.open).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(navigation.open).toHaveBeenCalled());+ expect(agentHarnessServiceClient.create).toHaveBeenCalledTimes(1);+ expect(agentHarnessServiceClient.control).toHaveBeenCalledTimes(2);+ });++ it('does not send the prompt when model setup fails, and retries on the same session', async () => {+ vi.mocked(agentHarnessServiceClient.control).mockResolvedValueOnce(failure);+ mount();+ enterPrompt();+ const model = Model.opus5;+ fireEvent.click(+ screen.getByRole('button', { name: MODEL_PRETTYNAME[model] })+ );+ hotkeys.submit();+ await screen.findByRole('alert');+ expect(agentHarnessServiceClient.control).toHaveBeenCalledTimes(1);+ expect(navigation.open).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(navigation.open).toHaveBeenCalled());+ expect(agentHarnessServiceClient.create).toHaveBeenCalledTimes(1);+ expect(agentHarnessServiceClient.control).toHaveBeenNthCalledWith(+ 2,+ sessionId,+ { type: 'setModel', model }+ );+ expect(agentHarnessServiceClient.control).toHaveBeenNthCalledWith(+ 3,+ sessionId,+ { type: 'prompt', prompt: 'Fix the tests' }+ );+ });++ it('can open the created session even when prompt setup fails', async () => {+ vi.mocked(agentHarnessServiceClient.control).mockRejectedValueOnce(+ new Error('Network unavailable')+ );+ mount();+ enterPrompt();+ fireEvent.click(screen.getByRole('button', { name: 'Start session' }));+ await screen.findByRole('alert');+ fireEvent.click(screen.getByRole('button', { name: 'Open session' }));+ expect(navigation.open).toHaveBeenCalledWith(+ { type: 'agent', id: sessionId },+ { referredFrom: 'launcher', preferNewSplit: false }+ );+ expect(agentHarnessServiceClient.create).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsxindex 86e7d35e8c..b56ae4fac7 100644--- a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx+++ b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx@@ -10,23 +10,46 @@ import {MACRO_AGENT_HANDLE,MACRO_AGENT_NAME,} from '@core/constant/macroAgent';+import { useSettingsState } from '@core/constant/SettingsState';+import { useUserId } from '@core/context/user';import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';+import { idToDisplayName } from '@core/user/util';import CaretDownIcon from '@phosphor/caret-down.svg';import CaretRightIcon from '@phosphor/caret-right.svg';import CheckIcon from '@phosphor/check.svg';-import CpuIcon from '@phosphor/cpu.svg';-import RobotIcon from '@phosphor/robot.svg';+import PlusIcon from '@phosphor/plus.svg';import XIcon from '@phosphor/x.svg';+import {+ useAgentSessionControlMutation,+ useCreateAgentSessionMutation,+} from '@queries/agent-session/mutations';import { useAgentsQuery } from '@queries/agents/agents';+import { useAgentModelsQuery } from '@queries/agents/models';import {useCursorApiKeyStatusQuery,useCursorModelsQuery,} from '@queries/auth/cursor-api-key';-import { Avatar, Button, badgeTriggerClasses, cn, Dropdown, Hotkey } from '@ui';-import { createSignal, For, onMount, Show } from 'solid-js';-import { startPendingSession } from '../context/pending-session';+import { useNavigate } from '@solidjs/router';+import {+ Button,+ badgeTriggerClasses,+ cn,+ Dropdown,+ SendButton,+ Surface,+} from '@ui';+import {+ createMemo,+ createSignal,+ For,+ onMount,+ Show,+ Suspense,+} from 'solid-js';+import { createRecentAgentSelections } from '../context/recent-agent-selections';+import { AgentPicker } from './AgentPicker';import {- harnessDisplayName,+ agentRuntimeDescription,isManagedHarness,type ModelOption,type ModelShortlist,@@ -52,12 +75,9 @@ const PILL_CLASS = badgeTriggerClasses({variant: 'outline',size: 'sm',class:- 'max-w-64 gap-1.5 pl-1.5 pr-2 text-ink-muted data-expanded:bg-hover data-expanded:text-ink',+ 'max-w-64 gap-1.5 px-2 text-ink-muted data-expanded:bg-hover data-expanded:text-ink',});-/** Long harness catalogs scroll instead of growing the menu without bound. */-const MENU_LIST_CLASS = 'max-h-72 overflow-y-auto overscroll-contain';-export interface ComposeAgentSessionProps {/** Open the new session in a fresh split instead of the current one. */preferNewSplit?: boolean;@@ -65,27 +85,55 @@ export interface ComposeAgentSessionProps {/** Task-style preflight composer for a new managed agent session. */export function ComposeAgentSession(props: ComposeAgentSessionProps) {+ return (+ <Suspense>+ <ComposeAgentSessionContent {...props} />+ </Suspense>+ );+}++function ComposeAgentSessionContent(props: ComposeAgentSessionProps) {const splitPanel = useSplitPanelOrThrow();const { openWithSplit } = useSplitLayout();+ const { openSettings } = useSettingsState();+ const navigate = useNavigate();const agentsQuery = useAgentsQuery();const cursorStatus = useCursorApiKeyStatusQuery();const cursorConnected = () =>cursorStatus.isSuccess ? cursorStatus.data.registered : false;+ const cursorNeedsConnection = () =>+ cursorStatus.isSuccess &&+ !cursorStatus.isPlaceholderData &&+ !cursorStatus.data.registered;const cursorModels = useCursorModelsQuery(cursorConnected);+ const macroDefaults = useAgentModelsQuery(() => ({ harness: 'in-memory' }));+ const cursorDefaults = useAgentModelsQuery(+ () => ({ harness: 'cursor' }),+ cursorConnected+ );+ const createSessionMutation = useCreateAgentSessionMutation();+ const controlMutation = useAgentSessionControlMutation();+ const userId = useUserId();+ const recentAgents = createRecentAgentSelections(userId());const [prompt, setPrompt] = createSignal('');const [personaId, setPersonaId] = createSignal(MACRO_PERSONA_ID);const [modelOverride, setModelOverride] = createSignal('');const [submitting, setSubmitting] = createSignal(false);+ const [sessionId, setSessionId] = createSignal<string>();+ const [error, setError] = createSignal<string>();+ let appliedModel: string | undefined;const [containerRef, setContainerRef] = createSignal<HTMLDivElement>();- let promptRef: HTMLTextAreaElement | undefined;- // The two first-party coders lead, then the user's own personas.- const personas = (): PersonaOption[] => [+ // The two first-party agents lead, then the user's own personas.+ const personas = createMemo<PersonaOption[]>(() => [{id: MACRO_PERSONA_ID,name: MACRO_AGENT_NAME,handle: MACRO_AGENT_HANDLE,harness: 'in-memory',+ defaultModel: macroDefaults.isSuccess+ ? (macroDefaults.data.currentModel ?? undefined)+ : undefined,},{id: CURSOR_BOT_ID,@@ -94,12 +142,15 @@ export function ComposeAgentSession(props: ComposeAgentSessionProps) {handle: CURSOR_BOT_HANDLE,harness: 'cursor',defaultModel: cursorStatus.isSuccess- ? (cursorStatus.data.defaultModelId ?? undefined)+ ? (cursorStatus.data.defaultModelId ??+ (cursorDefaults.isSuccess+ ? (cursorDefaults.data.currentModel ?? undefined)+ : undefined)): undefined,unavailableReason: cursorConnected()? undefined: 'Connect Cursor in Settings → Harness',- unavailableLabel: cursorConnected() ? undefined : 'Not connected',+ connectLabel: cursorNeedsConnection() ? 'Connect Cursor' : undefined,},...(agentsQuery.isSuccess ? agentsQuery.data : [])// Only runtimes Macro provisions can be started from here; a persona on@@ -110,13 +161,27 @@ export function ComposeAgentSession(props: ComposeAgentSessionProps) {botId: agent.bot.id,name: agent.bot.name,handle: agent.bot.handle,+ description: agent.bot.description ?? undefined,avatarUrl: agent.bot.avatar_url ?? undefined,harness: agent.harness,defaultModel: agent.default_model,+ ownerId:+ agent.bot.owner?.type === 'user'+ ? agent.bot.owner.user_id+ : (agent.bot.created_by ?? undefined),})),- ];+ ]);const selectedPersona = () =>personas().find((persona) => persona.id === personaId()) ?? personas()[0];+ const runtimeDescription = () => {+ const persona = selectedPersona();+ return agentRuntimeDescription(+ persona,+ persona?.harness === 'macrod' && persona.ownerId+ ? idToDisplayName(persona.ownerId)+ : undefined+ );+ };const availableModels = (): ModelOption[] => {if (selectedPersona()?.harness === 'cursor') {return cursorModels.isSuccess@@ -131,27 +196,98 @@ export function ComposeAgentSession(props: ComposeAgentSessionProps) {};const modelShortlist = () =>shortlistModelOptions(selectedPersona(), availableModels());+ const modelsForPersona = (persona: PersonaOption): ModelOption[] => {+ const defaults =+ persona.harness === 'cursor' ? cursorDefaults : macroDefaults;+ const models =+ persona.harness === 'cursor'+ ? cursorModels.isSuccess+ ? cursorModels.data.models.map(({ id, displayName }) => ({+ id,+ name: displayName,+ }))+ : []+ : IN_MEMORY_MODELS;+ return defaults.isSuccess+ ? [+ ...models,+ ...defaults.data.models.map(({ id, name }) => ({ id, name })),+ ]+ : models;+ };const close = () => splitPanel.handle.close();+ const openCreateAgent = () => {+ if (submitting() || sessionId()) return;+ close();+ navigate('/settings/agents?createAgent=true');+ };+ const connectPersona = (id: string) => {+ if (submitting() || sessionId()) return;+ const persona = personas().find((item) => item.id === id);+ if (persona?.harness !== 'cursor' || !persona.connectLabel) return;+ close();+ openSettings('Harness');+ };const setPersona = (id: string) => {+ if (submitting() || sessionId()) return;setPersonaId(id);setModelOverride('');};- const createSession = () => {- if (submitting()) return;- setSubmitting(true);- const persona = selectedPersona();- const placeholder = startPendingSession({- botId: persona?.botId,- prompt: prompt().trim() || undefined,- modelOverride: modelOverride() || undefined,- });+ const openSession = (id: string) => {close();openWithSplit(- { type: 'agent', id: placeholder },+ { type: 'agent', id },{ referredFrom: 'launcher', preferNewSplit: props.preferNewSplit });};+ const createSession = async () => {+ const persona = selectedPersona();+ if (submitting() || !persona || persona.unavailableReason) return;+ setSubmitting(true);+ setError(undefined);+ const model = modelOverride();+ const firstPrompt = prompt().trim();+ let id = sessionId();+ let failureMessage =+ 'Could not create the agent session. Please try again.';+ try {+ if (!id) {+ const created = await createSessionMutation.mutateAsync({+ ...(persona.botId ? { botId: persona.botId } : {}),+ });+ id = created.session.id;+ // Keep the real session even if a subsequent control request fails.+ // Retrying setup must not create a second session.+ setSessionId(id);+ recentAgents.remember(persona.id);+ }+ if (model && model !== appliedModel) {+ failureMessage =+ 'Session created, but the model could not be changed. Retry or open the session.';+ await controlMutation.mutateAsync({+ sessionId: id,+ request: { type: 'setModel', model },+ });+ appliedModel = model;+ }+ if (firstPrompt) {+ failureMessage =+ 'Session created, but the prompt could not be sent. Retry or open the session.';+ await controlMutation.mutateAsync({+ sessionId: id,+ request: { type: 'prompt', prompt: firstPrompt },+ });+ }+ } catch (cause) {+ console.error(failureMessage, cause);+ setError(failureMessage);+ return;+ } finally {+ setSubmitting(false);+ }+ openSession(id);+ };const [attachHotkeys, hotkeyScope] = useHotkeyDOMScope('compose-agent-session',@@ -160,17 +296,13 @@ export function ComposeAgentSession(props: ComposeAgentSessionProps) {onMount(() => {const container = containerRef();if (container) attachHotkeys(container);- // The dialog's focus scope lands on its first focusable child once the- // popover has mounted; take the prompt after that so typing can start- // immediately.- requestAnimationFrame(() => promptRef?.focus());});registerHotkey({hotkey: 'cmd+enter',scopeId: hotkeyScope,description: 'Create agent session',keyDownHandler: () => {- createSession();+ void createSession();return true;},runWithInputFocused: true,@@ -178,36 +310,69 @@ export function ComposeAgentSession(props: ComposeAgentSessionProps) {return (<div- class="portal-scope relative flex h-full max-h-full min-h-0 flex-col gap-4 p-4"+ class="portal-scope relative flex max-h-full min-h-0 min-w-0 flex-col overflow-y-auto px-4 pt-8 pb-10 sm:px-9 sm:pt-10 sm:pb-12"tabIndex={-1}ref={setContainerRef}data-agent-session-composer>- <div class="flex items-center gap-1">- <div class="flex flex-1 items-center gap-2 px-2 text-xs font-medium text-ink-extra-muted">- <RobotIcon class="size-3.5" />- New agent session- </div>+ <div class="mb-8 shrink-0 text-center">+ <h1 class="text-3xl/9 font-medium text-ink">Start a session</h1><Show when={splitPanel.handle.isPopover()}><ButtononMouseDown={close}tabIndex={-1}tooltip="Close"size="icon-sm"+ class="absolute top-3 right-3"><XIcon /></Button></Show></div>- <div class="flex min-h-0 flex-1 flex-col overflow-hidden">+ <Surface+ class="mb-3 flex h-auto shrink-0 items-stretch gap-2 rounded-xl p-1.5"+ depth={1}+ solid+ >+ <div class="min-w-0 flex-1">+ <AgentPicker+ personas={personas()}+ recentIds={recentAgents.ids()}+ selected={selectedPersona()}+ loading={agentsQuery.isPending}+ error={agentsQuery.isError}+ disabled={submitting() || !!sessionId()}+ onSelect={setPersona}+ onConnect={connectPersona}+ />+ </div>+ <Button+ variant="accent"+ size="sm"+ class="h-auto shrink-0 gap-1.5 rounded-lg px-3"+ disabled={submitting() || !!sessionId()}+ onClick={openCreateAgent}+ >+ <PlusIcon class="size-4" />+ Create agent+ </Button>+ </Surface>++ <Surface+ role="group"+ aria-label="New session prompt"+ class="flex h-auto min-h-36 shrink-0 flex-col rounded-xl touch:rounded-2xl"+ depth={1}+ solid+ ><textarea- ref={promptRef}- rows={4}+ rows={3}aria-label="Task for the agent"- class="ph-no-capture min-h-24 w-full grow resize-none bg-transparent px-2 text-xl/7 font-medium text-ink outline-none placeholder:text-ink-placeholder"- placeholder="Give your agent a prompt..."+ class="ph-no-capture min-h-20 w-full flex-1 resize-none bg-transparent px-4 pt-4 pb-2 text-sm/6 text-ink outline-none placeholder:text-ink-placeholder touch:text-base"+ placeholder={`What would you like ${selectedPersona()?.name ?? MACRO_AGENT_NAME} to work on?`}value={prompt()}+ disabled={submitting()}onInput={(event) => setPrompt(event.currentTarget.value)}onKeyDown={(event) => {// Escape inside the prompt steps out to the dialog first, matching@@ -219,158 +384,63 @@ export function ComposeAgentSession(props: ComposeAgentSessionProps) {}}}/>- </div>- <PersonaGrid- personas={personas()}- selected={selectedPersona()}- loading={agentsQuery.isPending}- error={agentsQuery.isError}- onSelect={setPersona}- />+ <Show when={error()}>+ {(message) => (+ <div role="alert" class="px-2 text-sm text-negative">+ {message()}+ <Show when={sessionId()}>+ {(id) => (+ <Button+ disabled={submitting()}+ onClick={() => openSession(id())}+ >+ Open session+ </Button>+ )}+ </Show>+ </div>+ )}+ </Show>- <div class="flex shrink-0 flex-wrap items-end justify-between gap-2">- <div class="m-px flex min-h-7 flex-wrap items-center gap-2 text-sm">- <ModelPicker- persona={selectedPersona()}- available={availableModels()}- shortlist={modelShortlist()}- value={modelOverride()}- loading={- selectedPersona()?.harness === 'cursor' && cursorModels.isPending+ <div class="mt-auto flex shrink-0 items-center justify-between gap-2 px-4 pt-1 pb-3">+ <div class="m-px flex min-h-7 min-w-0 flex-wrap items-center gap-2 text-sm">+ <Suspense>+ <ModelPicker+ persona={selectedPersona()}+ available={modelsForPersona(selectedPersona())}+ shortlist={modelShortlist()}+ value={modelOverride()}+ loading={+ selectedPersona()?.harness === 'cursor' &&+ cursorModels.isPending+ }+ disabled={submitting() || !!sessionId()}+ onSelect={setModelOverride}+ />+ </Suspense>+ </div>++ <SendButton+ type="button"+ aria-label={+ submitting() ? 'Starting…' : error() ? 'Retry' : 'Start session'}- onSelect={setModelOverride}+ tooltip={error() ? 'Retry' : 'Start session'}+ shortcut="cmd+enter"+ pending={submitting()}+ disabled={submitting() || !!selectedPersona()?.unavailableReason}+ onClick={() => void createSession()}/></div>-- <Button- type="button"- variant="accent"- depth={3}- class="gap-3 rounded-lg border-0"- disabled={submitting()}- onClick={createSession}- >- {submitting() ? 'Creating…' : 'Create Session'}- <Hotkey shortcut="cmd+enter" theme="current" />- </Button>- </div>- </div>- );-}--/**- * Personas as a visible radio grid rather than a menu: the user sees every- * choice without opening anything. Cards auto-fit the row and stretch to- * fill it, so the grid is even at any count. Arrow keys move the selection;- * Tab lands on the current choice and moves on.- */-function PersonaGrid(props: {- personas: PersonaOption[];- selected: PersonaOption | undefined;- loading: boolean;- error: boolean;- onSelect: (id: string) => void;-}) {- let groupRef: HTMLDivElement | undefined;- const selectable = () =>- props.personas.filter((persona) => !persona.unavailableReason);-- const moveSelection = (event: KeyboardEvent, step: 1 | -1) => {- const options = selectable();- const index = options.findIndex(- (persona) => persona.id === props.selected?.id- );- const next = options[(index + step + options.length) % options.length];- if (!next) return;- event.preventDefault();- props.onSelect(next.id);- queueMicrotask(() => {- groupRef- ?.querySelector<HTMLElement>(`[data-persona-id="${next.id}"]`)- ?.focus();- });- };-- return (- <section class="flex shrink-0 flex-col gap-2 px-2" aria-label="Agent">- <div class="flex items-center justify-between text-xxs font-medium uppercase text-ink-extra-muted">- <span>Agent</span>- <Show when={props.loading}>- <span class="normal-case">Loading yours…</span>- </Show>- </div>- <div- ref={groupRef}- role="radiogroup"- aria-label="Agent"- class="grid grid-cols-[repeat(auto-fit,minmax(9.5rem,1fr))] gap-2"- onKeyDown={(event) => {- if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {- moveSelection(event, 1);- } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {- moveSelection(event, -1);- }- }}+ </Surface>+ <p+ aria-live="polite"+ class="mt-7 shrink-0 text-center text-sm text-ink-muted">- <For each={props.personas}>- {(persona) => {- const selected = () => persona.id === props.selected?.id;- const disabled = () => persona.unavailableReason !== undefined;- return (- <button- type="button"- role="radio"- aria-checked={selected()}- aria-disabled={disabled()}- data-persona-id={persona.id}- tabIndex={selected() ? 0 : -1}- title={persona.unavailableReason}- class={cn(- 'flex h-12 min-w-0 items-center gap-2.5 rounded-lg border px-2.5 text-left outline-none transition-colors',- 'focus-visible:ring-2 focus-visible:ring-accent/30',- selected()- ? 'border-accent bg-accent-bg text-ink'- : 'border-edge-muted bg-surface-2 text-ink-muted hover:bg-hover hover:text-ink',- disabled() &&- 'cursor-not-allowed opacity-50 hover:bg-surface-2'- )}- onClick={() => {- if (!disabled()) props.onSelect(persona.id);- }}- >- <PersonaAvatar persona={persona} />- <span class="flex min-w-0 flex-1 flex-col leading-tight">- <span class="truncate text-sm font-medium">- {persona.name}- </span>- <span class="truncate text-xs text-ink-extra-muted">- @{persona.handle}- {' · '}- {disabled()- ? (persona.unavailableLabel ?? 'Unavailable')- : harnessDisplayName(persona.harness)}- </span>- </span>- {/* Always laid out so selecting a card never changes its width. */}- <CheckIcon- class={cn(- 'size-3.5 shrink-0 text-accent',- !selected() && 'invisible'- )}- />- </button>- );- }}- </For>- </div>- <Show when={props.error}>- <p class="text-xs text-negative">- Your saved agents could not be loaded. You can still start with{' '}- {MACRO_AGENT_NAME} or {CURSOR_BOT_NAME}.- </p>- </Show>- </section>+ {runtimeDescription()}+ </p>+ </div>);}@@ -380,6 +450,7 @@ function ModelPicker(props: {shortlist: ModelShortlist;value: string;loading: boolean;+ disabled: boolean;onSelect: (id: string) => void;}) {const label = () =>@@ -391,16 +462,16 @@ function ModelPicker(props: {size="sm"class={PILL_CLASS}aria-label="Model override"+ disabled={props.disabled}tooltip={props.value ? 'Model override' : 'Model (agent default)'}>- <CpuIcon class="size-3.5 shrink-0" /><span class={cn('min-w-0 truncate', props.value && 'text-ink')}>{label()}</span><CaretDownIcon class="size-3 shrink-0 text-current/70" /></Dropdown.Trigger><Dropdown.Content class="w-72 max-w-[min(24rem,calc(100vw-1rem))]">- <Dropdown.Group class={MENU_LIST_CLASS}>+ <Dropdown.Group class="max-h-72 overflow-y-auto overscroll-contain"><Dropdown.GroupLabel>Model</Dropdown.GroupLabel><ModelRowlabel={personaDefaultLabel(props.persona, props.available)}@@ -426,7 +497,7 @@ function ModelPicker(props: {</span></Dropdown.SubTrigger><Dropdown.SubContent class="w-72 max-w-[min(24rem,calc(100vw-1rem))]">- <Dropdown.Group class={MENU_LIST_CLASS}>+ <Dropdown.Group class="max-h-72 overflow-y-auto overscroll-contain"><For each={props.shortlist.more}>{(model) => (<ModelRow@@ -479,25 +550,3 @@ function ModelRow(props: {</Dropdown.Item>);}--function PersonaAvatar(props: { persona: PersonaOption }) {- return (- <Avatar size="md" class="shrink-0 bg-surface text-accent">- <Show- when={props.persona.avatarUrl}- fallback={- <Avatar.Fallback>- <RobotIcon class="size-4" />- </Avatar.Fallback>- }- >- {(avatarUrl) => (- <Avatar.Image- src={avatarUrl()}- alt={`${props.persona.name} avatar`}- />- )}- </Show>- </Avatar>- );-}diff --git a/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts b/apps/web/src/features/block-agent/component/compose-agent-session-options.test.tsindex 237575d7c9..1ae9674c2e 100644--- a/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import {+ agentRuntimeDescription,harnessDisplayName,isManagedHarness,modelPillLabel,@@ -30,6 +31,34 @@ const ENGINEER: PersonaOption = {defaultModel: 'anthropic/claude-sonnet-5',};+describe('agentRuntimeDescription', () => {+ it('describes in-memory agents without implying a local sandbox', () => {+ for (const harness of ['in-memory', 'macro-inmem']) {+ expect(agentRuntimeDescription({ ...ENGINEER, harness })).toBe(+ 'Starts quickly and runs in-memory. Great for workspace tasks'+ );+ }+ });++ it('describes Cursor coding work', () => {+ expect(agentRuntimeDescription({ ...ENGINEER, harness: 'cursor' })).toBe(+ 'Bring in Cursor for some heavier coding work'+ );+ });++ it('names the local agent and its owner', () => {+ expect(+ agentRuntimeDescription({ ...ENGINEER, harness: 'macrod' }, 'Wolf')+ ).toBe('Do work locally using Test Engineer owned by Wolf');+ });++ it('does not invent an owner while their name is unavailable', () => {+ expect(agentRuntimeDescription({ ...ENGINEER, harness: 'macrod' })).toBe(+ 'Do work locally using Test Engineer'+ );+ });+});+describe('overrideModelOptions', () => {it('lists every model when the persona has no default', () => {expect(overrideModelOptions(CODER, MODELS)).toEqual(MODELS);@@ -127,19 +156,17 @@ describe('shortlistModelOptions', () => {describe('personaDefaultLabel', () => {it('is generic without a known default', () => {- expect(personaDefaultLabel(CODER, MODELS)).toBe('Agent default');+ expect(personaDefaultLabel(CODER, MODELS)).toBe('default');});it('names the default model when the persona has one', () => {- expect(personaDefaultLabel(ENGINEER, MODELS)).toBe(- 'Agent default · Sonnet 5'- );+ expect(personaDefaultLabel(ENGINEER, MODELS)).toBe('default (Sonnet 5)');});it('falls back to the raw id for models the catalog does not know', () => {expect(personaDefaultLabel({ ...ENGINEER, defaultModel: 'acme/x' }, MODELS)- ).toBe('Agent default · acme/x');+ ).toBe('default (acme/x)');});});@@ -151,10 +178,10 @@ describe('modelPillLabel', () => {});it('shows the persona default otherwise', () => {- expect(modelPillLabel('', ENGINEER, MODELS)).toBe('Sonnet 5');+ expect(modelPillLabel('', ENGINEER, MODELS)).toBe('default (Sonnet 5)');});it('shows a neutral label when nothing is known', () => {- expect(modelPillLabel('', CODER, MODELS)).toBe('Default model');+ expect(modelPillLabel('', CODER, MODELS)).toBe('default');});});diff --git a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts b/apps/web/src/features/block-agent/component/compose-agent-session-options.tsindex 0f7ba4be91..aedd916f5e 100644--- a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.ts@@ -7,13 +7,15 @@ export type PersonaOption = {botId?: string;name: string;handle: string;+ description?: string;avatarUrl?: string;harness: string;defaultModel?: string;+ ownerId?: string;/** Why this persona cannot be picked right now, when it cannot. */unavailableReason?: string;- /** Short form of `unavailableReason` for the card subtitle. */- unavailableLabel?: string;+ /** An unavailable agent with a setup action remains clickable. */+ connectLabel?: string;};/** A model the user can pin the session to instead of the persona default. */@@ -59,6 +61,24 @@ export function modelDisplayName(return available.find((model) => model.id === id)?.name ?? id;}+/** Explains the selected runtime below the composer, independently of its model. */+export function agentRuntimeDescription(+ persona: PersonaOption | undefined,+ ownerName?: string+): string {+ if (!persona) return '';+ if (persona.harness === 'in-memory' || persona.harness === 'macro-inmem') {+ return 'Starts quickly and runs in-memory. Great for workspace tasks';+ }+ if (persona.harness === 'cursor') {+ return 'Bring in Cursor for some heavier coding work';+ }+ if (persona.harness === 'macrod') {+ return `Do work locally using ${persona.name}${ownerName ? ` owned by ${ownerName}` : ''}`;+ }+ return `Runs using ${harnessDisplayName(persona.harness)}`;+}+/*** User-facing name for the runtime a persona runs on. Harness ids are* plumbing ("in-memory", "sandbox"); the product names are the coders.@@ -141,8 +161,8 @@ export function personaDefaultLabel(available: readonly ModelOption[]): string {const defaultModel = persona?.defaultModel;- if (!defaultModel) return 'Agent default';- return `Agent default · ${modelDisplayName(defaultModel, available)}`;+ if (!defaultModel) return 'default';+ return `default (${modelDisplayName(defaultModel, available)})`;}/** Short label for the closed model pill. */@@ -152,7 +172,5 @@ export function modelPillLabel(available: readonly ModelOption[]): string {if (override) return modelDisplayName(override, available);- const defaultModel = persona?.defaultModel;- if (!defaultModel) return 'Default model';- return modelDisplayName(defaultModel, available);+ return personaDefaultLabel(persona, available);}diff --git a/apps/web/src/features/block-agent/context/recent-agent-selections.test.ts b/apps/web/src/features/block-agent/context/recent-agent-selections.test.tsnew file mode 100644index 0000000000..b089d19392--- /dev/null+++ b/apps/web/src/features/block-agent/context/recent-agent-selections.test.ts@@ -0,0 +1,50 @@+import { createRoot } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createRecentAgentSelections } from './recent-agent-selections';++beforeEach(() => window.localStorage.clear());++describe('recent agent selections', () => {+ it('remembers five distinct choices, newest first, across composer mounts', () => {+ createRoot((dispose) => {+ const recent = createRecentAgentSelections('user-a');+ for (const id of ['a', 'b', 'c', 'd', 'e', 'f', 'c']) recent.remember(id);+ expect(recent.ids()).toEqual(['c', 'f', 'e', 'd', 'b']);+ dispose();+ });+ createRoot((dispose) => {+ expect(createRecentAgentSelections('user-a').ids()).toEqual([+ 'c',+ 'f',+ 'e',+ 'd',+ 'b',+ ]);+ expect(createRecentAgentSelections('user-b').ids()).toEqual([]);+ dispose();+ });+ });++ it('ignores malformed history', () => {+ window.localStorage.setItem('agent-session-recent-v1:user-a', 'not json');+ createRoot((dispose) => {+ expect(createRecentAgentSelections('user-a').ids()).toEqual([]);+ dispose();+ });+ });++ it('keeps working when storage cannot be written', () => {+ const write = vi+ .spyOn(Storage.prototype, 'setItem')+ .mockImplementation(() => {+ throw new Error('Storage unavailable');+ });+ createRoot((dispose) => {+ const recent = createRecentAgentSelections('user-a');+ recent.remember('a');+ expect(recent.ids()).toEqual(['a']);+ dispose();+ });+ write.mockRestore();+ });+});diff --git a/apps/web/src/features/block-agent/context/recent-agent-selections.ts b/apps/web/src/features/block-agent/context/recent-agent-selections.tsnew file mode 100644index 0000000000..bd72dd7f5f--- /dev/null+++ b/apps/web/src/features/block-agent/context/recent-agent-selections.ts@@ -0,0 +1,36 @@+import { makePersistedState } from '@app/lib/persistence';+import { createUserScopedStorage } from '@core/util/userScopedStorage';+import { createSignal } from 'solid-js';++const RECENT_AGENT_LIMIT = 5;++/** Successful choices from this composer, scoped to the signed-in user. */+export function createRecentAgentSelections(userId: string | undefined) {+ const storage = createUserScopedStorage('agent-session-recent-v1');+ const [ids, setIds] = makePersistedState(createSignal<string[]>([]), {+ storages: {+ restore: () => {+ if (!userId) return;+ const stored: unknown = JSON.parse(storage.read(userId) ?? '[]');+ if (!Array.isArray(stored)) return;+ return stored+ .filter((id): id is string => typeof id === 'string')+ .slice(0, RECENT_AGENT_LIMIT);+ },+ write: (value) => {+ if (userId) storage.write(userId, JSON.stringify(value));+ },+ },+ });++ return {+ ids,+ remember: (id: string) =>+ setIds((previous) =>+ [id, ...previous.filter((value) => value !== id)].slice(+ 0,+ RECENT_AGENT_LIMIT+ )+ ),+ };+}diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsxindex 29c78c7464..3201413ff4 100644--- a/apps/web/src/features/settings/Agents.test.tsx+++ b/apps/web/src/features/settings/Agents.test.tsx@@ -18,9 +18,22 @@ import {useQuery,} from '@tanstack/solid-query';import { Suspense } from 'solid-js';+import { createStore } from 'solid-js/store';import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { Agents } from './Agents';+const [searchParams, updateSearchParams] = createStore<{+ createAgent?: string;+}>({});+const setSearchParams = vi.fn((next: { createAgent?: string }) =>+ updateSearchParams(next)+);++vi.mock('@solidjs/router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@solidjs/router')>()),+ useSearchParams: () => [searchParams, setSearchParams],+}));+const cursorMocks = vi.hoisted(() => ({status: {isSuccess: true,@@ -233,6 +246,8 @@ beforeAll(() => {});beforeEach(() => {+ updateSearchParams({ createAgent: undefined });+ setSearchParams.mockClear();cursorMocks.status.data = {registered: false,updatedAt: null,@@ -276,6 +291,21 @@ const MACROD_HARNESS = {};describe('Agents', () => {+ it('opens the new-agent form from a link and clears the action on cancel', () => {+ updateSearchParams({ createAgent: 'true' });+ render(() => <Agents />);+ const dialog = screen.getByRole('dialog');+ expect(+ within(dialog).getByRole('button', { name: 'Create agent' })+ ).toBeTruthy();+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));+ expect(setSearchParams).toHaveBeenCalledWith(+ { createAgent: undefined },+ { replace: true }+ );+ expect(screen.queryByRole('dialog')).toBeNull();+ });+it.each(['success', 'error'] as const)('keeps settings visible while Cursor models load and after %s',async (outcome) => {diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsxindex cb642be515..3ba6317f20 100644--- a/apps/web/src/features/settings/Agents.tsx+++ b/apps/web/src/features/settings/Agents.tsx@@ -32,6 +32,7 @@ import { usePipedreamConnectedSlugs } from '@queries/pipedream-connectors';import { useCurrentTeamQuery, useIsTeamOwner } from '@queries/team/teams';import type { AgentMcpServer } from '@service-storage/generated/schemas/agentMcpServer';import type { AgentMcpServers } from '@service-storage/generated/schemas/agentMcpServers';+import { useSearchParams } from '@solidjs/router';import { Avatar, Button, Dialog, Panel } from '@ui';import { createMemo, createSignal, For, Show } from 'solid-js';import { botAssignableChannelOptions } from '../channel/Bots/botChannelOptions';@@ -93,6 +94,14 @@ const MACRO_AGENT: AgentSummary = {/** Settings page for viewing and creating persistent agents. */export function Agents() {const [creating, setCreating] = createSignal(false);+ const [searchParams, setSearchParams] = useSearchParams();+ const creatingFromLink = () => searchParams.createAgent === 'true';+ const closeCreateAgent = () => {+ setCreating(false);+ if (creatingFromLink()) {+ setSearchParams({ createAgent: undefined }, { replace: true });+ }+ };const [editingAgent, setEditingAgent] = createSignal<AgentWithHarnessId>();const [deletingAgent, setDeletingAgent] = createSignal<AgentWithHarnessId>();const channelsContext = useChannelsContext();@@ -291,14 +300,14 @@ export function Agents() {</SettingsSection></SettingsPage>- <Show when={creating()}>+ <Show when={creating() || creatingFromLink()}><AgentDialogconnectedHarnesses={connectedHarnesses()}currentTeamId={currentTeamId()}canShareWithTeam={canShareWithTeam()}canMakePrivatepending={createAgentMutation.isPending}- onClose={() => setCreating(false)}+ onClose={closeCreateAgent}onSave={createAgent}/></Show>diff --git a/apps/web/src/lib/queries/agent-session/mutations.ts b/apps/web/src/lib/queries/agent-session/mutations.tsnew file mode 100644index 0000000000..613f3cd070--- /dev/null+++ b/apps/web/src/lib/queries/agent-session/mutations.ts@@ -0,0 +1,25 @@+import { throwOnErr } from '@core/util/result';+import { agentHarnessServiceClient } from '@service-agent-harness/client';+import type {+ ControlRequest,+ CreateAgentSessionRequest,+} from '@service-agent-harness/generated/schemas';+import { useMutation } from '@tanstack/solid-query';++export function useCreateAgentSessionMutation() {+ return useMutation(() => ({+ retry: false,+ mutationFn: (request: CreateAgentSessionRequest) =>+ throwOnErr(() => agentHarnessServiceClient.create(request)),+ }));+}++export function useAgentSessionControlMutation() {+ return useMutation(() => ({+ retry: false,+ mutationFn: (vars: { sessionId: string; request: ControlRequest }) =>+ throwOnErr(() =>+ agentHarnessServiceClient.control(vars.sessionId, vars.request)+ ),+ }));+}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex cffccd664d..495fcd40b9 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -16,25 +16,61 @@ directly at `/app/agent/<uuid>` (the runtime starts while the block mounts).That create path focuses the agent composer so you can type immediately.When the `enable-agent-session-composer` flag is on (default in dev;`VITE_ENABLE_AGENT_SESSION_COMPOSER` overrides), the same entry instead opens-the **New agent session** composer popover. The prompt textarea (`Give your agent a-prompt...`) is focused on open, so you can `type_text` immediately. Below the prompt a-**Agent** section (`aria-label` `Agent`) lists the choices in the open, as a-`radiogroup` of cards (`role="radio"`, `aria-checked`): **Macro** `@macro`-(the default), **Cursor** `@cursor` (disabled with a `Connect Cursor in-Settings → Harness` hint until a Cursor API key is stored), then the user's-own agents, each card showing avatar, name and `@handle · Macro|Cursor` for-the runtime (a disabled card reads `@cursor · Not connected`). Every agent is-shown; the cards form an even grid that fills the popover width. Click a card-or use arrow keys to change agent. The **Model-override** pill (`aria-label` `Model override`) at the bottom left opens a-menu whose first row is `Agent default · <model>`, followed by at most five-featured models; longer catalogs put the rest under a `More models` submenu.-Changing agent resets the override. Tab order is prompt → selected agent card → Model →-**Create Session**; the close `X` is skipped. The menu opens on Enter/Space-and selects with arrow keys + Enter. Escape in the prompt first blurs to the-dialog, a second Escape closes it. Press **Create Session** or-`Cmd/Ctrl+Enter`; the composer closes and the new `/app/agent/<uuid>` session-opens while its runtime starts.+the **Start a session** composer popover. A centered title sits above two rounded+boxes of equal width: a shallow agent strip and a prompt box about twice its+height, separated by a small gap. The picker has+compact choices in a horizontally scrolling `radiogroup` (`aria-label="Agent"`,+`aria-orientation="horizontal"`, `role="radio"`, `aria-checked`). All agents are+available by scrolling sideways, with recent successful choices first.+An accent **Create agent** button stays fixed to the right of the strip.+It closes the session composer and opens the new-agent form at+`/app/settings/agents?createAgent=true`; it does not create a session.+Recents are remembered per user on this device. With no history, **Macro**+`@macro` (the default) and **Cursor** `@cursor` lead, followed by saved agents.+Without a connected Cursor API key, Cursor is a **Connect Cursor** button:+clicking it closes the composer and opens Settings → Harness without creating+a session. It is keyboard-accessible; arrow navigation focuses it without+activating it. Connected Cursor remains a selectable agent. Setup navigation+is disabled while a session is being created or its setup is being retried.+Each row shows its `@handle` beneath the name. There are no coding tags;+default models appear only in the prompt's model selector.+There is no search field or browse/expand control. Left/Right change the selected+agent and scroll it into view; Home/End jump to the first/last available agent.+Unavailable agents without a connection action are skipped.++The prompt box uses the agent session composer's surface, regular message text,+and arrow send button, with a three-line editing area. It names the+current selection:+`What would you like Macro to work on?` becomes+`What would you like Cursor to work on?` when Cursor is selected. Its aria-label+is `Task for the agent`. The dialog's default autofocus lands on the selected+agent row, its first tabbable control.+The prompt and agent strip share the same surface layer and background.+A centered caption below the prompt describes the selected runtime: Macro+shows “Starts quickly and runs in-memory. Great for workspace tasks”; Cursor+shows “Bring in Cursor for some heavier coding work”. Local-connector agents+are still excluded from creation by this modal's managed-session endpoint.+The **Model override** selector (`aria-label="Model override"`) sits inside the+prompt box at the bottom left. It+shows `default (<model name>)` when using the agent's configured default and+the model name alone when overridden. It has no model icon. Saved-agent defaults+come from their configuration; built-in defaults are loaded from model discovery.+While a default is unknown, the selector reads `default`. Changing agent resets+the override. Tab order is selected agent row (and any connection action) →+**Create agent** → prompt → model → **Start session**.+Escape in the prompt first blurs to the dialog; a second Escape closes it.+Press the arrow send button (labelled **Start session**) or `Cmd/Ctrl+Enter`;+the button shows a spinner and is labelled **Starting…**+while the server creates the session, applies the model override, and accepts the+first prompt. It then closes+and opens the real `/app/agent/<uuid>` URL. It never navigates to a temporary+`pending-…` URL. Creation failures keep the prompt in the modal and show **Retry**.+If model setup or prompt delivery fails after creation, **Retry** reuses that+session, and **Open session** opens it directly; agent and model selection stay+locked to the session already created.+Leaving Macro selected uses the backend's in-memory default in every+environment, including production; it does not provision a Daytona container.+Explicit coding-agent selections still use their configured runtimes.## Start a doc-scoped chatdiff --git a/infra/packages/shared/src/ai_tools.ts b/infra/packages/shared/src/ai_tools.tsindex f478e0ca37..bf7968c0fe 100644--- a/infra/packages/shared/src/ai_tools.ts+++ b/infra/packages/shared/src/ai_tools.ts@@ -128,16 +128,10 @@ export function getAiToolsServiceRoleArns(): pulumi.Output<string>[] {'ai-tools-agent-schedule-service-stack',{ name: `macro-inc/agent-schedule-service/${stack}` });- const agentHarnessServiceRoleArns =- stack === 'dev'- ? [- new pulumi.StackReference('ai-tools-agent-harness-service-stack', {- name: `macro-inc/agent-harness-service/${stack}`,- })- .getOutput('agentHarnessServiceRoleArn')- .apply((v) => v as string),- ]- : [];+ const agentHarnessServiceStack = new pulumi.StackReference(+ 'ai-tools-agent-harness-service-stack',+ { name: `macro-inc/agent-harness-service/${stack}` }+ );return [mcpServerStack.getOutput('mcpServerRoleArn').apply((v) => v as string),@@ -147,6 +141,8 @@ export function getAiToolsServiceRoleArns(): pulumi.Output<string>[] {agentScheduleServiceStack.getOutput('agentScheduleServiceRoleArn').apply((v) => v as string),- ...agentHarnessServiceRoleArns,+ agentHarnessServiceStack+ .getOutput('agentHarnessServiceRoleArn')+ .apply((v) => v as string),];}diff --git a/infra/stacks/agent-harness-service/index.ts b/infra/stacks/agent-harness-service/index.tsindex bee08b65e6..a537590c61 100644--- a/infra/stacks/agent-harness-service/index.ts+++ b/infra/stacks/agent-harness-service/index.ts@@ -47,10 +47,7 @@ const MACRO_API_TOKENS = getMacroApiToken();// ── AI tools infra ───────────────────────────────────────────────────────────-const aiTools =- stack === 'dev'- ? getAiToolsInfra()- : { secretArns: [], queueArns: [], bucketArns: [] };+const aiTools = getAiToolsInfra();// ── Stack references ─────────────────────────────────────────────────────────@@ -66,18 +63,6 @@ const cloudStorageClusterName = cloudStorageStack.getOutput('cloudStorageClusterName').apply((value) => value as string);-// ── Queues ───────────────────────────────────────────────────────────────────-// Channel side effects use these in every environment. Dev's AI tool bundle-// includes both plus the additional tool queues.--const notificationIngressQueueArn = aws.sqs- .getQueueOutput({ name: `notification-ingress-queue-${stack}` })- .apply((queue) => queue.arn);--const contactsQueueArn = aws.sqs- .getQueueOutput({ name: `contacts-queue-${stack}` })- .apply((queue) => queue.arn);-// ── Service ──────────────────────────────────────────────────────────────────const vpc = get_coparse_api_vpc();@@ -98,10 +83,7 @@ const service = new AgentHarnessService(`agent-harness-service-${stack}`, {githubSyncAppPemArn,...aiTools.secretArns,],- queueArns:- stack === 'dev'- ? [...aiTools.queueArns]- : [notificationIngressQueueArn, contactsQueueArn],+ queueArns: [...aiTools.queueArns],bucketArns: [...aiTools.bucketArns],containerEnvVars: [{diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex a592c9f633..7b1ead6db6 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -186,17 +186,9 @@ async fn run() -> anyhow::Result<()> {config.environment,Environment::Local | Environment::Develop);- // The in-process "macro(new)" bot is a compile-time identity, not- // configuration: it is always `bot_id::MACRO_NEW_BOT_ID`, so the only real- // question is whether this environment serves it. Production stays off- // until its AI tool config lands - `build_tool_service_context_from_env`- // below is fatal, so turning it on without that config would refuse to- // boot. (`@macro` itself is not served here at all: its mentions get the- // classic in-channel reply from `document_storage_service`.)- let inmem_bot = match config.environment {- Environment::Local | Environment::Develop => Some(bot_id::MACRO_NEW_BOT_ID),- Environment::Production => None,- };+ // Unselected sessions use the in-process bot in every environment.+ // Explicit coding-agent selections still use their configured runtimes.+ let inmem_bot = bot_id::MACRO_NEW_BOT_ID;let pool = PgPoolOptions::new().min_connections(1)@@ -369,33 +361,25 @@ async fn run() -> anyhow::Result<()> {// against it, so the two must be the same string.let egress_base_url = AgentHarnessEgressUrl::new()?.to_string();- let mut inmem_model_engine: Option<Arc<dyn TurnEngine>> = None;- let inmem = match inmem_bot {- Some(_) => {- let tool_context = ai_tools::build_tool_service_context_from_env(- pool.clone(),- event_broker_tracker.clone(),- )+ let tool_context =+ ai_tools::build_tool_service_context_from_env(pool.clone(), event_broker_tracker.clone()).await.context("failed to build the in-memory agent tool context")?;- let engine = Arc::new(RigTurnEngine::new(pool.clone(), tool_context));- inmem_model_engine = Some(engine.clone());- // Cold attaches (fresh spawns and post-restart resumes) rebuild- // their model context from the same log every frame lands in.- let frames = Arc::new(LogFrameSource::new(session_repo.clone()));- Some(InMemRuntime {- manager: InMemAgentManager::new(- engine,- frames,- Arc::new(AcpMcpConnector::new(EgressMcpClient::new(- Arc::clone(&egress),- &egress_base_url,- ))),- )- .with_dev_commands(enable_dev_commands),- })- }- None => None,+ let inmem_model_engine: Arc<dyn TurnEngine> =+ Arc::new(RigTurnEngine::new(pool.clone(), tool_context));+ // Cold attaches (fresh spawns and post-restart resumes) rebuild+ // their model context from the same log every frame lands in.+ let frames = Arc::new(LogFrameSource::new(session_repo.clone()));+ let inmem = InMemRuntime {+ manager: InMemAgentManager::new(+ Arc::clone(&inmem_model_engine),+ frames,+ Arc::new(AcpMcpConnector::new(EgressMcpClient::new(+ Arc::clone(&egress),+ &egress_base_url,+ ))),+ )+ .with_dev_commands(enable_dev_commands),};// The sandbox provider serves every bot but the in-memory one, which the// router pulls out by bot id before the provider ever sees it.@@ -408,7 +392,7 @@ async fn run() -> anyhow::Result<()> {lifecycle_publisher.clone(),replica,);- let sandbox_and_inmem = RoutedContainers::new(sandbox, inmem, inmem_sessions);+ let sandbox_and_inmem = RoutedContainers::new(sandbox, Some(inmem), inmem_sessions);// Cursor sessions run on their owner's own Cursor account, so there is no// deployment-wide key to arm this with: the manager reads each session@@ -444,18 +428,16 @@ async fn run() -> anyhow::Result<()> {mcp_servers: AgentMcpServers::OwnerConnections,},)];- if let Some(inmem_bot) = inmem_bot {- fixed_runtimes.push((- inmem_bot,- AgentRuntimeConfig {- kind: AgentKind::InMemory,- model: config.inmem_model.clone(),- harness: config.inmem_harness_slug.clone(),- instructions: String::new(),- mcp_servers: AgentMcpServers::OwnerConnections,- },- ));- }+ fixed_runtimes.push((+ inmem_bot,+ AgentRuntimeConfig {+ kind: AgentKind::InMemory,+ model: config.inmem_model.clone(),+ harness: config.inmem_harness_slug.clone(),+ instructions: String::new(),+ mcp_servers: AgentMcpServers::OwnerConnections,+ },+ ));fixed_runtimes.push((bot_id::CURSOR_BOT_ID,AgentRuntimeConfig {@@ -474,7 +456,7 @@ async fn run() -> anyhow::Result<()> {// for it.tracing::info!(bots = ?fixed_runtimes.iter().map(|(bot, _)| bot.as_uuid()).collect::<Vec<_>>(),- in_process_bot = ?inmem_bot.map(BotId::as_uuid),+ in_process_bot = %inmem_bot.as_uuid(),environment = %config.environment,"agent harness serving bots");@@ -526,29 +508,26 @@ async fn run() -> anyhow::Result<()> {let runtimes = RuntimeRegistry::with_presence(Arc::new(PgHarnessPresence::new(pool.clone())));let redis = redis::Client::open(config.redis_uri.as_ref()).context("failed to create the runtime command Redis client")?;- let mut defaults = HarnessDefaults::new(SessionDefaults {+ let defaults = HarnessDefaults::new(SessionDefaults {bot_id,model: config.harness_model.clone(),harness: config.harness_slug.clone(),repo_url: config.harness_repo_url.clone(),- });- if let Some(bot) = inmem_bot {- defaults = defaults- .with_bot(- bot,- SessionDefaults {- bot_id: bot,- model: config.inmem_model.clone(),- harness: config.inmem_harness_slug.clone(),- // Stamped but unused: the in-process agent has no- // workspace to clone anything into.- repo_url: config.harness_repo_url.clone(),- },- )- // Sessions nothing names a bot for (the create menu's) run- // in-process too; only mentioning the coder bot gets a sandbox.- .with_managed_bot(bot);- }+ })+ .with_bot(+ inmem_bot,+ SessionDefaults {+ bot_id: inmem_bot,+ model: config.inmem_model.clone(),+ harness: config.inmem_harness_slug.clone(),+ // Stamped but unused: the in-process agent has no+ // workspace to clone anything into.+ repo_url: config.harness_repo_url.clone(),+ },+ )+ // Sessions nothing names a bot for (the create menu's) run in-process;+ // explicitly selected coding agents keep their configured runtimes.+ .with_managed_bot(inmem_bot);let harness = Arc::new(AgentHarnessService::new(sessions,@@ -629,7 +608,7 @@ async fn run() -> anyhow::Result<()> {)));let model_service = Arc::new(AgentModelsServiceImpl::new(VisibleHarnessAccess::new(PgHarnessRepo::new(pool.clone())),- InMemoryModels::new(inmem_model_engine, config.inmem_model.clone()),+ InMemoryModels::new(Some(inmem_model_engine), config.inmem_model.clone()),CursorModels::new(cursor_keys, CURSOR_API_BASE_URL.to_owned()),macrod_models,model_probe_timeout,