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(web): improved MagicChip (#6275)
Wolf Mermelsteinba7e632b5734
diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsxindex 7f69c80a27..2871e3a627 100644--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx@@ -24,16 +24,9 @@ import type { AgentSessionResponse } from '@service-agent-harness/generated/scheimport { createSignal, For, Show } from 'solid-js';import { useAgentSession } from '../context/AgentSessionContext';import { AgentRenameModal } from './AgentRenameModal';+import { harnessTitle } from './compose-agent-session-options';-/** 'claude-code' → 'Claude Code'; the fallback when the fold has no title. */-export function harnessTitle(harness: string | undefined): string {- if (!harness) return 'Agent session';- return harness- .split(/[-_]/)- .filter(Boolean)- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))- .join(' ');-}+export { harnessTitle };/*** Agent-session identity in the split header chrome plus the standard splitdiff --git a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts b/apps/web/src/features/block-agent/component/compose-agent-session-options.tsindex ed90fae615..0f7ba4be91 100644--- a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.ts@@ -41,6 +41,24 @@ export function isManagedHarness(harness: string): boolean {);}+/** 'claude-code' → 'Claude Code'; the fallback when nothing names a harness. */+export function harnessTitle(harness: string | undefined): string {+ if (!harness) return 'Agent session';+ return harness+ .split(/[-_]/)+ .filter(Boolean)+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))+ .join(' ');+}++/** A model's display name, or its id when the runtime lists no name for it. */+export function modelDisplayName(+ id: string,+ available: readonly Pick<ModelOption, 'id' | 'name'>[]+): string {+ return available.find((model) => model.id === id)?.name ?? id;+}+/*** User-facing name for the runtime a persona runs on. Harness ids are* plumbing ("in-memory", "sandbox"); the product names are the coders.@@ -124,9 +142,7 @@ export function personaDefaultLabel(): string {const defaultModel = persona?.defaultModel;if (!defaultModel) return 'Agent default';- const name =- available.find((model) => model.id === defaultModel)?.name ?? defaultModel;- return `Agent default · ${name}`;+ return `Agent default · ${modelDisplayName(defaultModel, available)}`;}/** Short label for the closed model pill. */@@ -135,12 +151,8 @@ export function modelPillLabel(persona: PersonaOption | undefined,available: readonly ModelOption[]): string {- if (override) {- return available.find((model) => model.id === override)?.name ?? override;- }+ if (override) return modelDisplayName(override, available);const defaultModel = persona?.defaultModel;if (!defaultModel) return 'Default model';- return (- available.find((model) => model.id === defaultModel)?.name ?? defaultModel- );+ return modelDisplayName(defaultModel, available);}diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsxindex 5394b4ce1f..d046864aa5 100644--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx@@ -10,44 +10,30 @@* another viewer sees the same live card with its controls disabled and the* owner named as the one it waits on.*- * URL mode never opens anything on its own. The card shows the full URL and- * its host, and only after the user presses Open does it send the consent and- * open a new tab - never an iframe, never a prefetch.+ * The form, URL consent, and unrecognized-request controls are the+ * `LiveElicitation` ones the channel's Magic Chip shares; a Macro user tool+ * under review opens the tool's own composer here.*/-import { CalendarDraftComposer } from '@core/component/AI/component/tool/calendar/DraftComposer';-import { EmailDraftComposer } from '@core/component/AI/component/tool/email/DraftComposer';import type {AnsweredField,AnsweredValue,MessagePart,} from '@service-agent-fold/generated/types';-import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';-import { deserializeToolCall } from '@service-cognition/generated/tools/tool';-import type {- CreateCalendarEvent,- SendEmail,-} from '@service-cognition/generated/tools/types';-import { Button } from '@ui';-import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';-import { createStore } from 'solid-js/store';-import { match } from 'ts-pattern';+import { createMemo, For, Show } from 'solid-js';+import { match, P } from 'ts-pattern';import { useAgentSession } from '../../context/AgentSessionContext';+import { ToolCard } from '../../ui';import {- type FieldValue,- initialValues,- toContent,- validate,-} from '../../state/elicitation-form';-import { createElicitationReviewSink } from '../../state/elicitation-review-sink';-import { ElicitationForm, ToolCard } from '../../ui';+ LiveQuestionCard,+ parseDraftedTool,+ type RespondToElicitation,+ UserToolComposer,+ type UserToolRequest,+} from './LiveElicitation';import { UserToolCall } from './UserToolCall';type ElicitationPartData = Extract<MessagePart, { kind: 'elicitation' }>;-type UserToolRequest = Extract<- ElicitationPartData['request'],- { kind: 'user_tool' }->;function outcomeLabel(part: ElicitationPartData): string {return match(part.outcome)@@ -99,13 +85,6 @@ export function ElicitationPart(props: { part: ElicitationPartData }) {</div></Show>{match(props.part.request)- .with({ kind: 'form' }, (request) => (- <LiveForm- schema={request.schema}- locked={locked()}- onRespond={elicitation.respond}- />- )).with({ kind: 'user_tool' }, (request) => (<LiveUserToolrequest={request}@@ -114,24 +93,16 @@ export function ElicitationPart(props: { part: ElicitationPartData }) {onRespond={elicitation.respond}/>))- .with({ kind: 'url' }, (request) => (- <LiveUrl- url={request.url}- locked={locked()}- onRespond={elicitation.respond}- />- ))- .with({ kind: 'unrecognized' }, (request) => (- <div class="flex flex-col gap-2">- <div class="text-xs text-ink-extra-muted italic">- This client cannot display a "{request.mode}" request.- </div>- <DeclineCancel+ .with(+ { kind: P.union('form', 'url', 'unrecognized') },+ (request) => (+ <LiveQuestionCard+ request={request}locked={locked()}onRespond={elicitation.respond}/>- </div>- ))+ )+ ).exhaustive()}</div></ToolCard>@@ -139,184 +110,47 @@ export function ElicitationPart(props: { part: ElicitationPartData }) {);}-function DeclineCancel(props: {- locked: boolean;- onRespond: (answer: { action: 'decline' } | { action: 'cancel' }) => unknown;-}) {- return (- <>- <Button- variant="outline"- size="xs"- disabled={props.locked}- onClick={() => props.onRespond({ action: 'decline' })}- >- Decline- </Button>- <Button- variant="ghost"- size="xs"- disabled={props.locked}- onClick={() => props.onRespond({ action: 'cancel' })}- >- Cancel- </Button>- </>- );-}--function LiveForm(props: {- schema: Extract<ElicitationPartData['request'], { kind: 'form' }>['schema'];- locked: boolean;- onRespond: (answer: ElicitationAnswer) => unknown;-}) {- const [values, setValues] = createStore(initialValues(props.schema));- const [touched, setTouched] = createSignal(false);- const errors = createMemo(() => validate(props.schema, values));- const shownErrors = () => (touched() ? errors() : {});-- const submit = () => {- if (props.locked) return;- setTouched(true);- if (Object.keys(errors()).length > 0) return;- props.onRespond({- action: 'accept',- content: toContent(props.schema, values),- });- };-- return (- <div class="flex flex-col gap-3">- <ElicitationForm- schema={props.schema}- values={values}- errors={shownErrors()}- disabled={props.locked}- onChange={(name: string, value: FieldValue) => setValues(name, value)}- />- <div class="flex items-center gap-2">- <Button- variant="cta"- size="xs"- disabled={props.locked}- onClick={submit}- >- Submit- </Button>- <DeclineCancel locked={props.locked} onRespond={props.onRespond} />- </div>- </div>- );-}-/**- * A Macro user tool under review, in the tool's own composer: the calendar- * event form for `CreateCalendarEvent`, the email compose for `SendEmail`.- * The composer's Create/Send accepts the review with the whole edited draft;- * Cancel declines it. A draft the tool's schema rejects, or a tool with no- * composer here, falls back to the flat form the agent also sent.+ * A Macro user tool under review, in the tool's own composer. A draft the+ * tool's schema rejects, or a tool with no composer here, falls back to the+ * flat form the agent also sent. The email composer has only Send, so the+ * card adds a Cancel: without it the turn could only be refused from the+ * chip, or by stopping it.*/function LiveUserTool(props: {request: UserToolRequest;toolCall: string;locked: boolean;- onRespond: (answer: ElicitationAnswer) => Promise<boolean>;+ onRespond: RespondToElicitation;}) {const { elicitation } = useAgentSession();- const typed = createMemo(() => {- const call = deserializeToolCall({- id: props.toolCall,- name: props.request.tool,- json: props.request.draft,- });- return call.isOk() ? call.value : undefined;- });- const sink = <T,>() =>- createElicitationReviewSink<T>({- canAnswer: elicitation.canAnswer,- ownerName: elicitation.ownerName,- answering: elicitation.answering,- respond: props.onRespond,- });-- return (- <Switch- fallback={- <LiveForm- schema={props.request.schema}- locked={props.locked}- onRespond={props.onRespond}- />- }- >- <Match when={typed()?.name === 'CreateCalendarEvent' && typed()}>- {(tool) => (- <CalendarDraftComposer- initialData={tool().data as CreateCalendarEvent}- sink={sink<CreateCalendarEvent>()}- previewKey={props.toolCall}- />- )}- </Match>- <Match when={typed()?.name === 'SendEmail' && typed()}>- {(tool) => (- <div class="flex flex-col gap-2">- <EmailDraftComposer- initialData={tool().data as SendEmail}- sink={sink<SendEmail>()}- debugName={`agent-review:${props.toolCall}`}- />- {/* The email composer has only Send; the calendar one answers a- decline through the sink's `onReject`. Without this the turn- could only be refused from the chip, or by stopping it. */}- <div class="flex items-center gap-2">- <Button- variant="outline"- size="xs"- disabled={props.locked}- onClick={() => void props.onRespond({ action: 'decline' })}- >- Cancel- </Button>- </div>- </div>- )}- </Match>- </Switch>+ const drafted = createMemo(() =>+ parseDraftedTool(props.request, props.toolCall)+ );+ const fallback = (+ <LiveQuestionCard+ request={{ kind: 'form', schema: props.request.schema }}+ locked={props.locked}+ onRespond={props.onRespond}+ />);-}--function LiveUrl(props: {- url: string;- locked: boolean;- onRespond: (answer: {- action: 'accept' | 'decline' | 'cancel';- }) => Promise<boolean> | unknown;-}) {- const host = () => urlHost(props.url);- const open = async () => {- if (props.locked) return;- // Consent goes to the agent first so it learns the user agreed even if- // the popup is blocked; the link below stays as the fallback.- const accepted = await props.onRespond({ action: 'accept' });- if (accepted === false) return;- window.open(props.url, '_blank', 'noopener,noreferrer');- };return (- <div class="flex flex-col gap-2">- <div class="text-xs text-ink-muted">- Opens <span class="font-medium text-ink">{host()}</span> in a new tab.- </div>- <div class="rounded-md border border-edge-muted bg-surface px-2 py-1 font-mono text-xs text-ink-muted break-all">- {props.url}- </div>- <div class="flex items-center gap-2">- <Button variant="cta" size="xs" disabled={props.locked} onClick={open}>- Open- </Button>- <DeclineCancel locked={props.locked} onRespond={props.onRespond} />- </div>- </div>+ <Show when={drafted()} fallback={fallback}>+ {(tool) => (+ <UserToolComposer+ tool={tool()}+ toolCall={props.toolCall}+ cancel+ fallback={fallback}+ review={{+ canAnswer: elicitation.canAnswer,+ ownerName: elicitation.ownerName,+ answering: elicitation.answering,+ respond: props.onRespond,+ }}+ />+ )}+ </Show>);}@@ -356,15 +190,6 @@ function ResolvedElicitation(props: { part: ElicitationPartData }) {);}-/** The host of a URL-mode request, for the consent card, or the raw text. */-function urlHost(url: string): string {- try {- return new URL(url).host;- } catch {- return url;- }-}-/** One answer as a line of text. The fold has already resolved the values. */function answerText(value: AnsweredValue): string {return match(value)diff --git a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx b/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsxnew file mode 100644index 0000000000..cc87ba610f--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx@@ -0,0 +1,387 @@+/**+ * The live controls for a question the agent is waiting on, shared by the+ * session's card and the channel's Magic Chip: a form's fields and Submit,+ * a URL's consent, and the refusal of a request this client cannot display.+ *+ * Fields and decisions are separate components over one draft so a surface+ * can place them apart - the chip crops the fields in its area and keeps the+ * decisions on the row beneath - while `LiveQuestionCard` stacks them for+ * the session. A Macro user tool under review opens in the tool's own+ * composer (`UserToolComposer`); a draft the tool's schema rejects falls+ * back to the flat form the agent also sent, through these.+ */++import { CalendarDraftComposer } from '@core/component/AI/component/tool/calendar/DraftComposer';+import { EmailDraftComposer } from '@core/component/AI/component/tool/email/DraftComposer';+import type {+ ElicitationRequest,+ ElicitationSchema,+} from '@service-agent-fold/generated/types';+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';+import { deserializeToolCall } from '@service-cognition/generated/tools/tool';+import type {+ CreateCalendarEvent,+ SendEmail,+} from '@service-cognition/generated/tools/types';+import { Button } from '@ui';+import {+ type Accessor,+ createMemo,+ createSignal,+ type JSX,+ Match,+ Show,+ Switch,+} from 'solid-js';+import { createStore } from 'solid-js/store';+import { match } from 'ts-pattern';+import {+ type FieldValue,+ type FormValues,+ initialValues,+ toContent,+ validate,+} from '../../state/elicitation-form';+import { createElicitationReviewSink } from '../../state/elicitation-review-sink';+import { ElicitationForm } from '../../ui';++export type RespondToElicitation = (+ answer: ElicitationAnswer+) => Promise<boolean>;++/** Every request the shared controls answer; a user tool is the surface's. */+export type LiveQuestionRequest = Exclude<+ ElicitationRequest,+ { kind: 'user_tool' }+>;++/** A form being filled in: what was typed, and what is wrong with it. */+export type FormDraft = {+ schema: ElicitationSchema;+ values: FormValues;+ /** Problems shown to the user - none until the first submit attempt. */+ errors: Accessor<Record<string, string>>;+ setValue: (name: string, value: FieldValue) => void;+ /**+ * The content to accept with, or undefined while the draft is not valid -+ * from then on the problems show.+ */+ content: () => ReturnType<typeof toContent> | undefined;+};++/** A question with the state its controls need, made once per request. */+export type LiveQuestion =+ | { kind: 'form'; draft: FormDraft }+ | { kind: 'url'; url: string }+ | { kind: 'unrecognized'; mode: string };++function createFormDraft(schema: ElicitationSchema): FormDraft {+ const [values, setValues] = createStore(initialValues(schema));+ const [touched, setTouched] = createSignal(false);+ const problems = createMemo(() => validate(schema, values));+ return {+ schema,+ values,+ errors: () => (touched() ? problems() : {}),+ setValue: (name, value) => setValues(name, value),+ content: () => {+ setTouched(true);+ return Object.keys(problems()).length > 0+ ? undefined+ : toContent(schema, values);+ },+ };+}++/** The question's state; call it once per request, under a reactive owner. */+export function createLiveQuestion(request: LiveQuestionRequest): LiveQuestion {+ return match(request)+ .with(+ { kind: 'form' },+ ({ schema }): LiveQuestion => ({+ kind: 'form',+ draft: createFormDraft(schema),+ })+ )+ .with({ kind: 'url' }, ({ url }): LiveQuestion => ({ kind: 'url', url }))+ .with(+ { kind: 'unrecognized' },+ ({ mode }): LiveQuestion => ({ kind: 'unrecognized', mode })+ )+ .exhaustive();+}++function form(question: LiveQuestion) {+ return question.kind === 'form' ? question : undefined;+}++function url(question: LiveQuestion) {+ return question.kind === 'url' ? question : undefined;+}++function unrecognized(question: LiveQuestion) {+ return question.kind === 'unrecognized' ? question : undefined;+}++/** The host of a URL-mode request, for the consent card, or the raw text. */+function urlHost(url: string): string {+ try {+ return new URL(url).host;+ } catch {+ return url;+ }+}++/**+ * What a question shows: a form's fields, a URL and its host, or the notice+ * for a mode this client cannot display.+ */+export function QuestionFields(props: {+ question: LiveQuestion;+ locked: boolean;+}) {+ return (+ <Switch>+ <Match when={form(props.question)}>+ {(question) => (+ <ElicitationForm+ schema={question().draft.schema}+ values={question().draft.values}+ errors={question().draft.errors()}+ disabled={props.locked}+ onChange={question().draft.setValue}+ />+ )}+ </Match>+ <Match when={url(props.question)}>+ {(question) => (+ <div class="flex flex-col gap-2">+ <div class="text-xs text-ink-muted">+ Opens{' '}+ <span class="font-medium text-ink">+ {urlHost(question().url)}+ </span>{' '}+ in a new tab.+ </div>+ <div class="rounded-md border border-edge-muted bg-surface px-2 py-1 font-mono text-xs text-ink-muted break-all">+ {question().url}+ </div>+ </div>+ )}+ </Match>+ <Match when={unrecognized(props.question)}>+ {(question) => (+ <div class="text-xs text-ink-extra-muted italic">+ This client cannot display a "{question().mode}" request.+ </div>+ )}+ </Match>+ </Switch>+ );+}++/**+ * The decisions, as buttons for the caller's row: the question's own+ * (Submit, Open) then Decline and, unless the row is short of room, Cancel.+ *+ * URL mode never opens anything on its own: only after the user presses Open+ * does it send the consent and open a new tab - never an iframe, never a+ * prefetch. Consent goes to the agent first so it learns the user agreed even+ * if the popup is blocked; the URL shown in the fields stays as the fallback.+ */+export function QuestionActions(props: {+ question: LiveQuestion;+ locked: boolean;+ onRespond: RespondToElicitation;+ /** Whether Cancel joins Decline; default yes. */+ cancel?: boolean;+ /** Decline before the question's own button, as the chip's row reads. */+ declineFirst?: boolean;+}) {+ const respond = (answer: ElicitationAnswer) => {+ if (props.locked) return;+ void props.onRespond(answer);+ };+ const submit = (draft: FormDraft) => {+ const content = draft.content();+ if (content) respond({ action: 'accept', content });+ };+ const open = async (target: string) => {+ if (props.locked) return;+ const accepted = await props.onRespond({ action: 'accept' });+ if (!accepted) return;+ window.open(target, '_blank', 'noopener,noreferrer');+ };++ const primary = (+ <Switch>+ <Match when={form(props.question)}>+ {(question) => (+ <Button+ variant="cta"+ size="xs"+ disabled={props.locked}+ onClick={() => submit(question().draft)}+ >+ Submit+ </Button>+ )}+ </Match>+ <Match when={url(props.question)}>+ {(question) => (+ <Button+ variant="cta"+ size="xs"+ disabled={props.locked}+ onClick={() => void open(question().url)}+ >+ Open+ </Button>+ )}+ </Match>+ </Switch>+ );+ const decline = (+ <Button+ variant="outline"+ size="xs"+ disabled={props.locked}+ onClick={() => respond({ action: 'decline' })}+ >+ Decline+ </Button>+ );++ return (+ <>+ {props.declineFirst ? decline : primary}+ {props.declineFirst ? primary : decline}+ <Show when={props.cancel ?? true}>+ <Button+ variant="ghost"+ size="xs"+ disabled={props.locked}+ onClick={() => respond({ action: 'cancel' })}+ >+ Cancel+ </Button>+ </Show>+ </>+ );+}++/** The fields over the decisions, as the session's card lays them out. */+export function LiveQuestionCard(props: {+ request: LiveQuestionRequest;+ locked: boolean;+ onRespond: RespondToElicitation;+ trailing?: JSX.Element;+}) {+ // A part's request never changes, so its state is made once.+ const question = createLiveQuestion(props.request);+ return (+ <div class="flex flex-col gap-3">+ <QuestionFields question={question} locked={props.locked} />+ <div class="flex flex-wrap items-center gap-2">+ <QuestionActions+ question={question}+ locked={props.locked}+ onRespond={props.onRespond}+ />+ <Show when={props.trailing}>+ <span class="ml-auto">{props.trailing}</span>+ </Show>+ </div>+ </div>+ );+}++export type UserToolRequest = Extract<+ ElicitationRequest,+ { kind: 'user_tool' }+>;++/** A drafted Macro user tool, as its schema reads it. */+export type DraftedTool = { name: string; data: unknown };++/** What a review needs to know to act: the session's or the chip's answer. */+export type ReviewInputs = Parameters<typeof createElicitationReviewSink>[0];++/**+ * The draft as the tool's schema reads it, or undefined for a tool this+ * client has no schema for. A draft that a known tool's schema rejects is a+ * contract break between the agent and this build: it is reported, not+ * rendered around, before the caller falls back to the flat form.+ */+export function parseDraftedTool(+ request: UserToolRequest,+ toolCall: string+): DraftedTool | undefined {+ const call = deserializeToolCall({+ id: toolCall,+ name: request.tool,+ json: request.draft,+ });+ if (call.isOk()) return { name: call.value.name, data: call.value.data };+ if (call.error.some((problem) => problem.code === 'parse_error')) {+ console.error(+ '[elicitation] a user tool draft was rejected by its schema',+ {+ tool: request.tool,+ problems: call.error,+ }+ );+ }+ return undefined;+}++/**+ * A drafted Macro user tool in the tool's own composer: the calendar event+ * form for `CreateCalendarEvent`, the email compose for `SendEmail`. The+ * composer's Create/Send accepts the review with the whole edited draft; its+ * Cancel, where it has one, declines. The email composer has only Send, so+ * `cancel` adds a Cancel beneath it for a surface with no other refusal.+ * `fallback` renders a tool this client has no composer for.+ */+export function UserToolComposer(props: {+ tool: DraftedTool;+ toolCall: string;+ review: ReviewInputs;+ cancel?: boolean;+ fallback?: JSX.Element;+}) {+ const sink = <T,>() => createElicitationReviewSink<T>(props.review);+ const locked = () => !props.review.canAnswer() || props.review.answering();+ return (+ <Switch fallback={props.fallback}>+ <Match when={props.tool.name === 'CreateCalendarEvent'}>+ <CalendarDraftComposer+ initialData={props.tool.data as CreateCalendarEvent}+ sink={sink<CreateCalendarEvent>()}+ previewKey={props.toolCall}+ />+ </Match>+ <Match when={props.tool.name === 'SendEmail'}>+ <div class="flex flex-col gap-2">+ <EmailDraftComposer+ initialData={props.tool.data as SendEmail}+ sink={sink<SendEmail>()}+ debugName={`agent-review:${props.toolCall}`}+ />+ <Show when={props.cancel}>+ <div class="flex items-center gap-2">+ <Button+ variant="outline"+ size="xs"+ disabled={locked()}+ onClick={() => void props.review.respond({ action: 'decline' })}+ >+ Cancel+ </Button>+ </div>+ </Show>+ </div>+ </Match>+ </Switch>+ );+}diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsxindex 1aefc32a49..51654dc84f 100644--- a/apps/web/src/features/block-agent/debug/Gallery.tsx+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx@@ -5,10 +5,13 @@*/import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { MagicChipView } from '@core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView';+import type { MagicChipPresentation } from '@core/component/LexicalMarkdown/component/decorator/MagicChip/presentation';import type {ElicitationSchema,FoldedMessage,ModelOption,+ PendingElicitation,ToolStatus,} from '@service-agent-fold/generated/types';import { createSignal, type JSX, onCleanup } from 'solid-js';@@ -440,6 +443,59 @@ const FIXTURE_ELICITATION: ElicitationSchema = {],};+const GALLERY_CHIP_HEADER = {+ agent: 'Cursor Agent',+ model: 'Claude Opus 5 High',+};++/** The chip through a turn: booting, writing, and done. */+function MagicChipStateDemo(props: { presentation: MagicChipPresentation }) {+ return (+ <MagicChipView+ agentSessionId="gallery"+ presentation={props.presentation}+ header={GALLERY_CHIP_HEADER}+ onOpen={() => console.log('[gallery] open session')}+ />+ );+}++/** The chip asking, one per request kind; answers land in the console. */+function MagicChipAskingDemo(props: {+ request: PendingElicitation['request'];+}) {+ const presentation: MagicChipPresentation = {+ kind: 'asking',+ markdown: 'Happy to. One quick question before I go on.',+ asking: {+ question: {+ requestId: 0,+ turn: 0,+ toolCall: null,+ message: 'Which colour, and where should it run?',+ request: props.request,+ },+ canAnswer: true,+ ownerName: 'You',+ },+ };+ return (+ <MagicChipView+ agentSessionId="gallery"+ presentation={presentation}+ header={GALLERY_CHIP_HEADER}+ answer={{+ answering: false,+ respond: async (answer) => {+ console.log('[gallery] elicitation answer', answer);+ return true;+ },+ }}+ onOpen={() => console.log('[gallery] open session')}+ />+ );+}+function ElicitationFormDemo() {const [values, setValues] = createStore(initialValues(FIXTURE_ELICITATION));const errors = () => validate(FIXTURE_ELICITATION, values);@@ -468,6 +524,71 @@ export default function AgentUiGallery() {<ElicitationFormDemo /></Item>+ <Item label="MagicChip (booting, writing, done)">+ <MagicChipStateDemo+ presentation={{+ kind: 'working',+ activity: {+ label: 'Booting agent',+ detail: 'Preparing workspace',+ busy: true,+ },+ }}+ />+ <MagicChipStateDemo+ presentation={{+ kind: 'answering',+ markdown:+ 'The failing test is in `agent_fold`: the batch fold re-derives every message per frame, so the',+ activity: {+ label: 'Running command',+ detail: 'cargo test -p agent_fold',+ busy: true,+ },+ }}+ />+ <MagicChipStateDemo+ presentation={{+ kind: 'settled',+ markdown:+ '**Fixed.** The incremental machine now handles the replay; `cargo test -p agent_fold` passes.',+ }}+ />+ </Item>++ <Item label="MagicChip asking (form, url, tool draft)">+ <MagicChipAskingDemo+ request={{ kind: 'form', schema: FIXTURE_ELICITATION }}+ />+ <MagicChipAskingDemo+ request={{+ kind: 'url',+ elicitationId: 'gh-1',+ url: 'https://github.com/login/device?user_code=ABCD-1234',+ }}+ />+ <MagicChipAskingDemo+ request={{+ kind: 'user_tool',+ tool: 'CreateCalendarEvent',+ draft: {+ title: 'Q3 sync',+ time: {+ kind: 'timed',+ startsAt: '2026-08-20T17:00:00Z',+ endsAt: '2026-08-20T17:30:00Z',+ timeZone: 'UTC',+ },+ attendees: [],+ recurrenceLines: [],+ addGoogleMeet: false,+ eventType: 'default',+ },+ schema: FIXTURE_ELICITATION,+ }}+ />+ </Item>+<Item label="ComposerNotice"><ComposerNotice text="Waking the agent's sandbox…" active /></Item>diff --git a/apps/web/src/features/block-agent/ui/ElicitationForm.test.tsx b/apps/web/src/features/block-agent/ui/ElicitationForm.test.tsxindex 5ed20ff179..f18f96cc45 100644--- a/apps/web/src/features/block-agent/ui/ElicitationForm.test.tsx+++ b/apps/web/src/features/block-agent/ui/ElicitationForm.test.tsx@@ -3,14 +3,10 @@import type { ElicitationSchema } from '@service-agent-fold/generated/types';import { cleanup, fireEvent, render } from '@solidjs/testing-library';import { createStore } from 'solid-js/store';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it } from 'vitest';import { initialValues, toContent, validate } from '../state/elicitation-form';import { ElicitationForm } from './ElicitationForm';-// These cases exercise the real radio and text inputs, without loading the-// unrelated checkbox's UI dependencies.-vi.mock('@ui', () => ({ Checkbox: () => null }));-afterEach(cleanup);function question(customField: string | null): ElicitationSchema {@@ -41,8 +37,34 @@ function question(customField: string | null): ElicitationSchema {};}+function regions(customField: string | null): ElicitationSchema {+ return {+ title: null,+ description: null,+ required: [],+ properties: [+ {+ name: 'regions',+ title: 'Regions',+ description: null,+ schema: {+ type: 'multi_select',+ minItems: null,+ maxItems: null,+ default: ['us'],+ options: [+ { value: 'us', title: 'US', description: null },+ { value: 'eu', title: 'EU', description: null },+ ],+ customField,+ },+ },+ ],+ };+}+function form(schema: ElicitationSchema) {- return render(() => {+ const view = render(() => {const [values, setValues] = createStore(initialValues(schema));return (<>@@ -58,51 +80,86 @@ function form(schema: ElicitationSchema) {</>);});+ const answer = () => JSON.parse(view.getByTestId('answer').textContent!);+ const checked = (element: HTMLElement) =>+ element.getAttribute('aria-checked') === 'true';+ return { ...view, answer, checked };}describe('single-choice elicitation', () => {it('switches from the default option to empty Other, custom text, and back', () => {const view = form(question('colour_custom'));- const red = view.getByRole('radio', { name: 'Red' }) as HTMLInputElement;- const other = view.getByRole('radio', {- name: 'Other',- }) as HTMLInputElement;+ const red = view.getByRole('radio', { name: 'Red' });+ const other = view.getByRole('radio', { name: 'Other' });const text = view.getByPlaceholderText('Type your own answer') as HTMLInputElement;- const answer = () => JSON.parse(view.getByTestId('answer').textContent!);- expect(red.checked).toBe(true);- expect(answer()).toEqual({ colour: 'red' });+ expect(view.checked(red)).toBe(true);+ expect(view.answer()).toEqual({ colour: 'red' });fireEvent.click(other);- expect(other.checked).toBe(true);- expect(red.checked).toBe(false);+ expect(view.checked(other)).toBe(true);+ expect(view.checked(red)).toBe(false);expect(view.getByText('Required')).toBeTruthy();- expect(answer()).toEqual({});+ expect(view.answer()).toEqual({});fireEvent.input(text, { target: { value: 'teal' } });- expect(other.checked).toBe(true);+ expect(view.checked(other)).toBe(true);expect(view.queryByText('Required')).toBeNull();- expect(answer()).toEqual({ colour_custom: 'teal' });+ expect(view.answer()).toEqual({ colour_custom: 'teal' });++ // Pressing Other again keeps what was typed.+ fireEvent.click(other);+ expect(text.value).toBe('teal');fireEvent.click(red);- expect(red.checked).toBe(true);- expect(other.checked).toBe(false);+ expect(view.checked(red)).toBe(true);+ expect(view.checked(other)).toBe(false);expect(text.value).toBe('');- expect(answer()).toEqual({ colour: 'red' });+ expect(view.answer()).toEqual({ colour: 'red' });+ });++ it('is one tab stop whose arrow keys move the choice, Other included', () => {+ const view = form(question('colour_custom'));+ const red = view.getByRole('radio', { name: 'Red' });+ const literal = view.getByRole('radio', { name: 'A literal option' });+ const other = view.getByRole('radio', { name: 'Other' });+ expect(red.tabIndex).toBe(0);+ expect(literal.tabIndex).toBe(-1);+ expect(other.tabIndex).toBe(-1);+ expect(view.getByRole('radiogroup').getAttribute('aria-labelledby')).toBe(+ view.getByText('Colour').id+ );++ fireEvent.keyDown(red, { key: 'ArrowDown' });+ expect(view.checked(literal)).toBe(true);+ expect(literal.tabIndex).toBe(0);+ expect(red.tabIndex).toBe(-1);+ expect(document.activeElement).toBe(literal);++ fireEvent.keyDown(literal, { key: 'ArrowDown' });+ expect(view.checked(other)).toBe(true);+ expect(view.answer()).toEqual({});++ // Wraps, and the Other text box keeps its own arrows.+ fireEvent.keyDown(other, { key: 'ArrowRight' });+ expect(view.checked(red)).toBe(true);+ fireEvent.click(other);+ fireEvent.keyDown(view.getByPlaceholderText('Type your own answer'), {+ key: 'ArrowUp',+ });+ expect(view.checked(other)).toBe(true);});it('typing directly selects Other and keeps an empty Other selected', () => {const view = form(question('colour_custom'));const text = view.getByPlaceholderText('Type your own answer');- const other = view.getByRole('radio', {- name: 'Other',- }) as HTMLInputElement;+ const other = view.getByRole('radio', { name: 'Other' });fireEvent.input(text, { target: { value: 'teal' } });- expect(other.checked).toBe(true);+ expect(view.checked(other)).toBe(true);fireEvent.input(text, { target: { value: '' } });- expect(other.checked).toBe(true);+ expect(view.checked(other)).toBe(true);expect(view.getByText('Required')).toBeTruthy();expect(view.getByTestId('answer').textContent).toBe('{}');});@@ -112,8 +169,36 @@ describe('single-choice elicitation', () => {expect(view.queryByRole('radio', { name: 'Other' })).toBeNull();expect(view.queryByPlaceholderText('Type your own answer')).toBeNull();fireEvent.click(view.getByRole('radio', { name: 'A literal option' }));- expect(JSON.parse(view.getByTestId('answer').textContent!)).toEqual({- colour: '__custom',- });+ expect(view.answer()).toEqual({ colour: '__custom' });+ });+});++describe('multi-choice elicitation', () => {+ it('toggles options and never sends them alongside a custom answer', () => {+ const view = form(regions('regions_custom'));+ const us = view.getByRole('checkbox', { name: 'US' });+ const eu = view.getByRole('checkbox', { name: 'EU' });+ const other = view.getByRole('checkbox', { name: 'Other' });+ const text = view.getByPlaceholderText('Type your own answer');++ expect(view.checked(us)).toBe(true);+ expect(view.answer()).toEqual({ regions: ['us'] });++ fireEvent.click(eu);+ expect(view.answer()).toEqual({ regions: ['us', 'eu'] });++ fireEvent.input(text, { target: { value: 'mars' } });+ expect(view.checked(other)).toBe(true);+ expect(view.checked(us)).toBe(false);+ expect(view.answer()).toEqual({ regions_custom: 'mars' });++ fireEvent.click(us);+ expect(view.checked(other)).toBe(false);+ expect(view.answer()).toEqual({ regions: ['us'] });+ });++ it('has no Other row when the schema allows none', () => {+ const view = form(regions(null));+ expect(view.queryByRole('checkbox', { name: 'Other' })).toBeNull();});});diff --git a/apps/web/src/features/block-agent/ui/ElicitationForm.tsx b/apps/web/src/features/block-agent/ui/ElicitationForm.tsxindex 8dfffac875..f1c6194128 100644--- a/apps/web/src/features/block-agent/ui/ElicitationForm.tsx+++ b/apps/web/src/features/block-agent/ui/ElicitationForm.tsx@@ -2,14 +2,25 @@* The fields of an elicitation form, props-in JSX-out. The caller owns the* draft values and validation (`state/elicitation-form.ts`) and the card* chrome; this renders one control per property and reports edits.+ *+ * Choices are rows in the app's menu idiom - a box that fills accent when+ * chosen, round for one answer and square for several - rather than the+ * browser's radio and checkbox glyphs, so a question reads like the rest of+ * the session. The rows keep their ARIA roles (`radio`, `checkbox`); a radio+ * group keeps one tab stop and moves its choice with the arrow keys, as the+ * native control does.*/+import CheckIcon from '@phosphor/check.svg';import type {+ ElicitationOption,ElicitationProperty,+ ElicitationPropertySchema,ElicitationSchema,} from '@service-agent-fold/generated/types';-import { Checkbox } from '@ui';-import { For, Show } from 'solid-js';+import { cn } from '@ui';+import { For, type JSX, Show } from 'solid-js';+import { match, P } from 'ts-pattern';import type {FieldValue,FormValues,@@ -29,19 +40,406 @@ function textOf(value: FieldValue | undefined): string {return value?.kind === 'text' ? value.text : '';}-const INPUT_CLASS =- 'w-full rounded-md border border-edge-muted bg-surface px-2 py-1 text-sm text-ink placeholder:text-ink-placeholder focus:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50';+/** A typed answer: free text, or a number while it is being typed. */+function TextInput(props: {+ type: 'text' | 'email' | 'url' | 'number';+ value: string;+ disabled?: boolean;+ step?: number | 'any';+ min?: number;+ max?: number;+ onInput: (text: string) => void;+}) {+ return (+ <input+ type={props.type}+ class="h-8 w-full rounded-md border border-edge-muted bg-transparent px-2 text-sm text-ink outline-none transition-colors placeholder:text-ink-placeholder hover:border-edge focus:border-accent disabled:opacity-50"+ disabled={props.disabled}+ step={props.step}+ min={props.min}+ max={props.max}+ value={props.value}+ onInput={(event) => props.onInput(event.currentTarget.value)}+ />+ );+}++type SingleSelect = Extract<ElicitationPropertySchema, { type: 'string' }>;+type MultiSelect = Extract<ElicitationPropertySchema, { type: 'multi_select' }>;+type MultiSelectValue = Extract<FieldValue, { kind: 'multi_select' }>;++/** The box beside a choice: round for one answer, square for several. */+function ChoiceBox(props: { checked: boolean; multiple: boolean }) {+ return (+ <span+ aria-hidden="true"+ class={cn(+ 'mt-0.5 inline-flex size-3.5 shrink-0 items-center justify-center border text-surface transition-colors',+ props.multiple ? 'rounded-sm' : 'rounded-full',+ props.checked+ ? 'border-accent bg-accent'+ : 'border-edge-muted bg-transparent group-hover:border-edge'+ )}+ >+ <CheckIcon class={cn('size-2.5', !props.checked && 'hidden')} />+ </span>+ );+}++function OptionText(props: { option: ElicitationOption }) {+ return (+ <span class="flex min-w-0 flex-col">+ <span>{props.option.title ?? props.option.value}</span>+ <Show when={props.option.description}>+ {(description) => (+ <span class="text-xs text-ink-extra-muted">{description()}</span>+ )}+ </Show>+ </span>+ );+}++function ChoiceRow(props: {+ role: 'radio' | 'checkbox';+ checked: boolean;+ disabled?: boolean;+ /** A radio group's one tab stop is its chosen (or first) row. */+ tabIndex?: number;+ onSelect: () => void;+ option: ElicitationOption;+}) {+ return (+ <button+ type="button"+ role={props.role}+ aria-checked={props.checked}+ tabIndex={props.tabIndex}+ class="group flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left text-sm text-ink outline-none not-disabled:hover:bg-ink/5 focus-visible:bg-ink/5 disabled:opacity-50"+ disabled={props.disabled}+ onClick={props.onSelect}+ >+ <ChoiceBox checked={props.checked} multiple={props.role === 'checkbox'} />+ <OptionText option={props.option} />+ </button>+ );+}++/**+ * The free-text escape a select may offer: its box selects it like any other+ * choice, and typing selects it too.+ */+function OtherRow(props: {+ role: 'radio' | 'checkbox';+ checked: boolean;+ disabled?: boolean;+ tabIndex?: number;+ text: string;+ onSelect: () => void;+ onInput: (text: string) => void;+}) {+ return (+ <div+ class="group flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm text-ink outline-none"+ classList={{+ 'hover:bg-ink/5': !props.disabled,+ 'opacity-50': props.disabled,+ }}+ >+ <button+ type="button"+ role={props.role}+ aria-checked={props.checked}+ aria-label="Other"+ tabIndex={props.tabIndex}+ class="flex items-center outline-none"+ disabled={props.disabled}+ onClick={props.onSelect}+ >+ <ChoiceBox+ checked={props.checked}+ multiple={props.role === 'checkbox'}+ />+ </button>+ <input+ type="text"+ class="min-w-0 flex-1 bg-transparent text-sm text-ink outline-none placeholder:text-ink-placeholder"+ placeholder="Type your own answer"+ disabled={props.disabled}+ value={props.text}+ onInput={(event) => props.onInput(event.currentTarget.value)}+ />+ </div>+ );+}++/**+ * One answer from several, with the keyboard behavior of a native radio+ * group: one tab stop (the chosen row, or the first), and the arrow keys+ * move the choice - onto the Other row too, when there is one.+ */+function SingleChoice(props: {+ field: SingleSelect;+ value: FieldValue | undefined;+ disabled?: boolean;+ labelId: string;+ onChange: (next: FieldValue) => void;+}) {+ let group: HTMLDivElement | undefined;+ const selection = (): SingleSelection =>+ props.value?.kind === 'single_select'+ ? props.value.selection+ : { kind: 'none' };+ const pick = (selection: SingleSelection) =>+ props.onChange({ kind: 'single_select', selection });+ const chosen = (option: ElicitationOption) => {+ const current = selection();+ return current.kind === 'option' && current.value === option.value;+ };+ const customText = () => {+ const current = selection();+ return current.kind === 'custom' ? current.text : '';+ };+ // The rows in order, Other last; the tab stop is the chosen one, else the+ // first.+ const rowCount = () =>+ props.field.options.length + (props.field.customField ? 1 : 0);+ const chosenIndex = () => {+ const current = selection();+ if (current.kind === 'option') {+ const index = props.field.options.findIndex(+ (option) => option.value === current.value+ );+ return index === -1 ? 0 : index;+ }+ return current.kind === 'custom' ? props.field.options.length : 0;+ };+ const tabIndex = (index: number) => (index === chosenIndex() ? 0 : -1);+ const choose = (index: number) => {+ const option = props.field.options[index];+ if (option) pick({ kind: 'option', value: option.value });+ else if (selection().kind !== 'custom') pick({ kind: 'custom', text: '' });+ group?.querySelectorAll<HTMLElement>('[role="radio"]')[index]?.focus();+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (props.disabled) return;+ // Arrows inside the Other text box edit it; only a row moves the choice.+ if (+ !(event.target instanceof Element) ||+ event.target.getAttribute('role') !== 'radio'+ )+ return;+ const step = match(event.key)+ .with('ArrowDown', 'ArrowRight', () => 1)+ .with('ArrowUp', 'ArrowLeft', () => -1)+ .otherwise(() => 0);+ if (step === 0) return;+ event.preventDefault();+ choose((chosenIndex() + step + rowCount()) % rowCount());+ };++ return (+ <div+ ref={group}+ role="radiogroup"+ aria-labelledby={props.labelId}+ class="flex flex-col"+ onKeyDown={onKeyDown}+ >+ <For each={props.field.options}>+ {(option, index) => (+ <ChoiceRow+ role="radio"+ option={option}+ checked={chosen(option)}+ disabled={props.disabled}+ tabIndex={tabIndex(index())}+ onSelect={() => pick({ kind: 'option', value: option.value })}+ />+ )}+ </For>+ <Show when={props.field.customField}>+ <OtherRow+ role="radio"+ checked={selection().kind === 'custom'}+ disabled={props.disabled}+ tabIndex={tabIndex(props.field.options.length)}+ text={customText()}+ onSelect={() => {+ if (selection().kind !== 'custom')+ pick({ kind: 'custom', text: '' });+ }}+ onInput={(text) => pick({ kind: 'custom', text })}+ />+ </Show>+ </div>+ );+}++function MultiChoice(props: {+ field: MultiSelect;+ value: FieldValue | undefined;+ disabled?: boolean;+ labelId: string;+ onChange: (next: FieldValue) => void;+}) {+ const current = (): MultiSelectValue =>+ props.value?.kind === 'multi_select'+ ? props.value+ : { kind: 'multi_select', values: [], custom: undefined };+ // A custom answer and chosen options never travel together, so picking one+ // side clears the other.+ const toggle = (option: ElicitationOption) => {+ const { values } = current();+ props.onChange({+ kind: 'multi_select',+ values: values.includes(option.value)+ ? values.filter((item) => item !== option.value)+ : [...values, option.value],+ custom: undefined,+ });+ };+ const custom = () => current().custom;++ return (+ <div role="group" aria-labelledby={props.labelId} class="flex flex-col">+ <For each={props.field.options}>+ {(option) => (+ <ChoiceRow+ role="checkbox"+ option={option}+ checked={current().values.includes(option.value)}+ disabled={props.disabled}+ onSelect={() => toggle(option)}+ />+ )}+ </For>+ <Show when={props.field.customField}>+ <OtherRow+ role="checkbox"+ checked={custom() !== undefined}+ disabled={props.disabled}+ text={custom() ?? ''}+ onSelect={() =>+ props.onChange({+ kind: 'multi_select',+ values: [],+ custom: custom() === undefined ? '' : undefined,+ })+ }+ onInput={(text) =>+ props.onChange({ kind: 'multi_select', values: [], custom: text })+ }+ />+ </Show>+ </div>+ );+}++const YES: ElicitationOption = {+ value: 'true',+ title: 'Yes',+ description: null,+};++function FieldControl(props: {+ field: ElicitationPropertySchema;+ value: FieldValue | undefined;+ disabled?: boolean;+ /** The id of the field's title, for the groups' `aria-labelledby`. */+ labelId: string;+ onChange: (next: FieldValue) => void;+}): JSX.Element {+ return (+ <>+ {match(props.field)+ .with(+ { type: 'string', options: P.when((options) => options.length > 0) },+ (field) => (+ <SingleChoice+ field={field}+ value={props.value}+ disabled={props.disabled}+ labelId={props.labelId}+ onChange={props.onChange}+ />+ )+ )+ .with({ type: 'string' }, (field) => (+ <TextInput+ type={+ field.format === 'email'+ ? 'email'+ : field.format === 'uri'+ ? 'url'+ : 'text'+ }+ disabled={props.disabled}+ value={textOf(props.value)}+ onInput={(text) => props.onChange({ kind: 'text', text })}+ />+ ))+ .with({ type: 'number' }, { type: 'integer' }, (field) => (+ <TextInput+ type="number"+ disabled={props.disabled}+ step={field.type === 'integer' ? 1 : 'any'}+ min={field.minimum ?? undefined}+ max={field.maximum ?? undefined}+ value={textOf(props.value)}+ onInput={(text) => props.onChange({ kind: 'text', text })}+ />+ ))+ .with({ type: 'boolean' }, () => {+ const checked = () =>+ props.value?.kind === 'boolean' && props.value.checked;+ return (+ <ChoiceRow+ role="checkbox"+ option={YES}+ checked={checked()}+ disabled={props.disabled}+ onSelect={() =>+ props.onChange({ kind: 'boolean', checked: !checked() })+ }+ />+ );+ })+ .with({ type: 'multi_select' }, (field) => (+ <MultiChoice+ field={field}+ value={props.value}+ disabled={props.disabled}+ labelId={props.labelId}+ onChange={props.onChange}+ />+ ))+ .with({ type: 'unrecognized' }, (field) => (+ <div class="text-xs text-ink-extra-muted italic">+ This client cannot display a {field.typeName} field.+ </div>+ ))+ .exhaustive()}+ </>+ );+}++/** The id of a field's title, which its group of choices is labelled by. */+function labelIdOf(property: ElicitationProperty) {+ return `elicitation-${property.name}-label`;+}function Field(props: {property: ElicitationProperty;required: boolean;error?: string;- children: unknown;+ children: JSX.Element;}) {return (<div class="flex flex-col gap-1"><div class="flex items-baseline gap-1 text-xs text-ink-muted">- <span>{props.property.title ?? props.property.name}</span>+ <span id={labelIdOf(props.property)}>+ {props.property.title ?? props.property.name}+ </span><Show when={props.required}><span aria-hidden="true" class="text-failure">*@@ -53,7 +451,7 @@ function Field(props: {<div class="text-xs text-ink-extra-muted">{description()}</div>)}</Show>- {props.children as never}+ {props.children}<Show when={props.error}>{(error) => <div class="text-xs text-failure">{error()}</div>}</Show>@@ -72,220 +470,21 @@ export function ElicitationForm(props: ElicitationFormProps) {)}</Show><For each={props.schema.properties}>- {(property) => {- const value = () => props.values[property.name];- const selection = (): SingleSelection => {- const current = value();- return current?.kind === 'single_select'- ? current.selection- : { kind: 'none' };- };- const field = property.schema;- const set = (next: FieldValue) => props.onChange(property.name, next);- return (- <Field- property={property}- required={required(property.name)}- error={props.errors[property.name]}- >- {field.type === 'string' && field.options.length > 0 ? (- <div class="flex flex-col gap-1" role="radiogroup">- <For each={field.options}>- {(option) => {- const checked = () => {- const current = selection();- return (- current.kind === 'option' &&- current.value === option.value- );- };- return (- <label class="flex items-start gap-2 text-sm text-ink">- <input- type="radio"- class="mt-1 accent-accent"- name={`elicitation-${property.name}`}- value={option.value}- checked={checked()}- disabled={props.disabled}- onChange={() =>- set({- kind: 'single_select',- selection: {- kind: 'option',- value: option.value,- },- })- }- />- <span class="flex flex-col">- <span>{option.title ?? option.value}</span>- <Show when={option.description}>- {(description) => (- <span class="text-xs text-ink-extra-muted">- {description()}- </span>- )}- </Show>- </span>- </label>- );- }}- </For>- <Show when={field.customField}>- <label class="flex items-start gap-2 text-sm text-ink">- <input- type="radio"- class="mt-1 accent-accent"- name={`elicitation-${property.name}`}- checked={selection().kind === 'custom'}- disabled={props.disabled}- onChange={() =>- set({- kind: 'single_select',- selection: { kind: 'custom', text: '' },- })- }- />- <span class="flex min-w-0 flex-1 flex-col gap-1">- <span>Other</span>- <input- type="text"- class={INPUT_CLASS}- placeholder="Type your own answer"- disabled={props.disabled}- value={(() => {- const current = selection();- return current.kind === 'custom'- ? current.text- : '';- })()}- onInput={(event) =>- set({- kind: 'single_select',- selection: {- kind: 'custom',- text: event.currentTarget.value,- },- })- }- />- </span>- </label>- </Show>- </div>- ) : field.type === 'string' ? (- <input- type={- field.format === 'email'- ? 'email'- : field.format === 'uri'- ? 'url'- : 'text'- }- class={INPUT_CLASS}- disabled={props.disabled}- value={textOf(value())}- onInput={(event) =>- set({ kind: 'text', text: event.currentTarget.value })- }- />- ) : field.type === 'number' || field.type === 'integer' ? (- <input- type="number"- class={INPUT_CLASS}- disabled={props.disabled}- step={field.type === 'integer' ? 1 : 'any'}- min={field.minimum ?? undefined}- max={field.maximum ?? undefined}- value={textOf(value())}- onInput={(event) =>- set({ kind: 'text', text: event.currentTarget.value })- }- />- ) : field.type === 'boolean' ? (- <Checkbox- checked={(() => {- const current = value();- return current?.kind === 'boolean' && current.checked;- })()}- disabled={props.disabled}- onChange={(checked) => set({ kind: 'boolean', checked })}- >- <Checkbox.Control />- <Checkbox.Label class="text-sm text-ink">Yes</Checkbox.Label>- </Checkbox>- ) : field.type === 'multi_select' ? (- <div class="flex flex-col gap-1">- <For each={field.options}>- {(option) => {- const selected = () => {- const current = value();- return current?.kind === 'multi_select'- ? current.values- : [];- };- return (- <Checkbox- checked={selected().includes(option.value)}- disabled={props.disabled}- onChange={(checked) =>- set({- kind: 'multi_select',- values: checked- ? [...selected(), option.value]- : selected().filter(- (item) => item !== option.value- ),- custom: undefined,- })- }- >- <Checkbox.Control />- <Checkbox.Label class="flex flex-col text-sm text-ink">- <span>{option.title ?? option.value}</span>- <Show when={option.description}>- {(description) => (- <span class="text-xs text-ink-extra-muted">- {description()}- </span>- )}- </Show>- </Checkbox.Label>- </Checkbox>- );- }}- </For>- <Show when={field.customField}>- <input- type="text"- class={INPUT_CLASS}- placeholder="Or type your own answer"- disabled={props.disabled}- value={(() => {- const current = value();- return current?.kind === 'multi_select'- ? (current.custom ?? '')- : '';- })()}- onInput={(event) =>- set({- kind: 'multi_select',- values: [],- custom: event.currentTarget.value,- })- }- />- </Show>- </div>- ) : (- <div class="text-xs text-ink-extra-muted italic">- This client cannot display a {field.typeName} field.- </div>- )}- </Field>- );- }}+ {(property) => (+ <Field+ property={property}+ required={required(property.name)}+ error={props.errors[property.name]}+ >+ <FieldControl+ field={property.schema}+ value={props.values[property.name]}+ disabled={props.disabled}+ labelId={labelIdOf(property)}+ onChange={(next) => props.onChange(property.name, next)}+ />+ </Field>+ )}</For></div>);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsxindex 8b4ab4a55d..d1a8d72261 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx@@ -13,6 +13,7 @@ export const MagicChip: Component<MagicChipDecoratorProps> = (props) => {<MagicChipViewagentSessionId={props.agentSessionId}presentation={model.presentation()}+ header={model.header()}answer={{answering: model.elicitation.answering(),respond: model.elicitation.respond,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsxindex 72331a8d6a..f42a1c217b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx@@ -20,6 +20,14 @@ vi.mock('@core/component/LexicalMarkdown/theme', () => ({channelTheme: {},}));+// The chip answers a form with the real `ElicitationForm`; the rest of the+// block-agent ui barrel reaches the composer, comments, and a socket.+vi.mock('@app/features/block-agent/ui', async () => ({+ ElicitationForm: (+ await import('@app/features/block-agent/ui/ElicitationForm')+ ).ElicitationForm,+}));+afterEach(cleanup);const LONG_PATH =@@ -29,9 +37,69 @@ function answerArea(container: HTMLElement) {return container.querySelector('[data-magic-chip-answer]');}+function header(container: HTMLElement) {+ return container.querySelector('[data-magic-chip-header]');+}++/** The header's label, which opens the session and carries the preview. */+function headerLabel(container: HTMLElement) {+ return header(container)?.querySelector('button');+}++/** The question, in the answer area's place while one is live. */+function askingBody(container: HTMLElement) {+ return container.querySelector('[data-magic-chip-asking]');+}++/** The decisions at the bottom right of the question. */+function decisions(container: HTMLElement) {+ return container.querySelector('[data-magic-chip-decisions]');+}++// The composers are the chat block's real editors over calendar and email+// queries; the chip's job is to mount the right one and wire its sink, so+// each stub exposes the sink through two buttons.+type StubSink = {+ canAct: () => boolean;+ onExecute: (args: unknown) => Promise<boolean>;+ onReject: () => Promise<boolean>;+};+function composerStub(kind: string) {+ return (props: { initialData: unknown; sink: StubSink }) => (+ <div data-testid={`${kind}-composer`} data-can-act={props.sink.canAct()}>+ {/* A widget the area cannot recognize as a control. */}+ <div data-testid="composer-surface" />+ <button+ type="button"+ data-testid="composer-execute"+ onClick={() => void props.sink.onExecute(props.initialData)}+ />+ <button+ type="button"+ data-testid="composer-reject"+ onClick={() => void props.sink.onReject()}+ />+ </div>+ );+}+vi.mock('@core/component/AI/component/tool/calendar/DraftComposer', () => ({+ CalendarDraftComposer: composerStub('calendar'),+}));+vi.mock('@core/component/AI/component/tool/email/DraftComposer', () => ({+ EmailDraftComposer: composerStub('email'),+}));++const respond = vi.fn<(answer: ElicitationAnswer) => Promise<boolean>>();+const onOpen = vi.fn();++beforeEach(() => {+ respond.mockReset();+ respond.mockResolvedValue(true);+ onOpen.mockReset();+});+describe('MagicChipView', () => {- it('reserves the answer height and shows the activity row while working', () => {- const onOpen = vi.fn();+ it('reserves the answer height and reads the activity in the header while working', () => {const { container } = render(() => (<MagicChipViewagentSessionId="session"@@ -45,28 +113,43 @@ describe('MagicChipView', () => {const card = container.querySelector('[data-magic-chip-preview]');expect(card?.className).toContain('rounded-lg');- expect(card?.className).not.toContain('border-accent');- expect(answerArea(container)?.className).toContain('h-22');+ expect(answerArea(container)?.className).toMatch(/(^|\s)h-41(\s|$)/);expect(container.querySelector('[data-testid="chip-markdown"]')).toBeNull();expect(container.querySelector('[data-magic-chip-pending]')).toBeTruthy();- expect(container.querySelector('.bg-skeleton')).toBeNull();- const footer = card?.querySelector('button');- expect(footer?.textContent).toContain('Booting agent');- expect(footer?.getAttribute('data-message-reply-preview')).toBe(+ const label = headerLabel(container);+ expect(label?.textContent).toContain('Booting agent');+ expect(label?.getAttribute('data-message-reply-preview')).toBe('Booting agent');// Nothing to expand yet, so the answer area leads to the session too.expect(answerArea(container)?.getAttribute('aria-expanded')).toBeNull();fireEvent.click(answerArea(container)!);- fireEvent.click(footer!);- expect(onOpen).toHaveBeenCalledTimes(2);+ fireEvent.click(label!);+ fireEvent.click(screen.getByLabelText('Open in session'));+ expect(onOpen).toHaveBeenCalledTimes(3);+ });++ it('names the persona and its model in the header', () => {+ const { container } = render(() => (+ <MagicChipView+ agentSessionId="session"+ presentation={{+ kind: 'working',+ activity: { label: 'Thinking', busy: true },+ }}+ header={{ agent: 'Cursor Agent', model: 'Claude Opus 5' }}+ />+ ));+ const label = headerLabel(container);+ expect(label?.textContent).toContain('Cursor Agent');+ expect(label?.textContent).toContain('Claude Opus 5');+ expect(label?.textContent).toContain('Thinking');});it('keeps the same answer height once the answer streams in', () => {- const onOpen = vi.fn();const { container } = render(() => (<MagicChipViewagentSessionId="session"@@ -79,24 +162,24 @@ describe('MagicChipView', () => {/>));- expect(answerArea(container)?.className).toContain('h-22');+ expect(answerArea(container)?.className).toMatch(/(^|\s)h-41(\s|$)/);expect(container.querySelector('[data-magic-chip-pending]')).toBeNull();const clip = container.querySelector('[data-magic-chip-clip]');expect(clip?.className).toContain('overflow-hidden');+ // With prose in the area, the reply previews it, not the header.const preview = container.querySelector('[data-message-reply-preview]');expect(preview?.textContent).toBe('Hello from the agent');+ expect(+ headerLabel(container)?.getAttribute('data-message-reply-preview')+ ).toBeNull();- const footer = container.querySelector('[data-magic-chip-preview] button');- expect(footer?.textContent).toContain('Writing response');- expect(footer?.textContent).not.toContain('Open session');-- fireEvent.click(footer!);+ expect(headerLabel(container)?.textContent).toContain('Writing response');+ fireEvent.click(screen.getByLabelText('Open in session'));expect(onOpen).toHaveBeenCalledTimes(1);});it('expands the answer in place on click and collapses again', () => {- const onOpen = vi.fn();const { container } = render(() => (<MagicChipViewagentSessionId="session"@@ -109,44 +192,26 @@ describe('MagicChipView', () => {const clip = () => container.querySelector('[data-magic-chip-clip]');const fade = () => container.querySelector('[data-magic-chip-fade]');expect(area.getAttribute('aria-expanded')).toBe('false');- expect(area.className).toContain('h-22');+ expect(area.className).toMatch(/(^|\s)h-41(\s|$)/);expect(fade()).toBeTruthy();- expect(area.textContent).toContain('Show more');fireEvent.click(area);expect(area.getAttribute('aria-expanded')).toBe('true');- expect(area.className).not.toContain('h-22');+ expect(area.className).not.toMatch(/(^|\s)h-41(\s|$)/);+ expect(area.className).toContain('min-h-41');expect(clip()?.className).not.toContain('overflow-hidden');expect(fade()).toBeNull();- expect(area.textContent).toContain('Show less');expect(onOpen).not.toHaveBeenCalled();fireEvent.keyDown(area, { key: 'Enter' });expect(area.getAttribute('aria-expanded')).toBe('false');- expect(area.className).toContain('h-22');+ expect(area.className).toMatch(/(^|\s)h-41(\s|$)/);expect(clip()?.className).toContain('overflow-hidden');expect(fade()).toBeTruthy();- expect(area.textContent).toContain('Show more');expect(onOpen).not.toHaveBeenCalled();});- it('keeps the disclosure hint out of the reply preview text', () => {- const { container } = render(() => (- <MagicChipView- agentSessionId="session"- presentation={{ kind: 'settled', markdown: 'All done' }}- />- ));-- fireEvent.click(answerArea(container)!);- expect(answerArea(container)?.textContent).toContain('Show less');- expect(- container.querySelector('[data-message-reply-preview]')?.textContent- ).toBe('All done');- });-- it('labels the settled footer Open session', () => {- const onOpen = vi.fn();+ it('reads Done in the header once the turn settles', () => {const { container } = render(() => (<MagicChipViewagentSessionId="session"@@ -155,10 +220,10 @@ describe('MagicChipView', () => {/>));- expect(answerArea(container)?.className).toContain('h-22');- const footer = container.querySelector('[data-magic-chip-preview] button');- expect(footer?.textContent).toContain('Open session');- fireEvent.click(footer!);+ expect(answerArea(container)?.className).toMatch(/(^|\s)h-41(\s|$)/);+ expect(headerLabel(container)?.textContent).toContain('Done');+ expect(headerLabel(container)?.textContent).not.toContain('Open session');+ fireEvent.click(headerLabel(container)!);expect(onOpen).toHaveBeenCalledTimes(1);});@@ -184,15 +249,6 @@ describe('MagicChipView', () => {});});-vi.mock('@app/features/block-agent/component/parts/UserToolCall', () => ({- EventDraft: (props: { event: { title: string } }) => (- <div data-testid="event-draft">{props.event.title}</div>- ),- EmailDraft: (props: { email: { subject: string } }) => (- <div data-testid="email-draft">{props.email.subject}</div>- ),-}));-const draft = {title: 'Q3 sync',time: {@@ -231,18 +287,16 @@ function asking(canAnswer: boolean, markdown = ''): MagicChipPresentation {};}-const respond = vi.fn<(answer: ElicitationAnswer) => Promise<boolean>>();-const onOpen = vi.fn();--beforeEach(() => {- respond.mockReset();- respond.mockResolvedValue(true);- onOpen.mockReset();-});+/** The text of the decisions row, in order. */+function decisionLabels(container: HTMLElement) {+ return [...(decisions(container)?.querySelectorAll('button') ?? [])].map(+ (button) => button.textContent?.trim()+ );+}-describe('MagicChipView asking', () => {- it('summarizes the draft and sends it whole on Create, declines on Cancel', () => {- const { getByTestId, getByText } = render(() => (+describe('MagicChipView reviewing a tool draft', () => {+ it('mounts the draft in its composer with Dismiss and the session on the row', () => {+ const view = render(() => (<MagicChipViewagentSessionId="session"presentation={asking(true, 'Setting that up.')}@@ -250,23 +304,72 @@ describe('MagicChipView asking', () => {onOpen={onOpen}/>));- expect(getByTestId('chip-markdown').textContent).toBe('Setting that up.');- expect(getByTestId('event-draft').textContent).toBe('Q3 sync');- expect(getByText('Waiting for you')).not.toBeNull();+ // The question takes the area in the passage's place.+ const area = answerArea(view.container)!;+ expect(area.className).toMatch(/(^|\s)h-41(\s|$)/);+ expect(view.queryByTestId('chip-markdown')).toBeNull();+ const body = askingBody(view.container);+ expect(area.contains(body)).toBe(true);+ expect(body?.textContent).toContain('Create calendar event?');+ // The tool's own composer, editable in place, with Create as its own.+ const composer = view.getByTestId('calendar-composer');+ expect(body?.contains(composer)).toBe(true);+ expect(composer.dataset.canAct).toBe('true');++ expect(decisionLabels(view.container)).toEqual([+ 'Dismiss',+ 'Open in session',+ ]);+ expect(header(view.container)?.textContent).toContain('Waiting for you');+ expect(+ headerLabel(view.container)?.getAttribute('data-message-reply-preview')+ ).toBe('Waiting for you · Create calendar event?');- fireEvent.click(getByText('Create event'));+ fireEvent.click(view.getByTestId('composer-execute'));expect(respond).toHaveBeenCalledWith({action: 'accept',content: { draft: JSON.stringify(draft) },});- fireEvent.click(getByText('Cancel'));+ fireEvent.click(view.getByTestId('composer-reject'));expect(respond).toHaveBeenLastCalledWith({ action: 'decline' });- fireEvent.click(getByText('Edit in session'));- expect(onOpen).toHaveBeenCalled();+ fireEvent.click(view.getByText('Dismiss'));+ expect(respond).toHaveBeenLastCalledWith({ action: 'decline' });+ fireEvent.click(view.getByText('Open in session'));+ fireEvent.click(view.getByLabelText('Open in session'));+ expect(onOpen).toHaveBeenCalledTimes(2);+ });++ it('expands the question in place, and its buttons do not toggle it', () => {+ const view = render(() => (+ <MagicChipView+ agentSessionId="session"+ presentation={asking(true)}+ answer={{ answering: false, respond }}+ onOpen={onOpen}+ />+ ));+ const area = answerArea(view.container)!;+ const clip = () => view.container.querySelector('[data-magic-chip-clip]');+ expect(area.getAttribute('aria-expanded')).toBe('false');+ expect(clip()?.className).toContain('overflow-hidden');+ expect(view.container.querySelector('[data-magic-chip-fade]')).toBeTruthy();++ fireEvent.click(view.getByText('Dismiss'));+ fireEvent.click(view.getByTestId('composer-execute'));+ fireEvent.click(view.getByTestId('composer-surface'));+ expect(area.getAttribute('aria-expanded')).toBe('false');++ fireEvent.click(area);+ expect(area.getAttribute('aria-expanded')).toBe('true');+ expect(area.className).not.toMatch(/(^|\s)h-41(\s|$)/);+ expect(area.className).toContain('min-h-41');+ expect(clip()?.className).not.toContain('overflow-hidden');+ expect(view.container.querySelector('[data-magic-chip-fade]')).toBeNull();+ expect(onOpen).not.toHaveBeenCalled();});- it('a viewer who is not the owner sees who is being waited on and can only open the session', () => {- const { queryByText, getByText } = render(() => (+ it('a viewer who is not the owner sees the draft read-only and who is being waited on', () => {+ const view = render(() => (<MagicChipViewagentSessionId="session"presentation={asking(false)}@@ -274,29 +377,36 @@ describe('MagicChipView asking', () => {onOpen={onOpen}/>));- expect(getByText('Waiting for Alice Owner')).not.toBeNull();- expect(queryByText('Create event')).toBeNull();- expect(queryByText('Cancel')).toBeNull();- fireEvent.click(getByText('Open session'));+ expect(header(view.container)?.textContent).toContain(+ 'Waiting for Alice Owner'+ );+ // The composer is there to read, but cannot act for a viewer.+ expect(view.getByTestId('calendar-composer').dataset.canAct).toBe('false');+ fireEvent.click(view.getByTestId('composer-execute'));+ expect(decisions(view.container)).toBeNull();+ fireEvent.click(view.getByLabelText('Open in session'));expect(onOpen).toHaveBeenCalled();expect(respond).not.toHaveBeenCalled();});it('holds the buttons while an answer is on the wire', () => {- const { getByText } = render(() => (+ const view = render(() => (<MagicChipViewagentSessionId="session"presentation={asking(true)}answer={{ answering: true, respond }}/>));- fireEvent.click(getByText('Create event'));+ expect(view.getByTestId('calendar-composer').dataset.canAct).toBe('false');+ fireEvent.click(view.getByTestId('composer-execute'));+ fireEvent.click(view.getByText('Dismiss'));expect(respond).not.toHaveBeenCalled();});-});-describe('MagicChipView review transition', () => {- it('keeps the expanded answer while a review appears and the agent continues', () => {+ it('keeps the expanded answer while a review takes the area and gives it back', () => {+ // Answering unmounts the question while the composer's effects wind+ // down; nothing may read a `<Show>` accessor that has gone stale.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const [presentation, setPresentation] = createSignal<MagicChipPresentation>({kind: 'answering',@@ -317,16 +427,226 @@ describe('MagicChipView review transition', () => {expect(area.getAttribute('aria-expanded')).toBe('true');setPresentation(asking(true, 'Setting that up.'));- expect(view.getByText('Create event')).toBeTruthy();+ expect(view.getByTestId('calendar-composer')).toBeTruthy();+ expect(view.queryByTestId('chip-markdown')).toBeNull();expect(answerArea(view.container)).toBe(area);- expect(area.getAttribute('aria-expanded')).toBe('true');+ fireEvent.click(view.getByText('Dismiss'));setPresentation({ kind: 'settled', markdown: 'Created the event.' });- expect(view.queryByText('Create event')).toBeNull();+ expect(view.queryByTestId('calendar-composer')).toBeNull();+ expect(askingBody(view.container)).toBeNull();expect(view.getByText('Created the event.')).toBeTruthy();+ expect(header(view.container)?.textContent).toContain('Done');expect(answerArea(view.container)).toBe(area);expect(area.getAttribute('aria-expanded')).toBe('true');- fireEvent.click(view.getByText('Open session'));+ expect(+ warn.mock.calls.some((call) => String(call[0]).includes('stale'))+ ).toBe(false);+ warn.mockRestore();+ });+});++const colourForm = {+ kind: 'form' as const,+ schema: {+ title: null,+ description: null,+ required: ['question_0'],+ properties: [+ {+ name: 'question_0',+ title: 'Best colour',+ description: null,+ schema: {+ type: 'string' as const,+ minLength: null,+ maxLength: null,+ pattern: null,+ format: null,+ default: null,+ options: [+ { value: 'Red', title: 'Red', description: null },+ { value: 'Blue', title: 'Blue', description: null },+ ],+ customField: 'question_0_custom',+ },+ },+ ],+ },+};++function askingQuestion(+ request: Extract<+ MagicChipPresentation,+ { kind: 'asking' }+ >['asking']['question']['request'],+ options: { canAnswer?: boolean; requestId?: number; markdown?: string } = {}+): MagicChipPresentation {+ return {+ kind: 'asking',+ markdown: options.markdown ?? '',+ asking: {+ question: {+ requestId: options.requestId ?? 0,+ turn: 0,+ toolCall: null,+ message: "What's the best colour?",+ request,+ },+ canAnswer: options.canAnswer ?? true,+ ownerName: 'Alice Owner',+ },+ };+}++describe('MagicChipView asking a form', () => {+ it('offers the choices in the area and Decline, Submit, the session on the row', () => {+ const view = render(() => (+ <MagicChipView+ agentSessionId="session"+ presentation={askingQuestion(colourForm)}+ answer={{ answering: false, respond }}+ onOpen={onOpen}+ />+ ));+ const area = answerArea(view.container)!;+ expect(area.className).toMatch(/(^|\s)h-41(\s|$)/);+ const body = askingBody(view.container);+ expect(body?.contains(view.getByRole('radio', { name: 'Red' }))).toBe(true);+ expect(body?.textContent).toContain("What's the best colour?");+ expect(decisionLabels(view.container)).toEqual([+ 'Decline',+ 'Submit',+ 'Open in session',+ ]);+ expect(view.queryByText('Cancel')).toBeNull();+ expect(+ view.container.querySelector('[data-magic-chip-pending]')+ ).toBeNull();++ // A required question refuses an empty submit.+ fireEvent.click(view.getByText('Submit'));+ expect(respond).not.toHaveBeenCalled();+ expect(view.getByText('Required')).toBeTruthy();++ // Picking a choice is the choice's, not a toggle of the area.+ fireEvent.click(view.getByRole('radio', { name: 'Blue' }));+ expect(area.getAttribute('aria-expanded')).toBe('false');+ fireEvent.click(view.getByText('Submit'));+ expect(respond).toHaveBeenCalledWith({+ action: 'accept',+ content: { question_0: 'Blue' },+ });++ fireEvent.click(view.getByText('Decline'));+ expect(respond).toHaveBeenLastCalledWith({ action: 'decline' });+ fireEvent.click(view.getByText('Open in session'));expect(onOpen).toHaveBeenCalledOnce();});++ it('types a custom answer and sends it under the custom key', () => {+ const view = render(() => (+ <MagicChipView+ agentSessionId="session"+ presentation={askingQuestion(colourForm)}+ answer={{ answering: false, respond }}+ />+ ));+ fireEvent.input(view.getByPlaceholderText('Type your own answer'), {+ target: { value: 'teal' },+ });+ fireEvent.click(view.getByText('Submit'));+ expect(respond).toHaveBeenCalledWith({+ action: 'accept',+ content: { question_0_custom: 'teal' },+ });+ });++ it('keeps what was typed across a refresh of the same question, and starts clean for a new one', () => {+ const [presentation, setPresentation] = createSignal(+ askingQuestion(colourForm)+ );+ const view = render(() => (+ <MagicChipView+ agentSessionId="session"+ presentation={presentation()}+ answer={{ answering: false, respond }}+ />+ ));+ fireEvent.click(view.getByRole('radio', { name: 'Blue' }));++ // The same request, pushed again by a metadata refresh.+ setPresentation(askingQuestion(colourForm));+ expect(+ view.getByRole('radio', { name: 'Blue' }).getAttribute('aria-checked')+ ).toBe('true');++ setPresentation(askingQuestion(colourForm, { requestId: 1 }));+ expect(+ view.getByRole('radio', { name: 'Blue' }).getAttribute('aria-checked')+ ).toBe('false');+ });++ it('a viewer who is not the owner sees the choices locked and no decisions', () => {+ const view = render(() => (+ <MagicChipView+ agentSessionId="session"+ presentation={askingQuestion(colourForm, { canAnswer: false })}+ answer={{ answering: false, respond }}+ onOpen={onOpen}+ />+ ));+ expect(header(view.container)?.textContent).toContain(+ 'Waiting for Alice Owner'+ );+ const red = view.getByRole('radio', { name: 'Red' }) as HTMLButtonElement;+ expect(red.disabled).toBe(true);+ expect(decisions(view.container)).toBeNull();+ expect(view.queryByText('Submit')).toBeNull();+ expect(view.queryByText('Decline')).toBeNull();+ });++ it('a url request shows the host and opens only after consent', async () => {+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);+ const view = render(() => (+ <MagicChipView+ agentSessionId="session"+ presentation={askingQuestion({+ kind: 'url',+ elicitationId: 'gh-1',+ url: 'https://agent.example.com/connect?e=gh-1',+ })}+ answer={{ answering: false, respond }}+ />+ ));+ expect(view.getByText('agent.example.com')).toBeTruthy();+ expect(open).not.toHaveBeenCalled();+ fireEvent.click(view.getByText('Open'));+ await Promise.resolve();+ await Promise.resolve();+ expect(respond).toHaveBeenCalledWith({ action: 'accept' });+ expect(open).toHaveBeenCalledWith(+ 'https://agent.example.com/connect?e=gh-1',+ '_blank',+ 'noopener,noreferrer'+ );+ open.mockRestore();+ });++ it('a request this client cannot display can still be declined', () => {+ const view = render(() => (+ <MagicChipView+ agentSessionId="session"+ presentation={askingQuestion({+ kind: 'unrecognized',+ mode: 'hologram',+ raw: {},+ })}+ answer={{ answering: false, respond }}+ />+ ));+ expect(view.getByText(/cannot display a "hologram" request/)).toBeTruthy();+ fireEvent.click(view.getByText('Decline'));+ expect(respond).toHaveBeenCalledWith({ action: 'decline' });+ });});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsxindex 57e82a0147..8dede74aa3 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx@@ -1,8 +1,13 @@import {- EmailDraft,- EventDraft,-} from '@app/features/block-agent/component/parts/UserToolCall';-import { DRAFT_FIELD } from '@app/features/block-agent/state/elicitation-review-sink';+ createLiveQuestion,+ type DraftedTool,+ type LiveQuestion,+ parseDraftedTool,+ QuestionActions,+ QuestionFields,+ type RespondToElicitation,+ UserToolComposer,+} from '@app/features/block-agent/component/parts/LiveElicitation';import {StaticMarkdown,StaticMarkdownContext,@@ -10,13 +15,7 @@ import {import { channelTheme } from '@core/component/LexicalMarkdown/theme';import { PulsingStar } from '@entity/components/PulsingStar';import ArrowUpRight from '@phosphor/arrow-up-right.svg';-import CaretRight from '@phosphor/caret-right.svg';import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';-import { deserializeToolCall } from '@service-cognition/generated/tools/tool';-import type {- CreateCalendarEvent,- SendEmail,-} from '@service-cognition/generated/tools/types';import { Button, Layer } from '@ui';import {type Component,@@ -25,27 +24,37 @@ import {Match,Show,Switch,+ untrack,} from 'solid-js';-import { match } from 'ts-pattern';-import type {- MagicChipActivity,- MagicChipPresentation,- MagicChipQuestion,+import {+ type MagicChipActivity,+ type MagicChipHeader,+ type MagicChipPresentation,+ type MagicChipQuestion,+ presentationStatus,} from './presentation';function answerMarkdown(presentation: MagicChipPresentation) {return presentation.kind === 'working' ? undefined : presentation.markdown;}-function currentActivity(presentation: MagicChipPresentation) {- return presentation.kind === 'working' || presentation.kind === 'answering'- ? presentation.activity- : undefined;+const TEXT_ENTRY =+ 'input, textarea, [contenteditable]:not([contenteditable="false"])';++const CONTROL = `${TEXT_ENTRY}, button, select, a, label, [role="button"], [role="option"], [role="menuitem"]`;++/**+ * A press on one of the area's own controls is that control's, not a toggle+ * of the area (which is itself a button, so the search stops at it).+ */+function isControl(target: EventTarget | null, area: Element) {+ if (!(target instanceof Element) || target === area) return false;+ const control = target.closest(CONTROL);+ return control !== null && control !== area && area.contains(control);}-function replyPreview(activity: MagicChipActivity | undefined) {- if (!activity) return 'Open session';- return `${activity.label}${activity.detail ? ` ${activity.detail}` : ''}`;+function isTextEntry(target: EventTarget | null) {+ return target instanceof Element && target.closest(TEXT_ENTRY) !== null;}/** What the chip's answer to a question does. */@@ -56,128 +65,40 @@ export type MagicChipAnswer = {};/**- * A question the agent stopped to ask, kept small for a channel thread: what- * is being asked, a read-only summary of a user tool's draft, and the two- * decisions. Editing the draft, or answering a form field by field, happens- * in the session - "Edit in session" opens it. Anyone but the session's- * owner sees the summary and who is being waited on.+ * The chip's side of a question: the shared live state for a form, URL, or+ * unknown mode, or a Macro user tool's draft for the tool's own composer. A+ * draft the tool's schema rejects falls back to the flat form the agent also+ * sent, as the session does.*/-const AskingCard: Component<{- agentSessionId: string;- asking: MagicChipQuestion;- answer?: MagicChipAnswer;- onOpen?: () => void;-}> = (props) => {- const request = () => props.asking.question.request;- const userTool = createMemo(() => {- const current = request();- if (current.kind !== 'user_tool') return undefined;- const call = deserializeToolCall({- id:- props.asking.question.toolCall ??- String(props.asking.question.requestId),- name: current.tool,- json: current.draft,- });- return call.isOk() ? { tool: call.value, draft: current.draft } : undefined;- });- const locked = () =>- !props.asking.canAnswer || props.answer?.answering === true;- const waitingFor = () =>- props.asking.canAnswer- ? 'Waiting for you'- : `Waiting for ${props.asking.ownerName}`;- const confirmLabel = () =>- match(userTool()?.tool.name)- .with('CreateCalendarEvent', () => 'Create event')- .with('SendEmail', () => 'Send email')- .otherwise(() => 'Confirm');- const respond = (answer: ElicitationAnswer) => {- if (locked()) return;- void props.answer?.respond(answer);- };- // The chip sends the draft as the agent wrote it; edits need the session's- // composer.- const accept = () =>- respond({- action: 'accept',- content:- request().kind === 'user_tool'- ? { [DRAFT_FIELD]: JSON.stringify(userTool()?.draft ?? {}) }- : {},- });+type ChipQuestion =+ | LiveQuestion+ | { kind: 'user_tool'; tool: DraftedTool; toolCall: string };- return (- <div- class="flex w-full min-w-0 flex-col gap-2 rounded-lg border border-edge-muted bg-surface p-3"- data-magic-chip={props.agentSessionId}- data-magic-chip-asking- data-message-reply-preview={`${waitingFor()} · ${props.asking.question.message}`}- >- <div class="flex items-center gap-2 text-xs">- <span class="shrink-0 font-semibold text-ink-muted" aria-live="polite">- {waitingFor()}- </span>- <span class="min-w-0 truncate text-ink">- {props.asking.question.message}- </span>- </div>- <Switch>- <Match- when={userTool()?.tool.name === 'CreateCalendarEvent' && userTool()}- >- {(reviewed) => (- <EventDraft event={reviewed().tool.data as CreateCalendarEvent} />- )}- </Match>- <Match when={userTool()?.tool.name === 'SendEmail' && userTool()}>- {(reviewed) => (- <EmailDraft- email={reviewed().tool.data as SendEmail}- inFlight={false}- />- )}- </Match>- </Switch>- <div class="flex flex-wrap items-center gap-2">- <Show when={props.asking.canAnswer}>- <Show when={userTool()}>- <Button- variant="cta"- size="xs"- disabled={locked()}- onMouseDown={(event) => event.preventDefault()}- onClick={accept}- >- {confirmLabel()}- </Button>- </Show>- <Button- variant="outline"- size="xs"- disabled={locked()}- onMouseDown={(event) => event.preventDefault()}- onClick={() => respond({ action: 'decline' })}- >- {userTool() ? 'Cancel' : 'Decline'}- </Button>- </Show>- <Button- variant="ghost"- size="xs"- disabled={!props.onOpen}- onMouseDown={(event) => event.preventDefault()}- onClick={props.onOpen}- >- {props.asking.canAnswer- ? userTool()- ? 'Edit in session'- : 'Answer in session'- : 'Open session'}- </Button>- </div>- </div>- );+function createChipQuestion(asking: MagicChipQuestion): ChipQuestion {+ const request = asking.question.request;+ if (request.kind !== 'user_tool') return createLiveQuestion(request);+ const toolCall =+ asking.question.toolCall ?? String(asking.question.requestId);+ const tool = parseDraftedTool(request, toolCall);+ return tool+ ? { kind: 'user_tool', tool, toolCall }+ : createLiveQuestion({ kind: 'form', schema: request.schema });+}++function reviewedTool(question: ChipQuestion) {+ return question.kind === 'user_tool' ? question : undefined;+}++function liveQuestion(question: ChipQuestion): LiveQuestion | undefined {+ return question.kind === 'user_tool' ? undefined : question;+}++/** What the chip is waiting on, with the state behind its controls. */+type ChipAsking = {+ asking: MagicChipQuestion;+ question: ChipQuestion;+ locked: boolean;+ respond: RespondToElicitation;};/** The shimmering label plus its muted detail. */@@ -212,173 +133,331 @@ const ActivityText: Component<{ activity: MagicChipActivity }> = (props) => ();/**- * Holds the answer's space until the agent writes: the chat's own waiting- * glyph, pulsing while the agent is busy and still while it is not (a- * disconnected session, a turn that ended without prose).+ * The decisions for a live question, on the row under the area: the refusal+ * first (`Dismiss` for a tool draft, `Decline` for a question), the go-ahead+ * for a question (`Submit`, `Open`), then the way into the session. A tool+ * draft's go-ahead is its composer's own Send or Create, in the area.*/-const AnswerPending: Component<{ busy: boolean }> = (props) => (+const AskingActions: Component<ChipAsking & { onOpen?: () => void }> = (+ props+) => (+ <>+ <Switch>+ <Match when={reviewedTool(props.question)}>+ <Button+ variant="outline"+ size="xs"+ disabled={props.locked}+ onClick={() => void props.respond({ action: 'decline' })}+ >+ Dismiss+ </Button>+ </Match>+ <Match when={liveQuestion(props.question)}>+ {(question) => (+ <QuestionActions+ question={question()}+ locked={props.locked}+ onRespond={props.respond}+ cancel={false}+ declineFirst+ />+ )}+ </Match>+ </Switch>+ <Button+ variant="ghost"+ size="xs"+ disabled={!props.onOpen}+ onClick={props.onOpen}+ >+ Open in session+ </Button>+ </>+);++/**+ * The chip's top row: who is answering (`Macro Agent · model`), what the turn is+ * doing, and the way into the session. The whole label opens the session,+ * as does the arrow.+ */+const ChipHeader: Component<{+ header?: MagicChipHeader;+ status: MagicChipActivity;+ /** The reply preview, while the answer area has nothing to offer. */+ preview?: string;+ onOpen?: () => void;+}> = (props) => (<div- class="flex h-full items-center justify-center"- data-magic-chip-pending- aria-hidden="true"+ class="flex min-h-9 items-center gap-1.5 border-b border-edge-muted py-1 pr-1.5 pl-3 text-xs leading-5"+ data-magic-chip-header>- <PulsingStar kind="streamIndicator" animate={props.busy} />+ <button+ type="button"+ class="flex min-w-0 flex-1 items-center gap-1.5 rounded-md text-left text-ink-extra-muted"+ classList={{ 'hover:text-ink': Boolean(props.onOpen) }}+ data-message-reply-preview={props.preview}+ disabled={!props.onOpen}+ onClick={props.onOpen}+ >+ <Show when={props.header?.agent}>+ {(agent) => (+ <span class="shrink-0 font-semibold text-ink">{agent()}</span>+ )}+ </Show>+ <Show when={props.header?.model}>+ {(model) => (+ <>+ <Show when={props.header?.agent}>+ <span aria-hidden="true" class="shrink-0 text-ink-placeholder">+ ·+ </span>+ </Show>+ <span class="min-w-0 truncate text-ink-muted" title={model()}>+ {model()}+ </span>+ </>+ )}+ </Show>+ <Show when={props.header?.agent || props.header?.model}>+ <span aria-hidden="true" class="shrink-0 text-ink-placeholder">+ ·+ </span>+ </Show>+ <ActivityText activity={props.status} />+ </button>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Open in session"+ disabled={!props.onOpen}+ onClick={props.onOpen}+ >+ <ArrowUpRight />+ </Button></div>);/**- * The answer: clipped to the fixed answer area with a fade while collapsed,- * whole once expanded.+ * Holds the answer's space while the agent is busy writing nothing yet: the+ * chat's own waiting glyph. Once the agent is done (or waiting on the user)+ * with nothing said, the space stays empty rather than showing a still star.*/-const AnswerBody: Component<{ markdown: string; expanded: boolean }> = (- props-) => (- <div- class="relative"- classList={{ 'h-full overflow-hidden': !props.expanded }}- data-magic-chip-clip- >+const AnswerPending: Component<{ busy: boolean }> = (props) => (+ <Show when={props.busy}><div- class="pointer-events-none min-w-0 max-w-full wrap-break-word"- data-message-reply-preview+ class="flex h-full items-center justify-center"+ data-magic-chip-pending+ aria-hidden="true">- <StaticMarkdownContext theme={channelTheme}>- <StaticMarkdown markdown={props.markdown} target="external" />- </StaticMarkdownContext>+ <PulsingStar kind="streamIndicator" animate /></div>- <Show- when={props.expanded}- fallback={- <>- <div- class="pointer-events-none absolute inset-x-0 top-1/2 bottom-0 bg-linear-to-b from-transparent via-surface/80 to-surface group-hover/answer:via-hover/80 group-hover/answer:to-hover"- data-magic-chip-fade- />- <ExpandHint expanded={false} />- </>- }- >- <ExpandHint expanded />- </Show>+ </Show>+);++/** The agent's passage, inert so the area's click is the disclosure. */+const Passage: Component<{ markdown: string }> = (props) => (+ <div+ class="pointer-events-none min-w-0 max-w-full wrap-break-word"+ data-message-reply-preview+ >+ <StaticMarkdownContext theme={channelTheme}>+ <StaticMarkdown markdown={props.markdown} target="external" />+ </StaticMarkdownContext></div>);/**- * The disclosure cue: `Show more` over the fade, `Show less` under the text.- * The collapsed cue steps aside while the area is hovered so it never sits- * on top of the text the hover is inviting you to read.+ * The question in the passage's place: the prompt and what is asked - a+ * Macro user tool's draft in the tool's own composer, editable in place and+ * sent from there; a form's fields; a URL and its host. Cropped at the+ * chip's height until expanded.*/-const ExpandHint: Component<{ expanded: boolean }> = (props) => (- <span- class="pointer-events-none flex items-center gap-1 text-xs text-ink-extra-muted transition-opacity motion-reduce:transition-none"- classList={{- 'absolute right-0 bottom-0 pb-0.5 group-hover/answer:opacity-0':- !props.expanded,- 'pt-1 pb-0.5': props.expanded,- }}- aria-hidden="true"- >- <CaretRight- class="size-3 shrink-0 transition-transform motion-reduce:transition-none"- classList={{ 'rotate-90': props.expanded }}- />- {props.expanded ? 'Show less' : 'Show more'}- </span>+const Question: Component<ChipAsking> = (props) => (+ <div class="flex min-w-0 flex-col gap-2" data-magic-chip-asking>+ <span class="text-sm leading-5 text-ink wrap-break-word">+ {props.asking.question.message}+ </span>+ <Switch>+ <Match when={reviewedTool(props.question)}>+ {(review) => (+ // A press anywhere in the composer is the composer's: its widgets+ // are not all controls the area could recognize, and none may+ // collapse it mid-edit.+ <div onClick={(event) => event.stopPropagation()}>+ <UserToolComposer+ tool={review().tool}+ toolCall={review().toolCall}+ review={{+ canAnswer: () => props.asking.canAnswer,+ ownerName: () => props.asking.ownerName,+ answering: () => props.locked && props.asking.canAnswer,+ respond: props.respond,+ }}+ />+ </div>+ )}+ </Match>+ <Match when={liveQuestion(props.question)}>+ {(question) => (+ <QuestionFields question={question()} locked={props.locked} />+ )}+ </Match>+ </Switch>+ </div>);/**- * One card for the whole turn: the answer area is reserved from the first- * moment (a pulsing star while the agent works, the opening of the answer- * once it writes) so the thread never jumps, and the bottom row reads the- * current activity or `Open session`. Clicking the answer expands it in- * place; clicking the row opens the session.+ * One card for the whole turn, at one height: a header naming the persona,+ * its model, and what the turn is doing (clicking it opens the session),+ * over an area that holds the agent's latest passage - a pulsing star while+ * the agent is busy before it writes, the passage as it streams, the final+ * passage once the turn ends - or, while the agent waits on a question, the+ * question itself with its decisions on the row beneath. The area is cropped+ * with a fade; clicking it expands it in place, never below the cropped+ * height, so a short passage does not shrink the card.*/export const MagicChipView: Component<{agentSessionId: string;presentation: MagicChipPresentation;+ header?: MagicChipHeader;/** How the chip answers a question; absent renders it read-only. */answer?: MagicChipAnswer;onOpen?: () => void;}> = (props) => {- const asking = () =>- props.presentation.kind === 'asking'- ? props.presentation.asking- : undefined;- const markdown = () => answerMarkdown(props.presentation);- const activity = () => currentActivity(props.presentation);+ // Memoized: read from many places per flush, once per streamed chunk.+ const asking = createMemo(() =>+ props.presentation.kind === 'asking' ? props.presentation.asking : undefined+ );+ const markdown = createMemo(() => answerMarkdown(props.presentation));+ const status = createMemo(() => presentationStatus(props.presentation));const [expanded, setExpanded] = createSignal(false);- // Before there is an answer there is nothing to expand, so the whole card- // leads to the session.- const onAnswerClick = () => {- if (markdown()) setExpanded((open) => !open);+ // One draft per question: keyed on the request id so metadata refreshes of+ // the same question keep what was typed, and a new question starts clean.+ const requestKey = createMemo(() => {+ const current = asking();+ return current ? String(current.question.requestId) : undefined;+ });+ const question = createMemo(() => {+ if (!requestKey()) return undefined;+ return untrack(() => {+ const current = asking();+ return current ? createChipQuestion(current) : undefined;+ });+ });+ const chipAsking = (): ChipAsking | undefined => {+ const current = asking();+ const state = question();+ if (!current || !state) return undefined;+ const locked =+ !current.canAnswer || !props.answer || props.answer.answering;+ return {+ asking: current,+ question: state,+ locked,+ respond: async (answer) =>+ locked ? false : ((await props.answer?.respond(answer)) ?? false),+ };+ };+ // The question's state, kept through its own teardown: once the answer+ // lands the pending question clears while the composer's effects are still+ // winding down, and a prop getter reading a `<Show>` accessor then would+ // read a stale one. Children key on the request id and read this instead.+ const held = createMemo<ChipAsking | undefined>(+ (previous) => chipAsking() ?? previous,+ undefined+ );+ // There is something to expand once the agent has written, or asked.+ const expandable = () => Boolean(markdown()) || Boolean(chipAsking());+ // While the answer area has no prose, a reply to the message previews the+ // header's line instead.+ const preview = () => {+ const live = asking();+ if (markdown() && !live) return undefined;+ const current = status();+ const line = `${current.label}${current.detail ? ` ${current.detail}` : ''}`;+ return live ? `${line} · ${live.question.message}` : line;+ };++ // Before there is anything to expand, the whole card leads to the session.+ const onAreaClick = (event: MouseEvent & { currentTarget: Element }) => {+ if (isControl(event.target, event.currentTarget)) return;+ if (expandable()) setExpanded((open) => !open);else props.onOpen?.();};return (<Layer depth={2}><div- class="my-2 w-full min-w-0 max-w-full overflow-hidden rounded-lg border border-edge-muted bg-surface"+ class="my-2 flex w-full min-w-0 max-w-full flex-col overflow-hidden rounded-lg border border-edge-muted bg-surface"data-magic-chip={props.agentSessionId}data-magic-chip-preview- onMouseDown={(event) => event.preventDefault()}+ onMouseDown={(event) => {+ // The chip sits in a Lexical message; a press must not move the+ // editor's selection, unless it is landing in one of its own inputs.+ if (!isTextEntry(event.target)) event.preventDefault();+ }}>+ <ChipHeader+ header={props.header}+ status={status()}+ preview={preview()}+ onOpen={props.onOpen}+ /><divrole="button"tabIndex={0}- aria-expanded={markdown() ? expanded() : undefined}- class="group/answer px-3 py-1 text-left hover:bg-hover"- classList={{ 'h-22': !expanded() }}+ aria-expanded={expandable() ? expanded() : undefined}+ class="flex min-h-41 min-w-0 flex-col text-left"+ classList={{ 'h-41': !expanded() }}data-magic-chip-answer- onClick={onAnswerClick}+ onClick={onAreaClick}onKeyDown={(event) => {+ if (event.target !== event.currentTarget) return;if (event.key !== 'Enter' && event.key !== ' ') return;event.preventDefault();- onAnswerClick();+ if (expandable()) setExpanded((open) => !open);+ else props.onOpen?.();}}>- <Show- when={markdown()}- fallback={<AnswerPending busy={activity()?.busy ?? false} />}+ <div+ class="relative mx-3 mt-1 mb-1 min-h-0 flex-1"+ classList={{ 'overflow-hidden': !expanded() }}+ data-magic-chip-clip>- {(answer) => (- <AnswerBody markdown={answer()} expanded={expanded()} />- )}- </Show>- </div>- <Show- when={asking()}- fallback={- <button- type="button"- class="flex min-h-9 w-full items-center gap-1.5 border-t border-edge-muted px-3 py-2 text-left text-xs leading-5 text-ink-extra-muted hover:bg-hover"- data-message-reply-preview={- markdown() ? undefined : replyPreview(activity())- }- disabled={!props.onOpen}- onClick={props.onOpen}- >- <span class="flex min-w-0 flex-1 items-center gap-1.5">+ <Show+ when={requestKey()}+ keyed+ fallback={<Show- when={activity()}- fallback={<span class="text-ink-muted">Open session</span>}+ when={markdown()}+ fallback={<AnswerPending busy={status().busy} />}>- {(current) => <ActivityText activity={current()} />}+ {(answer) => <Passage markdown={answer()} />}</Show>- </span>- <ArrowUpRight aria-hidden="true" class="size-3 shrink-0" />- </button>- }- >- {(question) => (- <AskingCard- agentSessionId={props.agentSessionId}- asking={question()}- answer={props.answer}- onOpen={props.onOpen}- />- )}- </Show>+ }+ >+ {/* `held` is set whenever a request id is. */}+ <Question {...held()!} />+ </Show>+ {/* Cropped content fades out; expanding shows it whole. */}+ <Show when={expandable() && !expanded()}>+ <div+ class="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-linear-to-t from-surface to-transparent"+ data-magic-chip-fade+ />+ </Show>+ </div>+ <Show when={requestKey() && held()?.asking.canAnswer}>+ <div+ class="flex shrink-0 items-center justify-end gap-2 px-3 pb-2"+ data-magic-chip-decisions+ >+ <AskingActions {...held()!} onOpen={props.onOpen} />+ </div>+ </Show>+ </div></div></Layer>);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.tsindex b1f4601ec2..09c9ec6dc1 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts@@ -1,3 +1,8 @@+import {+ harnessDisplayName,+ harnessTitle,+ modelDisplayName,+} from '@app/features/block-agent/component/compose-agent-session-options';import {createElicitationController,type ElicitationController,@@ -14,16 +19,17 @@ import {} from '@queries/agent-session/session-fold';import type {FoldedMessage,- PendingElicitation,+ SessionMetadata,} from '@service-agent-fold/generated/types';import { agentHarnessServiceClient } from '@service-agent-harness/client';import type {AgentSessionLogEntryDto,SessionStatusDto,} from '@service-agent-harness/generated/schemas';-import { type Accessor, createSignal, onCleanup } from 'solid-js';+import { type Accessor, createMemo, createSignal, onCleanup } from 'solid-js';import {deriveMagicChipPresentation,+ type MagicChipHeader,type MagicChipPresentation,type MagicChipQuestion,} from './presentation';@@ -45,23 +51,53 @@ function magicChipStatus(return MAGIC_CHIP_STATUSES.find((candidate) => candidate === value);}+/** What the session row says about who runs it, until the fold says more. */+type SessionIdentity = { harness: string; model: string };++/**+ * The persona as the header names it: the runtime's product name followed+ * by "Agent" (`Macro Agent`, `Cursor Agent`), a titled slug for a runtime+ * the composer does not name.+ */+function agentName(harness: string | undefined): string | undefined {+ if (!harness) return undefined;+ const known = harnessDisplayName(harness);+ return `${known === harness ? harnessTitle(harness) : known} Agent`;+}++/**+ * The model's display name from the fold, its id when the runtime lists no+ * name, or the slug the session was created with before the fold reports.+ */+function modelName(+ metadata: SessionMetadata | undefined,+ session: SessionIdentity | undefined+): string | undefined {+ const model = metadata?.model;+ if (!model) return session?.model || undefined;+ return modelDisplayName(model, metadata.supportedModels);+}+/*** Observe the session lifecycle and the chip's anchored folded turn.** Also the chip's half of answering a question the agent stops to ask in* that turn: the session's metadata names the live question, the session* row names its owner, and {@link ElicitationController} sends the answer.+ * The header names the persona and model from the session row and the fold.*/export function createMagicChipModel(props: MagicChipDecoratorProps): {presentation: Accessor<MagicChipPresentation>;+ header: Accessor<MagicChipHeader | undefined>;elicitation: ElicitationController;} {const [latestEvent, setLatestEvent] = createSignal<string>();const [messages, setMessages] = createSignal<FoldedMessage[]>([]);const [persistedStatus, setPersistedStatus] = createSignal(props.status);const [ownerId, setOwnerId] = createSignal<string>();- const [pendingElicitation, setPendingElicitation] =- createSignal<PendingElicitation>();+ const [session, setSession] = createSignal<SessionIdentity>();+ const [metadata, setMetadata] = createSignal<SessionMetadata>();+ const pendingElicitation = () => metadata()?.pendingElicitation ?? undefined;const viewerId = useUserId();let active = true;let release: (() => void) | undefined;@@ -81,7 +117,13 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {.get(props.agentSessionId).catch(() => undefined);if (!active) return;- if (result?.isOk()) setOwnerId(result.value.ownerId);+ if (result?.isOk()) {+ setOwnerId(result.value.ownerId);+ setSession({+ harness: result.value.harness,+ model: result.value.model,+ });+ }const status = result?.isOk()? magicChipStatus(result.value.status): undefined;@@ -112,9 +154,7 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {));},- onMetadata: (metadata) => {- setPendingElicitation(metadata.pendingElicitation ?? undefined);- },+ onMetadata: setMetadata,}).then((acquired) => {if (!active) {@@ -123,7 +163,7 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {}release = acquired.release;setMessages(acquired.messages);- setPendingElicitation(acquired.metadata.pendingElicitation ?? undefined);+ setMetadata(acquired.metadata);}).catch((error: unknown) => {console.error('[magic-chip] session log could not be folded', error);@@ -158,7 +198,9 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {};};- const presentation = () => {+ // Memoized: the view reads these from many places per flush, and a fold+ // pushes a frame per streamed chunk.+ const presentation = createMemo(() => {const turn = props.promptedMessage.turn;const messagesForTurn = messages().filter((message) => message.turn === turn@@ -172,7 +214,13 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {(message) => message.author.kind === 'agent'),});- };+ });++ const header = createMemo((): MagicChipHeader | undefined => {+ const agent = agentName(session()?.harness);+ const model = modelName(metadata(), session());+ return agent || model ? { agent, model } : undefined;+ });- return { presentation, elicitation };+ return { presentation, header, elicitation };}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.tsindex 8587d11572..a03a880cdc 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts@@ -1,6 +1,9 @@import type { FoldedMessage } from '@service-agent-fold/generated/types';import { describe, expect, it } from 'vitest';-import { deriveMagicChipPresentation } from './presentation';+import {+ deriveMagicChipPresentation,+ presentationStatus,+} from './presentation';const response = (overrides: Partial<FoldedMessage> = {}): FoldedMessage => ({agentSessionId: 'session',@@ -399,3 +402,95 @@ describe('deriveMagicChipPresentation', () => {});});});++describe('the latest passage', () => {+ const twoPassages = [+ { kind: 'text' as const, text: 'Let me check the tests.' },+ {+ kind: 'tool_use' as const,+ id: 'ran',+ name: { kind: 'native' as const, name: 'Terminal' },+ status: 'completed' as const,+ detail: {+ kind: 'terminal' as const,+ command: 'cargo test',+ output: 'ok',+ exitCode: 0,+ },+ },+ { kind: 'text' as const, text: 'They pass.' },+ ];++ it('shows only what the agent says now, not what it said before a tool ran', () => {+ expect(+ deriveMagicChipPresentation({+ persistedStatus: 'acp_ready',+ response: response({ parts: twoPassages }),+ })+ ).toEqual({+ kind: 'answering',+ markdown: 'They pass.',+ activity: { label: 'Writing response', busy: false },+ });+ });++ it('settles on the final passage', () => {+ expect(+ deriveMagicChipPresentation({+ persistedStatus: 'acp_ready',+ response: response({+ parts: twoPassages,+ stop: { kind: 'end_turn' },+ }),+ })+ ).toEqual({ kind: 'settled', markdown: 'They pass.' });+ });+});++describe('presentationStatus', () => {+ const activity = {+ label: 'Running command',+ detail: 'cargo test',+ busy: true,+ };+ const question = {+ question: {+ requestId: 1,+ turn: 0,+ toolCall: null,+ message: 'Which?',+ request: { kind: 'unrecognized' as const, mode: 'x', raw: {} },+ },+ ownerName: 'Alice Owner',+ };++ it('reads the activity while the agent works or writes', () => {+ expect(presentationStatus({ kind: 'working', activity })).toBe(activity);+ expect(+ presentationStatus({ kind: 'answering', markdown: 'Hi', activity })+ ).toBe(activity);+ });++ it('names who a question waits on', () => {+ expect(+ presentationStatus({+ kind: 'asking',+ markdown: '',+ asking: { ...question, canAnswer: true },+ })+ ).toEqual({ label: 'Waiting for you', busy: false });+ expect(+ presentationStatus({+ kind: 'asking',+ markdown: '',+ asking: { ...question, canAnswer: false },+ })+ ).toEqual({ label: 'Waiting for Alice Owner', busy: false });+ });++ it('reads Done once settled', () => {+ expect(presentationStatus({ kind: 'settled', markdown: 'Fixed.' })).toEqual(+ { label: 'Done', busy: false }+ );+ });+});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 67e5a77965..df98b8d59e 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@@ -18,6 +18,14 @@ export type MagicChipActivity = {busy: boolean;};+/** Who is answering, for the chip's header: the persona and its model. */+export type MagicChipHeader = {+ /** The persona's name, e.g. `Macro Agent`. */+ agent?: string;+ /** The model's display name, when the runtime has reported one. */+ model?: string;+};+/*** A question the agent is waiting on, as the chip offers it: the live slot* from the session's metadata, and whether this viewer is the one who may@@ -34,9 +42,10 @@ export type MagicChipQuestion = {* The one state the chip renders.** Four: an activity line while the agent works with nothing to show, the- * answer as it is written with the activity line still under it, a question- * the agent has stopped to ask (with whatever answer it had written so far- * above it), and the answer alone once the turn ends.+ * agent's latest passage as it is written with the activity alongside, a+ * question the agent has stopped to ask (with that passage beside it), and+ * the final passage alone once the turn ends. `markdown` is always the+ * turn's latest text chunk, never the whole turn.*/export type MagicChipPresentation =| { kind: 'working'; activity: MagicChipActivity }@@ -321,25 +330,44 @@ function liveEventActivity(return statusActivity(name);}-function answerMarkdown(response: FoldedMessage | undefined): string {+/**+ * The agent's latest prose: the last text part of the turn, which the fold+ * appends into as chunks land. A passage written before a tool ran gives way+ * to what the agent says after it, and when the turn ends cleanly the final+ * passage is what stays.+ */+function latestChunk(response: FoldedMessage | undefined): string {return (- response?.parts- .filter(- (part): part is Extract<MessagePart, { kind: 'text' }> =>- part.kind === 'text' && Boolean(part.text.trim())- )- .map((part) => part.text)- .join('\n\n') ?? ''+ response?.parts.findLast(+ (part): part is Extract<MessagePart, { kind: 'text' }> =>+ part.kind === 'text' && Boolean(part.text.trim())+ )?.text ?? '');}+/** The one line the chip's header reads for the turn. */+export function presentationStatus(+ presentation: MagicChipPresentation+): MagicChipActivity {+ return match(presentation)+ .with({ kind: 'working' }, { kind: 'answering' }, (p) => p.activity)+ .with({ kind: 'asking' }, ({ asking }) => ({+ label: asking.canAnswer+ ? 'Waiting for you'+ : `Waiting for ${asking.ownerName}`,+ busy: false,+ }))+ .with({ kind: 'settled' }, () => ({ label: 'Done', busy: false }))+ .exhaustive();+}+/** Project fold and lifecycle facts into the one state the view renders. */export function deriveMagicChipPresentation(input: MagicChipPresentationInput): MagicChipPresentation {const { response, prompt, latestEvent, persistedStatus, asking } = input;- const markdown = answerMarkdown(response);+ const markdown = latestChunk(response);if (response?.stop?.kind === 'end_turn' && markdown) {return { kind: 'settled', markdown };}diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 96692eda58..d4281e8059 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -44,13 +44,28 @@ bot asks before scheduling a specific clock time. `@macro-new` / `@coder` / `@cuan agent session; follow-up`@` mentions of that bot in the same thread route to it.The reply renders a Magic Chip: a rounded card of constant height that is present-from the moment the session boots. Its answer area shows a pulsing star while the-agent works, then the opening of the answer clipped to four lines and faded out; its-bottom row reads the current activity (`Booting agent`, `Writing response`, ...) and-`Open session` once the turn ends. A `Show more` cue sits over the fade: click the-answer text to expand it in place (`Show less` collapses it again); click the-bottom row to open the agent session. Before an-answer exists, clicking the answer area also opens the session.+from the moment the session boots. Its header names the persona (`Macro Agent`,+`Cursor Agent`), the model, and what the turn is doing (`Booting agent`, `Running+command · cargo test`, `Waiting for you`, `Done`); clicking the header or its arrow+(`Open in session`) opens the agent session. The area under the header holds the agent's+latest passage: a pulsing star while the agent is busy before it writes, the passage as it+streams, and the final passage once the turn ends - the last text the agent wrote, not the+whole turn, and a finished turn with nothing said leaves the area empty. The area is+cropped at the chip's height with a fade at its foot; clicking it expands it in place, and+clicking again collapses it. Before anything is there to expand, clicking the area also+opens the session.++When the agent stops to ask a question the question takes the area in the passage's+place, cropped and expandable the same way: the prompt, then what is asked - a form's+fields (choice rows with an accent box, an `Other` row when the agent allows a free-text+answer, text and number inputs, a yes/no), a URL request's host and address, or a Macro+user tool's draft (`SendEmail`, `CreateCalendarEvent`) in the tool's own composer - the+same email compose or calendar event form the session shows, editable in place; expand+the area to reach its `Send`/`Create`, which answers with the edited draft. A row at the+bottom of the area carries the other decisions, refusal first: `Dismiss · Open in session`+for a tool draft, `Decline · Submit · Open in session` (or `Open` for a URL) for a question.+Only the session's owner can act; other viewers see the question read-only and the header+names who is being waited on. Once answered, the area shows the agent's passage again.Agent replies may contain mention chips (`<m-document-mention>`) that render like anyother channel mention. With GraphQL enabled, document mentions and preview cards loadin bounded batches, including task status/priority/assignees and the viewer's edit