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.

feat(agents): add session composer and keep Settings visible while loading (#6234)

Wolf Mermelsteinb70d8d14ede9
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 51361d7e47..e50f049c53 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -1,5 +1,6 @@
import { openEntityInSplit } from '@app/features/activity/open-entity-in-split';
import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';
+import { ComposeAgentSession } from '@app/features/block-agent/component/ComposeAgentSession';
import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
import type { CalendarEvent } from '@app/features/calendar/types';
import { ChannelsView } from '@app/features/channels-view/channels-view';
@@ -682,6 +683,12 @@ 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} />
+ );
+});
registerComponent('calendar-event-compose', (params) => {
usePageViewTracking('calendar-event-compose');
return (
diff --git a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx
new file mode 100644
index 0000000000..86e7d35e8c
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx
@@ -0,0 +1,503 @@
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';
+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 { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import CheckIcon from '@phosphor/check.svg';
+import CpuIcon from '@phosphor/cpu.svg';
+import RobotIcon from '@phosphor/robot.svg';
+import XIcon from '@phosphor/x.svg';
+import { useAgentsQuery } from '@queries/agents/agents';
+import {
+ useCursorApiKeyStatusQuery,
+ useCursorModelsQuery,
+} from '@queries/auth/cursor-api-key';
+import { Avatar, Button, badgeTriggerClasses, cn, Dropdown, Hotkey } from '@ui';
+import { createSignal, For, onMount, Show } from 'solid-js';
+import { startPendingSession } from '../context/pending-session';
+import {
+ harnessDisplayName,
+ isManagedHarness,
+ type ModelOption,
+ type ModelShortlist,
+ modelPillLabel,
+ type PersonaOption,
+ personaDefaultLabel,
+ shortlistModelOptions,
+} from './compose-agent-session-options';
+
+/**
+ * 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 pl-1.5 pr-2 text-ink-muted data-expanded:bg-hover data-expanded:text-ink',
+});
+
+/** Long harness catalogs scroll instead of growing the menu without bound. */
+const MENU_LIST_CLASS = 'max-h-72 overflow-y-auto overscroll-contain';
+
+export interface ComposeAgentSessionProps {
+ /** Open the new session in a fresh split instead of the current one. */
+ preferNewSplit?: boolean;
+}
+
+/** Task-style preflight composer for a new managed agent session. */
+export function ComposeAgentSession(props: ComposeAgentSessionProps) {
+ const splitPanel = useSplitPanelOrThrow();
+ const { openWithSplit } = useSplitLayout();
+ const agentsQuery = useAgentsQuery();
+ const cursorStatus = useCursorApiKeyStatusQuery();
+ const cursorConnected = () =>
+ cursorStatus.isSuccess ? cursorStatus.data.registered : false;
+ const cursorModels = useCursorModelsQuery(cursorConnected);
+ const [prompt, setPrompt] = createSignal('');
+ const [personaId, setPersonaId] = createSignal(MACRO_PERSONA_ID);
+ const [modelOverride, setModelOverride] = createSignal('');
+ const [submitting, setSubmitting] = createSignal(false);
+ const [containerRef, setContainerRef] = createSignal<HTMLDivElement>();
+ let promptRef: HTMLTextAreaElement | undefined;
+
+ // The two first-party coders lead, then the user's own personas.
+ const personas = (): PersonaOption[] => [
+ {
+ id: MACRO_PERSONA_ID,
+ name: MACRO_AGENT_NAME,
+ handle: MACRO_AGENT_HANDLE,
+ harness: 'in-memory',
+ },
+ {
+ id: CURSOR_BOT_ID,
+ botId: CURSOR_BOT_ID,
+ name: CURSOR_BOT_NAME,
+ handle: CURSOR_BOT_HANDLE,
+ harness: 'cursor',
+ defaultModel: cursorStatus.isSuccess
+ ? (cursorStatus.data.defaultModelId ?? undefined)
+ : undefined,
+ unavailableReason: cursorConnected()
+ ? undefined
+ : 'Connect Cursor in Settings → Harness',
+ unavailableLabel: cursorConnected() ? undefined : 'Not connected',
+ },
+ ...(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,
+ avatarUrl: agent.bot.avatar_url ?? undefined,
+ harness: agent.harness,
+ defaultModel: agent.default_model,
+ })),
+ ];
+ const selectedPersona = () =>
+ personas().find((persona) => persona.id === personaId()) ?? personas()[0];
+ const availableModels = (): ModelOption[] => {
+ 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 close = () => splitPanel.handle.close();
+ const setPersona = (id: string) => {
+ setPersonaId(id);
+ setModelOverride('');
+ };
+ const createSession = () => {
+ if (submitting()) return;
+ setSubmitting(true);
+ const persona = selectedPersona();
+ const placeholder = startPendingSession({
+ botId: persona?.botId,
+ prompt: prompt().trim() || undefined,
+ modelOverride: modelOverride() || undefined,
+ });
+ close();
+ openWithSplit(
+ { type: 'agent', id: placeholder },
+ { referredFrom: 'launcher', preferNewSplit: props.preferNewSplit }
+ );
+ };
+
+ const [attachHotkeys, hotkeyScope] = useHotkeyDOMScope(
+ 'compose-agent-session',
+ true
+ );
+ onMount(() => {
+ const container = containerRef();
+ if (container) attachHotkeys(container);
+ // The dialog's focus scope lands on its first focusable child once the
+ // popover has mounted; take the prompt after that so typing can start
+ // immediately.
+ requestAnimationFrame(() => promptRef?.focus());
+ });
+ registerHotkey({
+ hotkey: 'cmd+enter',
+ scopeId: hotkeyScope,
+ description: 'Create agent session',
+ keyDownHandler: () => {
+ createSession();
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
+ return (
+ <div
+ class="portal-scope relative flex h-full max-h-full min-h-0 flex-col gap-4 p-4"
+ tabIndex={-1}
+ ref={setContainerRef}
+ data-agent-session-composer
+ >
+ <div class="flex items-center gap-1">
+ <div class="flex flex-1 items-center gap-2 px-2 text-xs font-medium text-ink-extra-muted">
+ <RobotIcon class="size-3.5" />
+ New agent session
+ </div>
+ <Show when={splitPanel.handle.isPopover()}>
+ <Button
+ onMouseDown={close}
+ tabIndex={-1}
+ tooltip="Close"
+ size="icon-sm"
+ >
+ <XIcon />
+ </Button>
+ </Show>
+ </div>
+
+ <div class="flex min-h-0 flex-1 flex-col overflow-hidden">
+ <textarea
+ ref={promptRef}
+ rows={4}
+ aria-label="Task for the agent"
+ class="ph-no-capture min-h-24 w-full grow resize-none bg-transparent px-2 text-xl/7 font-medium text-ink outline-none placeholder:text-ink-placeholder"
+ placeholder="Give your agent a prompt..."
+ value={prompt()}
+ 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();
+ }
+ }}
+ />
+ </div>
+
+ <PersonaGrid
+ personas={personas()}
+ selected={selectedPersona()}
+ loading={agentsQuery.isPending}
+ error={agentsQuery.isError}
+ onSelect={setPersona}
+ />
+
+ <div class="flex shrink-0 flex-wrap items-end justify-between gap-2">
+ <div class="m-px flex min-h-7 flex-wrap items-center gap-2 text-sm">
+ <ModelPicker
+ persona={selectedPersona()}
+ available={availableModels()}
+ shortlist={modelShortlist()}
+ value={modelOverride()}
+ loading={
+ selectedPersona()?.harness === 'cursor' && cursorModels.isPending
+ }
+ onSelect={setModelOverride}
+ />
+ </div>
+
+ <Button
+ type="button"
+ variant="accent"
+ depth={3}
+ class="gap-3 rounded-lg border-0"
+ disabled={submitting()}
+ onClick={createSession}
+ >
+ {submitting() ? 'Creating…' : 'Create Session'}
+ <Hotkey shortcut="cmd+enter" theme="current" />
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Personas as a visible radio grid rather than a menu: the user sees every
+ * choice without opening anything. Cards auto-fit the row and stretch to
+ * fill it, so the grid is even at any count. Arrow keys move the selection;
+ * Tab lands on the current choice and moves on.
+ */
+function PersonaGrid(props: {
+ personas: PersonaOption[];
+ selected: PersonaOption | undefined;
+ loading: boolean;
+ error: boolean;
+ onSelect: (id: string) => void;
+}) {
+ let groupRef: HTMLDivElement | undefined;
+ const selectable = () =>
+ props.personas.filter((persona) => !persona.unavailableReason);
+
+ const moveSelection = (event: KeyboardEvent, step: 1 | -1) => {
+ const options = selectable();
+ const index = options.findIndex(
+ (persona) => persona.id === props.selected?.id
+ );
+ const next = options[(index + step + options.length) % options.length];
+ if (!next) return;
+ event.preventDefault();
+ props.onSelect(next.id);
+ queueMicrotask(() => {
+ groupRef
+ ?.querySelector<HTMLElement>(`[data-persona-id="${next.id}"]`)
+ ?.focus();
+ });
+ };
+
+ return (
+ <section class="flex shrink-0 flex-col gap-2 px-2" aria-label="Agent">
+ <div class="flex items-center justify-between text-xxs font-medium uppercase text-ink-extra-muted">
+ <span>Agent</span>
+ <Show when={props.loading}>
+ <span class="normal-case">Loading yours…</span>
+ </Show>
+ </div>
+ <div
+ ref={groupRef}
+ role="radiogroup"
+ aria-label="Agent"
+ class="grid grid-cols-[repeat(auto-fit,minmax(9.5rem,1fr))] gap-2"
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
+ moveSelection(event, 1);
+ } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
+ moveSelection(event, -1);
+ }
+ }}
+ >
+ <For each={props.personas}>
+ {(persona) => {
+ const selected = () => persona.id === props.selected?.id;
+ const disabled = () => persona.unavailableReason !== undefined;
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected()}
+ aria-disabled={disabled()}
+ data-persona-id={persona.id}
+ tabIndex={selected() ? 0 : -1}
+ title={persona.unavailableReason}
+ class={cn(
+ 'flex h-12 min-w-0 items-center gap-2.5 rounded-lg border px-2.5 text-left outline-none transition-colors',
+ 'focus-visible:ring-2 focus-visible:ring-accent/30',
+ selected()
+ ? 'border-accent bg-accent-bg text-ink'
+ : 'border-edge-muted bg-surface-2 text-ink-muted hover:bg-hover hover:text-ink',
+ disabled() &&
+ 'cursor-not-allowed opacity-50 hover:bg-surface-2'
+ )}
+ onClick={() => {
+ if (!disabled()) props.onSelect(persona.id);
+ }}
+ >
+ <PersonaAvatar persona={persona} />
+ <span class="flex min-w-0 flex-1 flex-col leading-tight">
+ <span class="truncate text-sm font-medium">
+ {persona.name}
+ </span>
+ <span class="truncate text-xs text-ink-extra-muted">
+ @{persona.handle}
+ {' · '}
+ {disabled()
+ ? (persona.unavailableLabel ?? 'Unavailable')
+ : harnessDisplayName(persona.harness)}
+ </span>
+ </span>
+ {/* Always laid out so selecting a card never changes its width. */}
+ <CheckIcon
+ class={cn(
+ 'size-3.5 shrink-0 text-accent',
+ !selected() && 'invisible'
+ )}
+ />
+ </button>
+ );
+ }}
+ </For>
+ </div>
+ <Show when={props.error}>
+ <p class="text-xs text-negative">
+ Your saved agents could not be loaded. You can still start with{' '}
+ {MACRO_AGENT_NAME} or {CURSOR_BOT_NAME}.
+ </p>
+ </Show>
+ </section>
+ );
+}
+
+function ModelPicker(props: {
+ persona: PersonaOption | undefined;
+ available: ModelOption[];
+ shortlist: ModelShortlist;
+ value: string;
+ loading: 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"
+ tooltip={props.value ? 'Model override' : 'Model (agent default)'}
+ >
+ <CpuIcon class="size-3.5 shrink-0" />
+ <span class={cn('min-w-0 truncate', props.value && 'text-ink')}>
+ {label()}
+ </span>
+ <CaretDownIcon class="size-3 shrink-0 text-current/70" />
+ </Dropdown.Trigger>
+ <Dropdown.Content class="w-72 max-w-[min(24rem,calc(100vw-1rem))]">
+ <Dropdown.Group class={MENU_LIST_CLASS}>
+ <Dropdown.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={MENU_LIST_CLASS}>
+ <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>
+ );
+}
+
+function PersonaAvatar(props: { persona: PersonaOption }) {
+ return (
+ <Avatar size="md" class="shrink-0 bg-surface text-accent">
+ <Show
+ when={props.persona.avatarUrl}
+ fallback={
+ <Avatar.Fallback>
+ <RobotIcon class="size-4" />
+ </Avatar.Fallback>
+ }
+ >
+ {(avatarUrl) => (
+ <Avatar.Image
+ src={avatarUrl()}
+ alt={`${props.persona.name} avatar`}
+ />
+ )}
+ </Show>
+ </Avatar>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts b/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts
new file mode 100644
index 0000000000..237575d7c9
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it } from 'vitest';
+import {
+ 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('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]]);
+ });
+});
+
+describe('harnessDisplayName', () => {
+ it('names Macro runtimes after the product', () => {
+ expect(harnessDisplayName('in-memory')).toBe('Macro');
+ expect(harnessDisplayName('sandbox')).toBe('Macro');
+ });
+
+ it('names the Cursor runtime', () => {
+ expect(harnessDisplayName('cursor')).toBe('Cursor');
+ });
+
+ it('leaves registered harness names alone', () => {
+ 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);
+ });
+
+ 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('Agent default');
+ });
+
+ it('names the default model when the persona has one', () => {
+ expect(personaDefaultLabel(ENGINEER, MODELS)).toBe(
+ 'Agent default · Sonnet 5'
+ );
+ });
+
+ it('falls back to the raw id for models the catalog does not know', () => {
+ expect(
+ personaDefaultLabel({ ...ENGINEER, defaultModel: 'acme/x' }, MODELS)
+ ).toBe('Agent default · acme/x');
+ });
+});
+
+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('Sonnet 5');
+ });
+
+ it('shows a neutral label when nothing is known', () => {
+ expect(modelPillLabel('', CODER, MODELS)).toBe('Default model');
+ });
+});
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
new file mode 100644
index 0000000000..ed90fae615
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.ts
@@ -0,0 +1,146 @@
+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;
+ avatarUrl?: string;
+ harness: string;
+ defaultModel?: string;
+ /** Why this persona cannot be picked right now, when it cannot. */
+ unavailableReason?: string;
+ /** Short form of `unavailableReason` for the card subtitle. */
+ unavailableLabel?: 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'
+ );
+}
+
+/**
+ * User-facing name for the runtime a persona runs on. Harness ids are
+ * plumbing ("in-memory", "sandbox"); the product names are the coders.
+ */
+export function harnessDisplayName(harness: string): string {
+ switch (harness) {
+ case 'in-memory':
+ case 'macro-inmem':
+ case 'sandbox':
+ return 'Macro';
+ case 'cursor':
+ return 'Cursor';
+ default:
+ return harness;
+ }
+}
+
+/**
+ * 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 'Agent default';
+ const name =
+ available.find((model) => model.id === defaultModel)?.name ?? defaultModel;
+ return `Agent default · ${name}`;
+}
+
+/** Short label for the closed model pill. */
+export function modelPillLabel(
+ override: string,
+ persona: PersonaOption | undefined,
+ available: readonly ModelOption[]
+): string {
+ if (override) {
+ return available.find((model) => model.id === override)?.name ?? override;
+ }
+ const defaultModel = persona?.defaultModel;
+ if (!defaultModel) return 'Default model';
+ return (
+ available.find((model) => model.id === defaultModel)?.name ?? defaultModel
+ );
+}
diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.ts
index 4ccaa4026c..dd54912cfd 100644
--- a/apps/web/src/features/block-agent/context/pending-session.ts
+++ b/apps/web/src/features/block-agent/context/pending-session.ts
@@ -17,6 +17,7 @@
*/
import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import type { CreateAgentSessionRequest } from '@service-agent-harness/generated/schemas';
import { type Accessor, createSignal } from 'solid-js';
/**
@@ -39,24 +40,62 @@ export function isPlaceholderSessionId(id: string): boolean {
return id.startsWith(PLACEHOLDER_PREFIX);
}
+/**
+ * Options captured by the preflight composer before a session exists.
+ */
+export type StartPendingSessionOptions = {
+ /** Persisted managed persona to run; omitted for Macro Coder. */
+ botId?: string;
+ /** First prompt, delivered after any model override. */
+ prompt?: string;
+ /** Optional model switch applied before the first prompt. */
+ modelOverride?: string;
+};
+
/**
* Start creating a managed session and return the placeholder to open a block
* against right now. The POST runs unattended; nothing awaits it.
*/
-export function startPendingSession(): string {
+export function startPendingSession(
+ options: StartPendingSessionOptions = {}
+): string {
const placeholder = `${PLACEHOLDER_PREFIX}${crypto.randomUUID()}`;
const [sessionId, setSessionId] = createSignal<string>();
const [failed, setFailed] = createSignal(false);
pending.set(placeholder, { sessionId, failed });
void agentHarnessServiceClient
- .create({})
- .then((result) => {
+ .create({
+ ...(options.botId ? { botId: options.botId } : {}),
+ } satisfies CreateAgentSessionRequest)
+ .then(async (result) => {
if (result.isErr()) {
setFailed(true);
return;
}
- setSessionId(result.value.session.id);
+ const id = result.value.session.id;
+ if (options.modelOverride) {
+ const changed = await agentHarnessServiceClient.control(id, {
+ type: 'setModel',
+ model: options.modelOverride,
+ });
+ if (changed.isErr()) {
+ setFailed(true);
+ return;
+ }
+ }
+ const prompt = options.prompt?.trim();
+ if (prompt) {
+ const delivered = await agentHarnessServiceClient.control(id, {
+ type: 'prompt',
+ prompt,
+ });
+ if (delivered.isErr()) {
+ setFailed(true);
+ return;
+ }
+ }
+ setSessionId(id);
})
.catch(() => setFailed(true));
diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts
index ac01e9ceed..0eb127b3f7 100644
--- a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts
+++ b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts
@@ -11,6 +11,7 @@ import { describe, expect, it, vi } from 'vitest';
const create = vi.hoisted(() => ({
resolve: undefined as ((id: string) => void) | undefined,
reject: undefined as (() => void) | undefined,
+ control: vi.fn(),
}));
vi.mock('@service-agent-harness/client', () => ({
@@ -23,6 +24,7 @@ vi.mock('@service-agent-harness/client', () => ({
create.reject = () => resolve({ isErr: () => true });
})
),
+ control: create.control,
},
}));
@@ -75,6 +77,28 @@ describe('a placeholder', () => {
});
});
+ it('applies a model override before delivering the first prompt', async () => {
+ create.control.mockResolvedValue({ isErr: () => false });
+ const placeholder = startPendingSession({
+ botId: 'persona-1',
+ modelOverride: 'model-2',
+ prompt: 'Fix the tests',
+ });
+ await createRoot(async (dispose) => {
+ const resolved = resolveSessionId(() => placeholder);
+ create.resolve?.('session-10');
+ await flush();
+ await flush();
+
+ expect(create.control.mock.calls).toEqual([
+ ['session-10', { type: 'setModel', model: 'model-2' }],
+ ['session-10', { type: 'prompt', prompt: 'Fix the tests' }],
+ ]);
+ expect(resolved.sessionId()).toBe('session-10');
+ dispose();
+ });
+ });
+
// A placeholder URL reloaded in a new tab: the create it named belonged to
// the tab that is gone, so there is nothing to wait for.
it('with no create behind it is a failure, not a wait', () => {
diff --git a/apps/web/src/features/command/Launcher.tsx b/apps/web/src/features/command/Launcher.tsx
index c6218bab91..9c773bb437 100644
--- a/apps/web/src/features/command/Launcher.tsx
+++ b/apps/web/src/features/command/Launcher.tsx
@@ -16,6 +16,7 @@ import { CHAT_INPUT_TEXT_AREA_ID } from '@core/component/AI/component/input/Chat
import { getIconConfig } from '@core/component/EntityIcon';
import {
ENABLE_ANIMATED_ICONS,
+ enableAgentSessionComposer,
enableChatV3Agents,
enableReminders,
enableSnippets,
@@ -237,13 +238,18 @@ const createComponent = async (spec: {
componentId: string;
shouldInsert?: boolean;
asPopover?: boolean;
+ params?: Record<string, unknown>;
}) => {
const { openWithSplit, popoverSplit } = useSplitLayout();
// For popovers, create the popover BEFORE closing launcher
// so the popover can acquire the focus lock while launcher still owns rootFocusElement
if (spec.asPopover) {
- popoverSplit({ type: 'component', id: spec.componentId });
+ popoverSplit({
+ type: 'component',
+ id: spec.componentId,
+ params: spec.params,
+ });
setCreateMenuOpen(false, false);
return;
}
@@ -412,15 +418,26 @@ export function runCreateAction(
setCreateMenuOpen(false, false);
openStandaloneReminderComposer();
return;
- // Nothing to ask for: a managed session's bot, repository and workspace
- // are all deployment configuration, so this opens one straight away.
- //
- // Opened against a placeholder rather than awaited: the create does not
- // answer until its sandbox has booted and cloned the repo, and no one
- // should watch a spinner for that. The block mounts now — composer live,
- // prompts queueing — and adopts the real id when it lands
- // (`block-agent/context/pending-session.ts`).
case 'agent': {
+ if (isFeatureEnabled(enableAgentSessionComposer)) {
+ 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 },
+ });
+ return;
+ }
+ // Without the composer there is nothing to ask for: a managed session's
+ // bot, repository and workspace are all deployment configuration, so
+ // this opens one straight away.
+ //
+ // Opened against a placeholder rather than awaited: the create does not
+ // answer until its sandbox has booted and cloned the repo, and no one
+ // should watch a spinner for that. The block mounts now — composer live,
+ // prompts queueing — and adopts the real id when it lands
+ // (`block-agent/context/pending-session.ts`).
const { openWithSplit } = useSplitLayout();
setCreateMenuOpen(false, false);
// On mobile the agent input doesn't autofocus on mount, so arm focus
diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsx
index 60a01d161a..02baff5985 100644
--- a/apps/web/src/features/settings/Agents.test.tsx
+++ b/apps/web/src/features/settings/Agents.test.tsx
@@ -3,6 +3,8 @@
*/
import { Model } from '@core/component/AI/constant/model';
+import { useCursorModelsQuery } from '@queries/auth/cursor-api-key';
+import type { CursorModelsResponse } from '@service-auth/generated/schemas';
import {
fireEvent,
render,
@@ -10,17 +12,28 @@ import {
waitFor,
within,
} from '@solidjs/testing-library';
+import {
+ QueryClient,
+ QueryClientProvider,
+ useQuery,
+} from '@tanstack/solid-query';
+import { Suspense } from 'solid-js';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { Agents } from './Agents';
const cursorMocks = vi.hoisted(() => ({
status: {
+ isSuccess: true,
+ isError: false,
data: {
registered: false,
updatedAt: null as string | null,
},
},
models: {
+ isSuccess: true,
+ isPending: false,
+ isError: false,
data: {
models: [
{ id: 'cursor-small', displayName: 'Cursor Small' },
@@ -32,6 +45,8 @@ const cursorMocks = vi.hoisted(() => ({
const agentMocks = vi.hoisted(() => ({
query: {
+ isSuccess: true,
+ isPending: false,
data: [] as unknown[],
isError: false,
},
@@ -47,11 +62,13 @@ const agentMocks = vi.hoisted(() => ({
vi.mock('@queries/auth/cursor-api-key', () => ({
useCursorApiKeyStatusQuery: () => cursorMocks.status,
- useCursorModelsQuery: () => cursorMocks.models,
+ useCursorModelsQuery: vi.fn(() => cursorMocks.models),
}));
const harnessMocks = vi.hoisted(() => ({
query: {
+ isSuccess: true,
+ isPending: false,
data: [] as unknown[],
},
}));
@@ -77,7 +94,10 @@ vi.mock('@queries/agents/agents', () => ({
}));
vi.mock('@queries/team/teams', () => ({
- useCurrentTeamQuery: () => ({ data: agentMocks.currentTeam }),
+ useCurrentTeamQuery: () => ({
+ data: agentMocks.currentTeam,
+ isSuccess: true,
+ }),
useIsTeamOwner: () => () => agentMocks.isTeamOwner,
}));
@@ -201,6 +221,88 @@ const MACROD_HARNESS = {
};
describe('Agents', () => {
+ it.each(['success', 'error'] as const)(
+ 'keeps settings visible while Cursor models load and after %s',
+ async (outcome) => {
+ cursorMocks.status.data.registered = true;
+ let resolveModels!: (models: CursorModelsResponse) => void;
+ let rejectModels!: (error: Error) => void;
+ const response = new Promise<CursorModelsResponse>((resolve, reject) => {
+ resolveModels = resolve;
+ rejectModels = reject;
+ });
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ vi.mocked(useCursorModelsQuery).mockImplementationOnce(() =>
+ useQuery(() => ({
+ queryKey: ['pending-cursor-models'],
+ queryFn: () => response,
+ }))
+ );
+ const view = render(() => (
+ <QueryClientProvider client={client}>
+ <Suspense fallback={<p>Settings suspended</p>}>
+ <Agents />
+ </Suspense>
+ </QueryClientProvider>
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));
+ fireEvent.change(screen.getByRole('combobox', { name: 'Harness' }), {
+ target: { value: 'cursor' },
+ });
+ expect(screen.queryByText('Settings suspended')).toBeNull();
+ expect(screen.getByText('Loading models…')).toBeTruthy();
+ expect(
+ (
+ screen.getByRole('combobox', {
+ name: 'Default model',
+ }) as HTMLSelectElement
+ ).disabled
+ ).toBe(true);
+
+ if (outcome === 'error') {
+ rejectModels(new Error('Cursor is unavailable'));
+ await waitFor(() =>
+ expect(screen.getByText(/Could not load Cursor models/)).toBeTruthy()
+ );
+ expect(screen.queryByText('Settings suspended')).toBeNull();
+ expect(
+ (
+ screen.getByRole('combobox', {
+ name: 'Default model',
+ }) as HTMLSelectElement
+ ).disabled
+ ).toBe(true);
+ } else {
+ resolveModels({
+ models: [
+ {
+ id: 'loaded-model',
+ displayName: 'Loaded Model',
+ group: 'Cursor',
+ },
+ ],
+ });
+ await waitFor(() =>
+ expect(
+ screen.getByRole('option', { name: 'Loaded Model' })
+ ).toBeTruthy()
+ );
+ expect(screen.queryByText('Settings suspended')).toBeNull();
+ expect(
+ (
+ screen.getByRole('combobox', {
+ name: 'Default model',
+ }) as HTMLSelectElement
+ ).disabled
+ ).toBe(false);
+ }
+ view.unmount();
+ client.clear();
+ }
+ );
+
it('lists the built-in global Macro agent as a team agent', () => {
render(() => <Agents />);
diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsx
index ac46a9608d..5e6e0f3190 100644
--- a/apps/web/src/features/settings/Agents.tsx
+++ b/apps/web/src/features/settings/Agents.tsx
@@ -64,6 +64,8 @@ type ConnectedHarness = {
id: string;
name: string;
models: readonly HarnessModel[];
+ modelsLoading?: boolean;
+ modelsError?: boolean;
kind: 'builtin' | 'macrod';
connected?: boolean;
};
@@ -111,7 +113,8 @@ export function Agents() {
const currentTeamQuery = useCurrentTeamQuery();
const isTeamOwner = useIsTeamOwner();
const cursorStatus = useCursorApiKeyStatusQuery();
- const cursorConnected = () => cursorStatus.data?.registered ?? false;
+ const cursorConnected = () =>
+ cursorStatus.isSuccess ? cursorStatus.data.registered : false;
const cursorModels = useCursorModelsQuery(cursorConnected);
const harnessesQuery = useHarnessesQuery();
const connectedHarnesses = (): readonly ConnectedHarness[] => [
@@ -121,16 +124,21 @@ export function Agents() {
{
id: 'cursor',
name: 'Cursor',
- models: (cursorModels.data?.models ?? []).map((model) => ({
+ models: (cursorModels.isSuccess
+ ? cursorModels.data.models
+ : []
+ ).map((model) => ({
id: model.id,
name: model.displayName,
group: model.group,
})),
+ modelsLoading: cursorModels.isPending,
+ modelsError: cursorModels.isError,
kind: 'builtin' as const,
},
]
: []),
- ...(harnessesQuery.data ?? []).map((harness) => ({
+ ...(harnessesQuery.isSuccess ? harnessesQuery.data : []).map((harness) => ({
id: harness.id,
name:
harness.owner.type === 'team' ? `${harness.name} · Team` : harness.name,
@@ -142,7 +150,8 @@ export function Agents() {
const channelOptions = createMemo(() =>
botAssignableChannelOptions(channelsContext.channels())
);
- const currentTeamId = () => currentTeamQuery.data?.team.id;
+ const currentTeamId = () =>
+ currentTeamQuery.isSuccess ? currentTeamQuery.data?.team.id : undefined;
const canShareWithTeam = () => currentTeamId() !== undefined;
const isAgentCreator = (agent: AgentWithHarnessId) =>
agent.bot.created_by === currentUserId();
@@ -151,7 +160,7 @@ export function Agents() {
const canDeleteAgent = (agent: AgentWithHarnessId) =>
canDeleteBot(agent.bot, currentUserId(), currentTeamId(), isTeamOwner());
const agents = createMemo(() =>
- (agentsQuery.data ?? []).map((agent) =>
+ (agentsQuery.isSuccess ? agentsQuery.data : []).map((agent) =>
summarizeAgent(agent, connectedHarnesses(), channelOptions())
)
);
@@ -256,7 +265,11 @@ export function Agents() {
when={privateAgents().length > 0}
fallback={
<p class="px-6 py-4 text-sm text-ink-muted">
- No private agents yet.
+ {agentsQuery.isPending
+ ? 'Loading agents…'
+ : agentsQuery.isError
+ ? 'Your agents are unavailable.'
+ : 'No private agents yet.'}
</p>
}
>
@@ -812,6 +825,11 @@ function AgentDialog(props: {
<select
class="settings-input w-full"
value={selectedDefaultModelId()}
+ aria-label="Default model"
+ disabled={
+ selectedHarness()?.modelsLoading ||
+ selectedHarness()?.modelsError
+ }
onChange={(event) =>
setDefaultModelId(event.currentTarget.value)
}
@@ -857,6 +875,14 @@ function AgentDialog(props: {
}
/>
</Show>
+ <Show when={selectedHarness()?.modelsLoading}>
+ <span class="text-xs text-ink-muted">Loading models…</span>
+ </Show>
+ <Show when={selectedHarness()?.modelsError}>
+ <span class="text-xs text-negative">
+ Could not load Cursor models. Try refreshing this page.
+ </span>
+ </Show>
</label>
</div>
</AgentFormSection>
diff --git a/apps/web/src/features/settings/Harness.test.tsx b/apps/web/src/features/settings/Harness.test.tsx
index 774a01b290..a7212985ad 100644
--- a/apps/web/src/features/settings/Harness.test.tsx
+++ b/apps/web/src/features/settings/Harness.test.tsx
@@ -2,6 +2,8 @@
* @vitest-environment jsdom
*/
+import { useCursorModelsQuery } from '@queries/auth/cursor-api-key';
+import type { CursorModelsResponse } from '@service-auth/generated/schemas';
import {
fireEvent,
render,
@@ -9,11 +11,19 @@ import {
waitFor,
within,
} from '@solidjs/testing-library';
+import {
+ QueryClient,
+ QueryClientProvider,
+ useQuery,
+} from '@tanstack/solid-query';
+import { Suspense } from 'solid-js';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { Harness } from './Harness';
const mocks = vi.hoisted(() => ({
status: {
+ isSuccess: true,
+ isError: false,
data: {
registered: false,
defaultModelId: null as string | null,
@@ -22,6 +32,9 @@ const mocks = vi.hoisted(() => ({
isPlaceholderData: false,
},
models: {
+ isSuccess: true,
+ isPending: false,
+ isError: false,
data: {
models: [{ id: 'default-model', displayName: 'Default Model' }],
},
@@ -35,6 +48,8 @@ const mocks = vi.hoisted(() => ({
const harnessMocks = vi.hoisted(() => ({
query: {
+ isSuccess: true,
+ isPending: false,
data: [] as unknown[],
isError: false,
},
@@ -65,7 +80,7 @@ vi.mock('@queries/auth/cursor-api-key', () => ({
mutateAsync: mocks.disconnect,
isPending: false,
}),
- useCursorModelsQuery: () => mocks.models,
+ useCursorModelsQuery: vi.fn(() => mocks.models),
useSetCursorDefaultModel: () => ({
mutateAsync: mocks.setDefaultModel,
isPending: false,
@@ -151,6 +166,84 @@ beforeEach(() => {
});
describe('Harness', () => {
+ it.each(['success', 'error'] as const)(
+ 'keeps settings visible while Cursor models load and after %s',
+ async (outcome) => {
+ mocks.status.data.registered = true;
+ let resolveModels!: (models: CursorModelsResponse) => void;
+ let rejectModels!: (error: Error) => void;
+ const response = new Promise<CursorModelsResponse>((resolve, reject) => {
+ resolveModels = resolve;
+ rejectModels = reject;
+ });
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ vi.mocked(useCursorModelsQuery).mockImplementationOnce(() =>
+ useQuery(() => ({
+ queryKey: ['pending-cursor-models'],
+ queryFn: () => response,
+ }))
+ );
+ const view = render(() => (
+ <QueryClientProvider client={client}>
+ <Suspense fallback={<p>Settings suspended</p>}>
+ <Harness />
+ </Suspense>
+ </QueryClientProvider>
+ ));
+ expect(screen.queryByText('Settings suspended')).toBeNull();
+ expect(screen.getByText('Loading models…')).toBeTruthy();
+ expect(
+ (
+ screen.getByRole('combobox', {
+ name: 'Default model',
+ }) as HTMLSelectElement
+ ).disabled
+ ).toBe(true);
+
+ if (outcome === 'error') {
+ rejectModels(new Error('Cursor is unavailable'));
+ await waitFor(() =>
+ expect(screen.getByText(/Could not load Cursor models/)).toBeTruthy()
+ );
+ expect(screen.queryByText('Settings suspended')).toBeNull();
+ expect(
+ (
+ screen.getByRole('combobox', {
+ name: 'Default model',
+ }) as HTMLSelectElement
+ ).disabled
+ ).toBe(true);
+ } else {
+ resolveModels({
+ models: [
+ {
+ id: 'loaded-model',
+ displayName: 'Loaded Model',
+ group: 'Cursor',
+ },
+ ],
+ });
+ await waitFor(() =>
+ expect(
+ screen.getByRole('option', { name: 'Loaded Model' })
+ ).toBeTruthy()
+ );
+ expect(screen.queryByText('Settings suspended')).toBeNull();
+ expect(
+ (
+ screen.getByRole('combobox', {
+ name: 'Default model',
+ }) as HTMLSelectElement
+ ).disabled
+ ).toBe(false);
+ }
+ view.unmount();
+ client.clear();
+ }
+ );
+
it('shows the three configurable harness options', () => {
render(() => <Harness />);
diff --git a/apps/web/src/features/settings/Harness.tsx b/apps/web/src/features/settings/Harness.tsx
index 6439cd200e..b1274c4347 100644
--- a/apps/web/src/features/settings/Harness.tsx
+++ b/apps/web/src/features/settings/Harness.tsx
@@ -44,7 +44,8 @@ export function Harness() {
const cursorStatus = useCursorApiKeyStatusQuery();
const saveCursorApiKey = useSaveCursorApiKey();
const disconnectCursor = useDisconnectCursorApiKey();
- const cursorRegistered = () => cursorStatus.data?.registered ?? false;
+ const cursorRegistered = () =>
+ cursorStatus.isSuccess ? cursorStatus.data.registered : false;
const harnessesQuery = useHarnessesQuery();
const deleteHarnessMutation = useDeleteHarnessMutation();
const [pairingDialog, setPairingDialog] = createSignal<{
@@ -79,13 +80,15 @@ export function Harness() {
const cursorModels = useCursorModelsQuery(cursorRegistered);
const setCursorDefaultModel = useSetCursorDefaultModel();
const cursorModelOptions = () =>
- (cursorModels.data?.models ?? []).map((model) => ({
+ (cursorModels.isSuccess ? cursorModels.data.models : []).map((model) => ({
id: model.id,
label: model.displayName,
group: model.group,
}));
const selectedCursorModelId = () =>
- cursorStatus.data?.defaultModelId ?? cursorModelOptions()[0]?.id ?? null;
+ (cursorStatus.isSuccess ? cursorStatus.data.defaultModelId : null) ??
+ cursorModelOptions()[0]?.id ??
+ null;
const handleCursorModelChange = async (modelId: string) => {
try {
@@ -167,8 +170,14 @@ export function Harness() {
</p>
<Show
- when={!cursorStatus.isPlaceholderData}
- fallback={<p class="mt-4 text-xs text-ink-muted">Loading…</p>}
+ when={cursorStatus.isSuccess && !cursorStatus.isPlaceholderData}
+ fallback={
+ <p class="mt-4 text-xs text-ink-muted">
+ {cursorStatus.isError
+ ? 'Could not load your Cursor connection. Try refreshing this page.'
+ : 'Loading…'}
+ </p>
+ }
>
<Show
when={cursorRegistered()}
@@ -229,19 +238,20 @@ export function Harness() {
<select
id="cursor-default-model"
class="settings-input w-56"
- value={cursorStatus.data?.defaultModelId ?? ''}
- disabled={setCursorDefaultModel.isPending}
+ value={selectedCursorModelId() ?? ''}
+ disabled={
+ setCursorDefaultModel.isPending ||
+ !cursorModels.isSuccess
+ }
onChange={(event) =>
void handleCursorModelChange(
event.currentTarget.value
)
}
>
- <For each={cursorModels.data?.models ?? []}>
+ <For each={cursorModelOptions()}>
{(model) => (
- <option value={model.id}>
- {model.displayName}
- </option>
+ <option value={model.id}>{model.label}</option>
)}
</For>
</select>
@@ -251,11 +261,22 @@ export function Harness() {
value={selectedCursorModelId()}
options={cursorModelOptions()}
onSelect={(id) => void handleCursorModelChange(id)}
- disabled={setCursorDefaultModel.isPending}
+ disabled={
+ setCursorDefaultModel.isPending ||
+ !cursorModels.isSuccess
+ }
ariaLabel="Default model"
triggerClass="w-72 max-w-full justify-between"
/>
</Show>
+ <Show when={cursorModels.isPending}>
+ <p class="text-xs text-ink-muted">Loading models…</p>
+ </Show>
+ <Show when={cursorModels.isError}>
+ <p class="text-xs text-negative">
+ Could not load Cursor models. Try refreshing this page.
+ </p>
+ </Show>
<p class="text-xs text-ink-extra-muted">
The model new `@cursor` sessions start on. Recommended
models stay up top; everything else is behind More models.
@@ -322,10 +343,16 @@ export function Harness() {
Connected agents
</div>
<For
- each={harnessesQuery.data ?? []}
+ each={harnessesQuery.isSuccess ? harnessesQuery.data : []}
fallback={
<div class="flex flex-col items-center py-6 text-center">
- <p class="text-sm text-ink">No agents connected</p>
+ <p class="text-sm text-ink">
+ {harnessesQuery.isPending
+ ? 'Loading connected agents…'
+ : harnessesQuery.isError
+ ? 'Could not load connected agents.'
+ : 'No agents connected'}
+ </p>
<p class="mt-1 text-xs text-ink-extra-muted">
Agents connected through macrod will appear here.
</p>
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index a0dc422f19..03693e0621 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -665,6 +665,16 @@ export const enableChatV3Agents = defineFlag({
default: onInDev,
});
+// The agent session composer behind `Create → Agent`: pick an agent and a
+// model override before the session opens. Off, the entry opens a managed
+// session straight away as it always has. Override with
+// VITE_ENABLE_AGENT_SESSION_COMPOSER.
+export const enableAgentSessionComposer = defineFlag({
+ key: 'enable-agent-session-composer',
+ env: 'ENABLE_AGENT_SESSION_COMPOSER',
+ default: onInDev,
+});
+
// The `@cursor` mention entry: agent sessions served by Cursor cloud agents
// on Macro's Cursor account. PostHog-gated per user; the backend additionally
// restricts these sessions to @macro.com senders. Override with
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
index dac6f5c896..f8a063f1f3 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
@@ -18,19 +18,20 @@ import type { CreateAgentSessionRequestWorkspace } from './createAgentSessionReq
Carries two shapes, told apart by `workspace`. Naming one asks for an
external session: the runtime is the bot operator's, so the caller has to
say which bot and which directory, and must own that bot. Omitting it asks
-for a managed session, whose sandbox this deployment provisions from its
-own configuration - which is why the fields describing someone else's
-runtime must be omitted along with it rather than quietly ignored. Mixing
-the two is refused rather than guessed at, so that no request can reach the
-managed path carrying a bot the caller was never entitled to name.
+for a managed session, whose runtime this deployment provisions. A managed
+request may select an authorized persisted persona with `botId`; omitting
+it uses the deployment's default coding persona. Fields describing someone
+else's runtime must still be omitted rather than quietly ignored. Mixing
+the two shapes is refused rather than guessed at.
Clients serialize this, so both derives are used.
*/
export interface CreateAgentSessionRequest {
- /** Bot the session runs for. Bot callers may omit it (their own identity
-is used) and must not name another bot; user callers must supply a
-bot they own. External sessions only: a managed session runs as the
-bot its deployment is configured for. */
+ /** Bot the session runs for. On a managed request this optionally selects
+a persisted persona the user owns or may use through team membership;
+omitting it uses the deployment's default coding persona. On an
+external request, bot callers may omit it (their own identity is used)
+and must not name another bot; user callers must supply a bot they own. */
botId?: CreateAgentSessionRequestBotId;
/** Instructions the session's runtime works under, for its whole life.
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts
index ccb9aa474e..1456e0d568 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts
@@ -6,9 +6,10 @@
*/
/**
- * Bot the session runs for. Bot callers may omit it (their own identity
-is used) and must not name another bot; user callers must supply a
-bot they own. External sessions only: a managed session runs as the
-bot its deployment is configured for.
+ * Bot the session runs for. On a managed request this optionally selects
+a persisted persona the user owns or may use through team membership;
+omitting it uses the deployment's default coding persona. On an
+external request, bot callers may omit it (their own identity is used)
+and must not name another bot; user callers must supply a bot they own.
*/
export type CreateAgentSessionRequestBotId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 46518c953e..5609adc0c9 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -1100,12 +1100,12 @@
},
"CreateAgentSessionRequest": {
"type": "object",
- "description": "Request body for `POST /agent-sessions`.\n\nCarries two shapes, told apart by `workspace`. Naming one asks for an\nexternal session: the runtime is the bot operator's, so the caller has to\nsay which bot and which directory, and must own that bot. Omitting it asks\nfor a managed session, whose sandbox this deployment provisions from its\nown configuration - which is why the fields describing someone else's\nruntime must be omitted along with it rather than quietly ignored. Mixing\nthe two is refused rather than guessed at, so that no request can reach the\nmanaged path carrying a bot the caller was never entitled to name.\n\nClients serialize this, so both derives are used.",
+ "description": "Request body for `POST /agent-sessions`.\n\nCarries two shapes, told apart by `workspace`. Naming one asks for an\nexternal session: the runtime is the bot operator's, so the caller has to\nsay which bot and which directory, and must own that bot. Omitting it asks\nfor a managed session, whose runtime this deployment provisions. A managed\nrequest may select an authorized persisted persona with `botId`; omitting\nit uses the deployment's default coding persona. Fields describing someone\nelse's runtime must still be omitted rather than quietly ignored. Mixing\nthe two shapes is refused rather than guessed at.\n\nClients serialize this, so both derives are used.",
"properties": {
"botId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "Bot the session runs for. Bot callers may omit it (their own identity\nis used) and must not name another bot; user callers must supply a\nbot they own. External sessions only: a managed session runs as the\nbot its deployment is configured for."
+ "description": "Bot the session runs for. On a managed request this optionally selects\na persisted persona the user owns or may use through team membership;\nomitting it uses the deployment's default coding persona. On an\nexternal request, bot callers may omit it (their own identity is used)\nand must not name another bot; user callers must supply a bot they own."
},
"instructions": {
"type": ["string", "null"],
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index 4e6214276b..dc662e12fc 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -2,6 +2,8 @@
//! external runtime that dials in. Each creates the row, provisions egress
//! where there is a sandbox to give it to, and attaches the runtime.
+use agent_session::domain::ports::SelectedManagedPersona;
+
use super::*;
/// External sessions create the row and announce - the magic-chip message
@@ -84,8 +86,9 @@ where
Ok(session)
}
- /// Provision the managed-default bot's runtime, open a session on it,
- /// and deliver the first prompt if one came with the request.
+ /// Provision the selected managed persona's runtime, open a session on it,
+ /// and deliver the first prompt if one came with the request. An omitted
+ /// profile uses the deployment's default coding persona.
///
/// Nothing is announced: a managed session opened this way has no
/// originating mention and no thread to answer back into. The runtime is
@@ -95,7 +98,42 @@ where
&self,
request: agent_session::domain::ports::OpenManagedSession,
) -> agent_session::domain::error::Result<AgentSession> {
- let defaults = self.inner.defaults.managed();
+ let managed_defaults = self.inner.defaults.managed();
+ let (bot_id, model, harness, instructions, mcp_servers) = match request.profile {
+ Some(SelectedManagedPersona {
+ bot_id,
+ profile: Some(profile),
+ }) => (
+ bot_id,
+ profile.model,
+ profile.harness,
+ Some(profile.instructions).filter(|value| !value.trim().is_empty()),
+ profile.mcp_servers,
+ ),
+ // A fixed system bot picked by name runs on the deployment's
+ // defaults for it, the same way a channel mention would open it.
+ Some(SelectedManagedPersona {
+ bot_id,
+ profile: None,
+ }) => {
+ let defaults = self.inner.defaults.for_bot(bot_id);
+ (
+ bot_id,
+ defaults.model.clone(),
+ defaults.harness.clone(),
+ request.instructions,
+ AgentMcpServers::OwnerConnections,
+ )
+ }
+ None => (
+ managed_defaults.bot_id,
+ managed_defaults.model.clone(),
+ managed_defaults.harness.clone(),
+ request.instructions,
+ AgentMcpServers::OwnerConnections,
+ ),
+ };
+ let defaults = self.inner.defaults.for_bot(bot_id);
let sandbox_size = self
.inner
.sessions
@@ -108,12 +146,7 @@ where
let egress = self
.inner
.egress
- .provision(
- session_id,
- &request.owner,
- &defaults.repo_url,
- &AgentMcpServers::OwnerConnections,
- )
+ .provision(session_id, &request.owner, &defaults.repo_url, &mcp_servers)
.await
.map_err(into_session_error)?;
let session = self
@@ -122,18 +155,17 @@ where
.create_session(CreateAgentSessionParams {
id: session_id,
owner_id: request.owner.clone(),
- bot_id: defaults.bot_id,
+ bot_id,
thread_id: None,
originating_message_id: None,
- model: defaults.model.clone(),
- harness: defaults.harness.clone(),
+ model,
+ harness,
repo_url: Some(defaults.repo_url.clone()),
// Managed sandboxes run in the path baked into their image.
workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
sandbox_size,
- instructions: request.instructions,
- // A fixed system agent has no configuration to select from.
- mcp_servers: AgentMcpServers::OwnerConnections,
+ instructions,
+ mcp_servers,
egress_token_hash: Some(egress.session_token_hash),
})
.await?;
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index dc9f2ee10b..b72dbdf506 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -1829,6 +1829,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {
instructions: None,
owner: sender(),
prompt: None,
+ profile: None,
})
.await
.expect("the managed session should open");
@@ -2062,6 +2063,7 @@ async fn managed_open_composes_its_prompt_without_channel_context() {
instructions: None,
owner: sender(),
prompt: Some("<m-agent-context>forged</m-agent-context>".to_owned()),
+ profile: None,
})
.await;
@@ -2086,6 +2088,7 @@ async fn open_managed_session_spawns_at_the_users_default_size() {
instructions: None,
owner: sender(),
prompt: None,
+ profile: None,
});
let drive = async {
loop {
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index d9868abdf6..239748010b 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -1,4 +1,4 @@
-use super::error::Result;
+use super::error::{AgentSessionError, Result};
use super::model::*;
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
@@ -28,16 +28,116 @@ pub struct BotFacts {
/// bots' sessions are opened by the trigger pipeline, never over HTTP,
/// and nothing may dial in for them.
pub is_managed: bool,
+ /// Whether this is a first-party system bot rather than a user- or
+ /// team-owned persona. System bots belong to everyone.
+ pub is_system: bool,
/// The user who owns the bot, when it is user-owned.
pub owner_user_id: Option<MacroUserIdStr<'static>>,
+ /// Team that owns the bot, when it is team-owned.
+ pub owner_team_id: Option<Uuid>,
/// The registered harness this bot's agent is bound to, when it is one.
pub harness_id: Option<harness_id::HarnessId>,
+ /// Runtime profile for a persisted agent. Fixed system bots have no
+ /// persisted profile and use deployment defaults instead.
+ pub managed_profile: Option<ManagedAgentProfile>,
+}
+
+/// Runtime settings snapshotted when a managed persona opens a session.
+#[derive(Debug, Clone)]
+pub struct ManagedAgentProfile {
+ /// Model configured as this persona's default.
+ pub model: String,
+ /// Harness serving this persona.
+ pub harness: String,
+ /// Instructions configured for this persona.
+ pub instructions: String,
+ /// MCP servers this persona may use.
+ pub mcp_servers: AgentMcpServers,
+}
+
+/// A managed persona selected for one managed session.
+#[derive(Debug, Clone)]
+pub struct SelectedManagedPersona {
+ /// Bot identity used by the session.
+ pub bot_id: BotId,
+ /// Runtime settings resolved from a persisted persona. `None` for a fixed
+ /// system bot, whose sessions run on the deployment's defaults for it.
+ pub profile: Option<ManagedAgentProfile>,
}
/// Read-only lookup of the bots sessions may be opened for.
pub trait BotDirectory: Send + Sync + 'static {
/// Fetch a bot's facts; `None` when no such bot exists.
fn bot_facts(&self, bot: BotId) -> impl Future<Output = Result<Option<BotFacts>>> + Send;
+
+ /// Whether a user belongs to a team that owns a persona.
+ fn user_has_team(
+ &self,
+ user: MacroUserIdStr<'static>,
+ team_id: Uuid,
+ ) -> impl Future<Output = Result<bool>> + Send;
+}
+
+/// Why a user cannot select a bot as a managed session persona.
+#[derive(Debug)]
+pub enum ManagedPersonaError {
+ /// No active bot has this id.
+ Unknown,
+ /// The bot has no agent runtime.
+ NotAgent,
+ /// The bot is served by an external runtime.
+ External,
+ /// The user does not own or belong to the persona's owner.
+ Forbidden,
+ /// Looking up the persona or its owner failed.
+ Lookup(AgentSessionError),
+}
+
+/// Resolve and authorize a managed persona for a user.
+///
+/// Ownership policy lives in the domain: private personas belong to their
+/// owner, team personas are available to team members, and managed system
+/// bots (the deployment's own coders) are available to everyone, exactly as
+/// they are when mentioned in a channel.
+pub async fn managed_persona_for_user<Bots: BotDirectory>(
+ bots: &Bots,
+ bot_id: BotId,
+ user: &MacroUserIdStr<'static>,
+) -> std::result::Result<SelectedManagedPersona, ManagedPersonaError> {
+ let facts = bots
+ .bot_facts(bot_id)
+ .await
+ .map_err(ManagedPersonaError::Lookup)?
+ .ok_or(ManagedPersonaError::Unknown)?;
+ if !facts.has_agent {
+ return Err(ManagedPersonaError::NotAgent);
+ }
+ if !facts.is_managed {
+ return Err(ManagedPersonaError::External);
+ }
+ if facts.is_system {
+ return Ok(SelectedManagedPersona {
+ bot_id,
+ profile: None,
+ });
+ }
+ let authorized = if let Some(owner) = facts.owner_user_id {
+ owner.as_ref() == user.as_ref()
+ } else if let Some(team_id) = facts.owner_team_id {
+ bots.user_has_team(user.clone(), team_id)
+ .await
+ .map_err(ManagedPersonaError::Lookup)?
+ } else {
+ false
+ };
+ if !authorized {
+ return Err(ManagedPersonaError::Forbidden);
+ }
+ let profile = facts.managed_profile.ok_or(ManagedPersonaError::NotAgent)?;
+ Ok(SelectedManagedPersona {
+ bot_id,
+ profile: Some(profile),
+ })
}
/// The mention that triggered a session, when one did.
@@ -92,8 +192,11 @@ pub struct OpenManagedSession {
/// First prompt to deliver once the sandbox is attached. `None` opens an
/// idle session its owner prompts from the session's own surface.
pub prompt: Option<String>,
- /// Instructions the session's runtime works under, for its whole life.
- /// `None` runs the runtime's own default.
+ /// A selected persona's authoritative runtime profile. `None` uses the
+ /// deployment's default managed coding persona.
+ pub profile: Option<SelectedManagedPersona>,
+ /// Ad-hoc instructions for the default managed persona. Ignored when a
+ /// persisted persona profile is selected.
pub instructions: Option<String>,
}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 9592e0f604..2d4d36968c 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -50,7 +50,8 @@ use crate::domain::model::{
};
use crate::domain::ports::{
AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlDisposition, ControlEvent,
- OpenExternalAgentSession, OpenManagedSession, SessionOpener, SessionThread,
+ ManagedPersonaError, OpenExternalAgentSession, OpenManagedSession, SessionOpener,
+ SessionThread, managed_persona_for_user,
};
use crate::domain::service::AgentSessionService;
use bots::domain::models::BotId;
@@ -1180,20 +1181,21 @@ where
/// Carries two shapes, told apart by `workspace`. Naming one asks for an
/// external session: the runtime is the bot operator's, so the caller has to
/// say which bot and which directory, and must own that bot. Omitting it asks
-/// for a managed session, whose sandbox this deployment provisions from its
-/// own configuration - which is why the fields describing someone else's
-/// runtime must be omitted along with it rather than quietly ignored. Mixing
-/// the two is refused rather than guessed at, so that no request can reach the
-/// managed path carrying a bot the caller was never entitled to name.
+/// for a managed session, whose runtime this deployment provisions. A managed
+/// request may select an authorized persisted persona with `botId`; omitting
+/// it uses the deployment's default coding persona. Fields describing someone
+/// else's runtime must still be omitted rather than quietly ignored. Mixing
+/// the two shapes is refused rather than guessed at.
///
/// Clients serialize this, so both derives are used.
#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateAgentSessionRequest {
- /// Bot the session runs for. Bot callers may omit it (their own identity
- /// is used) and must not name another bot; user callers must supply a
- /// bot they own. External sessions only: a managed session runs as the
- /// bot its deployment is configured for.
+ /// Bot the session runs for. On a managed request this optionally selects
+ /// a persisted persona the user owns or may use through team membership;
+ /// omitting it uses the deployment's default coding persona. On an
+ /// external request, bot callers may omit it (their own identity is used)
+ /// and must not name another bot; user callers must supply a bot they own.
pub bot_id: Option<Uuid>,
/// Absolute directory the bot's harness runs in on its runtime. Present
/// for an external session, absent for a managed one, which runs in the
@@ -1287,6 +1289,8 @@ pub enum CreateSessionApiError {
NotAnAgentBot,
/// The bot's sessions are opened by the trigger pipeline, not this route.
ManagedBot,
+ /// The selected persona is served by an external runtime.
+ ExternalPersona,
/// The caller identified no user to own the session.
OwnerRequired,
/// The owner is not a parseable user id.
@@ -1330,6 +1334,10 @@ impl IntoResponse for CreateSessionApiError {
StatusCode::UNPROCESSABLE_ENTITY,
"this bot's sessions are opened by the trigger pipeline".to_owned(),
),
+ Self::ExternalPersona => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "this persona cannot be started from Macro".to_owned(),
+ ),
Self::OwnerRequired => (
StatusCode::UNPROCESSABLE_ENTITY,
"owner is required for bot callers".to_owned(),
@@ -1341,8 +1349,8 @@ impl IntoResponse for CreateSessionApiError {
Self::InvalidWorkspace(reason) => (StatusCode::UNPROCESSABLE_ENTITY, reason.to_owned()),
Self::MixedSessionShape => (
StatusCode::UNPROCESSABLE_ENTITY,
- "a managed session takes only a prompt; naming a workspace, bot, repo, \
- owner or thread asks for an external one"
+ "a managed session may take a prompt, persona and instructions; naming a \
+ workspace, repo, owner or thread asks for an external one"
.to_owned(),
),
Self::ThreadSessionExists { session_id } => {
@@ -1479,25 +1487,35 @@ pub async fn create_agent_session_handler<
// absence, whichever shape the request turns out to be.
let instructions = request.instructions.filter(|text| !text.trim().is_empty());
- // No workspace means the managed shape. It shares this route but not its
- // authorization: nothing about which bot runs the session is the caller's
- // to say, so the bot-ownership checks below have nothing to check and are
- // skipped. That is only sound while the request carries none of the
- // external fields, which is what this refuses.
+ // No workspace means the managed shape. A bot id selects a managed
+ // persona; the domain resolver owns its user/team authorization policy.
+ // External-only fields remain invalid on this shape.
let Some(workspace) = request.workspace else {
- if request.bot_id.is_some()
- || request.repo_url.is_some()
- || request.thread.is_some()
- || request.owner.is_some()
- {
+ if request.repo_url.is_some() || request.thread.is_some() || request.owner.is_some() {
return Err(CreateSessionApiError::MixedSessionShape);
}
let owner = resolve_owner(&caller.authorization, None)?;
+ let profile = if let Some(bot_id) = request.bot_id {
+ let selected =
+ managed_persona_for_user(state.bots.as_ref(), BotId::new_from_uuid(bot_id), &owner)
+ .await
+ .map_err(|error| match error {
+ ManagedPersonaError::Unknown => CreateSessionApiError::UnknownBot,
+ ManagedPersonaError::NotAgent => CreateSessionApiError::NotAnAgentBot,
+ ManagedPersonaError::External => CreateSessionApiError::ExternalPersona,
+ ManagedPersonaError::Forbidden => CreateSessionApiError::NotYourBot,
+ ManagedPersonaError::Lookup(error) => CreateSessionApiError::Domain(error),
+ })?;
+ Some(selected)
+ } else {
+ None
+ };
let session = state
.opener
.open_managed_session(OpenManagedSession {
owner,
prompt: request.prompt,
+ profile,
instructions,
})
.await?;
@@ -1521,6 +1539,7 @@ pub async fn create_agent_session_handler<
is_managed,
owner_user_id,
harness_id,
+ ..
} = state
.bots
.bot_facts(bot_id)
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 065de6837c..c061dbca3a 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -135,6 +135,10 @@ impl SessionOpener for RecordingOpener {
&self,
request: OpenManagedSession,
) -> crate::domain::error::Result<AgentSession> {
+ let bot_id = request
+ .profile
+ .as_ref()
+ .map_or(BotId::TEST_B, |selected| selected.bot_id);
let session = AgentSession {
id: AgentSessionId::TEST_A,
name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),
@@ -142,7 +146,7 @@ impl SessionOpener for RecordingOpener {
thread_id: None,
thread_channel_id: None,
originating_message_id: None,
- bot_id: BotId::TEST_A,
+ bot_id,
model: "claude".to_owned(),
harness: "opencode".to_owned(),
repo_url: Some("https://github.com/macro-inc/macro".to_owned()),
@@ -181,8 +185,11 @@ impl OneBotDirectory {
facts: BotFacts {
has_agent: true,
is_managed: false,
+ is_system: false,
owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
+ owner_team_id: None,
harness_id: Some(harness_id::HarnessId::TEST_A),
+ managed_profile: None,
},
}
}
@@ -192,8 +199,16 @@ impl OneBotDirectory {
facts: BotFacts {
has_agent: true,
is_managed: true,
- owner_user_id: None,
+ is_system: false,
+ owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
+ owner_team_id: None,
harness_id: None,
+ managed_profile: Some(crate::domain::ports::ManagedAgentProfile {
+ model: "persona-model".to_owned(),
+ harness: "in-memory".to_owned(),
+ instructions: "persona instructions".to_owned(),
+ mcp_servers: Default::default(),
+ }),
},
}
}
@@ -203,8 +218,27 @@ impl OneBotDirectory {
facts: BotFacts {
has_agent: false,
is_managed: false,
+ is_system: false,
owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
+ owner_team_id: None,
harness_id: None,
+ managed_profile: None,
+ },
+ }
+ }
+
+ /// A fixed first-party coder such as the Cursor bot: managed, owned by
+ /// nobody, and with no persisted profile of its own.
+ fn system_coder() -> Self {
+ Self {
+ facts: BotFacts {
+ has_agent: true,
+ is_managed: true,
+ is_system: true,
+ owner_user_id: None,
+ owner_team_id: None,
+ harness_id: None,
+ managed_profile: None,
},
}
}
@@ -214,6 +248,14 @@ impl BotDirectory for OneBotDirectory {
async fn bot_facts(&self, bot: BotId) -> crate::domain::error::Result<Option<BotFacts>> {
Ok((bot == BotId::TEST_A).then(|| self.facts.clone()))
}
+
+ async fn user_has_team(
+ &self,
+ _user: MacroUserIdStr<'static>,
+ _team_id: Uuid,
+ ) -> crate::domain::error::Result<bool> {
+ Ok(false)
+ }
}
fn router_for(opener: Arc<RecordingOpener>, bots: OneBotDirectory) -> Router {
@@ -578,6 +620,72 @@ async fn a_managed_open_carries_its_instructions() {
);
}
+#[tokio::test]
+async fn an_owner_can_select_a_managed_persona() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ OWNER,
+ serde_json::json!({
+ "botId": BotId::TEST_A.as_uuid(),
+ "prompt": "fix it"
+ })
+ .to_string(),
+ );
+
+ let response = router_for(opener.clone(), OneBotDirectory::managed_agent())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ let managed = opener.managed.lock().unwrap();
+ let selected = managed[0].profile.as_ref().expect("selected persona");
+ assert_eq!(selected.bot_id, BotId::TEST_A);
+ let profile = selected.profile.as_ref().expect("persisted profile");
+ assert_eq!(profile.model, "persona-model");
+ assert_eq!(profile.instructions, "persona instructions");
+}
+
+/// The deployment's own coders are everybody's: a user who could mention the
+/// Cursor bot in a channel can pick it here too. Having no persisted profile,
+/// it is passed through for the harness to stamp with its per-bot defaults.
+#[tokio::test]
+async fn anyone_can_select_a_managed_system_bot() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ STRANGER,
+ serde_json::json!({ "botId": BotId::TEST_A.as_uuid(), "prompt": "fix it" }).to_string(),
+ );
+
+ let response = router_for(opener.clone(), OneBotDirectory::system_coder())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ let managed = opener.managed.lock().unwrap();
+ let selected = managed[0].profile.as_ref().expect("selected persona");
+ assert_eq!(selected.bot_id, BotId::TEST_A);
+ assert!(selected.profile.is_none());
+}
+
+#[tokio::test]
+async fn a_stranger_cannot_select_someone_elses_managed_persona() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ STRANGER,
+ serde_json::json!({ "botId": BotId::TEST_A.as_uuid() }).to_string(),
+ );
+
+ let response = router_for(opener.clone(), OneBotDirectory::managed_agent())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert!(opener.managed.lock().unwrap().is_empty());
+}
+
/// Whitespace-only instructions are absence stated clumsily, and are
/// normalized away rather than stored as a section a runtime would splice in
/// empty.
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index ad319fe6a3..47619f83c0 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -11,8 +11,30 @@
Almost every list surface (Home, Agents, Files, Tasks, Customers, Email) has a bottom
composer with placeholder **`Ask AI, @mention anything`**. Click it, `type_text` the message,
press Enter — the app creates a chat and navigates to `/app/chat/<uuid>`. Alternatively
-`Create` → `Agent A`, or keyboard `c` then `a`. That create path focuses the
-agent composer so you can type immediately.
+`Create` → `Agent A`, or keyboard `c` then `a`, opens a managed agent session
+directly at `/app/agent/<uuid>` (the runtime starts while the block mounts).
+That create path focuses the agent composer so you can type immediately.
+When the `enable-agent-session-composer` flag is on (default in dev;
+`VITE_ENABLE_AGENT_SESSION_COMPOSER` overrides), the same entry instead opens
+the **New agent session** composer popover. The prompt textarea (`Give your agent a
+prompt...`) is focused on open, so you can `type_text` immediately. Below the prompt a
+**Agent** section (`aria-label` `Agent`) lists the choices in the open, as a
+`radiogroup` of cards (`role="radio"`, `aria-checked`): **Macro** `@macro`
+(the default), **Cursor** `@cursor` (disabled with a `Connect Cursor in
+Settings → Harness` hint until a Cursor API key is stored), then the user's
+own agents, each card showing avatar, name and `@handle · Macro|Cursor` for
+the runtime (a disabled card reads `@cursor · Not connected`). Every agent is
+shown; the cards form an even grid that fills the popover width. Click a card
+or use arrow keys to change agent. The **Model
+override** pill (`aria-label` `Model override`) at the bottom left opens a
+menu whose first row is `Agent default · <model>`, followed by at most five
+featured models; longer catalogs put the rest under a `More models` submenu.
+Changing agent resets the override. Tab order is prompt → selected agent card → Model →
+**Create Session**; the close `X` is skipped. The menu opens on Enter/Space
+and selects with arrow keys + Enter. Escape in the prompt first blurs to the
+dialog, a second Escape closes it. Press **Create Session** or
+`Cmd/Ctrl+Enter`; the composer closes and the new `/app/agent/<uuid>` session
+opens while its runtime starts.
## Start a doc-scoped chat
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 79ec68006c..9e9ac63d0e 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -73,3 +73,7 @@ category, Esc closes.
- Splits: `` ` `` split, `Shift+H`/`Shift+L` move focus, `Shift+Esc` maximize.
- In any text surface: `@` mentions (bidirectional links), `#` tags, `/` block commands,
`:` emoji. Clicking a rendered tag opens a Search split filtered to that tag.
+
+Settings → Agents and Settings → Harness render while their requests are pending.
+A pending Cursor model catalog shows `Loading models…` beside a disabled model
+picker; a failed catalog shows an inline error. The rest of settings stays usable.
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 8093bc41ba..28628e5eac 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -242,20 +242,21 @@ export type ControlStatusDto = 'sent' | 'queued';
* Carries two shapes, told apart by `workspace`. Naming one asks for an
* external session: the runtime is the bot operator's, so the caller has to
* say which bot and which directory, and must own that bot. Omitting it asks
- * for a managed session, whose sandbox this deployment provisions from its
- * own configuration - which is why the fields describing someone else's
- * runtime must be omitted along with it rather than quietly ignored. Mixing
- * the two is refused rather than guessed at, so that no request can reach the
- * managed path carrying a bot the caller was never entitled to name.
+ * for a managed session, whose runtime this deployment provisions. A managed
+ * request may select an authorized persisted persona with `botId`; omitting
+ * it uses the deployment's default coding persona. Fields describing someone
+ * else's runtime must still be omitted rather than quietly ignored. Mixing
+ * the two shapes is refused rather than guessed at.
*
* Clients serialize this, so both derives are used.
*/
export type CreateAgentSessionRequest = {
/**
- * Bot the session runs for. Bot callers may omit it (their own identity
- * is used) and must not name another bot; user callers must supply a
- * bot they own. External sessions only: a managed session runs as the
- * bot its deployment is configured for.
+ * Bot the session runs for. On a managed request this optionally selects
+ * a persisted persona the user owns or may use through team membership;
+ * omitting it uses the deployment's default coding persona. On an
+ * external request, bot callers may omit it (their own identity is used)
+ * and must not name another bot; user callers must supply a bot they own.
*/
botId?: string | null;
/**
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 46518c953e..5609adc0c9 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -1100,12 +1100,12 @@
},
"CreateAgentSessionRequest": {
"type": "object",
- "description": "Request body for `POST /agent-sessions`.\n\nCarries two shapes, told apart by `workspace`. Naming one asks for an\nexternal session: the runtime is the bot operator's, so the caller has to\nsay which bot and which directory, and must own that bot. Omitting it asks\nfor a managed session, whose sandbox this deployment provisions from its\nown configuration - which is why the fields describing someone else's\nruntime must be omitted along with it rather than quietly ignored. Mixing\nthe two is refused rather than guessed at, so that no request can reach the\nmanaged path carrying a bot the caller was never entitled to name.\n\nClients serialize this, so both derives are used.",
+ "description": "Request body for `POST /agent-sessions`.\n\nCarries two shapes, told apart by `workspace`. Naming one asks for an\nexternal session: the runtime is the bot operator's, so the caller has to\nsay which bot and which directory, and must own that bot. Omitting it asks\nfor a managed session, whose runtime this deployment provisions. A managed\nrequest may select an authorized persisted persona with `botId`; omitting\nit uses the deployment's default coding persona. Fields describing someone\nelse's runtime must still be omitted rather than quietly ignored. Mixing\nthe two shapes is refused rather than guessed at.\n\nClients serialize this, so both derives are used.",
"properties": {
"botId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "Bot the session runs for. Bot callers may omit it (their own identity\nis used) and must not name another bot; user callers must supply a\nbot they own. External sessions only: a managed session runs as the\nbot its deployment is configured for."
+ "description": "Bot the session runs for. On a managed request this optionally selects\na persisted persona the user owns or may use through team membership;\nomitting it uses the deployment's default coding persona. On an\nexternal request, bot callers may omit it (their own identity is used)\nand must not name another bot; user callers must supply a bot they own."
},
"instructions": {
"type": ["string", "null"],
diff --git a/services/agent_harness_service/src/bots_directory.rs b/services/agent_harness_service/src/bots_directory.rs
index ec4c165c84..6de57b771c 100644
--- a/services/agent_harness_service/src/bots_directory.rs
+++ b/services/agent_harness_service/src/bots_directory.rs
@@ -6,9 +6,9 @@
use agent_harness::domain::model::AgentKind;
use agent_session::domain::error::{AgentSessionError, Result};
-use agent_session::domain::ports::{BotDirectory, BotFacts};
+use agent_session::domain::ports::{BotDirectory, BotFacts, ManagedAgentProfile};
use bot_id::BotId;
-use bots::domain::models::BotOwner;
+use bots::domain::models::{BotKind, BotOwner};
use bots::domain::ports::BotRepo;
use bots::outbound::pg_bots_repo::PgBotsRepo;
use macro_user_id::user_id::MacroUserIdStr;
@@ -36,17 +36,19 @@ impl BotDirectory for PgBotDirectory {
else {
return Ok(None);
};
- let owner_user_id = match row.owner {
+ let (owner_user_id, owner_team_id) = match row.owner {
Some(BotOwner::User { user_id }) => {
- Some(MacroUserIdStr::try_from(user_id).map_err(|error| {
+ let owner = MacroUserIdStr::try_from(user_id).map_err(|error| {
AgentSessionError::Unknown(anyhow::anyhow!(
"bot has an unparseable owner: {error}"
))
- })?)
+ })?;
+ (Some(owner), None)
}
- Some(BotOwner::Team { .. }) | None => None,
+ Some(BotOwner::Team { team_id }) => (None, Some(team_id)),
+ None => (None, None),
};
- let (is_managed, harness_id) = if row.has_agent {
+ let (is_managed, harness_id, managed_profile) = if row.has_agent {
let agent = self
.repo
.get_agent(bot)
@@ -54,20 +56,43 @@ impl BotDirectory for PgBotDirectory {
.map_err(AgentSessionError::Unknown)?;
let harness_id = agent.as_ref().and_then(|agent| agent.harness_id);
let is_managed = agent
+ .as_ref()
.map_or_else(
|| AgentKind::of(bot),
|agent| AgentKind::from_harness(&agent.harness),
)
.is_managed();
- (is_managed, harness_id)
+ let managed_profile = agent
+ .filter(|_| is_managed)
+ .map(|agent| ManagedAgentProfile {
+ model: agent.default_model,
+ harness: agent.harness,
+ instructions: agent.instructions,
+ mcp_servers: agent.mcp,
+ });
+ (is_managed, harness_id, managed_profile)
} else {
- (false, None)
+ (false, None, None)
};
Ok(Some(BotFacts {
has_agent: row.has_agent,
is_managed,
+ is_system: row.kind == BotKind::System,
owner_user_id,
+ owner_team_id,
harness_id,
+ managed_profile,
}))
}
+
+ async fn user_has_team(
+ &self,
+ user: MacroUserIdStr<'static>,
+ team_id: macro_uuid::Uuid,
+ ) -> Result<bool> {
+ self.repo
+ .user_has_team(user, team_id)
+ .await
+ .map_err(AgentSessionError::Unknown)
+ }
}