Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agent-sessions): create standalone sessions from the create menu (#5778)
Eric Hayes3637d3d394d7
diff --git a/apps/web/src/components/app/GlobalHotkeys.tsx b/apps/web/src/components/app/GlobalHotkeys.tsxindex 766619af36..74fb2ea42c 100644--- a/apps/web/src/components/app/GlobalHotkeys.tsx+++ b/apps/web/src/components/app/GlobalHotkeys.tsx@@ -200,6 +200,10 @@ export default function GlobalShortcuts() {(item.condition?.() ?? true) &&(item.enabled?.() ?? true) &&(item.blockName !== 'snippet' || snippetsFlag().enabled),+ // Entries that deliberately share a key (the flagged agent pair) opt+ // into 'add' so both survive registration and the dispatcher picks the+ // one whose condition passes, rather than the later silently winning.+ registrationType: item.registrationType,keyDownHandler: item.keyDownHandler,icon: Plus,tags: item.tags,diff --git a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsxindex 89a05d6cbf..30f7bc4dde 100644--- a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx+++ b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx@@ -81,6 +81,8 @@ function PopoverSplitModal(props: {isViewerSplit: () => false,isControllerSplit: () => false,replace: () => {},+ // A popover has no URL and no history to rewrite.+ adoptContentId: () => {},removeFromHistory: () => {},registerContentChangeListener: () => {},unregisterContentChangeListener: () => {},diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.tsindex e1650da5a6..3ab9fb86d9 100644--- a/apps/web/src/components/app/split-layout/layoutManager.ts+++ b/apps/web/src/components/app/split-layout/layoutManager.ts@@ -489,6 +489,22 @@ export type SplitHandle<TMeta extends ComponentMeta = ComponentMeta> = {mergeHistory?: boolean;referredFrom?: ReferredFrom;}) => void;+ /**+ * Point this split at a new id for the same block *without* remounting it.+ *+ * `replace` tears the mount down and builds a new one, which is right when+ * the user navigates somewhere else. This is the other case: the block is+ * already showing the right thing and only just learned what it is called.+ * The agent block opens on a client-minted placeholder and adopts its real+ * session id when the create resolves, with the composer the user is typing+ * into left untouched.+ *+ * Only the id moves — same block type, same mount, same history entry+ * (rewritten in place, so Back still goes where it did and the URL swaps+ * without a new entry). A no-op unless the split currently shows a block of+ * `type`.+ */+ adoptContentId: (options: { type: BlockName; nextId: string }) => void;removeFromHistory: (predicate: (content: SplitContent) => boolean) => void;toggleSpotlight: (force?: boolean) => void;setDisplayName: (name: string) => void;@@ -1006,6 +1022,60 @@ export function createSplitLayout(});}+ /**+ * Move a split onto a new id for the block it is already showing, keeping+ * the mount. See `SplitHandle.adoptContentId` for why this exists.+ *+ * The history entry is rewritten rather than pushed, and the navigation+ * cause is `replace`, so the URL sync swaps the path in place instead of+ * adding a back step to a placeholder the user can never return to.+ */+ function adoptContentId(id: SplitId, type: BlockName, nextId: string) {+ const i = splitIndexById(id);+ if (i < 0) return;++ const split = state.splits[i];+ const current = split.content;+ if (current.type !== type || current.id === nextId) return;+ if (+ isDuplicateSplit(+ state.splits.filter((s) => s.id !== id),+ {+ ...current,+ id: nextId,+ }+ )+ ) {+ return;+ }++ const next: SplitContent = { ...current, id: nextId, params: undefined };++ batch(() => {+ split.history.replaceCurrent(next);+ setState('splits', (splits) => {+ const index = splits.findIndex((s) => s.id === id);+ if (index < 0) return splits;+ const previous = splits[index];+ return splits.with(index, {+ ...previous,+ content: next,+ // The same mount, re-labelled: nothing unmounts here.+ mount:+ previous.mount.kind === 'block'+ ? { ...previous.mount, id: nextId }+ : previous.mount,+ lastNavigationCause: 'replace',+ });+ });+ orchestrator.rekeyBlockInstance(+ resolveBlockAlias(type),+ current.id,+ nextId+ );+ });+ }+function reset(id: SplitId) {const i = splitIndexById(id);if (i < 0) return console.error(`Split with id ${id} not found`);@@ -1117,6 +1187,8 @@ export function createSplitLayout(goForward: () => forward(currentSplit.id),replace: ({ next, mergeHistory = false, referredFrom }) =>replace(currentSplit.id, { next, mergeHistory, referredFrom }),+ adoptContentId: ({ type, nextId }) =>+ adoptContentId(currentSplit.id, type, nextId),removeFromHistory: (predicate: (content: SplitContent) => boolean) => {removeFromHistory(currentSplit.id, predicate);},diff --git a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts b/apps/web/src/components/app/split-layout/tests/layoutManager.test.tsindex ff8beda2e6..b55c605019 100644--- a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts+++ b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts@@ -47,6 +47,7 @@ function createMockOrchestrator(): BlockOrchestrator {detach: vi.fn(),dispose: vi.fn(),})),+ rekeyBlockInstance: vi.fn(),} as unknown as BlockOrchestrator;}@@ -454,6 +455,88 @@ describe('layoutManager', () => {});});+ describe('adoptContentId', () => {+ it('moves the split onto the new id without remounting or pushing history', () => {+ createRoot((dispose) => {+ const orchestrator = createMockOrchestrator();+ const manager = createSplitLayout(orchestrator, [+ { type: 'agent', id: 'pending-1' },+ ]);+ const split = manager.splits()[0]!;+ const handle = manager.getSplit(split.id)!;+ const mountBefore = split.mount;+ const historyLengthBefore = handle.history().length;+ const mountsBefore = (+ orchestrator.createBlockInstance as ReturnType<typeof vi.fn>+ ).mock.calls.length;++ handle.adoptContentId({ type: 'agent', nextId: 'session-1' });++ const after = manager.splits()[0]!;+ expect(after.content).toEqual({ type: 'agent', id: 'session-1' });+ // The same block instance, re-labelled: nothing was mounted again.+ expect(after.mount.kind).toBe('block');+ expect(+ after.mount.kind === 'block' ? after.mount.handle : undefined+ ).toBe(mountBefore.kind === 'block' ? mountBefore.handle : null);+ expect(+ (orchestrator.createBlockInstance as ReturnType<typeof vi.fn>).mock+ .calls.length+ ).toBe(mountsBefore);+ expect(handle.history()).toHaveLength(historyLengthBefore);+ expect(handle.history().at(-1)).toEqual({+ type: 'agent',+ id: 'session-1',+ });+ expect(orchestrator.rekeyBlockInstance).toHaveBeenCalledWith(+ 'agent',+ 'pending-1',+ 'session-1'+ );+ // `replace` is what the URL sync reads to swap the path in place+ // rather than adding a step back to a placeholder.+ expect(after.lastNavigationCause).toBe('replace');++ dispose();+ });+ });++ it('ignores a type that is not what the split is showing', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'agent', id: 'pending-1' },+ ]);+ const handle = manager.getSplit(manager.splits()[0]!.id)!;++ handle.adoptContentId({ type: 'md', nextId: 'session-1' });++ expect(manager.splits()[0]!.content).toEqual({+ type: 'agent',+ id: 'pending-1',+ });+ dispose();+ });+ });++ it('refuses an id another split already shows', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'agent', id: 'pending-1' },+ { type: 'agent', id: 'session-1' },+ ]);+ const handle = manager.getSplit(manager.splits()[0]!.id)!;++ handle.adoptContentId({ type: 'agent', nextId: 'session-1' });++ expect(manager.splits()[0]!.content).toEqual({+ type: 'agent',+ id: 'pending-1',+ });+ dispose();+ });+ });+ });+describe('replaceAllSplits', () => {it('keeps the first split that already contains the target content', () => {createRoot((dispose) => {diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsxindex b03a8f8aff..5947322143 100644--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx@@ -5,14 +5,29 @@* boundary.*/+import { Show } from 'solid-js';import { useAgentSession } from '../context/AgentSessionContext';-import { AgentInput, QueuedPromptList } from '../ui';+import {+ AgentInput,+ AgentModelSelector,+ ComposerNotice,+ QueuedPromptList,+} from '../ui';export function AgentComposer() {- const { composer, loadFailed } = useAgentSession();+ const { composer, loadFailed, metadata, pending, resuming } =+ useAgentSession();++ // A session still being created was created by this user, one action ago,+ // and has an empty transcript: the only thing to do with it is type. The+ // wait for the sandbox is exactly when that matters most.+ const autofocus = pending();return (<>+ <Show when={resuming()}>+ <ComposerNotice text="Waking the agent's sandbox…" active />+ </Show><QueuedPromptListprompts={composer.queue()}sendingId={composer.sendingId()}@@ -22,10 +37,20 @@ export function AgentComposer() {/><AgentInputplaceholder="Message the agent"+ autofocus={autofocus}busy={composer.busy()}disabled={loadFailed()}onSend={composer.send}onStop={composer.stop}+ modelControl={+ <AgentModelSelector+ model={metadata()?.model ?? null}+ changingTo={composer.changingModel()}+ options={metadata()?.supportedModels ?? []}+ disabled={loadFailed()}+ onSelect={composer.setModel}+ />+ }/></>);diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsxindex 994193439b..6274af0e3f 100644--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx@@ -11,7 +11,8 @@ import type {} from '@service-agent-fold/generated/types';import { For, type JSX, Show } from 'solid-js';import { match } from 'ts-pattern';-import { Thought } from '../ui';+import { isControlMessage } from '../state/control-message';+import { ActionLine, Thought } from '../ui';import { ControlPart } from './parts/ControlPart';import { PermissionPart } from './parts/PermissionPart';import { PlanPart } from './parts/PlanPart';@@ -55,15 +56,33 @@ function UserMessage(props: { message: FoldedMessage }) {export function Message(props: { message: FoldedMessage }) {const inFlight = () =>props.message.author.kind === 'agent' && props.message.stop == null;+ const failure = () =>+ props.message.stop?.kind === 'failed'+ ? props.message.stop.message+ : undefined;return (<Show- when={props.message.author.kind === 'user'}+ when={+ props.message.author.kind === 'user' && !isControlMessage(props.message)+ }fallback={<div class="flex flex-col gap-1 min-w-0"><For each={props.message.parts}>{(part) => <AgentMessagePart part={part} inFlight={inFlight()} />}</For>+ {/* A turn the runtime errored is something that happened to the+ session, like a model change or a stop — so it reads as one,+ at the foot of whatever the agent managed to say first. */}+ <Show when={failure()}>+ {(message) => (+ <ActionLine+ label={`The agent couldn't answer — ${message()}`}+ detail={message()}+ failed+ />+ )}+ </Show></div>}>diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsxindex c46738ab19..e5357481d6 100644--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx@@ -10,7 +10,6 @@ import {SplitHeaderRight,} from '@components/app/split-layout/components/SplitHeader';import { StaticSplitLabel } from '@components/app/split-layout/components/SplitLabel';-import { useBlockId } from '@core/block';import { toast } from '@core/component/Toast/Toast';import { isMobile } from '@core/mobile/isMobile';import { buildSimpleEntityUrl, openExternalUrl } from '@core/util/url';@@ -19,6 +18,7 @@ import LinkIcon from '@phosphor/link.svg';import TreeStructure from '@phosphor/tree-structure.svg';import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';import { For, Show } from 'solid-js';+import { useAgentSession } from '../context/AgentSessionContext';import {ORIGIN_THREAD_DRAWER_ID,sessionOriginThread,@@ -45,13 +45,18 @@ export function AgentSplitHeader(props: {/** The fold's session title, preferred over the harness fallback. */title?: string;}) {- const blockId = useBlockId();+ // The session, not `useBlockId()`: a block created from the launcher mounts+ // against a placeholder and keeps reporting it (see `Block.tsx`), so the+ // block id is the one thing here that is not a shareable session id.+ const { sessionId } = useAgentSession();const title = () => props.title ?? harnessTitle(props.session?.harness);const originThreadDrawer = useDrawerControl(ORIGIN_THREAD_DRAWER_ID);const copyLink = async () => {+ const id = sessionId();+ if (!id) return;await navigator.clipboard.writeText(- buildSimpleEntityUrl({ type: 'agent', id: blockId })+ buildSimpleEntityUrl({ type: 'agent', id }));toast.success('Link copied to clipboard');};@@ -68,6 +73,8 @@ export function AgentSplitHeader(props: {label: 'Copy link',icon: LinkIcon,action: copyLink,+ // Nothing to link to until the session exists.+ condition: () => sessionId() !== undefined,},];@@ -110,7 +117,7 @@ export function AgentSplitHeader(props: {tools={[]}menuTools={tools}ops={ops}- id={blockId}+ id={sessionId() ?? ''}itemType="foreign"name={title()}/>diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsxindex 53605f10a0..aacbde0427 100644--- a/apps/web/src/features/block-agent/component/Block.tsx+++ b/apps/web/src/features/block-agent/component/Block.tsx@@ -1,8 +1,9 @@import { SidePanel } from '@components/app/side-panel';+import { SplitPanelContext } from '@components/app/split-layout/context';import { useBlockId } from '@core/block';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { LinkedConversationDrawer } from '@core/linked-conversation';-import { Show } from 'solid-js';+import { Show, useContext } from 'solid-js';import {AgentSessionProvider,@@ -12,6 +13,7 @@ import {ORIGIN_THREAD_DRAWER_ID,sessionOriginThread,} from '../context/origin-thread';+import { forgetPendingSession } from '../context/pending-session';import { AgentComposer } from './AgentComposer';import { AgentSplitHeader } from './AgentSplitHeader';import { AgentSidePanelSections } from './sidepanel/AgentSidePanelSections';@@ -56,11 +58,23 @@ function AgentBlockContent() {export default function BlockAgent() {const blockId = useBlockId();+ const split = useContext(SplitPanelContext);++ // A block opened from the create menu mounts against a placeholder while+ // `POST /agent-sessions` provisions its sandbox — minutes, during which the+ // user is already typing. When the real id lands the split adopts it in+ // place: the URL becomes the session's, this mount keeps running, and the+ // placeholder is gone from history rather than being a back step to+ // nowhere.+ const adoptSessionId = (sessionId: string) => {+ split?.handle.adoptContentId({ type: 'agent', nextId: sessionId });+ forgetPendingSession(blockId);+ };return (<Show when={blockId}>{(id) => (- <AgentSessionProvider sessionId={id()}>+ <AgentSessionProvider blockId={id()} onSessionId={adoptSessionId}><AgentBlockContent /></AgentSessionProvider>)}diff --git a/apps/web/src/features/block-agent/component/parts/ControlPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ControlPart.test.tsxnew file mode 100644index 0000000000..b71aa7a0b8--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/ControlPart.test.tsx@@ -0,0 +1,96 @@+/**+ * @vitest-environment jsdom+ *+ * A control's outcome is what the line has to get right: a refused model+ * switch that reads like a successful one is the bug this component exists+ * to prevent.+ */++import type { MessagePart } from '@service-agent-fold/generated/types';+import { render } from '@solidjs/testing-library';+import { describe, expect, it, vi } from 'vitest';+import { ControlPart } from './ControlPart';++// The `ui` barrel reaches the chat input's storage module on import; the+// layer under test is the outcome vocabulary, so the line itself is a stub+// (the `ToolCallPart.test.tsx` idiom).+vi.mock('../../ui', () => ({+ ActionLine: (props: { label: string; failed?: boolean; detail?: string }) => (+ <div+ data-testid="action-line"+ data-failed={String(props.failed ?? false)}+ title={props.detail}+ >+ {props.label}+ </div>+ ),+}));++type Control = Extract<MessagePart, { kind: 'control' }>;++const setModel = (outcome: Control['outcome']): Control => ({+ kind: 'control',+ control: { kind: 'set_model', model: 'openai/gpt-5' },+ outcome,+});++const lineOf = (part: Control) => {+ const { container } = render(() => <ControlPart part={part} />);+ return container.textContent ?? '';+};++const failedOf = (part: Control) => {+ const { getByTestId } = render(() => <ControlPart part={part} />);+ return getByTestId('action-line').getAttribute('data-failed');+};++describe('a model change', () => {+ it('reads as done only once it is accepted', () => {+ expect(lineOf(setModel({ kind: 'pending' }))).toContain(+ 'Setting model to openai/gpt-5'+ );+ expect(lineOf(setModel({ kind: 'accepted' }))).toBe(+ 'Model set to openai/gpt-5'+ );+ });++ it('says it did not happen when the runtime refuses', () => {+ const part = setModel({ kind: 'rejected', message: 'unknown model' });+ expect(lineOf(part)).toContain("Couldn't switch to openai/gpt-5");+ expect(lineOf(part)).not.toContain('Model set to');+ expect(failedOf(part)).toBe('true');+ expect(failedOf(setModel({ kind: 'accepted' }))).toBe('false');+ });++ it('carries the runtime message verbatim, on hover', () => {+ const { getByTitle } = render(() => (+ <ControlPart+ part={setModel({ kind: 'rejected', message: 'no credentials' })}+ />+ ));+ expect(getByTitle('no credentials')).toBeTruthy();+ });+});++describe('the other controls', () => {+ it('name their own failure', () => {+ expect(+ lineOf({+ kind: 'control',+ control: { kind: 'compact' },+ outcome: { kind: 'rejected', message: 'nope' },+ })+ ).toContain("Couldn't compact the context");+ });++ // Nothing answers a stop, so the fold accepts it the moment it is issued.+ it('reads a stop as done whether or not anything answered', () => {+ const stop = (outcome: Control['outcome']): Control => ({+ kind: 'control',+ control: { kind: 'stop' },+ outcome,+ });+ expect(lineOf(stop({ kind: 'pending' }))).toBe('Stopped');+ expect(lineOf(stop({ kind: 'accepted' }))).toBe('Stopped');+ });+});diff --git a/apps/web/src/features/block-agent/component/parts/ControlPart.tsx b/apps/web/src/features/block-agent/component/parts/ControlPart.tsxindex a2903785da..cda2497007 100644--- a/apps/web/src/features/block-agent/component/parts/ControlPart.tsx+++ b/apps/web/src/features/block-agent/component/parts/ControlPart.tsx@@ -1,18 +1,71 @@-/** A control the user issued mid-session: model switch, compaction, stop. */+/**+ * A control the user issued mid-session: model switch, compaction, stop.+ *+ * The outcome is half the message. A runtime that refuses a control answers+ * with a JSON-RPC error the fold records as `rejected` — most often a model+ * the harness advertised but cannot actually run — and a line that read+ * "Model set to X" either way would be reporting a change that never+ * happened. So each control names all three states, and a rejection carries+ * the runtime's own words.+ */import type { MessagePart } from '@service-agent-fold/generated/types';import { match } from 'ts-pattern';-import { ToolCard } from '../../ui';+import { ActionLine } from '../../ui';-export function ControlPart(props: {- part: Extract<MessagePart, { kind: 'control' }>;-}) {- const label = () =>- match(props.part.control)- .with({ kind: 'set_model' }, (control) => `Model set to ${control.model}`)- .with({ kind: 'compact' }, () => 'Context compacted')- .with({ kind: 'stop' }, () => 'Stopped')- .exhaustive();+type ControlPartData = Extract<MessagePart, { kind: 'control' }>;- return <ToolCard title={label()} status="completed" />;+/** What to call the control, in each of the three outcomes. */+function label(part: ControlPartData): string {+ return (+ match([part.control, part.outcome] as const)+ .with(+ [{ kind: 'set_model' }, { kind: 'pending' }],+ ([control]) => `Setting model to ${control.model}…`+ )+ .with(+ [{ kind: 'set_model' }, { kind: 'accepted' }],+ ([control]) => `Model set to ${control.model}`+ )+ .with(+ [{ kind: 'set_model' }, { kind: 'rejected' }],+ ([control]) => `Couldn't switch to ${control.model}`+ )+ .with(+ [{ kind: 'compact' }, { kind: 'pending' }],+ () => 'Compacting context…'+ )+ .with(+ [{ kind: 'compact' }, { kind: 'accepted' }],+ () => 'Context compacted'+ )+ .with(+ [{ kind: 'compact' }, { kind: 'rejected' }],+ () => "Couldn't compact the context"+ )+ // A stop is acknowledged the moment it is issued — nothing answers it, so+ // it has no pending state worth naming and cannot be refused.+ .with(+ [{ kind: 'stop' }, { kind: 'rejected' }],+ () => "Couldn't stop the agent"+ )+ .with([{ kind: 'stop' }, { kind: 'pending' }], () => 'Stopped')+ .with([{ kind: 'stop' }, { kind: 'accepted' }], () => 'Stopped')+ .exhaustive()+ );+}++export function ControlPart(props: { part: ControlPartData }) {+ const rejection = () =>+ props.part.outcome.kind === 'rejected'+ ? props.part.outcome.message+ : undefined;++ return (+ <ActionLine+ label={label(props.part)}+ failed={rejection() !== undefined}+ detail={rejection()}+ />+ );}diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsxindex 4a9c67b818..bd075307d0 100644--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx@@ -20,6 +20,7 @@ import type {import {type Accessor,createContext,+ createEffect,type ParentProps,useContext,} from 'solid-js';@@ -30,11 +31,20 @@ import {} from './create-composer-controller';import {createSessionStatusController,+ isDisconnected,type SessionStatus,} from './create-session-status-controller';+import { resolveSessionId } from './resolve-session-id';export type AgentSessionState = {- sessionId: Accessor<string>;+ /**+ * The session this block shows, absent while a just-created one's `POST`+ * is still on the wire. See `pending-session.ts`.+ */+ sessionId: Accessor<string | undefined>;+ /** The session is still being created — everything else is empty because+ * there is nothing to show yet, not because the load failed. */+ pending: Accessor<boolean>;/** Session metadata, absent until the load resolves. */session: Accessor<AgentSessionResponse | undefined>;/** The bot the session runs as, absent until the fold is acquired. */@@ -54,15 +64,35 @@ export type AgentSessionState = {working: Accessor<boolean>;/** The runtime's status: the GET snapshot, followed live over the log. */status: Accessor<SessionStatus>;+ /**+ * The runtime is gone and the user has asked it for something anyway, so+ * the service is bringing its sandbox back before it can deliver.+ *+ * There is no signal for this on the wire: the resume happens inside the+ * service, and the session log stays silent until the container answers.+ * It is inferred instead, from the one thing the block does know — the+ * runtime was disconnected, and a request it must wait on is outstanding.+ */+ resuming: Accessor<boolean>;composer: ComposerController;};const AgentSessionCtx = createContext<AgentSessionState>();export function AgentSessionProvider(- props: ParentProps & { sessionId: string }+ props: ParentProps & {+ /** The block's id: a session, or a placeholder for one being created. */+ blockId: string;+ /** The real id, once known — the block adopts it into the URL. */+ onSessionId?: (sessionId: string) => void;+ }) {- const sessionId = () => props.sessionId;+ const { sessionId, pending, failed } = resolveSessionId(() => props.blockId);++ createEffect(() => {+ const id = sessionId();+ if (id && id !== props.blockId) props.onSessionId?.(id);+ });const feed = createAgentSessionFeed(sessionId);const status = createSessionStatusController({@@ -72,21 +102,35 @@ export function AgentSessionProvider(// A last message with no stop reason reads as an open turn forever; the// status stream knows when the runtime disconnected without closing it.// Combining them here is what keeps "working" a single truth.- const working = () =>- feed.working() && status.status().kind !== 'disconnected';- const composer = createComposerController({ sessionId, working });+ const working = () => feed.working() && !isDisconnected(status.status());+ const composer = createComposerController({+ sessionId,+ working,+ model: () => feed.metadata()?.model,+ });++ // Anything the service can only deliver over a live transport: a prompt on+ // the wire, or a model change waiting to be seen in the fold.+ const awaitingRuntime = () =>+ composer.sendingId() !== undefined ||+ composer.changingModel() !== undefined;+ const resuming = () => isDisconnected(status.status()) && awaitingRuntime();return (<AgentSessionCtx.Providervalue={{sessionId,+ pending,session: feed.session,bot: feed.bot,metadata: feed.metadata,messages: feed.messages,- loadFailed: feed.loadFailed,+ // A create that failed leaves the block with nothing to load, which+ // is the same dead end for the reader as a load that failed.+ loadFailed: () => feed.loadFailed() || failed(),working,status: status.status,+ resuming,composer,}}>diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.tsindex e729539d11..19430e4e6f 100644--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts@@ -28,6 +28,7 @@ import {onCleanup,} from 'solid-js';import { createStore, produce, reconcile } from 'solid-js/store';+import { lastTurnMessage } from '../state/control-message';export type AgentSessionFeed = {/** Session metadata, absent until the load resolves. */@@ -57,8 +58,14 @@ function sameMessage(a: FoldedMessage, b: FoldedMessage): boolean {return a.turn === b.turn && a.author.kind === b.author.kind;}+/**+ * `sessionId` is absent while a just-created session's `POST` is still on the+ * wire (`pending-session.ts`). `createResource` treats an absent source as+ * "nothing to fetch", so the block simply renders its empty transcript until+ * the id lands and the fetch runs itself.+ */export function createAgentSessionFeed(- sessionId: Accessor<string>+ sessionId: Accessor<string | undefined>): AgentSessionFeed {const [list, setList] = createStore<FoldedMessage[]>([]);const [bot, setBot] = createSignal<SessionBot>();@@ -138,8 +145,13 @@ export function createAgentSessionFeed(});const messages = () => list;+ // A user-authored tail means a prompt is awaiting its reply — except when+ // it is a control, which is user-authored, never gets a stop reason, and+ // starts no turn. Counting one would latch this signal true forever, and+ // the composer's drain holds every prompt behind it: changing the model+ // would silently stop the session from accepting anything again.const working = () => {- const last = list.at(-1);+ const last = lastTurnMessage(list);if (!last) return false;return last.author.kind === 'user' || last.stop == null;};diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts b/apps/web/src/features/block-agent/context/create-composer-controller.test.tsindex fb885ed405..31dd7ef661 100644--- a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts+++ b/apps/web/src/features/block-agent/context/create-composer-controller.test.ts@@ -42,14 +42,21 @@ const prompts = () =>.filter((c) => (c.action as { type: string }).type === 'prompt').map((c) => (c.action as { prompt: string }).prompt);-function setup(options?: { working?: boolean }) {+function setup(options?: {+ working?: boolean;+ sessionId?: string;+ model?: string | null;+}) {const [working, setWorking] = createSignal(options?.working ?? false);- const [sessionId, setSessionId] = createSignal('session-1');+ const [sessionId, setSessionId] = createSignal<string | undefined>(+ 'sessionId' in (options ?? {}) ? options?.sessionId : 'session-1'+ );+ const [model, setModel] = createSignal<string | null>(options?.model ?? null);const { controller, dispose } = createRoot((dispose) => ({- controller: createComposerController({ sessionId, working }),+ controller: createComposerController({ sessionId, working, model }),dispose,}));- return { controller, setWorking, setSessionId, dispose };+ return { controller, setWorking, setSessionId, setModel, dispose };}beforeEach(() => {@@ -237,6 +244,95 @@ describe('stop', () => {});});+describe('a session that does not exist yet', () => {+ it('queues prompts typed before the create lands, then drains them in order', async () => {+ const { controller, setWorking, setSessionId, dispose } = setup({+ sessionId: undefined,+ });+ controller.send('first');+ controller.send('second');+ await flush();++ // Nothing on the wire: there is nowhere to post to.+ expect(prompts()).toEqual([]);+ expect(controller.queue().map((p) => p.markdown)).toEqual([+ 'first',+ 'second',+ ]);++ setSessionId('session-1');+ await flush();+ // The queue survived acquiring the id, and its head went out against it.+ expect(prompts()).toEqual(['first']);+ expect(control.calls.every((c) => c.sessionId === 'session-1')).toBe(true);++ setWorking(true); // the fold shows first's turn+ await flush();+ setWorking(false); // ...and it settles+ await flush();++ expect(prompts()).toEqual(['first', 'second']);+ expect(controller.queue()).toEqual([]);+ dispose();+ });++ it('does not post stop or setModel before there is a session', async () => {+ const { controller, dispose } = setup({ sessionId: undefined });+ controller.stop();+ controller.setModel('opus');+ await flush();++ expect(control.calls).toEqual([]);+ dispose();+ });+});++describe('a model change in flight', () => {+ it('holds until the fold shows the runtime moved, not until the POST returns', async () => {+ const { controller, setModel, dispose } = setup({ model: 'old-model' });+ controller.setModel('new-model');+ await flush();++ // The POST has already come back; the runtime has not moved yet.+ expect(control.calls.at(-1)?.action).toEqual({+ type: 'setModel',+ model: 'new-model',+ });+ expect(controller.changingModel()).toBe('new-model');++ setModel('new-model');+ await flush();++ expect(controller.changingModel()).toBeUndefined();+ dispose();+ });++ it('clears when the runtime settles on something else entirely', async () => {+ const { controller, setModel, dispose } = setup({ model: 'old-model' });+ controller.setModel('new-model');+ await flush();++ // A later change overtook this one; nothing is still pending.+ setModel('third-model');+ await flush();+ controller.setModel('third-model');+ await flush();++ expect(controller.changingModel()).toBeUndefined();+ dispose();+ });++ it('clears immediately when the POST fails', async () => {+ const { controller, dispose } = setup({ model: 'old-model' });+ control.outcome = 'err';+ controller.setModel('new-model');+ await flush();++ expect(controller.changingModel()).toBeUndefined();+ dispose();+ });+});+describe('session switch', () => {it('drops the queue — prompts never leak into another session', async () => {const { controller, setSessionId, dispose } = setup({ working: true });diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.ts b/apps/web/src/features/block-agent/context/create-composer-controller.tsindex fd2c756089..8e159ed870 100644--- a/apps/web/src/features/block-agent/context/create-composer-controller.ts+++ b/apps/web/src/features/block-agent/context/create-composer-controller.ts@@ -16,7 +16,7 @@import { toast } from '@core/component/Toast/Toast';import { agentHarnessServiceClient } from '@service-agent-harness/client';-import { type Accessor, batch, createEffect, on, onCleanup } from 'solid-js';+import { type Accessor, batch, createEffect, onCleanup } from 'solid-js';import { createStore } from 'solid-js/store';import {isBusy,@@ -34,12 +34,25 @@ export type ComposerController = {sendFailed: Accessor<boolean>;/** A turn is running or a post is starting one — the stop affordance shows. */busy: Accessor<boolean>;+ /**+ * A model change is on the wire: the id requested, until the fold shows the+ * runtime moved to it (or the POST fails).+ *+ * Worth its own signal because this is the request that can take longest+ * with the least to show for it — a change issued to a reaped sandbox+ * blocks in the service for the whole container resume, and nothing is+ * written to the log until it lands, so without this the UI has no+ * evidence anything is happening at all.+ */+ changingModel: Accessor<string | undefined>;send: (markdown: string) => void;/** Release a failed head so the drain tries it again. */retry: () => void;/** Drop a queued prompt. Dropping the failed head clears the failure. */remove: (promptId: string) => void;stop: () => void;+ /** Ask the agent to run on a different model from here on. */+ setModel: (model: string) => void;};/**@@ -51,22 +64,33 @@ export type ComposerController = {export const TURN_OBSERVE_TIMEOUT_MS = 10_000;export function createComposerController(options: {- sessionId: Accessor<string>;+ /** The fold's current model, which is how a model change is seen to land. */+ model?: Accessor<string | null | undefined>;+ /**+ * Absent until a just-created session's `POST` lands+ * (`context/pending-session.ts`). Prompts typed before then queue and+ * drain themselves when it arrives — that is the whole point of `send`+ * only enqueueing.+ */+ sessionId: Accessor<string | undefined>;/** The block's one working signal — see `AgentSessionContext`. */working: Accessor<boolean>;}): ComposerController {const [state, setState] = createStore<{queue: QueuedPrompt[];post: PostPhase;+ /** The model a `setModel` is currently asking for. */+ requestedModel: string | undefined;}>({queue: [],post: { type: 'idle' },+ requestedModel: undefined,});- const postHead = async (prompt: QueuedPrompt) => {+ const postHead = async (sessionId: string, prompt: QueuedPrompt) => {setState('post', { type: 'posting', promptId: prompt.id });const result = await agentHarnessServiceClient- .control(options.sessionId(), { type: 'prompt', prompt: prompt.markdown })+ .control(sessionId, { type: 'prompt', prompt: prompt.markdown }).catch(() => undefined);if (result === undefined || result.isErr()) {@@ -82,9 +106,24 @@ export function createComposerController(options: {});};- const postStop = async () => {+ const postSetModel = async (sessionId: string, model: string) => {+ setState('requestedModel', model);const result = await agentHarnessServiceClient- .control(options.sessionId(), { type: 'stop' })+ .control(sessionId, { type: 'setModel', model })+ .catch(() => undefined);+ if (result === undefined || result.isErr()) {+ setState('requestedModel', undefined);+ toast.failure('The model could not be changed');+ }+ // Success is observed through the fold: the runtime acks the config+ // change and the session metadata's `model` moves. The POST returning is+ // not the end of the wait — it only means the service accepted it — so+ // `requestedModel` is cleared by the effect below, not here.+ };++ const postStop = async (sessionId: string) => {+ const result = await agentHarnessServiceClient+ .control(sessionId, { type: 'stop' }).catch(() => undefined);if (result === undefined || result.isErr()) {toast.failure('The agent could not be stopped');@@ -97,12 +136,29 @@ export function createComposerController(options: {// it. Deciding from present facts — rather than reacting to event edges —// is what makes this wedge-proof: there is no exit event to miss.createEffect(() => {+ const sessionId = options.sessionId();const action = nextAction({post: state.post,head: state.queue[0],agentWorking: options.working(),+ sessionExists: sessionId !== undefined,});- if (action.type === 'post_head') void postHead(action.prompt);+ // `sessionExists` is what makes the id below sound: the drain cannot+ // choose to post without one.+ if (action.type === 'post_head' && sessionId) {+ void postHead(sessionId, action.prompt);+ }+ });++ // A model change is done when the fold says the runtime moved, not when+ // the POST returns. Also clears when the runtime settles somewhere else+ // entirely — another change overtook this one — so this can never stick.+ createEffect(() => {+ const requested = state.requestedModel;+ if (requested === undefined) return;+ const current = options.model?.();+ if (current == null) return;+ if (current === requested) setState('requestedModel', undefined);});// `awaiting_turn` resolves on whichever comes first: the fold reports the@@ -123,13 +179,27 @@ export function createComposerController(options: {// A session switch resets the composer: queued prompts belong to the// session they were typed in, never the next one.- createEffect(- on(- options.sessionId,- () => setState({ queue: [], post: { type: 'idle' } }),- { defer: true }- )- );+ //+ // Acquiring an id is not a switch. A block that opened on a placeholder+ // goes `undefined -> id` when its create lands, and everything typed+ // during the wait was typed for exactly that session — wiping it there is+ // the one thing that would make typing early pointless. The previous id is+ // tracked by hand rather than read from `on`'s `prevInput`, which a+ // deferred `on` leaves undefined through the first change and so cannot+ // tell the two apart.+ let previousSessionId = options.sessionId();+ createEffect(() => {+ const sessionId = options.sessionId();+ if (sessionId === previousSessionId) return;+ const acquired = previousSessionId === undefined;+ previousSessionId = sessionId;+ if (acquired) return;+ setState({+ queue: [],+ post: { type: 'idle' },+ requestedModel: undefined,+ });+ });return {queue: () => state.queue,@@ -139,6 +209,7 @@ export function createComposerController(options: {: undefined,sendFailed: () => state.post.type === 'failed',busy: () => isBusy(state.post, options.working()),+ changingModel: () => state.requestedModel,send: (markdown) => {batch(() => {setState('queue', (queue) => [@@ -163,8 +234,15 @@ export function createComposerController(options: {});},stop: () => {+ const sessionId = options.sessionId();+ if (!sessionId) return;if (!isBusy(state.post, options.working())) return;- void postStop();+ void postStop(sessionId);+ },+ setModel: (model) => {+ const sessionId = options.sessionId();+ if (!sessionId) return;+ void postSetModel(sessionId, model);},};}diff --git a/apps/web/src/features/block-agent/context/create-session-status-controller.test.ts b/apps/web/src/features/block-agent/context/create-session-status-controller.test.tsindex 90dc377379..b84e14a0ce 100644--- a/apps/web/src/features/block-agent/context/create-session-status-controller.test.ts+++ b/apps/web/src/features/block-agent/context/create-session-status-controller.test.ts@@ -1,6 +1,9 @@import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';import { describe, expect, it } from 'vitest';-import { statusFromEntry } from './create-session-status-controller';+import {+ isDisconnected,+ statusFromEntry,+} from './create-session-status-controller';function entry(content: unknown): AgentSessionLogEntryDto {return { direction: 'to_server', content } as AgentSessionLogEntryDto;@@ -29,3 +32,18 @@ describe('statusFromEntry', () => {return statusFromEntry(entry(content));}});++describe('isDisconnected', () => {+ // The bug this closes: a live disconnect arrives as an *event*, never as+ // the snapshot's own kind, so checking only the latter missed every+ // disconnect that happened while the block was open.+ it('recognises the live event, not just the snapshot kind', () => {+ expect(isDisconnected({ kind: 'disconnected' })).toBe(true);+ expect(isDisconnected({ kind: 'event', event: 'disconnected' })).toBe(true);+ });++ it('leaves every other status alone', () => {+ expect(isDisconnected({ kind: 'no_messages' })).toBe(false);+ expect(isDisconnected({ kind: 'event', event: 'acp_ready' })).toBe(false);+ });+});diff --git a/apps/web/src/features/block-agent/context/create-session-status-controller.ts b/apps/web/src/features/block-agent/context/create-session-status-controller.tsindex c441664e3b..1e1d33e3ef 100644--- a/apps/web/src/features/block-agent/context/create-session-status-controller.ts+++ b/apps/web/src/features/block-agent/context/create-session-status-controller.ts@@ -41,8 +41,30 @@ export type SessionStatusController = {status: Accessor<SessionStatus>;};+/**+ * Whether the runtime is gone, in either shape the status can take.+ *+ * The GET snapshot reports it as its own kind; a live frame always arrives+ * as `{ kind: 'event', event: 'disconnected' }`, because the projection+ * keeps the wire name. Reading only the former is how a live disconnect gets+ * missed — which left `working` latched on and the composer waiting on a+ * runtime that had gone away.+ */+export function isDisconnected(status: SessionStatus): boolean {+ return (+ status.kind === 'disconnected' ||+ (status.kind === 'event' && status.event === 'disconnected')+ );+}++/**+ * `sessionId` is absent until a just-created session's `POST` lands+ * (`pending-session.ts`). There is no log to follow before then, so the+ * controller holds its initial `no_messages` — which the pill reads as+ * "Starting" — and subscribes once there is something to subscribe to.+ */export function createSessionStatusController(options: {- sessionId: Accessor<string>;+ sessionId: Accessor<string | undefined>;/** The GET snapshot's status, absent until the session loads. */seed: Accessor<SessionStatus | undefined>;}): SessionStatusController {@@ -60,16 +82,15 @@ export function createSessionStatusController(options: {});createEffect(() => {+ const id = options.sessionId();+ if (!id) return;live = false;- const unsubscribe = subscribeAgentSessionLog(- options.sessionId(),- (event) => {- const next = statusFromEntry(event);- if (!next) return;- live = true;- setStatus(next);- }- );+ const unsubscribe = subscribeAgentSessionLog(id, (event) => {+ const next = statusFromEntry(event);+ if (!next) return;+ live = true;+ setStatus(next);+ });onCleanup(unsubscribe);});diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.tsnew file mode 100644index 0000000000..4ccaa4026c--- /dev/null+++ b/apps/web/src/features/block-agent/context/pending-session.ts@@ -0,0 +1,83 @@+/**+ * Sessions that exist on screen before they exist on the server.+ *+ * `POST /agent-sessions` does not answer until its Daytona sandbox is booted,+ * cloned and answering — minutes, not milliseconds. Waiting on that before+ * opening anything means staring at a spinner for the whole provision, so the+ * block opens immediately against a placeholder id minted here, and adopts+ * the real one when the create lands.+ *+ * The registry is module-level on purpose: the create is in flight before any+ * block mounts, and must survive the mount either way round — resolving+ * before the block is on screen is normal, not a race.+ *+ * Everything downstream of the block reads its session id as+ * `Accessor<string | undefined>`, so "not created yet" is the same absence+ * they already handle while the GET is in flight.+ */++import { agentHarnessServiceClient } from '@service-agent-harness/client';+import { type Accessor, createSignal } from 'solid-js';++/**+ * Placeholder ids are prefixed so a session id can never be mistaken for one:+ * real ids are UUIDs.+ */+const PLACEHOLDER_PREFIX = 'pending-';++export type PendingSession = {+ /** The real session id, once the create resolves. */+ sessionId: Accessor<string | undefined>;+ /** The create failed — this block has nothing to become. */+ failed: Accessor<boolean>;+};++const pending = new Map<string, PendingSession>();++/** Whether `id` is a placeholder this module minted rather than a session. */+export function isPlaceholderSessionId(id: string): boolean {+ return id.startsWith(PLACEHOLDER_PREFIX);+}++/**+ * 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 {+ 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) => {+ if (result.isErr()) {+ setFailed(true);+ return;+ }+ setSessionId(result.value.session.id);+ })+ .catch(() => setFailed(true));++ return placeholder;+}++/**+ * The pending session behind a placeholder, or undefined when there is none —+ * a placeholder URL reloaded in a new tab, whose create belonged to the tab+ * that is gone.+ */+export function pendingSession(+ placeholder: string+): PendingSession | undefined {+ return pending.get(placeholder);+}++/**+ * Drop a resolved placeholder. Called once the block has adopted the real id,+ * so the map does not grow for the life of the tab.+ */+export function forgetPendingSession(placeholder: string): void {+ pending.delete(placeholder);+}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.tsnew file mode 100644index 0000000000..ac01e9ceed--- /dev/null+++ b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts@@ -0,0 +1,88 @@+/**+ * @vitest-environment jsdom+ *+ * The two shapes a block id can have — a session, or a placeholder standing+ * in for one being created — resolved into the one the block consumes.+ */++import { createRoot } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';++const create = vi.hoisted(() => ({+ resolve: undefined as ((id: string) => void) | undefined,+ reject: undefined as (() => void) | undefined,+}));++vi.mock('@service-agent-harness/client', () => ({+ agentHarnessServiceClient: {+ create: vi.fn(+ () =>+ new Promise((resolve) => {+ create.resolve = (id: string) =>+ resolve({ isErr: () => false, value: { session: { id } } });+ create.reject = () => resolve({ isErr: () => true });+ })+ ),+ },+}));++const { startPendingSession } = await import('./pending-session');+const { resolveSessionId } = await import('./resolve-session-id');++/** Let the mocked create's `.then` run. */+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++describe('a block id that is already a session', () => {+ it('resolves to itself, never pending', () => {+ createRoot((dispose) => {+ const resolved = resolveSessionId(() => 'session-1');+ expect(resolved.sessionId()).toBe('session-1');+ expect(resolved.pending()).toBe(false);+ expect(resolved.failed()).toBe(false);+ dispose();+ });+ });+});++describe('a placeholder', () => {+ it('has no session until the create lands, then has that one', async () => {+ const placeholder = startPendingSession();+ await createRoot(async (dispose) => {+ const resolved = resolveSessionId(() => placeholder);+ expect(resolved.sessionId()).toBeUndefined();+ expect(resolved.pending()).toBe(true);+ expect(resolved.failed()).toBe(false);++ create.resolve?.('session-9');+ await flush();++ expect(resolved.sessionId()).toBe('session-9');+ expect(resolved.pending()).toBe(false);+ dispose();+ });+ });++ it('fails when the create fails', async () => {+ const placeholder = startPendingSession();+ await createRoot(async (dispose) => {+ const resolved = resolveSessionId(() => placeholder);+ create.reject?.();+ await flush();++ expect(resolved.failed()).toBe(true);+ expect(resolved.sessionId()).toBeUndefined();+ 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', () => {+ createRoot((dispose) => {+ const resolved = resolveSessionId(() => 'pending-nothing');+ expect(resolved.pending()).toBe(false);+ expect(resolved.failed()).toBe(true);+ dispose();+ });+ });+});diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.ts b/apps/web/src/features/block-agent/context/resolve-session-id.tsnew file mode 100644index 0000000000..740733eb12--- /dev/null+++ b/apps/web/src/features/block-agent/context/resolve-session-id.ts@@ -0,0 +1,45 @@+/**+ * A block's session id, which may not exist yet.+ *+ * The block mounts with whatever id the split gave it. Usually that is a real+ * session; for a just-created one it is a placeholder standing in for a create+ * still on the wire (`pending-session.ts`). This resolves the two into the one+ * shape the block consumes: an id that is absent until there is one, plus the+ * two facts the block chrome needs to explain the wait.+ */++import { type Accessor, createMemo } from 'solid-js';+import { isPlaceholderSessionId, pendingSession } from './pending-session';++export type ResolvedSessionId = {+ /** The real session id; absent while a create is still in flight. */+ sessionId: Accessor<string | undefined>;+ /** This block is waiting on a create it started. */+ pending: Accessor<boolean>;+ /** The create failed, or the placeholder has no create behind it. */+ failed: Accessor<boolean>;+};++export function resolveSessionId(blockId: Accessor<string>): ResolvedSessionId {+ const entry = createMemo(() => {+ const id = blockId();+ return isPlaceholderSessionId(id)+ ? (pendingSession(id) ?? null)+ : undefined;+ });++ // `undefined` entry: the block id is already a session. `null`: a+ // placeholder nothing is creating — a reloaded placeholder URL, which can+ // only be an error, never a wait.+ const sessionId = () => {+ const session = entry();+ if (session === undefined) return blockId();+ return session?.sessionId();+ };++ return {+ sessionId,+ pending: () => entry() != null && entry()?.sessionId() === undefined,+ failed: () => entry() === null || (entry()?.failed() ?? false),+ };+}diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsxindex 794364e2d3..ff7a334754 100644--- a/apps/web/src/features/block-agent/debug/Gallery.tsx+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx@@ -12,8 +12,10 @@ import type {import { createSignal, type JSX, onCleanup } from 'solid-js';import { Message } from '../component/AgentMessage';import {+ ActionLine,AgentInput,AnimatedNumber,+ ComposerNotice,CountSummary,DiffChanges,PierreDiff,@@ -136,6 +138,26 @@ export default function AgentUiGallery() {<StaticMarkdownContext><div class="size-full overflow-auto"><div class="mx-auto flex max-w-3xl flex-col gap-8 px-6 py-8">+ <Item label="ComposerNotice">+ <ComposerNotice text="Waking the agent's sandbox…" active />+ </Item>++ <Item label="ActionLine">+ <ActionLine label="Setting model to claude-opus-5…" />+ <ActionLine label="Model set to claude-opus-5" />+ <ActionLine label="Context compacted" />+ <ActionLine+ label="Couldn't switch to openai/gpt-5"+ failed+ detail="no credentials configured for provider openai"+ />+ <ActionLine+ label="The agent couldn't answer — Internal error: Bad Request: bad request: Authorization header is badly formatted"+ detail="Internal error: Bad Request: bad request: Authorization header is badly formatted"+ failed+ />+ </Item>+<Item label="ToolCard"><ToolCardtitle="Bash"diff --git a/apps/web/src/features/block-agent/debug/replay/Replay.tsx b/apps/web/src/features/block-agent/debug/replay/Replay.tsxindex 3a1bd296bf..4d3d32e867 100644--- a/apps/web/src/features/block-agent/debug/replay/Replay.tsx+++ b/apps/web/src/features/block-agent/debug/replay/Replay.tsx@@ -255,7 +255,7 @@ export default function AgentReplay() {keyed>{(session) => (- <AgentSessionProvider sessionId={session.id}>+ <AgentSessionProvider blockId={session.id}><StaticMarkdownContext><div class="flex-1 min-h-0 flex flex-col"><SessionChrome />diff --git a/apps/web/src/features/block-agent/definition.ts b/apps/web/src/features/block-agent/definition.tsindex 77b0b5fc9d..ce4ca7e00e 100644--- a/apps/web/src/features/block-agent/definition.ts+++ b/apps/web/src/features/block-agent/definition.ts@@ -1,6 +1,10 @@import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';import { ok } from 'neverthrow';import { lazy } from 'solid-js';+import {+ isPlaceholderSessionId,+ pendingSession,+} from './context/pending-session';export const definition = defineBlock({name: 'agent',@@ -9,6 +13,13 @@ export const definition = defineBlock({liveTrackingEnabled: false,async load(source, _intent) {if (source.type === 'dss') {+ // A placeholder is only meaningful to the tab that minted it (see+ // `context/pending-session.ts`). One arriving from anywhere else — a+ // reloaded URL, a restored layout — names a session this tab cannot+ // find, so it is missing rather than merely slow.+ if (isPlaceholderSessionId(source.id) && !pendingSession(source.id)) {+ return LoadErrors.MISSING;+ }return ok({ id: source.id });}return LoadErrors.MISSING;diff --git a/apps/web/src/features/block-agent/state/composer-state.test.ts b/apps/web/src/features/block-agent/state/composer-state.test.tsindex c7138c39c2..c6e598c4d5 100644--- a/apps/web/src/features/block-agent/state/composer-state.test.ts+++ b/apps/web/src/features/block-agent/state/composer-state.test.ts@@ -12,9 +12,33 @@ const facts = (overrides: Partial<ComposerFacts>): ComposerFacts => ({post: { type: 'idle' },head: undefined,agentWorking: false,+ sessionExists: true,...overrides,});+describe('nextAction: before the session exists', () => {+ it('holds the head until the create lands', () => {+ const waiting = facts({ head: prompt('a'), sessionExists: false });+ expect(nextAction(waiting).type).toBe('hold');+ expect(nextAction(facts({ head: prompt('a') }))).toEqual({+ type: 'post_head',+ prompt: prompt('a'),+ });+ });++ it('outranks every other hold — nothing can post to nowhere', () => {+ const action = nextAction(+ facts({+ head: prompt('a'),+ sessionExists: false,+ post: { type: 'failed', promptId: 'a' },+ agentWorking: true,+ })+ );+ expect(action.type).toBe('hold');+ });+});+describe('nextAction: when the head sends', () => {it('idle, agent idle, something queued → post the head', () => {const action = nextAction(facts({ head: prompt('a') }));diff --git a/apps/web/src/features/block-agent/state/composer-state.ts b/apps/web/src/features/block-agent/state/composer-state.tsindex 2c4bb4f7ae..92fff44b15 100644--- a/apps/web/src/features/block-agent/state/composer-state.ts+++ b/apps/web/src/features/block-agent/state/composer-state.ts@@ -55,6 +55,14 @@ export type ComposerFacts = {head: QueuedPrompt | undefined;/** The block's one working signal (fold ∧ not disconnected). */agentWorking: boolean;+ /**+ * There is a session to post to. False on a just-created block whose+ * `POST /agent-sessions` has not answered yet: the user can type and queue+ * from the first frame, and the queue drains itself the moment the session+ * exists. Absence of a session is a hold like any other, not a special+ * case the composer has to be told about.+ */+ sessionExists: boolean;};export type ComposerAction =@@ -69,6 +77,9 @@ const hold = (reason: string): ComposerAction => ({ type: 'hold', reason });*/export function nextAction(facts: ComposerFacts): ComposerAction {return match(facts)+ .with({ sessionExists: false }, () =>+ hold('the session has not been created yet')+ ).with({ post: { type: 'posting' } }, () => hold('a post is on the wire')).with({ post: { type: 'awaiting_turn' } }, () =>hold('posted; the fold has not shown the turn yet')diff --git a/apps/web/src/features/block-agent/state/control-message.test.ts b/apps/web/src/features/block-agent/state/control-message.test.tsnew file mode 100644index 0000000000..4a6285b904--- /dev/null+++ b/apps/web/src/features/block-agent/state/control-message.test.ts@@ -0,0 +1,75 @@+/**+ * The latch this exists to prevent: a model change is user-authored and+ * never gets a stop reason, so a naive read of the transcript's tail says+ * "the agent is working" forever after one.+ */++import type { FoldedMessage } from '@service-agent-fold/generated/types';+import { describe, expect, it } from 'vitest';+import { isControlMessage, lastTurnMessage } from './control-message';++const message = (+ id: number,+ author: 'user' | 'agent',+ parts: FoldedMessage['parts'],+ stop: FoldedMessage['stop'] = null+): FoldedMessage =>+ ({+ turn: id,+ author:+ author === 'user' ? { kind: 'user', userId: null } : { kind: 'agent' },+ parts,+ stop,+ }) as unknown as FoldedMessage;++const prompt = (id: number) =>+ message(id, 'user', [{ kind: 'text', text: 'hi' }]);+const reply = (id: number, stopped: boolean) =>+ message(+ id,+ 'agent',+ [{ kind: 'text', text: 'hello' }],+ stopped ? ({ kind: 'end_turn' } as FoldedMessage['stop']) : null+ );+const modelChange = (id: number) =>+ message(id, 'user', [+ {+ kind: 'control',+ control: { kind: 'set_model', model: 'github-copilot/gpt-5.6-terra' },+ outcome: { kind: 'accepted' },+ },+ ]);++describe('isControlMessage', () => {+ it('is the whole message or nothing', () => {+ expect(isControlMessage(modelChange(1))).toBe(true);+ expect(isControlMessage(prompt(1))).toBe(false);+ });+});++describe('lastTurnMessage', () => {+ it('looks past controls to the settled turn behind them', () => {+ const messages = [prompt(0), reply(0, true), modelChange(1)];+ expect(lastTurnMessage(messages)).toBe(messages[1]);+ });++ it('looks past a run of them', () => {+ const messages = [+ prompt(0),+ reply(0, true),+ modelChange(1),+ modelChange(2),+ modelChange(3),+ ];+ expect(lastTurnMessage(messages)).toBe(messages[1]);+ });++ it('still sees a turn that is genuinely running', () => {+ const messages = [prompt(0), reply(0, false), modelChange(1)];+ expect(lastTurnMessage(messages)?.stop).toBeNull();+ });++ it('is undefined when a session has only ever had controls', () => {+ expect(lastTurnMessage([modelChange(0)])).toBeUndefined();+ });+});diff --git a/apps/web/src/features/block-agent/state/control-message.ts b/apps/web/src/features/block-agent/state/control-message.tsnew file mode 100644index 0000000000..cb217cff77--- /dev/null+++ b/apps/web/src/features/block-agent/state/control-message.ts@@ -0,0 +1,34 @@+/**+ * Telling a control apart from a turn.+ *+ * The fold gives every control the user issues — a model change, a stop — its+ * own single-part message, authored by the user (`agent_fold`'s+ * `record_control`). That makes it indistinguishable by author from a prompt,+ * which two places downstream care about: a control is not a prompt bubble,+ * and — the one that bites — a control is not a turn in flight.+ */++import type { FoldedMessage } from '@service-agent-fold/generated/types';++/** Every part is a control: the message is an action, not a conversation. */+export function isControlMessage(message: FoldedMessage): boolean {+ return message.parts.every((part) => part.kind === 'control');+}++/**+ * The newest message that is not a control, which is the one that says+ * whether a turn is running.+ *+ * A control has no stop reason and never gets one — nothing answers a model+ * change with a turn — so reading the raw tail would latch "the agent is+ * working" on forever the moment one lands.+ */+export function lastTurnMessage(+ messages: readonly FoldedMessage[]+): FoldedMessage | undefined {+ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index]!;+ if (!isControlMessage(message)) return message;+ }+ return undefined;+}diff --git a/apps/web/src/features/block-agent/ui/ActionLine.tsx b/apps/web/src/features/block-agent/ui/ActionLine.tsxnew file mode 100644index 0000000000..65fe6c9860--- /dev/null+++ b/apps/web/src/features/block-agent/ui/ActionLine.tsx@@ -0,0 +1,52 @@+/**+ * An action the session took, rendered as a rule with its label in the middle.+ *+ * The quiet treatment for things that happened *to* the session rather than in+ * it — a model switch, a compaction — so they read as punctuation between+ * turns instead of competing with tool cards for attention.+ */++import type { JSX } from 'solid-js';+import { Show } from 'solid-js';++export interface ActionLineProps {+ /** What happened, e.g. `Model set to opus`. */+ label: string;+ /**+ * The action did not take. Reads in the failure ink, so a refused action+ * cannot be mistaken for one that went through.+ */+ failed?: boolean;+ /**+ * Verbatim detail behind the label — a runtime's error message. Shown on+ * hover rather than inline: the line is punctuation between turns, and an+ * arbitrarily long message would make it the loudest thing in the+ * transcript.+ */+ detail?: string;+ /** Optional glyph before the label. */+ icon?: JSX.Element;+}++export function ActionLine(props: ActionLineProps) {+ return (+ <div+ class="flex w-full items-center gap-4 px-4 py-1 text-xs"+ classList={{+ 'text-ink-extra-muted': !props.failed,+ 'text-failure': props.failed,+ }}+ >+ <span aria-hidden="true" class="h-px flex-1 bg-edge-muted" />+ <span class="flex min-w-0 items-center gap-1.5" title={props.detail}>+ <Show when={props.icon}>+ <span aria-hidden="true" class="flex shrink-0 items-center">+ {props.icon}+ </span>+ </Show>+ <span class="min-w-0 truncate">{props.label}</span>+ </span>+ <span aria-hidden="true" class="h-px flex-1 bg-edge-muted" />+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsxindex 233902c491..3660c1175f 100644--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx@@ -2,14 +2,14 @@* The agent block's composer: the chat input's look and its markdown editing* surface (`MarkdownShell` over a lean `EditorConfigBuilder`), without the* rest of `ChatInput`'s machinery — no mentions, attachments, upload queue,- * model plumbing, or contexts. Visual chrome mirrors- * `@core/component/AI/component/input/ChatInput.tsx`.+ * or contexts; model plumbing arrives through the `modelControl` slot. Visual+ * chrome mirrors `@core/component/AI/component/input/ChatInput.tsx`.*/import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';import { Button, SendButton, Surface } from '@ui';-import { createSignal, Show } from 'solid-js';+import { createSignal, type JSX, Show } from 'solid-js';export interface AgentInputProps {placeholder?: string;@@ -20,6 +20,8 @@ export interface AgentInputProps {/** Receives the composed markdown. */onSend: (markdown: string) => void;onStop?: () => void;+ /** Sits as a pill above the input box, e.g. the session's model selector. */+ modelControl?: JSX.Element;}/** Past this height the controls drop below the text instead of overlaying it. */@@ -62,48 +64,61 @@ export function AgentInput(props: AgentInputProps) {.onChange(setMarkdown);return (- <Surface class="rounded-xl" depth={2} solid>- <div class="relative px-2 py-1.5">- {/* No vertical padding of its own: the shell is min-h-8 and editor+ <div class="flex flex-col gap-1.5">+ {/* Above the surface rather than inside it: the pill belongs to the+ composer, not to the outlined field, so it must not eat into the+ editor's frame or sit within its border. */}+ <Show when={props.modelControl}>+ <div class="flex items-center px-0.5">{props.modelControl}</div>+ </Show>+ <Surface class="rounded-xl" depth={2} solid>+ <div class="relative px-2 py-1.5">+ {/* No vertical padding of its own: the shell is min-h-8 and editorparagraphs carry my-1.5, so the row's py-1.5 is the whole frame —the same 44px single-line height as ChatInput. */}- <div- ref={bodyRef}- class="pl-1 text-sm text-ink"- classList={{- 'pr-10': !isMultiline(),- 'pb-8': isMultiline(),- // While empty only the placeholder renders; keep it to one clipped- // line so it doesn't wrap into the single-line height.- 'overflow-hidden whitespace-nowrap': markdown().trim().length === 0,- }}- >- <MarkdownShell- config={editor}- placeholder={props.placeholder ?? 'Message the agent'}- autofocus={props.autofocus}- />- </div>-- <div class="absolute right-1.5 bottom-1.5">- <Show- when={props.busy && props.onStop}- fallback={- <SendButton tooltip="Send" disabled={!canSend()} onClick={send} />- }+ <div+ ref={bodyRef}+ class="pl-1 text-sm text-ink"+ classList={{+ 'pr-10': !isMultiline(),+ 'pb-8': isMultiline(),+ // While empty only the placeholder renders; keep it to one clipped+ // line so it doesn't wrap into the single-line height.+ 'overflow-hidden whitespace-nowrap':+ markdown().trim().length === 0,+ }}>- <Button- variant="ghost"- size="icon-sm"- label="Stop"- onClick={() => props.onStop?.()}- class="rounded-[11px] size-7.5 text-ink-extra-muted not-disabled:bg-ink/5 not-disabled:hover:bg-ink/10"+ <MarkdownShell+ config={editor}+ placeholder={props.placeholder ?? 'Message the agent'}+ autofocus={props.autofocus}+ />+ </div>++ <div class="absolute right-1.5 bottom-1.5">+ <Show+ when={props.busy && props.onStop}+ fallback={+ <SendButton+ tooltip="Send"+ disabled={!canSend()}+ onClick={send}+ />+ }>- <div class="size-3.5 rounded-sm bg-current" />- </Button>- </Show>+ <Button+ variant="ghost"+ size="icon-sm"+ label="Stop"+ onClick={() => props.onStop?.()}+ class="rounded-[11px] size-7.5 text-ink-extra-muted not-disabled:bg-ink/5 not-disabled:hover:bg-ink/10"+ >+ <div class="size-3.5 rounded-sm bg-current" />+ </Button>+ </Show>+ </div></div>- </div>- </Surface>+ </Surface>+ </div>);}diff --git a/apps/web/src/features/block-agent/ui/AgentModelSelector.tsx b/apps/web/src/features/block-agent/ui/AgentModelSelector.tsxnew file mode 100644index 0000000000..2b2f1e4f4a--- /dev/null+++ b/apps/web/src/features/block-agent/ui/AgentModelSelector.tsx@@ -0,0 +1,74 @@+/**+ * The session's model, as a pill that opens the harness's own model list.+ *+ * Everything here is harness-reported: the options come from the runtime's+ * ACP `configOptions` and the current model is the fold's rejection-safe+ * projection of them, so this component never needs a model registry of its+ * own. Renders nothing until the harness has advertised its models.+ */++import CaretDown from '@phosphor-icons/core/regular/caret-down.svg?component-solid';+import type { ModelOption } from '@service-agent-fold/generated/types';+import { cn, Dropdown } from '@ui';+import { For, Show } from 'solid-js';+import { TextShimmer } from './TextShimmer';++export interface AgentModelSelectorProps {+ /** Current model id, when the fold has learned it. */+ model: string | null;+ /**+ * A change to this model is on the wire. The pill shows it, shimmering,+ * so the switch is visibly in progress rather than appearing not to have+ * registered — the request can block for a whole container resume.+ */+ changingTo?: string;+ /** The models the harness offers, in the order it listed them. */+ options: ModelOption[];+ disabled?: boolean;+ /** Receives the id of the model to switch to. */+ onSelect: (model: string) => void;+}++export function AgentModelSelector(props: AgentModelSelectorProps) {+ const shown = () => props.changingTo ?? props.model;+ const label = () =>+ props.options.find((option) => option.id === shown())?.name ??+ shown() ??+ 'Model';++ return (+ <Show when={props.options.length > 0}>+ <Dropdown placement="top-start">+ <Dropdown.Trigger+ variant="ghost"+ size="sm"+ class="h-6 gap-1 rounded-full bg-ink/5 px-2 text-xs text-ink-muted hover:bg-ink/10"+ disabled={props.disabled || props.changingTo !== undefined}+ >+ <TextShimmer text={label()} active={props.changingTo !== undefined} />+ <CaretDown />+ </Dropdown.Trigger>+ <Dropdown.Content>+ <Dropdown.Group>+ <For each={props.options}>+ {(option) => (+ <Dropdown.Item+ class={cn(+ 'gap-2',+ option.id === shown() && 'text-ink font-medium'+ )}+ title={option.description ?? undefined}+ onSelect={() => {+ if (option.id !== props.model) props.onSelect(option.id);+ }}+ >+ <span class="flex-1 truncate text-xs">{option.name}</span>+ </Dropdown.Item>+ )}+ </For>+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ </Show>+ );+}diff --git a/apps/web/src/features/block-agent/ui/ComposerNotice.tsx b/apps/web/src/features/block-agent/ui/ComposerNotice.tsxnew file mode 100644index 0000000000..a5e4e5fadc--- /dev/null+++ b/apps/web/src/features/block-agent/ui/ComposerNotice.tsx@@ -0,0 +1,26 @@+/**+ * A one-line explanation above the composer for a wait the transcript cannot+ * show.+ *+ * The case it exists for: acting on a session whose sandbox was reaped for+ * idleness. The service resumes the container before it can deliver anything,+ * which takes as long as a cold start, and nothing is written to the session+ * log until it lands — so the transcript stays empty, the pill still says+ * "Disconnected", and the block otherwise looks like it ignored the click.+ */++import { TextShimmer } from './TextShimmer';++export interface ComposerNoticeProps {+ text: string;+ /** Shimmer the text: something is happening, not merely stated. */+ active?: boolean;+}++export function ComposerNotice(props: ComposerNoticeProps) {+ return (+ <div class="flex items-center gap-2 pb-2 text-xs text-ink-extra-muted">+ <TextShimmer text={props.text} active={props.active ?? false} />+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.tsindex f9a3d1e281..55dbd0db66 100644--- a/apps/web/src/features/block-agent/ui/index.ts+++ b/apps/web/src/features/block-agent/ui/index.ts@@ -6,8 +6,14 @@* opencode); see individual file headers.*/+export { ActionLine, type ActionLineProps } from './ActionLine';export { AgentInput, type AgentInputProps } from './AgentInput';+export { AgentModelSelector } from './AgentModelSelector';export { AnimatedNumber } from './AnimatedNumber';+export {+ ComposerNotice,+ type ComposerNoticeProps,+} from './ComposerNotice';export { type CountItem, CountSummary } from './CountSummary';export { DiffChanges, type DiffChangesProps } from './DiffChanges';export { FoldedAnsiText } from './FoldedAnsiText';diff --git a/apps/web/src/features/command/Launcher.tsx b/apps/web/src/features/command/Launcher.tsxindex 584d9cf0ef..d584f91f17 100644--- a/apps/web/src/features/command/Launcher.tsx+++ b/apps/web/src/features/command/Launcher.tsx@@ -1,3 +1,4 @@+import { startPendingSession } from '@app/features/block-agent/context/pending-session';import { openStandaloneReminderComposer } from '@app/features/reminders/reminder-composer';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { setAutomationComposerOpen } from '@block-automation/component';@@ -14,6 +15,9 @@ import { CHAT_INPUT_TEXT_AREA_ID } from '@core/component/AI/component/input/Chatimport { getIconConfig } from '@core/component/EntityIcon';import {ENABLE_ANIMATED_ICONS,+ ENABLE_CHAT_V3_AGENTS,+ ENABLE_CHAT_V3_AGENTS_FLAG,+ ENABLE_CHAT_V3_AGENTS_OVERRIDE,ENABLE_REMINDERS,ENABLE_REMINDERS_FLAG,ENABLE_REMINDERS_OVERRIDE,@@ -66,6 +70,7 @@ import type { Span } from '@macro-inc/observability';import BellSimpleIcon from '@phosphor/bell-simple.svg';import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';import PlusIcon from '@phosphor/plus.svg';+import Robot from '@phosphor/robot.svg';import { createProject } from '@queries/storage/projects';import { makePersisted } from '@solid-primitives/storage';import {@@ -410,6 +415,23 @@ 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': {+ const { openWithSplit } = useSplitLayout();+ setCreateMenuOpen(false, false);+ openWithSplit(+ { type: 'agent', id: startPendingSession() },+ { referredFrom: 'launcher', preferNewSplit: shouldInsert }+ );+ return;+ }}}@@ -432,6 +454,9 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [},},{+ // The pre-agent-session chat, kept on `a` for anyone the new agent flag+ // has not reached. Mutually exclusive with the Coding Agent entry below:+ // both bind `a`, and exactly one is ever enabled.label: 'Agent',icon: WideStar,animatedIcon: AnimatedStarIcon,@@ -442,6 +467,11 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [hotkeyToken: TOKENS.create.chat,altHotkeyToken: TOKENS.create.chatNewSplit,hotkey: 'a',+ // Both `a` entries have to survive registration for the dispatcher to+ // pick between them by condition; the default 'override' would let the+ // later one silently replace the earlier.+ registrationType: 'add',+ enabled: () => !ENABLE_CHAT_V3_AGENTS(),keyDownHandler: () => {runCreateAction('chat', { shouldInsert: pressedKeys().has('shift') });return true;@@ -461,6 +491,23 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [return true;},},+ {+ label: 'Coding Agent',+ icon: Robot,+ description: 'Create agent session',+ launcherHint: 'Sandboxed coding session',+ keywords: ['new', 'make', 'add', 'agent', 'code', 'coder', 'session'],+ blockName: 'agent',+ hotkeyToken: TOKENS.create.agent,+ altHotkeyToken: TOKENS.create.agentNewSplit,+ hotkey: 'a',+ registrationType: 'add',+ enabled: () => ENABLE_CHAT_V3_AGENTS(),+ keyDownHandler: () => {+ runCreateAction('agent', { shouldInsert: pressedKeys().has('shift') });+ return true;+ },+ },{label: 'Skill',icon: SkillIcon,@@ -638,13 +685,16 @@ export function useCreateMenuBlocks(const remindersFlag = useFeatureFlag(ENABLE_REMINDERS_FLAG, {enabledOverride: ENABLE_REMINDERS_OVERRIDE,});+ const agentsFlag = useFeatureFlag(ENABLE_CHAT_V3_AGENTS_FLAG, {+ enabledOverride: ENABLE_CHAT_V3_AGENTS_OVERRIDE,+ });return createMemo(() => {remindersFlag();- return source().filter(- (block) =>- (block.blockName !== 'snippet' || snippetsFlag().enabled) &&- (block.enabled?.() ?? true)- );+ agentsFlag();+ return source().filter((block) => {+ if (block.blockName === 'snippet') return snippetsFlag().enabled;+ return block.enabled?.() ?? true;+ });});}diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsxindex dddbf5a1f1..78da0d17c3 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx@@ -29,7 +29,7 @@ import { NewCallButton } from './NewCallButton';const VIEW_CREATE_BLOCKNAMES: Partial<Record<ListView, CreatableName[]>> = {documents: ['md', 'snippet', 'canvas', 'code', 'project'],tasks: ['task'],- agents: ['chat', 'automation', 'skill'],+ agents: ['agent', 'chat', 'automation', 'skill'],mail: ['email'],channels: ['channel'],folders: ['project'],diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.tsindex b2c447ad7f..d02b492318 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts@@ -144,28 +144,36 @@ function turnEndedActivity(): MagicChipActivity | undefined {const stop = response?.stop;if (!stop) return undefined;- return match(stop)- .with({ kind: 'end_turn' }, () => ({- // A clean end with prose settles before activity is consulted, so- // reaching this arm means the agent closed the turn empty-handed.- label: 'Agent finished without a response',- busy: false,- }))- .with({ kind: 'cancelled' }, () => ({ label: 'Stopped', busy: false }))- .with({ kind: 'refusal' }, () => ({- label: 'Request refused',- busy: false,- }))- .with({ kind: 'max_tokens' }, () => ({- label: 'Response limit reached',- busy: false,- }))- .with({ kind: 'max_turn_requests' }, () => ({- label: 'Turn limit reached',- busy: false,- }))- .with({ kind: 'other' }, ({ reason }) => ({ label: reason, busy: false }))- .exhaustive();+ return (+ match(stop)+ .with({ kind: 'end_turn' }, () => ({+ // A clean end with prose settles before activity is consulted, so+ // reaching this arm means the agent closed the turn empty-handed.+ label: 'Agent finished without a response',+ busy: false,+ }))+ .with({ kind: 'cancelled' }, () => ({ label: 'Stopped', busy: false }))+ .with({ kind: 'refusal' }, () => ({+ label: 'Request refused',+ busy: false,+ }))+ .with({ kind: 'max_tokens' }, () => ({+ label: 'Response limit reached',+ busy: false,+ }))+ .with({ kind: 'max_turn_requests' }, () => ({+ label: 'Turn limit reached',+ busy: false,+ }))+ .with({ kind: 'other' }, ({ reason }) => ({ label: reason, busy: false }))+ // The runtime errored the prompt. The chip has one line, so it says that+ // much and leaves the runtime's message to the session itself.+ .with({ kind: 'failed' }, () => ({+ label: "Agent couldn't answer",+ busy: false,+ }))+ .exhaustive()+ );}/**diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.tsindex 22c6159dcd..24ff721617 100644--- a/apps/web/src/lib/core/hotkey/tokens.ts+++ b/apps/web/src/lib/core/hotkey/tokens.ts@@ -282,6 +282,8 @@ export const TOKENS = {automation: 'create.automation',skill: 'create.skill',reminder: 'create.reminder',+ agent: 'create.agent',+ agentNewSplit: 'create.agentNewSplit',close_menu: 'create.close_menu',},diff --git a/apps/web/src/lib/core/orchestrator.tsx b/apps/web/src/lib/core/orchestrator.tsxindex 7c49490707..d5f53c39be 100644--- a/apps/web/src/lib/core/orchestrator.tsx+++ b/apps/web/src/lib/core/orchestrator.tsx@@ -327,6 +327,22 @@ export type BlockOrchestrator = {* @returns A managed block instance*/createBlockInstance: CreateBlockInstanceFn;+ /**+ * Re-file a mounted instance under a new id, keeping the instance itself+ * alive.+ *+ * For a block whose id is not knowable at mount time: the agent block opens+ * on a client-minted placeholder and learns its real session id when the+ * create resolves (`features/block-agent/context/pending-session.ts`). The+ * mount must survive that — the user is already typing into it — so the+ * registry is re-keyed rather than the block re-created. The element keeps+ * the id it closed over, so `useBlockId()` still reports the placeholder;+ * that is what the block resolves through the pending registry.+ *+ * A no-op when nothing is registered under `fromId`, or when `toId` is+ * already taken.+ */+ rekeyBlockInstance: (type: BlockName, fromId: string, toId: string) => void;};export function createBlockOrchestrator(): BlockOrchestrator {@@ -359,9 +375,17 @@ export function createBlockOrchestrator(): BlockOrchestrator {return ownedHandle;};+ /** Placeholder id -> the id its instance was re-filed under. */+ const rekeyed = new Map<string, string>();+const deregisterBlock = (type: BlockName, id: string) => {- instances.delete(keyOf(type, id));- setBlocks(id, undefined!);+ // The element closed over the id it mounted with, so a re-keyed instance+ // asks to be torn down under its placeholder. Follow the move, or the+ // real entry outlives the mount.+ const current = rekeyed.get(keyOf(type, id)) ?? id;+ rekeyed.delete(keyOf(type, id));+ instances.delete(keyOf(type, current));+ setBlocks(current, undefined!);};const getBlockHandle: GetBlockHandleFn = async function (@@ -424,9 +448,29 @@ export function createBlockOrchestrator(): BlockOrchestrator {return instance;}+ function rekeyBlockInstance(type: BlockName, fromId: string, toId: string) {+ if (fromId === toId) return;+ const from = keyOf(type, fromId);+ const to = keyOf(type, toId);+ const instance = instances.get(from);+ if (!instance || instances.has(to)) return;++ instances.delete(from);+ instances.set(to, { ...instance, key: to, id: toId });+ rekeyed.set(from, toId);++ // The handle's `block.id` is what `getBlockHandle` resolves and what+ // method registrations are looked up by, so it moves with the instance.+ const existing = (blocks as any)[fromId] as BlockWithHandle | undefined;+ if (!existing) return;+ setBlocks(fromId, undefined!);+ setBlocks(toId, { ...existing, id: toId });+ }+return {getBlockHandle,createBlockInstance: createManagedBlockInstance,+ rekeyBlockInstance,};}diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.tsindex eb7d118477..11f7a04073 100644--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts@@ -316,9 +316,11 @@ export type SessionMetadata = {/*** Why a turn stopped.*- * Parsed straight off ACP's `stopReason` wire string by [`FromStr`]: the- * `snake_case` variant names are the wire names, and anything unmodelled- * falls through to [`Self::Other`], so parsing never fails.+ * All but one variant is parsed straight off ACP's `stopReason` wire string+ * by [`FromStr`]: the `snake_case` variant names are the wire names, and+ * anything unmodelled falls through to [`Self::Other`], so parsing never+ * fails. [`Self::Failed`] is the exception - no wire string produces it,+ * because it is what a turn that got no `stopReason` at all stopped for.*/export type StopReason =/** The agent finished its turn. */@@ -336,6 +338,22 @@ export type StopReason =kind: 'other';/** The unrecognized wire value. */reason: string;+ }+ /**+ * The runtime answered the prompt with a JSON-RPC error, so the turn+ * produced no reply and never will.+ *+ * Constructed by the fold, never parsed: an error response carries no+ * `stopReason` to read. Modelled as a stop reason rather than as+ * something alongside one because that is what it is - a turn that+ * ended - and because every reader already asks `stop` whether a turn+ * is still running. A turn left with no stop reason reads as forever in+ * flight, which is how a failed prompt used to wedge a session.+ */+ | {+ kind: 'failed';+ /** The runtime's error message, verbatim. */+ message: string;};/**diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.tsindex a3f8a1f912..cdbce78fcb 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts@@ -4,12 +4,25 @@ import type {AgentSessionLogResponse,AgentSessionResponse,ControlRequest,+ CreateAgentSessionRequest,+ CreateAgentSessionResponse,} from './generated/schemas';const agentHarnessHost = SERVER_HOSTS['agent-harness'];/** Authenticated client for controlling live agent sessions. */export const agentHarnessServiceClient = {+ create(request: CreateAgentSessionRequest) {+ return fetchWithToken<CreateAgentSessionResponse>(+ `${agentHarnessHost}/agent-sessions`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(request),+ }+ );+ },+get(sessionId: string) {return fetchWithToken<AgentSessionResponse>(`${agentHarnessHost}/agent-sessions/${sessionId}`,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.tsindex 4ad8448d83..81cc586d98 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@@ -6,18 +6,30 @@*/import type { CreateAgentSessionRequestBotId } from './createAgentSessionRequestBotId';import type { CreateAgentSessionRequestOwner } from './createAgentSessionRequestOwner';+import type { CreateAgentSessionRequestPrompt } from './createAgentSessionRequestPrompt';import type { CreateAgentSessionRequestRepoUrl } from './createAgentSessionRequestRepoUrl';import type { CreateAgentSessionRequestThread } from './createAgentSessionRequestThread';+import type { CreateAgentSessionRequestWorkspace } from './createAgentSessionRequestWorkspace';/*** Request body for `POST /agent-sessions`.+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.+Clients serialize this, so both derives are used.*/export interface CreateAgentSessionRequest {/** Bot the session runs for. Bot callers may omit it (their own identityis used) and must not name another bot; user callers must supply a-bot they own. */+bot they own. External sessions only: a managed session runs as the+bot its deployment is configured for. */botId?: CreateAgentSessionRequestBotId;/** The user who owns the session. Ignored for user callers, who alwaysown their own sessions; required for bot callers without verified@@ -27,10 +39,16 @@ For bot callers this is a claim, not a verified fact: it is scoped tothe bot's own sessions, but the named user owns the session on thebot's say-so. */owner?: CreateAgentSessionRequestOwner;+ /** First prompt to deliver once the session is running. Managed sessions+only - an external runtime sends its own first prompt through the+control endpoint. Omitted, the session opens idle. */+ prompt?: CreateAgentSessionRequestPrompt;/** Repository nominally checked out at `workspace`. Informational andoptional: having it cloned there is the runtime operator's job. */repoUrl?: CreateAgentSessionRequestRepoUrl;thread?: CreateAgentSessionRequestThread;- /** Absolute directory the bot's harness runs in on its runtime. */- workspace: string;+ /** 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+path baked into its image. */+ workspace?: CreateAgentSessionRequestWorkspace;}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.tsindex 82cd4355c3..ccb9aa474e 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@@ -8,6 +8,7 @@/*** Bot the session runs for. Bot callers may omit it (their own identityis used) and must not name another bot; user callers must supply a-bot they own.+bot they own. External sessions only: a managed session runs as the+bot its deployment is configured for.*/export type CreateAgentSessionRequestBotId = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestPrompt.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestPrompt.tsnew file mode 100644index 0000000000..cca7da399e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestPrompt.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * First prompt to deliver once the session is running. Managed sessions+only - an external runtime sends its own first prompt through the+control endpoint. Omitted, the session opens idle.+ */+export type CreateAgentSessionRequestPrompt = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestWorkspace.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestWorkspace.tsnew file mode 100644index 0000000000..ce7e5d52f8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestWorkspace.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * 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+path baked into its image.+ */+export type CreateAgentSessionRequestWorkspace = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex 92853cbf6b..1fe3feca5d 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts@@ -34,8 +34,10 @@ export * from './controlRequest';export * from './createAgentSessionRequest';export * from './createAgentSessionRequestBotId';export * from './createAgentSessionRequestOwner';+export * from './createAgentSessionRequestPrompt';export * from './createAgentSessionRequestRepoUrl';export * from './createAgentSessionRequestThread';+export * from './createAgentSessionRequestWorkspace';export * from './createAgentSessionResponse';export * from './createSessionThread';export * from './createSessionThreadThreadId';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.jsonindex 421f1f521a..3e1483d1ad 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@@ -566,18 +566,21 @@},"CreateAgentSessionRequest": {"type": "object",- "description": "Request body for `POST /agent-sessions`.\n\nClients serialize this, so both derives are used.",- "required": ["workspace"],+ "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.","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."+ "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."},"owner": {"type": ["string", "null"],"description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions; required for bot callers without verified\nacting-user claims.\n\nFor bot callers this is a claim, not a verified fact: it is scoped to\nthe bot's own sessions, but the named user owns the session on the\nbot's say-so."},+ "prompt": {+ "type": ["string", "null"],+ "description": "First prompt to deliver once the session is running. Managed sessions\nonly - an external runtime sends its own first prompt through the\ncontrol endpoint. Omitted, the session opens idle."+ },"repoUrl": {"type": ["string", "null"],"description": "Repository nominally checked out at `workspace`. Informational and\noptional: having it cloned there is the runtime operator's job."@@ -594,8 +597,8 @@]},"workspace": {- "type": "string",- "description": "Absolute directory the bot's harness runs in on its runtime."+ "type": ["string", "null"],+ "description": "Absolute directory the bot's harness runs in on its runtime. Present\nfor an external session, absent for a managed one, which runs in the\npath baked into its image."}}},diff --git a/crates/agent_fold/src/bin/fold_jsonl.rs b/crates/agent_fold/src/bin/fold_jsonl.rsindex f35a5a33be..fdf0897526 100644--- a/crates/agent_fold/src/bin/fold_jsonl.rs+++ b/crates/agent_fold/src/bin/fold_jsonl.rs@@ -380,6 +380,7 @@ fn render_stop(stop: &StopReason) -> String {StopReason::Refusal => "refused".to_owned(),StopReason::Cancelled => "cancelled".to_owned(),StopReason::Other { reason } => format!("stopped: {reason}"),+ StopReason::Failed { message } => format!("failed: {message}"),}}diff --git a/crates/agent_fold/src/domain/fold.rs b/crates/agent_fold/src/domain/fold.rsindex cc1115c079..d9e43b155e 100644--- a/crates/agent_fold/src/domain/fold.rs+++ b/crates/agent_fold/src/domain/fold.rs@@ -413,7 +413,7 @@ impl FoldState {if self.pending_config_requests.remove(id) || control.is_some() {StepChange::message(control)} else {- StepChange::message(self.end_turn(id, None))+ StepChange::message(self.fail_turn(id, &error.message))}}RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => Vec::new(),@@ -624,6 +624,55 @@ impl FoldState {self.close_turn(stop)}+ /// End the open turn because its prompt was answered with an error.+ ///+ /// The turn has to end even when the agent produced nothing at all -+ /// which is the common case, since a runtime that rejects a prompt+ /// rejects it before writing anything. That is why this cannot go+ /// through [`Self::close_turn`], whose job is to stamp a stop reason on+ /// an agent message that exists: here the agent message is created if+ /// need be, so the failure has somewhere to live and the turn is+ /// unambiguously over.+ fn fail_turn(&mut self, response_id: &RequestId, message: &str) -> Option<Changed> {+ let closes_the_open_turn = self+ .turn+ .as_ref()+ .and_then(|turn| turn.prompt_id.as_ref())+ .is_some_and(|prompt_id| prompt_id == response_id);+ if !closes_the_open_turn {+ return None;+ }++ // Give the turn an agent message if the runtime never opened one, so+ // the stop reason - and with it the error - has a message to sit on.+ let agent = match self.turn.as_ref()?.agent {+ Some(agent) => agent,+ None => {+ let turn_id = self.turn.as_ref()?.id;+ let agent = self.messages.len();+ self.messages.push(FoldedMessage {+ id: turn_id,+ author: Author::Agent,+ request_id: None,+ parts: NonEmpty::one(MessagePart::Text {+ text: String::new(),+ }),+ stop: None,+ });+ if let Some(turn) = self.turn.as_mut() {+ turn.agent = Some(agent);+ }+ agent+ }+ };++ self.turn = None;+ self.messages[agent].stop = Some(StopReason::Failed {+ message: message.to_owned(),+ });+ Some(Changed::new(agent))+ }+/// Handle a `session/update`.fn apply_session_update(&mut self, params: Option<&RawJsonRpcParams>) -> Vec<StepChange> {// Only the `update` field is folded; the rest of the notificationdiff --git a/crates/agent_fold/src/domain/model.rs b/crates/agent_fold/src/domain/model.rsindex 6e529a00d0..e065ac30f1 100644--- a/crates/agent_fold/src/domain/model.rs+++ b/crates/agent_fold/src/domain/model.rs@@ -520,9 +520,11 @@ pub enum PermissionOutcome {/// Why a turn stopped.///-/// Parsed straight off ACP's `stopReason` wire string by [`FromStr`]: the-/// `snake_case` variant names are the wire names, and anything unmodelled-/// falls through to [`Self::Other`], so parsing never fails.+/// All but one variant is parsed straight off ACP's `stopReason` wire string+/// by [`FromStr`]: the `snake_case` variant names are the wire names, and+/// anything unmodelled falls through to [`Self::Other`], so parsing never+/// fails. [`Self::Failed`] is the exception - no wire string produces it,+/// because it is what a turn that got no `stopReason` at all stopped for.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]#[serde(tag = "kind", rename_all = "snake_case")]pub enum StopReason {@@ -541,6 +543,19 @@ pub enum StopReason {/// The unrecognized wire value.reason: String,},+ /// The runtime answered the prompt with a JSON-RPC error, so the turn+ /// produced no reply and never will.+ ///+ /// Constructed by the fold, never parsed: an error response carries no+ /// `stopReason` to read. Modelled as a stop reason rather than as+ /// something alongside one because that is what it is - a turn that+ /// ended - and because every reader already asks `stop` whether a turn+ /// is still running. A turn left with no stop reason reads as forever in+ /// flight, which is how a failed prompt used to wedge a session.+ Failed {+ /// The runtime's error message, verbatim.+ message: String,+ },}impl FromStr for StopReason {diff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rsindex fad5631afc..a3157cccb9 100644--- a/crates/agent_fold/src/domain/test/fold.rs+++ b/crates/agent_fold/src/domain/test/fold.rs@@ -478,3 +478,63 @@ fn replays_local_recordings() {}}}++/// The exchange the local database recorded after a switch to a provider+/// whose credentials were broken: the prompt is answered with a JSON-RPC+/// error and nothing else ever arrives.+const FAILED_PROMPT: &str = concat!(+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s1","prompt":[{"type":"text","text":"hi"}]}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","error":{"code":-32603,"message":"Internal error: Bad Request: bad request: Authorization header is badly formatted"}}}"#,+);++/// A turn whose prompt errors is over, and says why.+///+/// The bug this pins: the turn used to be left with no stop reason at all,+/// which every reader takes to mean "still running" — so one failed prompt+/// wedged the composer against a turn that had already died, and the error+/// itself was dropped on the floor.+#[test]+fn a_prompt_answered_with_an_error_ends_its_turn() {+ let messages = fold(parse_log(FAILED_PROMPT));++ assert_eq!(messages.len(), 2, "the prompt, and the turn that failed");+ let agent = messages.last().expect("an agent message");+ assert_eq!(agent.author, Author::Agent);+ assert_eq!(+ agent.stop,+ Some(StopReason::Failed {+ message: "Internal error: Bad Request: bad request: Authorization header is badly \+ formatted"+ .to_owned()+ }),+ "the runtime's own words, carried verbatim"+ );+}++/// The failure lands on whatever the agent had already said, rather than+/// opening a second message beside it.+#[test]+fn a_turn_that_had_started_talking_fails_in_place() {+ let chunk = concat!(+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","#,+ r#""params":{"sessionId":"s1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"working"}}}}}"#,+ );+ let (prompt, error) = FAILED_PROMPT+ .split_once('\n')+ .expect("the fixture has two frames");+ let log = format!("{prompt}\n{chunk}\n{error}");++ let messages = fold(parse_log(&log));++ assert_eq!(messages.len(), 2, "no extra message for the failure");+ let agent = messages.last().expect("an agent message");+ assert!(matches!(agent.stop, Some(StopReason::Failed { .. })));+ assert_eq!(+ agent.parts.first(),+ Some(&MessagePart::Text {+ text: "working".to_owned()+ }),+ "what the agent managed to say is kept"+ );+}diff --git a/crates/agent_harness/container/opencode.json b/crates/agent_harness/container/opencode.jsonindex b8fa443283..9ee0a2e5a1 100644--- a/crates/agent_harness/container/opencode.json+++ b/crates/agent_harness/container/opencode.json@@ -1,7 +1,12 @@{"$schema": "https://opencode.ai/config.json",- "model": "anthropic/claude-sonnet-5",- "instructions": ["/etc/macro-agent/SYSTEM.md"],+ "enabled_providers": [+ "opencode"+ ],+ "model": "opencode/big-pickle",+ "instructions": [+ "/etc/macro-agent/SYSTEM.md"+ ],"permission": {"*": "allow","external_directory": "deny"@@ -9,7 +14,12 @@"mcp": {"github": {"type": "local",- "command": ["github-mcp-server", "stdio", "--toolsets", "issues,pull_requests"],+ "command": [+ "github-mcp-server",+ "stdio",+ "--toolsets",+ "issues,pull_requests"+ ],"environment": {"GITHUB_PERSONAL_ACCESS_TOKEN": "{env:GITHUB_TOKEN}"},diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex 606bea6084..74a4294891 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -26,7 +26,7 @@ pub struct MentionOrigin {////// Only for managed sessions - the ones whose sandbox this deployment/// provisions. External sessions are opened through-/// [`agent_session::domain::ports::ExternalSessionOpener`] instead: they+/// [`agent_session::domain::ports::SessionOpener`] instead: they/// need no provisioning, no announcement, and no first prompt, so they are/// a plain create rather than a harness command.#[derive(Debug, Clone)]@@ -174,6 +174,12 @@ pub struct SpawnContainer {/// Session-row values that remain deployment configuration for now.#[derive(Debug, Clone)]pub struct SessionDefaults {+ /// The bot managed sessions run as.+ ///+ /// Configuration rather than a constant for the same reason as the+ /// trigger path's: `@claude` and `@codex` are separate deployments of one+ /// binary, differing only in the bot they answer for.+ pub bot_id: BotId,/// Model slug, e.g. `claude`.pub model: String,/// Harness slug, e.g. `opencode`.diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rsindex 740dbc0117..9a39f1be13 100644--- a/crates/agent_harness/src/domain/service.rs+++ b/crates/agent_harness/src/domain/service.rs@@ -213,7 +213,7 @@ where/// The announcement is best-effort: a session a runtime is about to serve/// must not die because the courtesy post failed, most plainly when the bot/// cannot post in the claimed channel.-impl<Sessions, Containers, Announcer, Runtimes> agent_session::domain::ports::ExternalSessionOpener+impl<Sessions, Containers, Announcer, Runtimes> agent_session::domain::ports::SessionOpenerfor AgentHarnessService<Sessions, Containers, Announcer, Runtimes>whereSessions: AgentSessionService,@@ -265,6 +265,84 @@ whereOk(session)}+ /// Provision a sandbox, open a session on it, and deliver the first+ /// prompt if one came with the request.+ ///+ /// Nothing is announced: a managed session opened this way has no+ /// originating mention and no thread to answer back into. The sandbox is+ /// spawned before the session is attached because there is nothing to+ /// attach to until it exists.+ async fn open_managed_session(+ &self,+ request: agent_session::domain::ports::OpenManagedSession,+ ) -> agent_session::domain::error::Result<AgentSession> {+ let defaults = &self.inner.defaults;+ let session = self+ .inner+ .sessions+ .create_session(CreateAgentSessionParams {+ id: AgentSessionId::new(),+ owner_id: request.owner.clone(),+ bot_id: defaults.bot_id,+ thread_id: None,+ originating_message_id: None,+ model: defaults.model.clone(),+ harness: defaults.harness.clone(),+ 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(),+ })+ .await?;++ let container = match self+ .inner+ .containers+ .spawn(SpawnContainer {+ session_id: session.id,+ repo_url: defaults.repo_url.clone(),+ })+ .await+ {+ Ok(container) => container,+ // The row is already persisted, so a sandbox that never arrived+ // would otherwise leave a session claiming to be live. Same+ // handling as the trigger path's open.+ Err(error) => {+ let _ = self+ .inner+ .sessions+ .mark_disconnected(session.id)+ .await+ .inspect_err(|status_error| {+ tracing::error!(+ error = ?status_error,+ session_id = %session.id,+ "failed to mark an unprovisioned session disconnected"+ );+ });+ return Err(into_session_error(error));+ }+ };+ self.inner+ .sessions+ .attach_session(session.id, RuntimeAttachment::solo(container))+ .await?;++ if let Some(prompt) = request.prompt {+ self.inner+ .sessions+ .send_action(+ session.id,+ Some(request.owner),+ AgentAction::prompt(prompt),+ AgentActionId::mint(),+ )+ .await?;+ }++ Ok(session)+ }+async fn find_thread_session(&self,thread_id: macro_uuid::Uuid,diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 79490584e2..47d743d0e5 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -39,7 +39,7 @@ use crate::testing::helpers::agent::FakeAgent;use crate::testing::helpers::announcer::AnnouncerMock;use crate::testing::helpers::containers::{ContainerMock, ContainerSender, MockContainerManager};use agent_session::domain::error::AgentSessionError;-use agent_session::domain::ports::{ExternalSessionOpener as _, OpenExternalAgentSession};+use agent_session::domain::ports::{OpenExternalAgentSession, SessionOpener as _};fn sender() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")@@ -105,6 +105,7 @@ fn harness() -> (announcer.clone(),Arc::clone(&runtimes),SessionDefaults {+ bot_id: BotId::TEST_A,model: "claude".to_owned(),harness: "opencode".to_owned(),repo_url: "https://github.com/macro-inc/macro".to_owned(),diff --git a/crates/agent_harness/src/outbound/daytona/manager.rs b/crates/agent_harness/src/outbound/daytona/manager.rsindex fdfe1326b3..fb0d6ff1dc 100644--- a/crates/agent_harness/src/outbound/daytona/manager.rs+++ b/crates/agent_harness/src/outbound/daytona/manager.rs@@ -242,6 +242,13 @@ impl ContainerManager for DaytonaContainerManager {session_id,repo_url,} = command;+ // `GITHUB_TOKEN` is here for `gh auth setup-git` and the github MCP+ // server. It is also the env var opencode's `github-copilot` provider+ // activates on, so its mere presence makes opencode advertise every+ // Copilot model - and a plain PAT is not a Copilot credential, so each+ // one fails at prompt time with "Authorization header is badly+ // formatted". `container/opencode.json` pins `enabled_providers` to+ // keep that list honest; do not drop that pin while this var is set.let env = Env::from(HashMap::from([("REPO_URL".to_owned(), repo_url),(diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 783d249773..5cc7c01191 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -75,16 +75,42 @@ pub struct OpenExternalAgentSession {pub thread: Option<SessionThread>,}-/// Opens externally-served sessions: rows whose runtime is hosted by the-/// bot's operator and dials in on its own schedule. Implemented by the-/// harness, which owns the session-opening semantics.-pub trait ExternalSessionOpener: Send + Sync + 'static {+/// Everything needed to open a session the server hosts itself.+///+/// Deliberately thin: a managed session runs in a sandbox this deployment+/// provisions from its own configuration, so the bot, the repository and the+/// workspace are not the caller's to choose. There is no originating mention+/// and nothing to announce.+#[derive(Debug, Clone)]+pub struct OpenManagedSession {+ /// The user who owns the session and is credited for its messages.+ pub owner: MacroUserIdStr<'static>,+ /// 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>,+}++/// Opens sessions, however they are served. Implemented by the harness, which+/// owns the session-opening semantics.+///+/// Two openings, because the two runtimes differ in who owns the machine: an+/// external session's runtime is hosted by the bot's operator and dials in on+/// its own schedule, while a managed session's sandbox is provisioned here.+/// That difference is why only one of them takes a workspace.+pub trait SessionOpener: Send + Sync + 'static {/// Open a session and return the persisted row.fn open_external_session(&self,request: OpenExternalAgentSession,) -> impl Future<Output = Result<AgentSession>> + Send;+ /// Provision a sandbox, open a session on it and return the persisted+ /// row, delivering `prompt` once it is attached.+ fn open_managed_session(+ &self,+ request: OpenManagedSession,+ ) -> impl Future<Output = Result<AgentSession>> + Send;+/// The session a thread's mentions already route to, if one exists./// What a caller whose open conflicted needs to recover: redeliveries/// resume serving the existing session instead of being dropped.diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex b2a3af2152..3224b1945c 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -45,8 +45,8 @@ use crate::domain::model::{AgentSession, AgentSessionId, Message, SessionBot, SessionStatus, StoredAgentSessionLog,};use crate::domain::ports::{- AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlEvent, ExternalSessionOpener,- OpenExternalAgentSession, SessionThread,+ AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlEvent,+ OpenExternalAgentSession, OpenManagedSession, SessionOpener, SessionThread,};use crate::domain::service::AgentSessionService;use bots::domain::models::BotId;@@ -648,7 +648,7 @@ pub fn agent_session_create_router<Opener, Bots, Auth, S>(state: CreateSessionState<Opener, Bots, Auth>,) -> Router<S>where- Opener: ExternalSessionOpener,+ Opener: SessionOpener,Bots: BotDirectory,Auth: MacroAuthorizationService,S: Clone + Send + Sync + 'static,@@ -663,16 +663,32 @@ where/// Request body for `POST /agent-sessions`.///+/// 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.+////// Clients serialize this, so both derives are used.-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+#[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.+ /// bot they own. External sessions only: a managed session runs as the+ /// bot its deployment is configured for.pub bot_id: Option<Uuid>,- /// Absolute directory the bot's harness runs in on its runtime.- pub workspace: String,+ /// 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+ /// path baked into its image.+ pub workspace: Option<String>,+ /// First prompt to deliver once the session is running. Managed sessions+ /// only - an external runtime sends its own first prompt through the+ /// control endpoint. Omitted, the session opens idle.+ pub prompt: Option<String>,/// Repository nominally checked out at `workspace`. Informational and/// optional: having it cloned there is the runtime operator's job.pub repo_url: Option<String>,@@ -756,6 +772,8 @@ pub enum CreateSessionApiError {UnparseableOwner,/// The workspace is not an acceptable path.InvalidWorkspace(&'static str),+ /// The request mixed the managed and external shapes.+ MixedSessionShape,/// The thread already routes to a session; carries it for recovery.ThreadSessionExists {/// The existing session, when it could be resolved.@@ -800,6 +818,12 @@ impl IntoResponse for CreateSessionApiError {"owner is not a user id".to_owned(),),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"+ .to_owned(),+ ),Self::ThreadSessionExists { session_id } => {let body = ThreadSessionExistsResponse {message: THREAD_SESSION_EXISTS_MESSAGE.to_owned(),@@ -910,7 +934,7 @@ fn resolve_owner(/// first prompt through the control endpoint.#[tracing::instrument(skip_all, err(Debug))]pub async fn create_agent_session_handler<- Opener: ExternalSessionOpener,+ Opener: SessionOpener,Bots: BotDirectory,Auth: MacroAuthorizationService,>(@@ -918,6 +942,40 @@ pub async fn create_agent_session_handler<caller: MacroAuthorizationExtractor<Auth, UserOrBot>,Json(request): Json<CreateAgentSessionRequest>,) -> Result<(StatusCode, Json<CreateAgentSessionResponse>), CreateSessionApiError> {+ // 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.+ 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()+ {+ return Err(CreateSessionApiError::MixedSessionShape);+ }+ let owner = resolve_owner(&caller.authorization, None)?;+ let session = state+ .opener+ .open_managed_session(OpenManagedSession {+ owner,+ prompt: request.prompt,+ })+ .await?;+ return Ok((+ StatusCode::CREATED,+ Json(CreateAgentSessionResponse {+ session: session.into(),+ }),+ ));+ };++ // An external runtime sends its own first prompt through the control+ // endpoint, so accepting one here would silently drop it.+ if request.prompt.is_some() {+ return Err(CreateSessionApiError::MixedSessionShape);+ }let bot_id = resolve_bot(&caller.authorization, request.bot_id)?;let BotFacts {@@ -944,7 +1002,7 @@ pub async fn create_agent_session_handler<return Err(CreateSessionApiError::NotYourBot);}- validate_workspace(&request.workspace)?;+ validate_workspace(&workspace)?;let owner = resolve_owner(&caller.authorization, request.owner)?;let thread = request.thread.map(|thread| SessionThread {@@ -957,7 +1015,7 @@ pub async fn create_agent_session_handler<.opener.open_external_session(OpenExternalAgentSession {bot_id,- workspace: request.workspace,+ workspace,repo_url: request.repo_url,owner,thread: thread.clone(),diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex 2bf91c7ea2..4816ed5d1b 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -58,9 +58,10 @@ impl BotAuthorizer for SelfBotAuthorizer {#[derive(Default)]struct RecordingOpener {opened: Mutex<Vec<OpenExternalAgentSession>>,+ managed: Mutex<Vec<OpenManagedSession>>,}-impl ExternalSessionOpener for RecordingOpener {+impl SessionOpener for RecordingOpener {async fn open_external_session(&self,request: OpenExternalAgentSession,@@ -85,6 +86,30 @@ impl ExternalSessionOpener for RecordingOpener {Ok(session)}+ async fn open_managed_session(+ &self,+ request: OpenManagedSession,+ ) -> crate::domain::error::Result<AgentSession> {+ let session = AgentSession {+ id: AgentSessionId::TEST_A,+ owner_id: request.owner.clone(),+ thread_id: None,+ thread_channel_id: None,+ originating_message_id: None,+ bot_id: BotId::TEST_A,+ model: "claude".to_owned(),+ harness: "opencode".to_owned(),+ repo_url: Some("https://github.com/macro-inc/macro".to_owned()),+ workspace: crate::MANAGED_CONTAINER_WORKSPACE.to_owned(),+ acp_session_id: None,+ status: SessionStatus::NoMessages,+ created_at: Utc::now(),+ modified_at: Utc::now(),+ };+ self.managed.lock().unwrap().push(request);+ Ok(session)+ }+async fn find_thread_session(&self,_thread_id: Uuid,diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rsindex f3db7726bf..6c9c87b4d3 100644--- a/crates/coding_agent_worker/src/dispatch.rs+++ b/crates/coding_agent_worker/src/dispatch.rs@@ -51,7 +51,11 @@ impl WorkExecutor for Dispatcher {// The bot is the one whose credentials this daemon holds,// and naming another one is refused anyway.bot_id: None,- workspace: self.workspace.path.to_string_lossy().into_owned(),+ workspace: Some(self.workspace.path.to_string_lossy().into_owned()),+ // External sessions carry no first prompt: this daemon is+ // the runtime, and it delivers the mention itself through+ // the control endpoint. Sending one here is refused.+ prompt: None,repo_url: self.workspace.repo_url.clone(),owner: Some(sender.as_ref().to_owned()),thread: Some(CreateSessionThread {diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rsindex 92c77b2683..7c0556cff1 100644--- a/services/agent_harness_service/src/api.rs+++ b/services/agent_harness_service/src/api.rs@@ -5,7 +5,7 @@use agent_harness::inbound::runtime_gateway::{RuntimeGatewayState, runtime_gateway_router};use agent_session::domain::ports::{- AgentSessionNotificationRecipient, BotDirectory, ExternalSessionOpener,+ AgentSessionNotificationRecipient, BotDirectory, SessionOpener,};use agent_session::domain::service::AgentSessionService;use agent_session::inbound::axum_router::{@@ -34,7 +34,7 @@ pub async fn setup_and_serve<T, R, Opener, Bots, Access, Auth>(whereT: AgentSessionService,R: AgentSessionNotificationRecipient,- Opener: ExternalSessionOpener,+ Opener: SessionOpener,Bots: BotDirectory,Access: EntityAccessService,Auth: MacroAuthorizationService,@@ -64,7 +64,7 @@ fn api_router<T, R, Opener, Bots, Access, Auth>(whereT: AgentSessionService,R: AgentSessionNotificationRecipient,- Opener: ExternalSessionOpener,+ Opener: SessionOpener,Bots: BotDirectory,Access: EntityAccessService,Auth: MacroAuthorizationService,diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 4c52100215..793efc73b2 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -210,6 +210,7 @@ async fn main() -> anyhow::Result<()> {announcer,Arc::clone(&runtimes),SessionDefaults {+ bot_id,model: config.harness_model.clone(),harness: config.harness_slug.clone(),repo_url: config.harness_repo_url.clone(),diff --git a/services/coding-agent-worker/container/opencode.json b/services/coding-agent-worker/container/opencode.jsonindex 483314e118..3694177f50 100644--- a/services/coding-agent-worker/container/opencode.json+++ b/services/coding-agent-worker/container/opencode.json@@ -1,6 +1,9 @@{"$schema": "https://opencode.ai/config.json",- "model": "anthropic/claude-sonnet-5",+ "enabled_providers": [+ "opencode"+ ],+ "model": "opencode/big-pickle","permission": {"edit": "allow","bash": "allow",@@ -9,7 +12,12 @@"mcp": {"github": {"type": "local",- "command": ["github-mcp-server", "stdio", "--toolsets", "issues,pull_requests"],+ "command": [+ "github-mcp-server",+ "stdio",+ "--toolsets",+ "issues,pull_requests"+ ],"environment": {"GITHUB_PERSONAL_ACCESS_TOKEN": "{env:GITHUB_TOKEN}"},