Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(agents): open focused composer from create shortcut (#6590)

Eric Hayesf5e7962b1dd8
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 54b652aff4..1daf2f5e42 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -2,7 +2,6 @@ import { openEntityInSplit } from '@app/features/activity/open-entity-in-split';
import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';
import { parseAgentsRoute } from '@app/features/agents-view/core/route';
import { AgentsView } from '@app/features/agents-view/views/AgentsView';
-import { ComposeAgentSession } from '@app/features/block-agent/component/ComposeAgentSession';
import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitives/use-spreadsheet-access';
import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
import type { CalendarEvent } from '@app/features/calendar/types';
@@ -769,12 +768,10 @@ registerComponent('task-compose', (params) => {
usePageViewTracking('task-compose');
return <ComposeTask {...params} />;
});
-registerComponent('agent-session-compose', (params) => {
- usePageViewTracking('agent-session-compose');
- return (
- <ComposeAgentSession preferNewSplit={params?.preferNewSplit === true} />
- );
-});
+// Restore old composer URLs into the shared Agents page.
+registerComponent('agent-session-compose', () => (
+ <RedirectSplit to={{ type: 'component', id: 'agents' }} />
+));
registerComponent('calendar-event-compose', (params) => {
usePageViewTracking('calendar-event-compose');
return (
diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
index 4bab9252f3..4804f5c83d 100644
--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
@@ -41,7 +41,6 @@ vi.mock('@app/features/activity/open-entity-in-split', () => ({
// Quarantine unrelated registered views and their module-load side effects.
vi.mock('@app/features/agents-view/views/AgentsView', () => ({}));
-vi.mock('@app/features/block-agent/component/ComposeAgentSession', () => ({}));
vi.mock('@app/features/channels-view/channels-view', () => ({}));
vi.mock('@app/features/drive-view/drive-view', () => ({}));
vi.mock('@app/features/email-compose/email-compose', () => ({}));
diff --git a/apps/web/src/features/agents-view/primitives/open-composer.test.ts b/apps/web/src/features/agents-view/primitives/open-composer.test.ts
new file mode 100644
index 0000000000..443eede97a
--- /dev/null
+++ b/apps/web/src/features/agents-view/primitives/open-composer.test.ts
@@ -0,0 +1,101 @@
+import type {
+ SplitContent,
+ SplitHandle,
+ SplitManager,
+} from '@components/app/split-layout/layoutManager';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { openAgentComposer } from './open-composer';
+
+const focus = vi.hoisted(() => ({
+ target: undefined as (() => HTMLElement | null | undefined) | undefined,
+}));
+vi.mock('@core/directive/focusInput', () => ({
+ triggerFocusInput: (target: () => HTMLElement | null | undefined) => {
+ focus.target = target;
+ target()?.focus();
+ },
+}));
+
+function layout(existing = false) {
+ let content: SplitContent = { type: 'component', id: 'agents' };
+ const replace = vi.fn(({ next }: { next: SplitContent }) => {
+ content = next;
+ });
+ const split = {
+ id: 'agents-split',
+ content: () => content,
+ replace,
+ } as unknown as SplitHandle;
+ const openWithSplit = vi.fn<SplitManager['openWithSplit']>((next) => {
+ if (!existing) content = next;
+ return split;
+ });
+ return { openWithSplit, replace, content: () => content };
+}
+
+function input(workspace: string, isNew = true) {
+ const root =
+ document.querySelector<HTMLElement>(
+ `[data-agents-workspace="${workspace}"]`
+ ) ?? document.createElement('div');
+ root.dataset.agentsWorkspace = workspace;
+ const page = document.createElement('div');
+ if (isNew) page.className = 'newchat';
+ const editor = document.createElement('div');
+ editor.setAttribute('contenteditable', 'true');
+ editor.tabIndex = 0;
+ page.append(editor);
+ root.append(page);
+ document.body.append(root);
+ return editor;
+}
+
+afterEach(() => {
+ document.body.replaceChildren();
+ focus.target = undefined;
+});
+
+describe('openAgentComposer', () => {
+ it('opens Agents with split placement and focuses only its new-chat input', () => {
+ const home = input('home');
+ input('agents-split', false);
+ const editor = input('agents-split');
+ home.focus();
+ const manager = layout();
+ openAgentComposer(manager, true);
+ expect(manager.openWithSplit).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'component', id: 'agents' }),
+ { referredFrom: 'launcher', preferNewSplit: true }
+ );
+ expect(manager.replace).not.toHaveBeenCalled();
+ expect(document.activeElement).toBe(editor);
+ });
+
+ it('issues a new composer request each time an existing Agents split is opened', () => {
+ const manager = layout(true);
+ openAgentComposer(manager);
+ const first = manager.content().params;
+ openAgentComposer(manager);
+ expect(manager.content().params).not.toEqual(first);
+ expect(manager.replace).toHaveBeenCalledTimes(2);
+ expect(manager.replace).toHaveBeenLastCalledWith({
+ next: expect.objectContaining({ id: 'agents' }),
+ mergeHistory: true,
+ });
+ });
+
+ it('can find the input after asynchronous navigation without touching another draft', () => {
+ const home = input('home');
+ home.textContent = 'Keep this draft';
+ openAgentComposer(layout());
+ expect(focus.target?.()).toBeUndefined();
+ const editor = input('agents-split');
+ expect(focus.target?.()).toBe(editor);
+ expect(home.textContent).toBe('Keep this draft');
+ });
+
+ it('does not steal focus when navigation is intercepted', () => {
+ openAgentComposer({ openWithSplit: () => undefined });
+ expect(focus.target).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/agents-view/primitives/open-composer.ts b/apps/web/src/features/agents-view/primitives/open-composer.ts
new file mode 100644
index 0000000000..3ce43b4ad5
--- /dev/null
+++ b/apps/web/src/features/agents-view/primitives/open-composer.ts
@@ -0,0 +1,38 @@
+import type { SplitManager } from '@components/app/split-layout/layoutManager';
+import { triggerFocusInput } from '@core/directive/focusInput';
+
+/** Open the new-conversation page, including when its split is already mounted. */
+export function openAgentComposer(
+ layout: Pick<SplitManager, 'openWithSplit'>,
+ preferNewSplit = false
+) {
+ const content = {
+ type: 'component' as const,
+ id: 'agents',
+ preserveParams: true,
+ params: { focusComposer: crypto.randomUUID() },
+ };
+ const split = layout.openWithSplit(content, {
+ referredFrom: 'launcher',
+ preferNewSplit,
+ });
+ if (!split) return;
+ // Opening an existing split activates it without updating its params.
+ // Publish a new request so an open roster returns to the composer as well.
+ const current = split.content();
+ if (
+ current.type !== 'component' ||
+ current.params?.focusComposer !== content.params.focusComposer
+ ) {
+ split.replace({ next: content, mergeHistory: true });
+ }
+ // Scope focus to this split and the new-chat input, never an existing session
+ // or Home's shared composer. Wait for asynchronous route/query mounting.
+ triggerFocusInput(() =>
+ Array.from(
+ document.querySelectorAll<HTMLElement>('[data-agents-workspace]')
+ )
+ .find((element) => element.dataset.agentsWorkspace === split.id)
+ ?.querySelector<HTMLElement>('.newchat [contenteditable="true"]')
+ );
+}
diff --git a/apps/web/src/features/agents-view/views/AgentsView.tsx b/apps/web/src/features/agents-view/views/AgentsView.tsx
index 43fc271286..5da13c8820 100644
--- a/apps/web/src/features/agents-view/views/AgentsView.tsx
+++ b/apps/web/src/features/agents-view/views/AgentsView.tsx
@@ -28,9 +28,11 @@ import { useSoupItemsQuery } from '@queries/soup/items';
import { useCurrentTeamQuery } from '@queries/team/teams';
import type { Harness } from '@service-storage/client';
import {
+ createEffect,
createMemo,
createSignal,
Match,
+ on,
onMount,
Show,
Suspense,
@@ -162,6 +164,20 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {
setSelected(undefined);
setPage('new');
};
+ // A launcher navigation can target this already-mounted workspace.
+ createEffect(
+ on(
+ () => {
+ const content = panel.handle.content();
+ return content.type === 'component'
+ ? content.params?.focusComposer
+ : undefined;
+ },
+ (request) => {
+ if (request) showComposer();
+ }
+ )
+ );
const openRoster = (kind: AgentKind) => {
setSelected(undefined);
setRosterKind(kind);
@@ -286,6 +302,7 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {
<DataModeProvider value={dataMode}>
<div
class="agents-view"
+ data-agents-workspace={panel.handle.id}
data-mode={dataMode()}
data-session={selected() ? '1' : undefined}
>
diff --git a/apps/web/src/features/block-agent/component/AgentPicker.test.tsx b/apps/web/src/features/block-agent/component/AgentPicker.test.tsx
deleted file mode 100644
index c2bedc40ac..0000000000
--- a/apps/web/src/features/block-agent/component/AgentPicker.test.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-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.tsx
deleted file mode 100644
index 591118d3c4..0000000000
--- a/apps/web/src/features/block-agent/component/AgentPicker.tsx
+++ /dev/null
@@ -1,171 +0,0 @@
-import CheckIcon from '@phosphor/check.svg';
-import AgentIcon from '@phosphor/sparkle.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>
- <AgentIcon 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.tsx
deleted file mode 100644
index 077478bb3a..0000000000
--- a/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx
+++ /dev/null
@@ -1,711 +0,0 @@
-const codexAccess = vi.hoisted(() => ({ enabled: true }));
-vi.mock('@core/codex/flag', () => ({
- useCodexAgentsAccess: () => () => codexAccess.enabled,
-}));
-
-import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';
-import { CODEX_BOT_ID } from '@core/constant/codexAgent';
-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 codexConnection = vi.hoisted(() => ({
- connected: false,
- environmentId: null as string | null,
-}));
-vi.mock('@queries/auth/codex', () => ({
- useCodexStatusQuery: () => ({
- isSuccess: true,
- isPlaceholderData: false,
- data: codexConnection,
- }),
-}));
-const cursorConnection = vi.hoisted(() => ({
- registered: true,
- isPlaceholderData: false,
-}));
-const hotkeys = vi.hoisted(() => ({
- enter: (): boolean => false,
- cmdEnter: (): boolean => false,
-}));
-const toasts = vi.hoisted(() => ({ success: vi.fn() }));
-const cmd = vi.hoisted(() => ({ held: 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', () => ({
- useCanAutofocusSplitContent: () => true,
- useSplitPanelOrThrow: () => ({
- handle: {
- close: navigation.close,
- isPopover: () => true,
- setDisplayName: vi.fn(),
- },
- }),
-}));
-vi.mock('@core/hotkey/hotkeys', () => ({
- useHotkeyDOMScope: () => [vi.fn(), 'test'],
- registerHotkey: (options: {
- hotkey?: string | string[];
- keyDownHandler: () => boolean;
- }) => {
- const keys = Array.isArray(options.hotkey)
- ? options.hotkey
- : [options.hotkey];
- for (const key of keys) {
- if (key === 'enter') hotkeys.enter = options.keyDownHandler;
- if (key === 'cmd+enter') hotkeys.cmdEnter = options.keyDownHandler;
- }
- },
-}));
-vi.mock('@core/hotkey/state', () => ({
- pressedKeys: () => new Set(cmd.held ? ['cmd'] : []),
-}));
-vi.mock('@core/component/Toast/Toast', () => ({
- toast: { success: (...args: unknown[]) => toasts.success(...args) },
-}));
-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',
- },
- {
- bot: {
- id: 'shared-reviewer',
- name: 'Shared Reviewer',
- handle: 'shared-reviewer',
- has_agent: true,
- owner: { type: 'user', user_id: 'macro|[email protected]' },
- },
- harness: 'in-memory',
- default_model: 'anthropic/claude-sonnet-5',
- },
- {
- bot: {
- id: 'team-helper',
- name: 'Team Helper',
- handle: 'team-helper',
- has_agent: true,
- owner: { type: 'team', team_id: 'team-1' },
- },
- harness: 'in-memory',
- default_model: 'anthropic/claude-sonnet-5',
- },
- {
- bot: {
- id: 'codex-reviewer',
- name: 'Codex Reviewer',
- handle: 'codex-reviewer',
- has_agent: true,
- },
- harness: 'codex-cloud',
- default_model: '',
- },
- {
- bot: { id: 'local', name: 'Local', handle: 'local', has_agent: true },
- harness: 'macrod',
- default_model: 'anthropic/claude-sonnet-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,
- }),
- Tooltip: (props: { children?: import('solid-js').JSX.Element }) =>
- props.children,
- Hotkey: () => null,
- SingleSelectCheck: () => null,
- badgeTriggerClasses: () => '',
- cn: (...inputs: Array<string | false | undefined>) =>
- inputs.filter(Boolean).join(' '),
- };
-});
-
-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(() => {
- codexAccess.enabled = true;
- codexConnection.connected = false;
- codexConnection.environmentId = null;
- cursorConnection.registered = true;
- cursorConnection.isPlaceholderData = false;
- cmd.held = 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('hides built-in and saved Codex personas when the rollout is disabled', () => {
- codexAccess.enabled = false;
- codexConnection.connected = true;
- codexConnection.environmentId = 'env-saved';
- mount();
- expect(screen.queryByText('Codex')).toBeNull();
- expect(screen.queryByText('Codex Reviewer')).toBeNull();
- expect(screen.queryByRole('button', { name: /Set up Codex/ })).toBeNull();
- });
-
- it('opens setup for a custom Codex persona without creating a session', () => {
- mount();
- fireEvent.click(
- screen.getByRole('button', { name: 'Set up Codex Reviewer' })
- );
- expect(navigation.settings).toHaveBeenCalledWith('Harness');
- expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();
- });
-
- it('opens Codex setup when disconnected', () => {
- mount();
- fireEvent.click(screen.getByRole('button', { name: 'Set up Codex' }));
- expect(navigation.settings).toHaveBeenCalledWith('Harness');
- expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();
- });
-
- it.each([null, '', ' '])(
- 'requires a saved environment when connected with %s',
- (environmentId) => {
- codexConnection.connected = true;
- codexConnection.environmentId = environmentId;
- mount();
- expect(
- screen.queryByRole('radio', { name: /^Codex @codex$/ })
- ).toBeNull();
- fireEvent.click(screen.getByRole('button', { name: 'Set up Codex' }));
- expect(navigation.settings).toHaveBeenCalledWith('Harness');
- expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();
- fireEvent.click(
- screen.getByRole('button', { name: 'Set up Codex Reviewer' })
- );
- expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();
- }
- );
-
- it.each(['environment-1'])(
- 'starts connected Codex with environment %s without a model override',
- async (environmentId) => {
- codexConnection.connected = true;
- codexConnection.environmentId = environmentId;
- mount();
- fireEvent.click(screen.getByRole('radio', { name: /^Codex @codex$/ }));
- expect(
- screen.queryByRole('button', { name: 'Model override' })
- ).toBeNull();
- hotkeys.enter();
- await waitFor(() =>
- expect(agentHarnessServiceClient.create).toHaveBeenCalledWith({
- botId: CODEX_BOT_ID,
- })
- );
- }
- );
- it('autofocuses the prompt when the composer opens', async () => {
- mount();
- const prompt = screen.getByRole('textbox', { name: 'Task for the agent' });
- await waitFor(() => expect(document.activeElement).toBe(prompt));
- });
-
- 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.enter();
- hotkeys.cmdEnter();
- 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(
- within(screen.getByRole('radio', { name: /Shared Reviewer/ })).getByText(
- '@shared-reviewer'
- )
- ).toBeTruthy();
- expect(
- within(screen.getByRole('radio', { name: /Team Helper/ })).getByText(
- '@team-helper'
- )
- ).toBeTruthy();
- expect(screen.queryByRole('radio', { name: /Local/ })).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.enter();
- 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.enter();
- 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.enter();
- 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);
- });
-
- it('starts in the background from the toggle without opening the session', async () => {
- mount();
- fireEvent.click(screen.getByRole('button', { name: 'Background' }));
- expect(
- screen
- .getByRole('group', { name: 'Session start mode' })
- .getAttribute('data-session-start-mode')
- ).toBe('background');
- fireEvent.click(
- screen.getByRole('button', { name: 'Start session in background' })
- );
- await waitFor(() => expect(toasts.success).toHaveBeenCalled());
- expect(navigation.close).toHaveBeenCalledOnce();
- expect(navigation.open).not.toHaveBeenCalled();
- expect(toasts.success).toHaveBeenCalledWith(
- 'Session started in background',
- expect.objectContaining({
- actions: [
- expect.objectContaining({
- label: 'Open session',
- onClick: expect.any(Function),
- }),
- ],
- })
- );
- expect(
- window.localStorage.getItem('agent-session-start-mode-v1:test-user')
- ).toBe('background');
- const open = toasts.success.mock.calls[0][1].actions[0]
- .onClick as () => void;
- open();
- expect(navigation.open).toHaveBeenCalledWith(
- { type: 'agent', id: sessionId },
- { referredFrom: 'launcher', preferNewSplit: false }
- );
- });
-
- it('restores a persisted background choice and starts in the background on enter', async () => {
- window.localStorage.setItem(
- 'agent-session-start-mode-v1:test-user',
- 'background'
- );
- mount();
- expect(
- screen.getByRole('button', { name: 'Start session in background' })
- ).toBeTruthy();
- hotkeys.enter();
- await waitFor(() => expect(toasts.success).toHaveBeenCalled());
- expect(navigation.open).not.toHaveBeenCalled();
- expect(navigation.close).toHaveBeenCalledOnce();
- });
-
- it('starts in the background on cmd+enter without persisting the toggle', async () => {
- cmd.held = true;
- mount();
- expect(
- screen
- .getByRole('group', { name: 'Session start mode' })
- .getAttribute('data-session-start-mode')
- ).toBe('background');
- hotkeys.cmdEnter();
- await waitFor(() => expect(toasts.success).toHaveBeenCalled());
- expect(navigation.open).not.toHaveBeenCalled();
- expect(
- window.localStorage.getItem('agent-session-start-mode-v1:test-user')
- ).toBeNull();
- });
-
- it('ignores cmd when background is already the committed mode', async () => {
- window.localStorage.setItem(
- 'agent-session-start-mode-v1:test-user',
- 'background'
- );
- cmd.held = true;
- mount();
- hotkeys.enter();
- await waitFor(() => expect(toasts.success).toHaveBeenCalled());
- expect(navigation.open).not.toHaveBeenCalled();
- expect(
- window.localStorage.getItem('agent-session-start-mode-v1:test-user')
- ).toBe('background');
- });
-});
diff --git a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx
deleted file mode 100644
index 1375bd916f..0000000000
--- a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx
+++ /dev/null
@@ -1,642 +0,0 @@
-import { useSplitLayout } from '@components/app/split-layout/layout';
-import {
- useCanAutofocusSplitContent,
- useSplitPanelOrThrow,
-} from '@components/app/split-layout/layoutUtils';
-import { useCodexAgentsAccess } from '@core/codex/flag';
-import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';
-import { toast } from '@core/component/Toast/Toast';
-import {
- CODEX_BOT_HANDLE,
- CODEX_BOT_ID,
- CODEX_BOT_NAME,
-} from '@core/constant/codexAgent';
-import {
- CURSOR_BOT_HANDLE,
- CURSOR_BOT_ID,
- CURSOR_BOT_NAME,
-} from '@core/constant/cursorAgent';
-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 { isTouchDevice } from '@core/mobile/isTouchDevice';
-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 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 { useCodexStatusQuery } from '@queries/auth/codex';
-import {
- useCursorApiKeyStatusQuery,
- useCursorModelsQuery,
-} from '@queries/auth/cursor-api-key';
-import { useNavigate } from '@solidjs/router';
-import { Button, badgeTriggerClasses, cn, Dropdown, 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 {
- agentRuntimeDescription,
- isManagedHarness,
- type ModelOption,
- type ModelShortlist,
- modelPillLabel,
- type PersonaOption,
- personaDefaultLabel,
- shortlistModelOptions,
-} from './compose-agent-session-options';
-import { createSessionStartMode } from './create-session-start-mode';
-import { SessionStartToggle } from './SessionStartToggle';
-
-/**
- * Macro's own agent: the deployment's managed default. Sent without a
- * `botId`, so the server picks the runtime it is configured to run it on.
- */
-const MACRO_PERSONA_ID = 'macro';
-
-const IN_MEMORY_MODELS: ModelOption[] = Object.values(Model).map((id) => ({
- id,
- name: MODEL_PRETTYNAME[id],
-}));
-
-/** The model picker shares the task composer's outline pill look. */
-const PILL_CLASS = badgeTriggerClasses({
- variant: 'outline',
- size: 'sm',
- class:
- 'max-w-64 gap-1.5 px-2 text-ink-muted data-expanded:bg-hover data-expanded:text-ink',
-});
-
-export interface ComposeAgentSessionProps {
- /** Open the new session in a fresh split instead of the current one. */
- preferNewSplit?: boolean;
-}
-
-/** 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 canUseCodex = useCodexAgentsAccess();
- const codexStatus = useCodexStatusQuery(canUseCodex);
- const codexReady = () =>
- canUseCodex() &&
- codexStatus.isSuccess &&
- codexStatus.data.connected &&
- !!codexStatus.data.environmentId?.trim();
- 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 startMode = createSessionStartMode(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>();
- const [submitMode, setSubmitMode] = createSignal<
- 'live' | 'background' | undefined
- >();
- let appliedModel: string | undefined;
- const [containerRef, setContainerRef] = createSignal<HTMLDivElement>();
- let promptRef: HTMLTextAreaElement | undefined;
- const canAutofocusSplitContent = useCanAutofocusSplitContent();
- const shouldAutofocusPrompt = () =>
- canAutofocusSplitContent && !isTouchDevice();
-
- // First-party agents lead, then saved personas the caller can start —
- // their own, team-shared, and selected-channel personas they can `@`.
- 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,
- botId: CURSOR_BOT_ID,
- name: CURSOR_BOT_NAME,
- handle: CURSOR_BOT_HANDLE,
- harness: 'cursor',
- defaultModel: cursorStatus.isSuccess
- ? (cursorStatus.data.defaultModelId ??
- (cursorDefaults.isSuccess
- ? (cursorDefaults.data.currentModel ?? undefined)
- : undefined))
- : undefined,
- unavailableReason: cursorConnected()
- ? undefined
- : 'Connect Cursor in Settings → Harness',
- connectLabel: cursorNeedsConnection() ? 'Connect Cursor' : undefined,
- },
- {
- id: CODEX_BOT_ID,
- botId: CODEX_BOT_ID,
- name: CODEX_BOT_NAME,
- handle: CODEX_BOT_HANDLE,
- harness: 'codex-cloud',
- unavailableReason: codexReady()
- ? undefined
- : 'Connect ChatGPT, then choose and save an environment in Settings → Harness',
- connectLabel:
- codexStatus.isSuccess &&
- !codexStatus.isPlaceholderData &&
- !codexReady()
- ? 'Set up Codex'
- : undefined,
- },
- ...(agentsQuery.isSuccess ? agentsQuery.data : [])
- // Only runtimes Macro provisions can be started from here; a persona on
- // a registered macrod daemon opens its own sessions.
- .filter((agent) => isManagedHarness(agent.harness))
- .map((agent) => ({
- id: agent.bot.id,
- 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,
- unavailableReason:
- agent.harness === 'codex-cloud' && !codexReady()
- ? 'Connect ChatGPT, then choose and save an environment in Settings → Harness'
- : undefined,
- connectLabel:
- agent.harness === 'codex-cloud' &&
- codexStatus.isSuccess &&
- !codexStatus.isPlaceholderData &&
- !codexReady()
- ? `Set up ${agent.bot.name}`
- : undefined,
- defaultModel: agent.default_model,
- ownerId:
- agent.bot.owner?.type === 'user'
- ? agent.bot.owner.user_id
- : (agent.bot.created_by ?? undefined),
- })),
- ] satisfies PersonaOption[]
- ).filter((persona) => persona.harness !== 'codex-cloud' || canUseCodex())
- );
- 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 === 'codex-cloud') return [];
- if (selectedPersona()?.harness === 'cursor') {
- return cursorModels.isSuccess
- ? cursorModels.data.models.map((model) => ({
- id: model.id,
- name: model.displayName,
- group: model.group ?? undefined,
- }))
- : [];
- }
- return IN_MEMORY_MODELS;
- };
- const modelShortlist = () =>
- shortlistModelOptions(selectedPersona(), availableModels());
- const modelsForPersona = (persona: PersonaOption): ModelOption[] => {
- if (persona.harness === 'codex-cloud') return [];
- 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?.connectLabel) return;
- close();
- openSettings('Harness');
- };
- const setPersona = (id: string) => {
- if (submitting() || sessionId()) return;
- setPersonaId(id);
- setModelOverride('');
- };
- const openSession = (id: string) => {
- close();
- openWithSplit(
- { type: 'agent', id },
- { referredFrom: 'launcher', preferNewSplit: props.preferNewSplit }
- );
- };
- const createSession = async () => {
- const persona = selectedPersona();
- if (submitting() || !persona || persona.unavailableReason) return;
- const background = startMode.effective() === 'background';
- setSubmitMode(background ? 'background' : 'live');
- 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);
- setSubmitMode(undefined);
- }
- if (background) {
- close();
- toast.success('Session started in background', {
- duration: 8000,
- actions: [
- {
- label: 'Open session',
- onClick: () =>
- openWithSplit(
- { type: 'agent', id },
- {
- referredFrom: 'launcher',
- preferNewSplit: props.preferNewSplit,
- }
- ),
- },
- ],
- });
- return;
- }
- openSession(id);
- };
-
- const [attachHotkeys, hotkeyScope] = useHotkeyDOMScope(
- 'compose-agent-session',
- true
- );
- onMount(() => {
- splitPanel.handle.setDisplayName('New agent session');
- const container = containerRef();
- if (container) attachHotkeys(container);
- if (!shouldAutofocusPrompt()) return;
- const focusPrompt = () => promptRef?.focus({ preventScroll: true });
- focusPrompt();
- // Dialog focus-on-open can run after this mount; reclaim the prompt.
- queueMicrotask(focusPrompt);
- requestAnimationFrame(focusPrompt);
- });
- registerHotkey({
- hotkey: ['enter', 'cmd+enter'],
- scopeId: hotkeyScope,
- description: 'Create agent session',
- keyDownHandler: () => {
- void createSession();
- return true;
- },
- runWithInputFocused: true,
- });
-
- return (
- <div
- 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="mb-8 shrink-0 text-center">
- <h1 class="text-3xl/9 font-medium text-ink">Start a session</h1>
- <Show when={splitPanel.handle.isPopover()}>
- <Button
- onMouseDown={close}
- tabIndex={-1}
- tooltip="Close"
- size="icon-sm"
- class="absolute top-3 right-3"
- >
- <XIcon />
- </Button>
- </Show>
- </div>
-
- <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={(el) => {
- promptRef = el;
- }}
- rows={3}
- aria-label="Task for the agent"
- autofocus={shouldAutofocusPrompt()}
- class="ph-no-capture min-h-20 w-full flex-1 resize-none bg-transparent px-4 pt-4 pb-2 text-base/6 text-ink outline-none placeholder:text-ink-placeholder"
- 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
- // the task composer; a second Escape closes the popover.
- if (event.key === 'Escape') {
- event.preventDefault();
- event.stopPropagation();
- containerRef()?.focus();
- }
- }}
- />
-
- <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="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">
- <Show when={selectedPersona()?.harness !== 'codex-cloud'}>
- <Suspense>
- <ModelPicker
- persona={selectedPersona()}
- available={modelsForPersona(selectedPersona())}
- shortlist={modelShortlist()}
- value={modelOverride()}
- loading={
- selectedPersona()?.harness === 'cursor' &&
- cursorModels.isPending
- }
- disabled={submitting() || !!sessionId()}
- onSelect={setModelOverride}
- />
- </Suspense>
- </Show>
- </div>
-
- <SessionStartToggle
- mode={submitMode() ?? startMode.effective()}
- committed={startMode.committed()}
- pending={submitting()}
- error={!!error()}
- disabled={submitting() || !!selectedPersona()?.unavailableReason}
- onModeChange={startMode.setCommitted}
- onStart={() => void createSession()}
- />
- </div>
- </Surface>
- <p
- aria-live="polite"
- class="mt-7 shrink-0 text-center text-sm text-ink-muted"
- >
- {runtimeDescription()}
- </p>
- </div>
- );
-}
-
-function ModelPicker(props: {
- persona: PersonaOption | undefined;
- available: ModelOption[];
- shortlist: ModelShortlist;
- value: string;
- loading: boolean;
- disabled: boolean;
- onSelect: (id: string) => void;
-}) {
- const label = () =>
- modelPillLabel(props.value, props.persona, props.available);
- return (
- <Dropdown placement="top-start">
- <Dropdown.Trigger
- variant="outline"
- size="sm"
- class={PILL_CLASS}
- aria-label="Model override"
- disabled={props.disabled}
- tooltip={props.value ? 'Model override' : 'Model (agent default)'}
- >
- <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="max-h-72 overflow-y-auto overscroll-contain">
- <Dropdown.GroupLabel>Model</Dropdown.GroupLabel>
- <ModelRow
- label={personaDefaultLabel(props.persona, props.available)}
- selected={props.value === ''}
- onSelect={() => props.onSelect('')}
- />
- <For each={props.shortlist.featured}>
- {(model) => (
- <ModelRow
- label={model.name}
- selected={props.value === model.id}
- onSelect={() => props.onSelect(model.id)}
- />
- )}
- </For>
- <Show when={props.shortlist.more.length > 0}>
- <Dropdown.Sub>
- <Dropdown.SubTrigger class="h-8">
- <span class="truncate">More models</span>
- <span class="flex shrink-0 items-center gap-1 text-xs text-ink-extra-muted">
- {props.shortlist.more.length}
- <CaretRightIcon class="size-3" />
- </span>
- </Dropdown.SubTrigger>
- <Dropdown.SubContent class="w-72 max-w-[min(24rem,calc(100vw-1rem))]">
- <Dropdown.Group class="max-h-72 overflow-y-auto overscroll-contain">
- <For each={props.shortlist.more}>
- {(model) => (
- <ModelRow
- label={model.name}
- hint={model.group}
- selected={props.value === model.id}
- onSelect={() => props.onSelect(model.id)}
- />
- )}
- </For>
- </Dropdown.Group>
- </Dropdown.SubContent>
- </Dropdown.Sub>
- </Show>
- <Show when={props.loading}>
- <div class="px-2 py-2 text-xs text-ink-extra-muted">
- Loading models…
- </div>
- </Show>
- <Show when={!props.loading && props.available.length === 0}>
- <div class="px-2 py-2 text-xs text-ink-extra-muted">
- This agent's harness did not report any models.
- </div>
- </Show>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- );
-}
-
-function ModelRow(props: {
- label: string;
- /** Trailing muted text, e.g. the family a model belongs to. */
- hint?: string;
- selected: boolean;
- onSelect: () => void;
-}) {
- return (
- <Dropdown.Item
- class={cn('h-8 gap-2', props.selected && 'bg-ink/5 text-ink font-medium')}
- onSelect={props.onSelect}
- >
- <span class="min-w-0 flex-1 truncate text-sm">{props.label}</span>
- <Show when={props.hint}>
- <span class="shrink-0 text-xs text-ink-extra-muted">{props.hint}</span>
- </Show>
- <Show when={props.selected}>
- <CheckIcon class="size-3.5 shrink-0 text-accent" />
- </Show>
- </Dropdown.Item>
- );
-}
diff --git a/apps/web/src/features/block-agent/component/SessionStartToggle.test.tsx b/apps/web/src/features/block-agent/component/SessionStartToggle.test.tsx
deleted file mode 100644
index 420b1da2ba..0000000000
--- a/apps/web/src/features/block-agent/component/SessionStartToggle.test.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { fireEvent, render, screen } from '@solidjs/testing-library';
-import { describe, expect, it, vi } from 'vitest';
-import { SessionStartToggle } from './SessionStartToggle';
-
-vi.mock('@ui', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@ui')>();
- const Pass = (props: { children?: import('solid-js').JSX.Element }) =>
- props.children;
- return {
- ...actual,
- Dropdown: Object.assign(Pass, {
- Trigger: (
- props: import('solid-js').JSX.ButtonHTMLAttributes<HTMLButtonElement>
- ) => (
- <button aria-label={props['aria-label']} disabled={props.disabled}>
- {props.children}
- </button>
- ),
- Content: Pass,
- Group: Pass,
- Item: (
- props: import('solid-js').JSX.ButtonHTMLAttributes<HTMLButtonElement> & {
- onSelect: () => void;
- }
- ) => (
- <button
- role={props.role}
- aria-checked={props['aria-checked']}
- onClick={props.onSelect}
- >
- {props.children}
- </button>
- ),
- }),
- };
-});
-
-describe('SessionStartToggle', () => {
- it('starts the selected mode from the send button and changes mode from the dropdown', () => {
- const onModeChange = vi.fn();
- const onStart = vi.fn();
- render(() => (
- <SessionStartToggle
- mode="live"
- committed="live"
- onModeChange={onModeChange}
- onStart={onStart}
- />
- ));
-
- fireEvent.click(screen.getByRole('button', { name: 'Start session' }));
- expect(onStart).toHaveBeenCalledOnce();
- expect(onModeChange).not.toHaveBeenCalled();
-
- fireEvent.click(screen.getByRole('menuitemradio', { name: /Background/ }));
- expect(onModeChange).toHaveBeenCalledWith('background');
- expect(onStart).toHaveBeenCalledOnce();
- });
-
- it('starts in background when that mode is already selected', () => {
- const onModeChange = vi.fn();
- const onStart = vi.fn();
- render(() => (
- <SessionStartToggle
- mode="background"
- committed="background"
- onModeChange={onModeChange}
- onStart={onStart}
- />
- ));
-
- fireEvent.click(
- screen.getByRole('button', { name: 'Start session in background' })
- );
- expect(onStart).toHaveBeenCalledOnce();
- fireEvent.click(screen.getByRole('menuitemradio', { name: /Live/ }));
- expect(onModeChange).toHaveBeenCalledWith('live');
- });
-
- it('keeps the mode dropdown to the left of the send button', () => {
- render(() => (
- <SessionStartToggle
- mode="live"
- committed="live"
- onModeChange={vi.fn()}
- onStart={vi.fn()}
- />
- ));
- const group = screen.getByRole('group', { name: 'Session start mode' });
- const mode = screen.getByRole('button', { name: 'Session start mode' });
- const send = screen.getByRole('button', { name: 'Start session' });
- expect(group.contains(mode)).toBe(true);
- expect(group.contains(send)).toBe(true);
- expect(
- mode.compareDocumentPosition(send) & Node.DOCUMENT_POSITION_FOLLOWING
- ).toBeTruthy();
- });
-
- it('previews background on the trigger without changing the committed check', () => {
- render(() => (
- <SessionStartToggle
- mode="background"
- committed="live"
- onModeChange={vi.fn()}
- onStart={vi.fn()}
- />
- ));
- expect(
- screen
- .getByRole('group', { name: 'Session start mode' })
- .getAttribute('data-session-start-mode')
- ).toBe('background');
- expect(
- screen.getByRole('button', { name: 'Start session in background' })
- ).toBeTruthy();
- expect(
- screen
- .getByRole('menuitemradio', { name: /Live/ })
- .getAttribute('aria-checked')
- ).toBe('true');
- expect(
- screen
- .getByRole('menuitemradio', { name: /Background/ })
- .getAttribute('aria-checked')
- ).toBe('false');
- });
-});
diff --git a/apps/web/src/features/block-agent/component/SessionStartToggle.tsx b/apps/web/src/features/block-agent/component/SessionStartToggle.tsx
deleted file mode 100644
index 3310cf2fb1..0000000000
--- a/apps/web/src/features/block-agent/component/SessionStartToggle.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import CaretDownIcon from '@phosphor/caret-down.svg';
-import {
- badgeTriggerClasses,
- cn,
- Dropdown,
- Hotkey,
- SendButton,
- SingleSelectCheck,
-} from '@ui';
-import type { SessionStartMode } from './session-start-mode';
-
-export function SessionStartToggle(props: {
- mode: SessionStartMode;
- /** Committed choice for menu checks. Cmd preview only changes `mode`. */
- committed?: SessionStartMode;
- pending?: boolean;
- disabled?: boolean;
- error?: boolean;
- onModeChange: (mode: SessionStartMode) => void;
- onStart: () => void;
-}) {
- const background = () => props.mode === 'background';
- const selected = () => props.committed ?? props.mode;
- const startLabel = () => {
- if (props.pending) return 'Starting…';
- if (props.error) return 'Retry';
- return background() ? 'Start session in background' : 'Start session';
- };
-
- return (
- <div
- role="group"
- aria-label="Session start mode"
- data-session-start-mode={props.mode}
- class={cn(
- 'flex h-7 shrink-0 items-center gap-1.5',
- props.disabled && 'opacity-60'
- )}
- >
- <Dropdown placement="top-end">
- <Dropdown.Trigger
- variant="outline"
- size="sm"
- class={badgeTriggerClasses({
- variant: 'outline',
- size: 'sm',
- class:
- 'gap-1 px-2 text-ink-muted data-expanded:bg-hover data-expanded:text-ink',
- })}
- aria-label="Session start mode"
- disabled={props.disabled}
- >
- <span class="text-ink">{background() ? 'Background' : 'Live'}</span>
- <CaretDownIcon class="size-3 shrink-0 text-current/70" />
- </Dropdown.Trigger>
- <Dropdown.Content class="min-w-40">
- <Dropdown.Group>
- <Dropdown.Item
- class="h-8"
- role="menuitemradio"
- aria-checked={selected() === 'live'}
- onSelect={() => props.onModeChange('live')}
- >
- <span class="min-w-0 flex-1 truncate">Live</span>
- <SingleSelectCheck active={selected() === 'live'} />
- </Dropdown.Item>
- <Dropdown.Item
- class="h-8"
- role="menuitemradio"
- aria-checked={selected() === 'background'}
- onSelect={() => props.onModeChange('background')}
- >
- <span class="min-w-0 flex-1 truncate">Background</span>
- <Hotkey shortcut="cmd" theme="subtle" />
- <SingleSelectCheck active={selected() === 'background'} />
- </Dropdown.Item>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- <SendButton
- aria-label={startLabel()}
- tooltip={startLabel()}
- pending={props.pending}
- disabled={props.disabled}
- onClick={() => props.onStart()}
- />
- </div>
- );
-}
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.ts
index 20b3f704ec..efd6debda8 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,73 +1,5 @@
import { describe, expect, it } from 'vitest';
-import {
- agentRuntimeDescription,
- harnessDisplayName,
- isManagedHarness,
- modelPillLabel,
- overrideModelOptions,
- type PersonaOption,
- personaDefaultLabel,
- shortlistModelOptions,
-} from './compose-agent-session-options';
-
-const MODELS = [
- { id: 'anthropic/claude-sonnet-5', name: 'Sonnet 5' },
- { id: 'anthropic/claude-opus-5', name: 'Opus 5' },
-];
-
-const CODER: PersonaOption = {
- id: 'macro-coder',
- name: 'Macro Coder',
- handle: 'coder',
- harness: 'sandbox',
-};
-
-const ENGINEER: PersonaOption = {
- ...CODER,
- id: 'bot-1',
- botId: 'bot-1',
- name: 'Test Engineer',
- handle: 'test-engineer',
- 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);
- });
-
- it('drops the persona default so it is not offered twice', () => {
- expect(overrideModelOptions(ENGINEER, MODELS)).toEqual([MODELS[1]]);
- });
-});
+import { harnessDisplayName } from './compose-agent-session-options';
describe('harnessDisplayName', () => {
it('names Macro runtimes after the product', () => {
@@ -83,106 +15,3 @@ describe('harnessDisplayName', () => {
expect(harnessDisplayName('my-laptop')).toBe('my-laptop');
});
});
-
-describe('isManagedHarness', () => {
- it('accepts the runtimes the deployment provisions', () => {
- expect(isManagedHarness('in-memory')).toBe(true);
- expect(isManagedHarness('macro-inmem')).toBe(true);
- expect(isManagedHarness('cursor')).toBe(true);
- expect(isManagedHarness('claude-cloud')).toBe(true);
- });
-
- it('refuses external daemons', () => {
- expect(isManagedHarness('macrod')).toBe(false);
- expect(isManagedHarness('harness-123')).toBe(false);
- });
-});
-
-describe('shortlistModelOptions', () => {
- it('shows a short list in full', () => {
- expect(shortlistModelOptions(ENGINEER, MODELS)).toEqual({
- featured: [MODELS[1]],
- more: [],
- });
- });
-
- it('caps a long catalog and keeps the rest behind more', () => {
- const catalog = [
- { id: 'auto', name: 'Auto' },
- { id: 'grok', name: 'Cursor Grok 4.6' },
- { id: 'opus', name: 'Claude Opus 5' },
- { id: 'opus-thinking', name: 'Claude Opus 5 Thinking' },
- { id: 'sonnet', name: 'Claude Sonnet 5' },
- { id: 'sonnet-thinking', name: 'Claude Sonnet 5 Thinking' },
- { id: 'gpt', name: 'GPT-5.6 Sol' },
- { id: 'gpt-fast', name: 'GPT-5.6 Sol Fast' },
- { id: 'gemini', name: 'Gemini 3.8 Flash' },
- ];
- const shortlist = shortlistModelOptions(CODER, catalog, 5);
-
- expect(shortlist.featured.map((model) => model.id)).toEqual([
- 'auto',
- 'grok',
- 'opus',
- 'sonnet',
- 'gpt',
- ]);
- expect(shortlist.more.map((model) => model.id)).toEqual([
- 'opus-thinking',
- 'sonnet-thinking',
- 'gpt-fast',
- 'gemini',
- ]);
- expect(shortlist.featured.length + shortlist.more.length).toBe(
- catalog.length
- );
- });
-
- it('never features the persona default', () => {
- const catalog = Array.from({ length: 8 }, (_, index) => ({
- id: `m${index}`,
- name: `Model ${index}`,
- }));
- const persona = { ...CODER, defaultModel: 'm0' };
- const shortlist = shortlistModelOptions(persona, catalog, 3);
-
- expect(shortlist.featured).toHaveLength(3);
- expect(
- [...shortlist.featured, ...shortlist.more].some(
- (model) => model.id === 'm0'
- )
- ).toBe(false);
- });
-});
-
-describe('personaDefaultLabel', () => {
- it('is generic without a known default', () => {
- expect(personaDefaultLabel(CODER, MODELS)).toBe('default');
- });
-
- it('names the default model when the persona has one', () => {
- 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('default (acme/x)');
- });
-});
-
-describe('modelPillLabel', () => {
- it('shows the override when one is set', () => {
- expect(modelPillLabel('anthropic/claude-opus-5', ENGINEER, MODELS)).toBe(
- 'Opus 5'
- );
- });
-
- it('shows the persona default otherwise', () => {
- expect(modelPillLabel('', ENGINEER, MODELS)).toBe('default (Sonnet 5)');
- });
-
- it('shows a neutral label when nothing is known', () => {
- 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.ts
index 808207a48c..9e08e7efe2 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
@@ -1,52 +1,3 @@
-import { buildModelCatalog } from '@core/component/AI/component/input/modelCatalog';
-
-/** A persona the composer can start a managed session as. */
-export type PersonaOption = {
- id: string;
- /** Persisted bot id; absent for the deployment's built-in default persona. */
- 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;
- /** 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. */
-export type ModelOption = {
- id: string;
- name: string;
- /** The heading the harness lists this model under, when it groups them. */
- group?: string;
-};
-
-/**
- * How many override rows the menu shows up front. Enough to compare the
- * flagship choices at a glance; the rest sits behind "More models".
- */
-export const MAX_FEATURED_MODELS = 5;
-
-/**
- * Harness slugs whose runtimes this deployment provisions itself — the only
- * personas the create composer can start. Anything else (a registered macrod
- * daemon, say) opens its own sessions and is refused by the create route.
- */
-export function isManagedHarness(harness: string): boolean {
- return (
- harness === 'in-memory' ||
- harness === 'macro-inmem' ||
- harness === 'cursor' ||
- harness === 'codex-cloud' ||
- harness === 'claude-cloud'
- );
-}
-
/** 'claude-code' → 'Claude Code'; the fallback when nothing names a harness. */
export function harnessTitle(harness: string | undefined): string {
if (!harness) return 'Agent session';
@@ -57,37 +8,6 @@ export function harnessTitle(harness: string | undefined): string {
.join(' ');
}
-/** A model's display name, or its id when the runtime lists no name for it. */
-export function modelDisplayName(
- id: string,
- available: readonly Pick<ModelOption, 'id' | 'name'>[]
-): string {
- 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 === 'codex-cloud')
- return 'Runs in your selected Codex cloud environment';
- if (persona.harness === 'claude-cloud') {
- return 'Runs in Claude’s cloud using your subscription';
- }
- 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.
@@ -109,81 +29,10 @@ export function harnessDisplayName(harness: string): string {
}
}
-/**
- * The models offered as explicit overrides. The persona's own default is
- * already the "Agent default" choice, so listing it again would offer two
- * rows that do the same thing.
- */
-export function overrideModelOptions(
- persona: PersonaOption | undefined,
- available: readonly ModelOption[]
-): ModelOption[] {
- const defaultModel = persona?.defaultModel;
- return defaultModel
- ? available.filter((model) => model.id !== defaultModel)
- : [...available];
-}
-
-/** The override rows split into the featured shortlist and the overflow. */
-export type ModelShortlist = {
- featured: ModelOption[];
- more: ModelOption[];
-};
-
-/**
- * Cap the override list so the user compares a handful of models rather
- * than scrolling a whole catalog. Short lists show in full. Long ones lead
- * with the catalog's recommended picks (the flagship of each family the
- * harness offers) and put everything else behind "More models".
- */
-export function shortlistModelOptions(
- persona: PersonaOption | undefined,
- available: readonly ModelOption[],
- max = MAX_FEATURED_MODELS
-): ModelShortlist {
- const overrides = overrideModelOptions(persona, available);
- if (overrides.length <= max) return { featured: overrides, more: [] };
-
- const catalog = buildModelCatalog(
- overrides.map((model) => ({
- id: model.id,
- label: model.name,
- group: model.group,
- }))
- );
- const featuredIds = new Set(
- catalog.recommended.slice(0, max).map((option) => option.id)
- );
- // Fill from the harness's own order if curation found fewer than `max`.
- for (const model of overrides) {
- if (featuredIds.size >= max) break;
- featuredIds.add(model.id);
- }
- return {
- featured: overrides.filter((model) => featuredIds.has(model.id)),
- more: overrides.filter((model) => !featuredIds.has(model.id)),
- };
-}
-
-/**
- * Label for the "leave the model alone" choice. Names the persona's default
- * when it is known so the user sees what they will get without overriding.
- */
-export function personaDefaultLabel(
- persona: PersonaOption | undefined,
- available: readonly ModelOption[]
-): string {
- const defaultModel = persona?.defaultModel;
- if (!defaultModel) return 'default';
- return `default (${modelDisplayName(defaultModel, available)})`;
-}
-
-/** Short label for the closed model pill. */
-export function modelPillLabel(
- override: string,
- persona: PersonaOption | undefined,
- available: readonly ModelOption[]
+/** A model's display name, or its id when the runtime lists no name for it. */
+export function modelDisplayName(
+ id: string,
+ available: readonly { id: string; name: string }[]
): string {
- if (override) return modelDisplayName(override, available);
- return personaDefaultLabel(persona, available);
+ return available.find((model) => model.id === id)?.name ?? id;
}
diff --git a/apps/web/src/features/block-agent/component/create-session-start-mode.test.ts b/apps/web/src/features/block-agent/component/create-session-start-mode.test.ts
deleted file mode 100644
index ce66811bd8..0000000000
--- a/apps/web/src/features/block-agent/component/create-session-start-mode.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { createRoot, createSignal } from 'solid-js';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createSessionStartMode } from './create-session-start-mode';
-import { SESSION_START_MODE_STORAGE_KEY } from './session-start-mode';
-
-beforeEach(() => window.localStorage.clear());
-
-function storageKey(userId: string) {
- return `${SESSION_START_MODE_STORAGE_KEY}:${encodeURIComponent(userId)}`;
-}
-
-describe('session start mode persistence', () => {
- it('defaults to live and persists a user-chosen background mode', () => {
- createRoot((dispose) => {
- const [cmdHeld] = createSignal(false);
- const mode = createSessionStartMode('user-a', cmdHeld);
- expect(mode.committed()).toBe('live');
- expect(mode.effective()).toBe('live');
- mode.setCommitted('background');
- expect(mode.committed()).toBe('background');
- expect(window.localStorage.getItem(storageKey('user-a'))).toBe(
- 'background'
- );
- dispose();
- });
- createRoot((dispose) => {
- const [cmdHeld] = createSignal(false);
- expect(createSessionStartMode('user-a', cmdHeld).committed()).toBe(
- 'background'
- );
- expect(createSessionStartMode('user-b', cmdHeld).committed()).toBe(
- 'live'
- );
- dispose();
- });
- });
-
- it('previews background while cmd is held and restores live on release', () => {
- createRoot((dispose) => {
- const [cmdHeld, setCmdHeld] = createSignal(false);
- const mode = createSessionStartMode('user-a', cmdHeld);
- setCmdHeld(true);
- expect(mode.effective()).toBe('background');
- expect(mode.committed()).toBe('live');
- expect(window.localStorage.getItem(storageKey('user-a'))).toBeNull();
- setCmdHeld(false);
- expect(mode.effective()).toBe('live');
- dispose();
- });
- });
-
- it('ignores cmd when the user has already chosen background', () => {
- createRoot((dispose) => {
- const [cmdHeld, setCmdHeld] = createSignal(false);
- const mode = createSessionStartMode('user-a', cmdHeld);
- mode.setCommitted('background');
- setCmdHeld(true);
- expect(mode.effective()).toBe('background');
- setCmdHeld(false);
- expect(mode.effective()).toBe('background');
- dispose();
- });
- });
-
- it('ignores malformed storage and keeps working when writes fail', () => {
- window.localStorage.setItem(storageKey('user-a'), 'nope');
- createRoot((dispose) => {
- const [cmdHeld] = createSignal(false);
- expect(createSessionStartMode('user-a', cmdHeld).committed()).toBe(
- 'live'
- );
- dispose();
- });
- const write = vi
- .spyOn(Storage.prototype, 'setItem')
- .mockImplementation(() => {
- throw new Error('Storage unavailable');
- });
- createRoot((dispose) => {
- const [cmdHeld] = createSignal(false);
- const mode = createSessionStartMode('user-a', cmdHeld);
- mode.setCommitted('background');
- expect(mode.committed()).toBe('background');
- dispose();
- });
- write.mockRestore();
- });
-});
diff --git a/apps/web/src/features/block-agent/component/create-session-start-mode.ts b/apps/web/src/features/block-agent/component/create-session-start-mode.ts
deleted file mode 100644
index ad8328c149..0000000000
--- a/apps/web/src/features/block-agent/component/create-session-start-mode.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { makePersistedState } from '@app/lib/persistence';
-import { pressedKeys } from '@core/hotkey/state';
-import { createUserScopedStorage } from '@core/util/userScopedStorage';
-import { createSignal } from 'solid-js';
-import {
- effectiveSessionStartMode,
- parseSessionStartMode,
- SESSION_START_MODE_STORAGE_KEY,
- type SessionStartMode,
-} from './session-start-mode';
-
-/**
- * Committed live/background choice for the session composer, persisted per
- * user on this device. Cmd/Ctrl previews background without writing storage.
- */
-export function createSessionStartMode(
- userId: string | undefined,
- cmdHeld: () => boolean = () => pressedKeys().has('cmd')
-) {
- const storage = createUserScopedStorage(SESSION_START_MODE_STORAGE_KEY);
- const [committed, setCommitted] = makePersistedState(
- createSignal<SessionStartMode>('live'),
- {
- storages: {
- restore: () => {
- if (!userId) return;
- return parseSessionStartMode(storage.read(userId));
- },
- write: (value) => {
- if (userId) storage.write(userId, value);
- },
- },
- }
- );
-
- return {
- committed,
- setCommitted,
- effective: () => effectiveSessionStartMode(committed(), cmdHeld()),
- };
-}
diff --git a/apps/web/src/features/command/Launcher.tsx b/apps/web/src/features/command/Launcher.tsx
index 04b4046c19..b2dd49df78 100644
--- a/apps/web/src/features/command/Launcher.tsx
+++ b/apps/web/src/features/command/Launcher.tsx
@@ -1,3 +1,4 @@
+import { openAgentComposer } from '@app/features/agents-view/primitives/open-composer';
import { startPendingSession } from '@app/features/block-agent/context/pending-session';
import { AGENT_INPUT_TEXT_AREA_ID } from '@app/features/block-agent/ui/AgentInput';
import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitives/use-spreadsheet-access';
@@ -432,13 +433,8 @@ export function runCreateAction(
return;
case 'agent': {
if (isFeatureEnabled(enableChatV3Agents)) {
- createComponent({
- componentId: 'agent-session-compose',
- asPopover: true,
- // The popover itself is not split-placed; the session it creates
- // is, so the new-split intent rides along for the composer to honor.
- params: { preferNewSplit: shouldInsert },
- });
+ setCreateMenuOpen(false, false);
+ openAgentComposer(useSplitLayout(), shouldInsert);
return;
}
// Without the composer there is nothing to ask for: a managed session's
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index acb46d3dcb..7e5111199b 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -152,30 +152,16 @@ composer with placeholder **`Ask AI, @mention anything`**. Click it, `type_text`
press Enter — the app creates a chat and navigates to `/app/chat/<uuid>`. Alternatively,
when `enable-chat-v3-agents` is on (default in dev;
`VITE_ENABLE_CHAT_V3_AGENTS` overrides), `Create` → `Agent`, or keyboard `c`
-then `a`, opens 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), **Cursor** `@cursor`, and **Codex** `@codex` lead, followed by saved agents
-the caller can start: their own, team-shared personas, and selected-channel
-personas they can `@` mention.
-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.
-Codex composer choices and its Settings → Harness section require both
-`enable-chat-v3-agents` and `enable-codex-agents`.
-Codex shows **Set up Codex** until ChatGPT is connected and a cloud environment
-is saved in Settings → Harness. New sessions use the saved environment and
-always start from `main`. The composer hides model overrides for
-Codex because this harness does not expose model selection. Codex assistant
+then `a`, opens `/app/component/agents` with the new-conversation input focused
+and ready to type. No session is created until you send a prompt. If Agents is
+already open on its roster, the shortcut returns it to the composer; if its
+composer already has a draft, that draft stays intact. `C Shift+A` requests a
+new split using the standard split-navigation behavior. The shared agent/model
+selector and coding repository controls are described above.
+
+## Codex session output
+
+Codex assistant
text appears when the provider supplies a completed message or final snapshot.
Incomplete text fragments are withheld; tool activity and thinking still update
during the turn. Verified Codex PR associations appear as a completed **Found
@@ -184,60 +170,7 @@ PR chip. This reports an existing PR; it does not publish one. Opening a detache
session reads saved history; sending a message reattaches the runtime.
Codex file citations render as inline code with the path and
line range, such as `.gitkeep:1` or `src/main.rs:2-12`; they do not link to a local
-file or a guessed remote revision. A recorded two-turn Codex conversation is
-covered by ACP/fold snapshots and checked with the production Markdown renderer. Setup navigation,
-selection, and the create/prompt payloads were verified in Chromium with mocked
-app navigation and backend state; no remote session was created by that check.
-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`. Autofocus lands on that prompt so you can type
-immediately; skip it on touch so the keyboard does not jump up unsolicited.
-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.
-The prompt footer’s start control is a **Live / Background** dropdown
-(`aria-label="Session start mode"`) to the left of the circular send button.
-**Live** (default) opens the new session; **Background** closes the composer
-and shows a bottom-right toast **Session started in background** with an
-**Open session** action. The send button starts the selected mode. The
-dropdown lists both options; **Background** shows `Cmd` / `Ctrl`. The choice
-persists per user in localStorage.
-Holding `Cmd`/`Ctrl` previews Background on the dropdown and send button only
-while Live is selected; releasing restores Live. If Background is already
-selected, the modifier does nothing.
-`Enter` starts the selected mode (`Shift+Enter` still inserts a newline).
-`Cmd`/`Ctrl+Enter` starts in the background when Live is selected.
-The send button shows a spinner and is labelled **Starting…**
-while the server creates the session, applies the model override, and accepts the
-first prompt. Live mode 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.
+file or a guessed remote revision.
## Starting from Home
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 6dcf5cdeb6..b43028e5ad 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -339,6 +339,10 @@ Home does not bind Delete or Backspace to deleting list items. These keys remain
available to the open editor (for example, clearing a selected spreadsheet range).
Use the item menu to delete an item from Home.
+`C A` (Create → Agent) opens the Agents new-conversation page and focuses its
+message input; `C Shift+A` requests a new split. It does not open a modal or
+create a session before the user sends. Repeating it focuses the existing draft.
+
### Content already open
Entity content can be open in only one split or inline preview/detail view at a