Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(web): the Magic Chip is a compact card that opens the session (#6943)

Wolf Mermelstein4bcdb1359ea9
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index 975565c047..7899eae645 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -926,7 +926,7 @@ function MagicChipStateDemo(props: { presentation: MagicChipPresentation }) {
);
}
-/** The chip asking, one per request kind; answers land in the console. */
+/** The chip asking: the question on its line, answered in the session. */
function MagicChipAskingDemo(props: {
request: PendingElicitation['request'];
}) {
@@ -951,12 +951,6 @@ function MagicChipAskingDemo(props: {
agentSessionId="gallery"
presentation={presentation}
header={GALLERY_CHIP_HEADER}
- answer={{
- respond: async (answer) => {
- console.log('[gallery] elicitation answer', answer);
- return true;
- },
- }}
onOpen={() => console.log('[gallery] open session')}
/>
);
diff --git a/apps/web/src/features/channel/Message/ChannelMessage.tsx b/apps/web/src/features/channel/Message/ChannelMessage.tsx
index 469d567646..5e9ce27a31 100644
--- a/apps/web/src/features/channel/Message/ChannelMessage.tsx
+++ b/apps/web/src/features/channel/Message/ChannelMessage.tsx
@@ -167,7 +167,7 @@ function GroupedMessageLayout(props: {
/>
{/* No sender line to sit on: the link takes the top right of the
content row instead. */}
- <Message.AgentSessionLink class="pt-1" />
+ <Message.AgentSessionLink class="mt-0.5" />
</div>
</Message.Slot>
<Message.Slot
diff --git a/apps/web/src/features/channel/Message/agent-session-link.ts b/apps/web/src/features/channel/Message/agent-session-link.ts
index 9ace4b5cdf..e8c402593c 100644
--- a/apps/web/src/features/channel/Message/agent-session-link.ts
+++ b/apps/web/src/features/channel/Message/agent-session-link.ts
@@ -24,9 +24,15 @@ export type SplitMessageContent = {
* The exact serialization `I_AGENT_SESSION_MENTION` reads - one JSON object
* inside the tag, with no line breaks - anchored to the start, plus the
* blank line the harness puts after it.
+ *
+ * The node has to be the whole first line. `crates/prompt` tells agents to
+ * write session mentions in their own replies, so a bot that opens one with
+ * a chip and keeps writing on the same line ("<chip> - picked this up
+ * there") means it as prose; only a node standing alone as its own
+ * paragraph is the chrome the harness prefixed.
*/
const LEADING_AGENT_SESSION_MENTION =
- /^<m-agent-session-mention>(.*?)<\/m-agent-session-mention>[ \t]*(?:\r?\n)*/;
+ /^<m-agent-session-mention>(.*?)<\/m-agent-session-mention>[ \t]*(?:(?:\r?\n)+|$)/;
function isAgentSessionMentionInfo(value: unknown): value is { id: string } {
return (
diff --git a/apps/web/src/features/channel/Message/tests/agent-session-link.test.ts b/apps/web/src/features/channel/Message/tests/agent-session-link.test.ts
index d1a94ac586..5d6da2d41f 100644
--- a/apps/web/src/features/channel/Message/tests/agent-session-link.test.ts
+++ b/apps/web/src/features/channel/Message/tests/agent-session-link.test.ts
@@ -49,3 +49,30 @@ describe('splitLeadingAgentSessionLink', () => {
});
});
});
+
+describe('a session mention the agent meant as prose', () => {
+ it('keeps a chip the message keeps writing after on the same line', () => {
+ const content =
+ '<m-agent-session-mention>{"id":"s1","label":"Agent session"}</m-agent-session-mention> - picked this up there';
+ expect(splitLeadingAgentSessionLink(content)).toEqual({
+ link: undefined,
+ body: content,
+ });
+ });
+
+ it('lifts a chip that stands alone as its own paragraph', () => {
+ expect(
+ splitLeadingAgentSessionLink(
+ '<m-agent-session-mention>{"id":"s1","label":"Agent session"}</m-agent-session-mention>\n\nOn it.'
+ )
+ ).toEqual({ link: { sessionId: 's1' }, body: 'On it.' });
+ });
+
+ it('lifts a chip that is the whole message', () => {
+ expect(
+ splitLeadingAgentSessionLink(
+ '<m-agent-session-mention>{"id":"s1","label":"Agent session"}</m-agent-session-mention>'
+ )
+ ).toEqual({ link: { sessionId: 's1' }, body: '' });
+ });
+});
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.tsx
index 61093d5c03..a258193fa9 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
@@ -17,7 +17,6 @@ export const MagicChip: Component<
presentation={model.presentation()}
header={model.header()}
onCollapse={props.onCollapse}
- answer={{ respond: model.interactions.respond }}
onOpen={() => insertSplit({ type: 'agent', id: props.agentSessionId })}
/>
);
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.tsx
deleted file mode 100644
index d1092d0bc8..0000000000
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
+++ /dev/null
@@ -1,773 +0,0 @@
-/** @vitest-environment jsdom */
-import type { InteractionResponse } from '@app/features/block-agent/context/interaction';
-import type { PendingElicitation } from '@service-agent-fold/generated/types';
-import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
-import { createSignal } from 'solid-js';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { MagicChipView } from './MagicChipView';
-import type { MagicChipPresentation } from './presentation';
-
-vi.mock(
- '@core/component/LexicalMarkdown/component/core/StaticMarkdown',
- () => ({
- StaticMarkdownContext: (props: { children: unknown }) => props.children,
- StaticMarkdown: (props: { markdown: string }) => (
- <div data-testid="chip-markdown">{props.markdown}</div>
- ),
- })
-);
-
-vi.mock('@core/component/LexicalMarkdown/theme', () => ({
- channelTheme: {},
-}));
-
-// The PR link resolves its entity over the network; the view only places it.
-vi.mock('./MagicChipPullRequest', () => ({
- MagicChipPullRequest: (props: { url: string }) => (
- <a data-testid="chip-pull-request" href={props.url}>
- {props.url}
- </a>
- ),
-}));
-
-// 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 =
- '/home/ubuntu/.cursor/projects/workspace/terminals/261831.txt'.repeat(8);
-
-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 elicitationAnswer = {
- respond: (response: InteractionResponse) =>
- response.kind === 'elicitation'
- ? respond(response.answer)
- : Promise.resolve(false),
-};
-const onOpen = vi.fn();
-
-beforeEach(() => {
- respond.mockReset();
- respond.mockResolvedValue(true);
- onOpen.mockReset();
-});
-
-describe('MagicChipView permission requests', () => {
- it.each([true, false])(
- 'replaces loading with an approval card for canAnswer=%s',
- (canAnswer) => {
- const answer = vi
- .fn<(response: InteractionResponse) => Promise<boolean>>()
- .mockResolvedValue(true);
- const [presentation, setPresentation] =
- createSignal<MagicChipPresentation>({
- kind: 'asking',
- markdown: '',
- asking: {
- request: {
- kind: 'permission',
- requestId: 0,
- turn: 3,
- toolCall: 'cmd',
- options: [
- {
- id: 'approve-command',
- kind: 'allow_once',
- name: 'Yes, proceed',
- },
- { id: 'reject-command', kind: 'reject_once', name: 'No' },
- ],
- },
- canAnswer,
- answering: false,
- action: 'Run command',
- detail: 'echo hi',
- },
- });
- const view = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={presentation()}
- answer={{ respond: answer }}
- />
- ));
- expect(view.getByText('Approval needed')).toBeTruthy();
- expect(view.getByText('echo hi')).toBeTruthy();
- expect(
- view.container.querySelector('[data-magic-chip-pending]')
- ).toBeNull();
- if (canAnswer) {
- fireEvent.click(view.getByRole('button', { name: 'Allow once' }));
- expect(answer).toHaveBeenCalledExactlyOnceWith({
- kind: 'permission',
- requestId: 0,
- turn: 3,
- answer: { kind: 'selected', optionId: 'approve-command' },
- });
- } else {
- expect(view.queryByRole('button', { name: 'Allow once' })).toBeNull();
- expect(view.queryByRole('button', { name: 'Deny' })).toBeNull();
- expect(answer).not.toHaveBeenCalled();
- }
- setPresentation({
- kind: 'answering',
- markdown: 'Done.',
- activity: { label: 'Writing response', busy: true },
- });
- expect(view.queryByText('Approval needed')).toBeNull();
- expect(view.getByText('Done.')).toBeTruthy();
- }
- );
-});
-
-describe('Magic Chip inside an editor', () => {
- it('collapses even when the editor stops delegated clicks', () => {
- const collapse = vi.fn();
- render(() => (
- <div on:click={(event) => event.stopPropagation()}>
- <MagicChipView
- agentSessionId="session"
- presentation={{ kind: 'settled', markdown: 'Latest answer' }}
- onCollapse={collapse}
- />
- </div>
- ));
- fireEvent.click(
- screen.getByRole('button', { name: 'Collapse to mention' })
- );
- expect(collapse).toHaveBeenCalledOnce();
- });
-});
-
-describe('MagicChipView', () => {
- it('reserves the answer height and reads the activity in the header while working', () => {
- const { container } = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={{
- kind: 'working',
- activity: { label: 'Booting agent', busy: true },
- }}
- onOpen={onOpen}
- />
- ));
-
- const card = container.querySelector('[data-magic-chip-preview]');
- expect(card?.className).toContain('rounded-lg');
-
- 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();
-
- 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(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.each(['Cursor Agent', 'Codex Agent'])(
- 'places the pull request in the %s header once the session opened one',
- (agent) => {
- const { container } = render(() => (
- <MagicChipView
- agentSessionId="session-1"
- presentation={{ kind: 'settled', markdown: 'Opened a PR.' }}
- header={{
- agent,
- pullRequestUrl: 'https://github.com/macro-inc/macro/pull/6303',
- }}
- />
- ));
- const link = header(container)?.querySelector(
- '[data-testid="chip-pull-request"]'
- );
- expect(link?.getAttribute('href')).toBe(
- 'https://github.com/macro-inc/macro/pull/6303'
- );
- }
- );
-
- it('keeps the same answer height once the answer streams in', () => {
- const { container } = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={{
- kind: 'answering',
- markdown: 'Hello from the agent',
- activity: { label: 'Writing response', busy: false },
- }}
- onOpen={onOpen}
- />
- ));
-
- 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();
-
- 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 { container } = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={{ kind: 'settled', markdown: 'All done' }}
- onOpen={onOpen}
- />
- ));
-
- const area = answerArea(container)!;
- 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).toMatch(/(^|\s)h-41(\s|$)/);
- expect(fade()).toBeTruthy();
-
- 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(fade()).toBeNull();
- expect(onOpen).not.toHaveBeenCalled();
-
- fireEvent.keyDown(area, { key: 'Enter' });
- expect(area.getAttribute('aria-expanded')).toBe('false');
- expect(area.className).toMatch(/(^|\s)h-41(\s|$)/);
- expect(clip()?.className).toContain('overflow-hidden');
- expect(fade()).toBeTruthy();
- expect(onOpen).not.toHaveBeenCalled();
- });
-
- it('reads Done in the header once the turn settles', () => {
- const { container } = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={{ kind: 'settled', markdown: 'All done' }}
- onOpen={onOpen}
- />
- ));
-
- 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);
- });
-
- it('keeps a long activity detail inside the message column', () => {
- const { container } = render(() => (
- <div style={{ width: '320px' }}>
- <MagicChipView
- agentSessionId="session-1"
- presentation={{
- kind: 'working',
- activity: { label: 'Thinking', detail: LONG_PATH, busy: true },
- }}
- />
- </div>
- ));
-
- const card = container.querySelector('[data-magic-chip="session-1"]');
- expect(card?.className).toContain('min-w-0');
- expect(card?.className).toContain('max-w-full');
- expect(card?.className).toContain('overflow-hidden');
- expect(screen.getByText('Thinking')).toBeTruthy();
- expect(screen.getByText(LONG_PATH).className).toContain('truncate');
- });
-});
-
-const draft = {
- title: 'Q3 sync',
- time: {
- kind: 'timed',
- startsAt: '2026-08-20T17:00:00Z',
- endsAt: '2026-08-20T17:30:00Z',
- timeZone: 'UTC',
- },
-};
-
-function asking(canAnswer: boolean, markdown = ''): MagicChipPresentation {
- return {
- kind: 'asking',
- markdown,
- asking: {
- request: {
- kind: 'elicitation',
- requestId: 9,
- turn: 0,
- toolCall: 'toolu_evt',
- message: 'Create calendar event?',
- request: {
- kind: 'user_tool',
- tool: 'CreateCalendarEvent',
- draft,
- schema: {
- title: null,
- description: null,
- properties: [],
- required: [],
- },
- },
- },
- canAnswer,
- answering: false,
- },
- };
-}
-
-/** The text of the decisions row, in order. */
-function decisionLabels(container: HTMLElement) {
- return [...(decisions(container)?.querySelectorAll('button') ?? [])].map(
- (button) => button.textContent?.trim()
- );
-}
-
-describe('MagicChipView reviewing a tool draft', () => {
- it('mounts the draft in its composer with Dismiss and the session on the row', () => {
- const view = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={asking(true, 'Setting that up.')}
- answer={elicitationAnswer}
- onOpen={onOpen}
- />
- ));
- // 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(view.getByTestId('composer-execute'));
- expect(respond).toHaveBeenCalledWith({
- action: 'accept',
- content: { draft: JSON.stringify(draft) },
- });
- fireEvent.click(view.getByTestId('composer-reject'));
- expect(respond).toHaveBeenLastCalledWith({ action: 'decline' });
- 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={elicitationAnswer}
- 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 the draft read-only and who is being waited on', () => {
- const view = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={asking(false)}
- answer={elicitationAnswer}
- onOpen={onOpen}
- />
- ));
- expect(header(view.container)?.textContent).toContain(
- 'Waiting for an editor'
- );
- // 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('a chip with no answer handler is read-only', () => {
- const view = render(() => (
- <MagicChipView agentSessionId="session" presentation={asking(true)} />
- ));
- expect(view.getByTestId('calendar-composer').dataset.canAct).toBe('false');
- fireEvent.click(view.getByTestId('composer-execute'));
- fireEvent.click(view.getByText('Dismiss'));
- expect(respond).not.toHaveBeenCalled();
- });
-
- 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',
- markdown: 'Setting that up.',
- activity: { label: 'Writing response', busy: false },
- }
- );
- const view = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={presentation()}
- answer={elicitationAnswer}
- onOpen={onOpen}
- />
- ));
- const area = answerArea(view.container)!;
- fireEvent.click(area);
- expect(area.getAttribute('aria-expanded')).toBe('true');
-
- setPresentation(asking(true, 'Setting that up.'));
- expect(view.getByTestId('calendar-composer')).toBeTruthy();
- expect(view.queryByTestId('chip-markdown')).toBeNull();
- expect(answerArea(view.container)).toBe(area);
-
- fireEvent.click(view.getByText('Dismiss'));
- setPresentation({ kind: 'settled', markdown: 'Created the event.' });
- 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');
- 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: PendingElicitation['request'],
- options: { canAnswer?: boolean; requestId?: number; markdown?: string } = {}
-): MagicChipPresentation {
- return {
- kind: 'asking',
- markdown: options.markdown ?? '',
- asking: {
- request: {
- kind: 'elicitation',
- requestId: options.requestId ?? 0,
- turn: 0,
- toolCall: null,
- message: "What's the best colour?",
- request,
- },
- canAnswer: options.canAnswer ?? true,
- answering: false,
- },
- };
-}
-
-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={elicitationAnswer}
- 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={elicitationAnswer}
- />
- ));
- 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={elicitationAnswer}
- />
- ));
- 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 without edit access sees the choices locked and no decisions', () => {
- const view = render(() => (
- <MagicChipView
- agentSessionId="session"
- presentation={askingQuestion(colourForm, { canAnswer: false })}
- answer={elicitationAnswer}
- onOpen={onOpen}
- />
- ));
- expect(header(view.container)?.textContent).toContain(
- 'Waiting for an editor'
- );
- 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={elicitationAnswer}
- />
- ));
- 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={elicitationAnswer}
- />
- ));
- 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.tsx
index e88e17018f..f7bda2c945 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,55 +1,24 @@
-import {
- createLiveQuestion,
- type DraftedTool,
- type LiveQuestion,
- parseDraftedTool,
- QuestionActions,
- QuestionFields,
- type RespondToElicitation,
- UserToolComposer,
-} from '@app/features/block-agent/component/parts/LiveElicitation';
-import type { InteractionResponse } from '@app/features/block-agent/context/interaction';
-import { PermissionCard } from '@app/features/block-agent/ui/PermissionCard';
-import {
- StaticMarkdown,
- StaticMarkdownContext,
-} from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import { channelTheme } from '@core/component/LexicalMarkdown/theme';
-import { PulsingStar } from '@entity/components/PulsingStar';
import ArrowUpRight from '@phosphor/arrow-up-right.svg';
import ArrowsIn from '@phosphor/arrows-in.svg';
-import type { PendingElicitation } from '@service-agent-fold/generated/types';
+import Check from '@phosphor/check.svg';
import { Button, Layer } from '@ui';
-import {
- type Component,
- createMemo,
- createSignal,
- Match,
- Show,
- Switch,
- untrack,
-} from 'solid-js';
+import { type Component, createMemo, Show } from 'solid-js';
import { MagicChipPullRequest } from './MagicChipPullRequest';
import {
type MagicChipActivity,
type MagicChipHeader,
- type MagicChipInteraction,
type MagicChipPresentation,
+ type MagicChipTone,
+ presentationLine,
presentationStatus,
+ presentationTone,
} from './presentation';
-function answerMarkdown(presentation: MagicChipPresentation) {
- return presentation.kind === 'working' ? undefined : presentation.markdown;
-}
-
-const TEXT_ENTRY =
- 'input, textarea, [contenteditable]:not([contenteditable="false"])';
-
-const CONTROL = `${TEXT_ENTRY}, button, select, a, label, [role="button"], [role="option"], [role="menuitem"]`;
+const CONTROL = 'button, select, a, label, [role="button"]';
/**
- * 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).
+ * A press on one of the card's own controls is that control's, not a toggle
+ * of the card (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;
@@ -57,56 +26,45 @@ function isControl(target: EventTarget | null, area: Element) {
return control !== null && control !== area && area.contains(control);
}
-function isTextEntry(target: EventTarget | null) {
- return target instanceof Element && target.closest(TEXT_ENTRY) !== null;
-}
-
-/** What the chip's answer to a question does. */
-export type MagicChipAnswer = {
- respond: (response: InteractionResponse) => Promise<boolean>;
+const TONE_DOT: Record<MagicChipTone, string> = {
+ busy: 'bg-accent',
+ asking: 'bg-amber',
+ done: 'bg-green',
};
/**
- * 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.
+ * The state at the head of the status row: a small dot that pulses while the
+ * turn is doing something, goes amber when it has stopped to ask, and
+ * becomes a green check once the turn is over.
*/
-type ChipQuestion =
- | LiveQuestion
- | { kind: 'user_tool'; tool: DraftedTool; toolCall: string };
-
-type MagicChipQuestion = Omit<MagicChipInteraction, 'request'> & {
- request: PendingElicitation & { kind: 'elicitation' };
-};
-
-function createChipQuestion(asking: MagicChipQuestion): ChipQuestion {
- const request = asking.request.request;
- if (request.kind !== 'user_tool') return createLiveQuestion(request);
- const toolCall = asking.request.toolCall ?? String(asking.request.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;
-};
+const StatusDot: Component<{ tone: MagicChipTone; busy: boolean }> = (
+ props
+) => (
+ <Show
+ when={props.tone === 'done'}
+ fallback={
+ <span
+ class="size-2 shrink-0 rounded-full"
+ classList={{
+ [TONE_DOT[props.tone]]: true,
+ 'animate-pulse motion-reduce:animate-none': props.busy,
+ }}
+ data-magic-chip-dot={props.tone}
+ aria-hidden="true"
+ />
+ }
+ >
+ <span
+ class="grid size-3.5 shrink-0 place-items-center rounded-full bg-green text-surface"
+ data-magic-chip-dot="done"
+ aria-hidden="true"
+ >
+ <Check class="size-2.5" />
+ </span>
+ </Show>
+);
-/** The shimmering label plus its muted detail. */
+/** The shimmering label plus its monospaced detail. */
const ActivityText: Component<{ activity: MagicChipActivity }> = (props) => (
<>
<span
@@ -126,7 +84,7 @@ const ActivityText: Component<{ activity: MagicChipActivity }> = (props) => (
·
</span>
<span
- class="min-w-0 flex-1 truncate text-ink-extra-muted"
+ class="min-w-0 flex-1 truncate font-mono text-[11.5px] text-ink-extra-muted"
title={detail()}
>
{detail()}
@@ -138,413 +96,172 @@ const ActivityText: Component<{ activity: MagicChipActivity }> = (props) => (
);
/**
- * 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 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, the pull request the session opened once there is one, and the way
- * into the session. The whole label opens the session, as does the arrow.
+ * The card's status row: who is answering, what the turn is doing, and the
+ * way into the session. Sits a surface above the card so it reads as the
+ * card's own chrome.
*/
-const ChipHeader: Component<{
+const StatusRow: Component<{
header?: MagicChipHeader;
status: MagicChipActivity;
- /** The reply preview, while the answer area has nothing to offer. */
+ tone: MagicChipTone;
+ /** The reply preview, while the output row has nothing to offer. */
preview?: string;
onOpen?: () => void;
onCollapse?: () => void;
}> = (props) => (
- <div
- 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
- >
- <button
- type="button"
- class="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden 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}
+ <Layer offset={1}>
+ <div
+ class="flex h-7 items-center gap-2 border-b border-edge-muted bg-surface pr-1 pl-2.5 text-xs leading-5 text-ink-muted"
+ data-magic-chip-header
>
- <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}>
+ <StatusDot tone={props.tone} busy={props.status.busy} />
+ <span
+ class="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden"
+ data-message-reply-preview={props.preview}
+ >
+ <Show when={props.header?.agent}>
+ {(agent) => (
+ <>
+ <span
+ class="shrink-0 font-semibold text-ink"
+ title={props.header?.model}
+ data-magic-chip-agent
+ >
+ {agent()}
+ </span>
<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} />
+ </span>
+ <Show when={props.onCollapse}>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Collapse to mention"
+ tooltip="Collapse to mention"
+ on:click={(event) => {
+ // Lexical intercepts delegated clicks inside editable decorators.
+ event.preventDefault();
+ event.stopPropagation();
+ props.onCollapse?.();
+ }}
+ >
+ <ArrowsIn />
+ </Button>
</Show>
- <ActivityText activity={props.status} />
- </button>
- <Show when={props.header?.pullRequestUrl}>
- {(url) => (
- <div class="flex min-w-0 max-w-[40%] justify-end overflow-hidden">
- <MagicChipPullRequest url={url()} />
- </div>
- )}
- </Show>
- <Show when={props.onCollapse}>
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label="Collapse to mention"
- tooltip="Collapse to mention"
- on:click={(event) => {
- // Lexical intercepts delegated clicks inside editable decorators.
- event.preventDefault();
- event.stopPropagation();
- props.onCollapse?.();
- }}
+ <button
+ type="button"
+ class="inline-flex h-5 shrink-0 items-center gap-1 whitespace-nowrap rounded-full border border-edge bg-surface px-2 font-medium text-ink-muted text-xs disabled:opacity-50"
+ classList={{ 'hover:bg-active hover:text-ink': Boolean(props.onOpen) }}
+ disabled={!props.onOpen}
+ onClick={props.onOpen}
>
- <ArrowsIn />
- </Button>
- </Show>
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label="Open in session"
- disabled={!props.onOpen}
- onClick={props.onOpen}
- >
- <ArrowUpRight />
- </Button>
- </div>
-);
-
-/**
- * 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 AnswerPending: Component<{ busy: boolean }> = (props) => (
- <Show when={props.busy}>
- <div
- class="flex h-full items-center justify-center"
- data-magic-chip-pending
- aria-hidden="true"
- >
- <PulsingStar kind="streamIndicator" animate />
+ View session
+ <ArrowUpRight class="size-3" />
+ </button>
</div>
- </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>
+ </Layer>
);
/**
- * 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 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.request.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 && !props.locked,
- 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, 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.
+ * One compact card for the whole turn: a status row naming the persona,
+ * what the turn is doing, and the way into the session, over a single line
+ * of the agent's latest prose with the pull request the session opened
+ * beside it. The card is one control: anywhere on it opens the session,
+ * which is where the passage whole, and any question the agent has stopped
+ * to ask, are read and answered.
*/
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;
onCollapse?: () => void;
}> = (props) => {
- // Memoized: read from many places per flush, once per streamed chunk.
- const asking = createMemo(() =>
- props.presentation.kind === 'asking' ? props.presentation.asking : undefined
- );
- const elicitation = (): MagicChipQuestion | undefined => {
- const current = asking();
- return current?.request.kind === 'elicitation'
- ? { ...current, request: current.request }
- : undefined;
- };
- const permission = () => {
- const current = asking();
- return current?.request.kind === 'permission'
- ? { ...current, request: current.request }
- : undefined;
- };
- const markdown = createMemo(() => answerMarkdown(props.presentation));
const status = createMemo(() => presentationStatus(props.presentation));
- const [expanded, setExpanded] = createSignal(false);
+ const tone = createMemo(() => presentationTone(props.presentation));
+ const line = createMemo(() => presentationLine(props.presentation));
- // 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 = elicitation();
- return current
- ? JSON.stringify([
- current.request.kind,
- current.request.turn,
- current.request.requestId,
- ])
- : undefined;
- });
- const question = createMemo(() => {
- if (!requestKey()) return undefined;
- return untrack(() => {
- const current = elicitation();
- return current ? createChipQuestion(current) : undefined;
- });
- });
- const chipAsking = (): ChipAsking | undefined => {
- const current = elicitation();
- const state = question();
- if (!current || !state) return undefined;
- const locked = !current.canAnswer || current.answering || !props.answer;
- return {
- asking: current,
- question: state,
- locked,
- respond: async (answer) =>
- locked
- ? false
- : ((await props.answer?.respond({
- kind: 'elicitation',
- requestId: current.request.requestId,
- turn: current.request.turn,
- 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.
+ // While the output row has no prose, a reply to the message previews the
+ // status row's line instead.
const preview = () => {
- const live = asking();
- if (markdown() && !live) return undefined;
+ if (line()) return undefined;
const current = status();
- const line = `${current.label}${current.detail ? ` ${current.detail}` : ''}`;
- return live?.request.kind === 'elicitation'
- ? `${line} · ${live.request.message}`
- : live?.detail
- ? `${line} · ${live.detail}`
- : line;
+ const activity = `${current.label}${current.detail ? ` ${current.detail}` : ''}`;
+ const agent = props.header?.agent;
+ return agent ? `${agent} · ${activity}` : activity;
};
- // Before there is anything to expand, the whole card leads to the session.
- const onAreaClick = (event: MouseEvent & { currentTarget: Element }) => {
+ const onCardClick = (event: MouseEvent & { currentTarget: Element }) => {
if (isControl(event.target, event.currentTarget)) return;
- if (expandable()) setExpanded((open) => !open);
- else props.onOpen?.();
+ props.onOpen?.();
};
return (
<Layer depth={2}>
<div
- class="my-2 flex w-full min-w-0 max-w-full flex-col overflow-hidden rounded-lg border border-edge-muted bg-surface"
+ role="button"
+ tabIndex={0}
+ aria-label="Open agent session"
+ class="my-2 flex w-full min-w-0 max-w-full flex-col overflow-hidden rounded-md border border-edge-muted bg-surface text-left hover:border-edge"
+ classList={{ 'cursor-pointer': Boolean(props.onOpen) }}
data-magic-chip={props.agentSessionId}
data-magic-chip-preview
data-lexical-interactive
- onClick={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.stopPropagation();
+ onCardClick(event);
+ }}
on:mousedown={(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();
+ // editor's selection.
+ event.preventDefault();
+ }}
+ on:keydown={(event) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ event.stopPropagation();
+ props.onOpen?.();
}}
>
- <ChipHeader
+ <StatusRow
header={props.header}
status={status()}
+ tone={tone()}
preview={preview()}
onOpen={props.onOpen}
onCollapse={props.onCollapse}
/>
- <Show
- when={permission()}
- fallback={
- <div
- role="button"
- tabIndex={0}
- 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={onAreaClick}
- on:keydown={(event) => {
- if (event.target !== event.currentTarget) return;
- if (event.key !== 'Enter' && event.key !== ' ') return;
- event.preventDefault();
- event.stopPropagation();
- if (expandable()) setExpanded((open) => !open);
- else props.onOpen?.();
- }}
+ <div
+ class="flex h-8 min-w-0 items-center gap-2 pr-2.5 pl-2.5 text-ink text-sm leading-5"
+ data-magic-chip-answer
+ >
+ <span class="min-w-0 flex-1 truncate" data-magic-chip-line>
+ <Show
+ when={line()}
+ fallback={
+ <span class="text-ink-subtle italic">Nothing written yet</span>
+ }
>
+ {(text) => <>{text()}</>}
+ </Show>
+ </span>
+ <Show when={props.header?.pullRequestUrl}>
+ {(url) => (
<div
- class="relative mx-3 mt-1 mb-1 min-h-0 flex-1"
- classList={{ 'overflow-hidden': !expanded() }}
- data-magic-chip-clip
+ class="flex h-6 min-w-0 max-w-[45%] shrink-0 items-center overflow-hidden rounded-full border border-edge-muted bg-surface px-1 text-xs"
+ data-magic-chip-pull-request-slot
>
- <Show
- when={requestKey()}
- keyed
- fallback={
- <Show
- when={markdown()}
- fallback={<AnswerPending busy={status().busy} />}
- >
- {(answer) => <Passage markdown={answer()} />}
- </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>
+ <MagicChipPullRequest url={url()} />
</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>
- }
- >
- {(pending) => (
- <div class="p-3" data-magic-chip-permission>
- <PermissionCard
- action={pending().action}
- detail={pending().detail}
- options={pending().request.options}
- canAnswer={pending().canAnswer && Boolean(props.answer)}
- disabled={pending().answering}
- onSelect={(optionId) => {
- const current = pending();
- if (!current.canAnswer || current.answering) return;
- void props.answer?.respond({
- kind: 'permission',
- requestId: current.request.requestId,
- turn: current.request.turn,
- answer: { kind: 'selected', optionId },
- });
- }}
- />
- </div>
- )}
- </Show>
+ )}
+ </Show>
+ </div>
</div>
</Layer>
);
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.ts
index 67d083ca13..96775ac912 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
@@ -2,6 +2,7 @@ import type { FoldedMessage } from '@service-agent-fold/generated/types';
import { describe, expect, it } from 'vitest';
import {
deriveMagicChipPresentation,
+ flattenToLine,
presentationStatus,
} from './presentation';
@@ -553,3 +554,23 @@ describe('presentationStatus', () => {
);
});
});
+
+describe('flattenToLine', () => {
+ it('collapses block structure onto one line', () => {
+ expect(
+ flattenToLine('## Fixed\n\n- The **batch** fold now\n buffers it.')
+ ).toBe('Fixed The batch fold now buffers it.');
+ });
+
+ it('keeps snake_case identifiers whole but drops emphasis', () => {
+ expect(flattenToLine('It buffers `turn_ended` _before_ the replay.')).toBe(
+ 'It buffers turn_ended before the replay.'
+ );
+ });
+
+ it('drops fenced code entirely', () => {
+ expect(
+ flattenToLine('Run it:\n\n```sh\ncargo test\n```\n\nThen look.')
+ ).toBe('Run it: Then look.');
+ });
+});
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.ts
index 62c8ffa339..8cdc0b83a4 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
@@ -1,5 +1,6 @@
import { modelLabel } from '@core/component/AI/constant/model-label';
import type { MagicChipStatus } from '@macro-inc/lexical-core';
+import { markdownToPlainText } from '@macro-inc/lexical-core/utils/parsers';
import type {
FoldedMessage,
MessagePart,
@@ -371,6 +372,76 @@ function latestChunk(response: FoldedMessage | undefined): string {
}
/** The one line the chip's header reads for the turn. */
+/**
+ * What the status dot says at a glance: the turn is running, it has stopped
+ * to ask, or it is over. Colour only - whether the dot pulses is the
+ * activity's `busy`, which a running turn can drop while still running.
+ */
+export type MagicChipTone = 'busy' | 'asking' | 'done';
+
+export function presentationTone(
+ presentation: MagicChipPresentation
+): MagicChipTone {
+ return match(presentation)
+ .with({ kind: 'asking' }, () => 'asking' as const)
+ .with({ kind: 'settled' }, () => 'done' as const)
+ .with({ kind: 'working' }, { kind: 'answering' }, () => 'busy' as const)
+ .exhaustive();
+}
+
+/**
+ * Markdown flattened to the single line the console's output row shows.
+ *
+ * The row is one line of prose, so the block structure goes: fences, list
+ * bullets, heading hashes and quote marks are dropped and every run of
+ * whitespace becomes one space. Emphasis and inline code markers go too -
+ * the row has no formatting to carry them. Macro's own `<m-*>` tags are
+ * resolved first, so a mention reads as its name rather than its JSON.
+ *
+ * An underscore between two word characters is left alone: agents write
+ * about `turn_ended` and `agent_fold` far more often than they emphasise a
+ * word, and stripping those would rename the thing being discussed.
+ */
+export function flattenToLine(markdown: string): string {
+ return markdownToPlainText(markdown)
+ .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/^\s{0,3}(?:[-*+]|\d+[.)])\s+/gm, '')
+ .replace(/^\s{0,3}#{1,6}\s+/gm, '')
+ .replace(/^\s{0,3}>\s?/gm, '')
+ .replace(/[*~`]/g, '')
+ .replace(/_+/g, (run, at: number, text: string) =>
+ isWordChar(text[at - 1]) && isWordChar(text[at + run.length]) ? run : ''
+ )
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+function isWordChar(character: string | undefined): boolean {
+ return character !== undefined && /[A-Za-z0-9]/.test(character);
+}
+
+/**
+ * The one line the console's output row shows, or `undefined` when the turn
+ * has written nothing yet and the row should say so itself.
+ *
+ * A turn that has stopped to ask shows the question rather than the prose
+ * before it: the question is why the chip is sitting there.
+ */
+export function presentationLine(
+ presentation: MagicChipPresentation
+): string | undefined {
+ if (presentation.kind === 'asking') {
+ const { request, action, detail } = presentation.asking;
+ const asked =
+ request.kind === 'elicitation'
+ ? request.message
+ : [action, detail].filter(Boolean).join(' · ');
+ return asked || undefined;
+ }
+ if (presentation.kind === 'working') return undefined;
+ return flattenToLine(presentation.markdown) || undefined;
+}
+
export function presentationStatus(
presentation: MagicChipPresentation
): MagicChipActivity {
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index d02277e4ba..681ffc71b2 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -142,17 +142,17 @@ A follow-up sent while that session is still working stops the current turn,
posts a new Magic Chip on the follow-up message, and steers the agent with
that text — the chip appears at the follow-up, not after the cancelled turn
finishes.
-The reply renders a Magic Chip: a rounded card of constant height that is present
-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.
+The reply renders a Magic Chip: a compact two-row card, present from the moment the
+session boots and the same height in every state. Its status row starts with a dot that
+pulses while the turn works, turns amber while it waits on a question, and becomes a green
+check once the turn is over; then the persona (`Cursor Agent`, or a custom agent's name),
+what the turn is doing (`Booting agent`, `Running command · cargo test`, `Waiting for
+you`, `Done`), and a `View session` pill. The row beneath holds one line of the agent's
+latest prose (`Nothing written yet` before it has written; the question itself while it
+waits), with the pull request the session opened as a pill beside it once there is one.
+The whole card is one control: clicking anywhere on it, or `View session`, opens the agent
+session, which is where the passage whole and any question are read and answered. The
+card never expands in place.
`@codex` and `@claude` are offered to every user before account setup. The built-in
`@cursor` entry requires the `enable-cursor-agents` rollout flag (local override: