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.

style(ai): magic ship clean up (#7012)

Seamusd2fb2f1454a7
diff --git a/apps/web/src/components/ui/components/Badge.docs.tsx b/apps/web/src/components/ui/components/Badge.docs.tsx
index 4e3f1cfdfd..fd9318cb33 100644
--- a/apps/web/src/components/ui/components/Badge.docs.tsx
+++ b/apps/web/src/components/ui/components/Badge.docs.tsx
@@ -33,7 +33,7 @@ function VariantsDemo() {
function SizesDemo() {
return (
<div class="flex flex-wrap items-end gap-3">
- <For each={['sm', 'md', 'lg'] as const}>
+ <For each={['xs', 'sm', 'md', 'lg'] as const}>
{(size) => (
<div class="flex flex-col items-start gap-1.5">
<span class="font-mono text-xs text-ink-subtle">{size}</span>
@@ -92,7 +92,8 @@ export default defineDoc({
{
id: 'sizes',
title: 'Sizes',
- description: 'Matches the Button `sm` / `md` / `lg` control sizes.',
+ description:
+ 'Matches the Button `xs` / `sm` / `md` / `lg` control sizes.',
render: SizesDemo,
},
{
diff --git a/apps/web/src/components/ui/components/Badge.tsx b/apps/web/src/components/ui/components/Badge.tsx
index 55b52dea97..80a62f058a 100644
--- a/apps/web/src/components/ui/components/Badge.tsx
+++ b/apps/web/src/components/ui/components/Badge.tsx
@@ -16,7 +16,10 @@ export const badgeVariants = createVariants(
ghost: 'bg-transparent text-ink-muted',
outline: 'bg-transparent text-ink-muted border-edge-muted',
},
- size: CONTROL_SIZE_VARIANTS,
+ size: {
+ xs: "h-5 gap-1 px-2 text-xs [&>svg:not([class*='size-'])]:size-3",
+ ...CONTROL_SIZE_VARIANTS,
+ },
},
{
variant: 'ghost',
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentSessionMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentSessionMention.tsx
index 4b8af3cde9..c523787b92 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentSessionMention.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentSessionMention.tsx
@@ -10,10 +10,11 @@ import {
import { useAgentSessionMentionPreview } from '@queries/agent-session/mentions';
import {
$getNodeByKey,
+ $isRootOrShadowRoot,
COMMAND_PRIORITY_NORMAL,
KEY_ENTER_COMMAND,
} from 'lexical';
-import { Show, Suspense, useContext } from 'solid-js';
+import { onMount, Show, Suspense, useContext } from 'solid-js';
import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import { autoRegister } from '../../plugins';
import { AgentSessionMentionLabel } from './AgentSessionMentionLabel';
@@ -22,6 +23,17 @@ import { MagicChip } from './MagicChip';
export function AgentSessionMention(props: AgentSessionMentionDecoratorProps) {
const wrapper = useContext(LexicalWrapperContext);
const layout = useSplitLayout();
+ // Older documents stored expanded references inside paragraphs. Parsing a
+ // saved editor state skips transforms; normalize this node on first mount.
+ onMount(() => {
+ if (!props.expanded) return;
+ wrapper?.editor.update(() => {
+ const node = $getNodeByKey(props.key);
+ if (!$isAgentSessionMentionNode(node)) return;
+ const parent = node.getParent();
+ if (parent && !$isRootOrShadowRoot(parent)) node.markDirty();
+ });
+ });
const query = useAgentSessionMentionPreview(
() => props.id,
() => !wrapper?.skipPreviewFetch
@@ -122,19 +134,17 @@ export function AgentSessionMention(props: AgentSessionMentionDecoratorProps) {
/>
}
>
- <span
- class="inline-block w-full align-top my-2"
- data-agent-session-expanded="true"
- >
+ <div class="block w-full" data-agent-session-expanded="true">
<Suspense>
<MagicChip
+ key={props.key}
agentSessionId={props.id}
promptedMessage={null}
status="no_messages"
onCollapse={canExpand() ? () => setExpanded(false) : undefined}
/>
</Suspense>
- </span>
+ </div>
</Show>
);
}
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 a258193fa9..7b998f6e3f 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
@@ -1,21 +1,47 @@
import { useSplitLayout } from '@components/app/split-layout/layout';
import type { MagicChipData } from '@macro-inc/lexical-core';
-import type { Component } from 'solid-js';
+import { $createNodeSelection, $setSelection, type NodeKey } from 'lexical';
+import { type Component, useContext } from 'solid-js';
+import { LexicalWrapperContext } from '../../../context/LexicalWrapperContext';
import { createMagicChipModel } from './create-magic-chip-model';
import { MagicChipView } from './MagicChipView';
/** Shared session response surface, optionally anchored to one turn. */
export const MagicChip: Component<
- MagicChipData & { onCollapse?: () => void }
+ MagicChipData & { key?: NodeKey; onCollapse?: () => void }
> = (props) => {
const { insertSplit } = useSplitLayout();
const model = createMagicChipModel(props);
+ const wrapper = useContext(LexicalWrapperContext);
+ const inDocument = () =>
+ wrapper?.type === 'markdown' || wrapper?.type === 'markdown-sync';
+ const selected = () =>
+ Boolean(
+ props.key &&
+ wrapper?.selection?.type === 'node' &&
+ wrapper.selection.nodeKeys.has(props.key)
+ );
+ const selectNode = () => {
+ const key = props.key;
+ if (!key || !wrapper?.editor.isEditable()) return;
+ wrapper.editor.update(() => {
+ const selection = $createNodeSelection();
+ selection.add(key);
+ $setSelection(selection);
+ });
+ };
return (
<MagicChipView
agentSessionId={props.agentSessionId}
presentation={model.presentation()}
header={model.header()}
+ loading={model.loading()}
+ inDocument={inDocument()}
+ selected={selected()}
+ onSelect={
+ inDocument() && wrapper?.editor.isEditable() ? selectNode : undefined
+ }
onCollapse={props.onCollapse}
onOpen={() => insertSplit({ type: 'agent', id: props.agentSessionId })}
/>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.test.tsx
index 444dd6d215..6c69d7f3e9 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.test.tsx
@@ -26,14 +26,10 @@ vi.mock('@queries/client', async () => {
vi.mock('@service-storage/client', () => ({
storageServiceClient: { getForeignEntityBySource: vi.fn() },
}));
-vi.mock(
- '@core/component/LexicalMarkdown/component/decorator/PullRequestMention',
- () => ({
- PullRequestEntityLink: (props: { entity: ForeignEntity }) => (
- <span>{(props.entity.metadata as { status: string }).status}</span>
- ),
- })
-);
+const openWithSplit = vi.fn();
+vi.mock('@components/app/split-layout/layout', () => ({
+ useSplitLayout: () => ({ openWithSplit }),
+}));
afterEach(() => {
cleanup();
@@ -84,7 +80,12 @@ it('keeps an already mounted chip current through late sync and merge', async ()
id: '019f0000-0000-7000-8000-000000000001',
foreignEntityId: 'macro-inc/macro/pull/6369',
foreignEntitySource: 'github_pull_request',
- metadata: { status: 'open' },
+ metadata: {
+ status: 'open',
+ name: 'Fix reply state',
+ additions: 42,
+ deletions: 0,
+ },
storedForId: 'macro|[email protected]',
storedForAuthEntity: 'user',
createdAt: '2026-09-11T00:00:00Z',
@@ -106,14 +107,29 @@ it('keeps an already mounted chip current through late sync and merge', async ()
expect(lookup).toHaveBeenCalledTimes(1);
await handlePullRequestUpdated(entity);
await vi.advanceTimersByTimeAsync(1);
- expect(screen.getByText('open')).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: '#6369 · Fix reply state' })
+ ).toBeTruthy();
+ expect(screen.getByLabelText('42 lines added')).toBeTruthy();
+ expect(screen.getByLabelText('0 lines deleted')).toBeTruthy();
await handlePullRequestUpdated({
...entity,
- metadata: { status: 'merged' },
+ metadata: {
+ status: 'merged',
+ name: 'Fix reply state',
+ additions: 48,
+ deletions: 2,
+ },
updatedAt: '2026-09-11T00:01:00Z',
});
await vi.advanceTimersByTimeAsync(1);
- expect(screen.getByText('merged')).toBeTruthy();
+ expect(screen.getByLabelText('48 lines added')).toBeTruthy();
+ expect(screen.getByLabelText('2 lines deleted')).toBeTruthy();
+ screen.getByRole('button', { name: '#6369 · Fix reply state' }).click();
+ expect(openWithSplit).toHaveBeenCalledWith(
+ { type: 'pr', id: entity.id },
+ expect.any(Object)
+ );
rendered.unmount();
const calls = lookup.mock.calls.length;
await vi.advanceTimersByTimeAsync(30_000);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx
index a9a1661a57..a275e39949 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx
@@ -3,27 +3,79 @@ import {
prDisplayName,
toGithubKey,
} from '@app/features/block-pr/util/prKey';
-import { PullRequestEntityLink } from '@core/component/LexicalMarkdown/component/decorator/PullRequestMention';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { openInNewSplitForMention } from '@core/util/openInNewSplit';
+import GitMerge from '@phosphor/git-merge.svg';
import GitPullRequest from '@phosphor/git-pull-request.svg';
import { usePullRequestByGithubKeyQuery } from '@queries/storage/pr-mention';
+import { Button, buttonClasses } from '@ui';
import { type Component, createMemo, Show } from 'solid-js';
-/**
- * The pull request a session opened, in the chip's header: our GitHub PR
- * entity once the webhook has synced it, a plain link to GitHub until then.
- * Cloud runtimes can report the URL before the GitHub webhook entity exists.
- * Connection gateway supplies the saved entity and subsequent status changes.
- */
+/** Resolves a live PR without suspending the surrounding message/editor. */
export const MagicChipPullRequest: Component<{ url: string }> = (props) => {
+ const layout = useSplitLayout();
const reference = createMemo(() => parseGithubPrUrl(props.url));
const githubKey = createMemo(() => {
const parsed = reference();
return parsed ? toGithubKey(parsed) : undefined;
});
const query = usePullRequestByGithubKeyQuery(githubKey);
-
const entity = () => (query.isSuccess ? query.data : undefined);
-
+ const metadata = (): Record<string, unknown> => {
+ const value = entity()?.metadata;
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+ };
+ const label = () => {
+ const title = metadata().name;
+ const parsed = reference();
+ return typeof title === 'string' && title
+ ? `${parsed ? `#${parsed.number} · ` : ''}${title}`
+ : parsed
+ ? prDisplayName(parsed)
+ : 'Pull request';
+ };
+ const count = (key: 'additions' | 'deletions') => {
+ const value = metadata()[key];
+ return typeof value === 'number' ? value : undefined;
+ };
+ const content = () => (
+ <>
+ <Show
+ when={metadata().status === 'merged'}
+ fallback={
+ <GitPullRequest
+ aria-hidden="true"
+ class="size-3.5"
+ classList={{
+ 'text-success': metadata().status === 'open',
+ 'text-failure': metadata().status === 'closed',
+ }}
+ />
+ }
+ >
+ <GitMerge aria-hidden="true" class="size-3.5 text-note" />
+ </Show>
+ <span class="min-w-0 flex-1 truncate text-left">{label()}</span>
+ <Show when={count('additions') != null}>
+ <span
+ class="shrink-0 font-mono tabular-nums text-success"
+ aria-label={`${count('additions')} lines added`}
+ >
+ +{count('additions')}
+ </span>
+ </Show>
+ <Show when={count('deletions') != null}>
+ <span
+ class="shrink-0 font-mono tabular-nums text-failure"
+ aria-label={`${count('deletions')} lines deleted`}
+ >
+ −{count('deletions')}
+ </span>
+ </Show>
+ </>
+ );
return (
<Show
when={entity()}
@@ -32,23 +84,40 @@ export const MagicChipPullRequest: Component<{ url: string }> = (props) => {
href={props.url}
target="_blank"
rel="noreferrer"
- title={reference() ? prDisplayName(reference()!) : 'Pull request'}
- class="inline-flex min-w-0 max-w-full items-center gap-1 rounded-xs px-1 py-0.5 text-ink-muted hover:bg-hover hover:text-ink"
+ aria-label={label()}
+ class={buttonClasses({
+ variant: 'plain',
+ size: 'sm',
+ fullWidth: true,
+ noTouchResize: true,
+ class: 'h-8 min-w-0 justify-start rounded-lg bg-hover p-2',
+ })}
data-magic-chip-pull-request={props.url}
- onClick={(event) => event.stopPropagation()}
+ on:click={(event) => event.stopPropagation()}
>
- <GitPullRequest class="size-[1em] shrink-0 text-success" />
- <span class="truncate">
- {reference() ? prDisplayName(reference()!) : 'Pull request'}
- </span>
+ {content()}
</a>
}
>
- {(entity) => (
- <PullRequestEntityLink
- entity={entity()}
- class="max-w-full text-ink-muted hover:text-ink"
- />
+ {(pr) => (
+ <Button
+ variant="plain"
+ size="sm"
+ fullWidth
+ noTouchResize
+ class="h-8 min-w-0 justify-start rounded-lg bg-hover p-2"
+ aria-label={label()}
+ data-magic-chip-pull-request={props.url}
+ on:click={(event) => {
+ event.stopPropagation();
+ layout.openWithSplit(
+ { type: 'pr', id: pr().id },
+ { preferNewSplit: openInNewSplitForMention(event.shiftKey, true) }
+ );
+ }}
+ >
+ {content()}
+ </Button>
)}
</Show>
);
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
new file mode 100644
index 0000000000..3aa545c2fa
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
@@ -0,0 +1,113 @@
+/** @vitest-environment jsdom */
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { MagicChipView } from './MagicChipView';
+import type { MagicChipPresentation } from './presentation';
+
+vi.mock('./MagicChipPullRequest', () => ({
+ MagicChipPullRequest: () => <button type="button">Open PR fixture</button>,
+}));
+afterEach(cleanup);
+
+it('switches exclusively between output, PR and error detail as live state changes', () => {
+ const [url, setUrl] = createSignal<string>();
+ const [presentation, setPresentation] = createSignal<MagicChipPresentation>({
+ kind: 'answering',
+ markdown: 'Checking the stack build.',
+ activity: {
+ label: 'Running command',
+ detail: 'private command',
+ tone: 'tool',
+ busy: true,
+ },
+ });
+ const view = render(() => (
+ <MagicChipView
+ agentSessionId="test"
+ header={{ agent: 'Cursor Agent', pullRequestUrl: url() }}
+ presentation={presentation()}
+ />
+ ));
+ expect(screen.getByText('Checking the stack build.')).toBeTruthy();
+ expect(screen.queryByText('private command')).toBeNull();
+ setUrl('https://github.com/macro-inc/macro/pull/42');
+ expect(screen.getByRole('button', { name: 'Open PR fixture' })).toBeTruthy();
+ expect(screen.queryByText('Checking the stack build.')).toBeNull();
+ setPresentation({
+ kind: 'answering',
+ markdown: 'Old output',
+ activity: {
+ label: "Agent couldn't answer",
+ detail: 'The runtime stopped without a result.',
+ tone: 'failure',
+ busy: false,
+ },
+ });
+ expect(screen.queryByRole('button', { name: 'Open PR fixture' })).toBeNull();
+ expect(
+ screen
+ .getByText('The runtime stopped without a result.')
+ .closest('[data-magic-chip-body]')
+ ).toBeTruthy();
+ expect(screen.queryByText('Old output')).toBeNull();
+ expect(view.container.querySelector('[title]')).toBeNull();
+});
+
+it('uses a pulse dot during lazy loading and preserves session and collapse actions', () => {
+ const [loading, setLoading] = createSignal(true);
+ const open = vi.fn();
+ const collapse = vi.fn();
+ const view = render(() => (
+ <MagicChipView
+ agentSessionId="test"
+ loading={loading()}
+ presentation={{ kind: 'settled', markdown: 'Done.' }}
+ onOpen={open}
+ onCollapse={collapse}
+ />
+ ));
+ const icon = view.container.querySelector(
+ '[data-magic-chip-status-icon="loading"]'
+ );
+ expect(icon?.querySelector('svg')).toBeNull();
+ expect(icon?.querySelector('.animate-pulse')).toBeTruthy();
+ expect(screen.queryByText('Done.')).toBeNull();
+ setLoading(false);
+ fireEvent.click(screen.getByRole('button', { name: 'Open session' }));
+ expect(open).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole('button', { name: 'Collapse to mention' }));
+ expect(collapse).toHaveBeenCalledTimes(1);
+ expect(open).toHaveBeenCalledTimes(1);
+ fireEvent.keyDown(
+ screen.getByRole('button', { name: 'Open agent session' }),
+ { key: 'Enter' }
+ );
+ expect(open).toHaveBeenCalledTimes(2);
+});
+
+it('selects document cards without navigating and preserves the explicit session action', () => {
+ const select = vi.fn();
+ const open = vi.fn();
+ const [selected, setSelected] = createSignal(false);
+ const view = render(() => (
+ <MagicChipView
+ agentSessionId="test"
+ inDocument
+ selected={selected()}
+ onSelect={select}
+ onOpen={open}
+ presentation={{ kind: 'settled', markdown: 'Document response' }}
+ />
+ ));
+ const card = view.container.querySelector('[data-magic-chip-card]')!;
+ expect(card.classList.contains('bg-surface')).toBe(true);
+ fireEvent.click(screen.getByText('Document response'));
+ expect(select).toHaveBeenCalledTimes(1);
+ expect(open).not.toHaveBeenCalled();
+ setSelected(true);
+ expect(card.classList.contains('ring-2')).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Open session' }));
+ expect(open).toHaveBeenCalledTimes(1);
+ expect(select).toHaveBeenCalledTimes(1);
+});
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 f7bda2c945..f511e68cba 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,268 +1,269 @@
import ArrowUpRight from '@phosphor/arrow-up-right.svg';
import ArrowsIn from '@phosphor/arrows-in.svg';
-import Check from '@phosphor/check.svg';
-import { Button, Layer } from '@ui';
+import CheckCircle from '@phosphor-fill/check-circle-fill.svg';
+import QuestionCircle from '@phosphor-fill/question-fill.svg';
+import WarningCircle from '@phosphor-fill/warning-circle-fill.svg';
+import { Badge, Button, Card, cn } from '@ui';
+import { match } from 'ts-pattern';
+import './magic-chip-morph.css';
import { type Component, createMemo, Show } from 'solid-js';
import { MagicChipPullRequest } from './MagicChipPullRequest';
import {
- type MagicChipActivity,
type MagicChipHeader,
type MagicChipPresentation,
- type MagicChipTone,
presentationLine,
presentationStatus,
- presentationTone,
} from './presentation';
-const CONTROL = 'button, select, a, label, [role="button"]';
-
-/**
- * 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;
- const control = target.closest(CONTROL);
- return control !== null && control !== area && area.contains(control);
-}
-
-const TONE_DOT: Record<MagicChipTone, string> = {
- busy: 'bg-accent',
- asking: 'bg-amber',
- done: 'bg-green',
+type ChipStatus = {
+ label: string;
+ detail?: string;
+ tone:
+ | 'neutral'
+ | 'active'
+ | 'attention'
+ | 'success'
+ | 'failure'
+ | 'tool'
+ | 'stopped';
};
-/**
- * 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.
- */
-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"
- />
- }
- >
+function MagicChipStatusIcon(props: { status: ChipStatus; loading?: boolean }) {
+ const icon = () =>
+ match(props.loading ? 'loading' : props.status.tone)
+ .with('loading', () => (
+ <span class="size-2 rounded-full bg-ink-muted animate-pulse motion-reduce:animate-none" />
+ ))
+ .with('failure', () => (
+ <WarningCircle aria-hidden="true" class="text-failure" />
+ ))
+ .with('stopped', () => (
+ <span class="size-2.5 rounded-[1px] bg-ink-muted" />
+ ))
+ .with('success', () => (
+ <CheckCircle aria-hidden="true" class="text-success" />
+ ))
+ .with('active', () => <span class="magic-chip-morph" />)
+ .with('attention', () => (
+ <QuestionCircle aria-hidden="true" class="text-warning" />
+ ))
+ .with('neutral', () => (
+ <span class="size-2 rounded-full bg-ink-muted animate-pulse motion-reduce:animate-none" />
+ ))
+ .with('tool', () => <span class="magic-chip-morph" />)
+ .exhaustive();
+
+ return (
<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"
+ class="flex size-5 shrink-0 items-center justify-center [&>svg]:size-5"
+ data-magic-chip-status-icon={
+ props.loading ? 'loading' : props.status.tone
+ }
>
- <Check class="size-2.5" />
+ {icon()}
</span>
- </Show>
-);
+ );
+}
-/** The shimmering label plus its monospaced detail. */
-const ActivityText: Component<{ activity: MagicChipActivity }> = (props) => (
- <>
- <span
- class="shrink-0"
- classList={{
- 'magic-chip-shimmer': props.activity.busy,
- 'text-ink-muted': !props.activity.busy,
- }}
- aria-live="polite"
- >
- {props.activity.label}
- </span>
- <Show when={props.activity.detail}>
- {(detail) => (
- <>
- <span aria-hidden="true" class="shrink-0 text-ink-placeholder">
- ·
- </span>
- <span
- class="min-w-0 flex-1 truncate font-mono text-[11.5px] text-ink-extra-muted"
- title={detail()}
- >
- {detail()}
- </span>
- </>
+function MagicChipStatusBadge(props: {
+ status: ChipStatus;
+ loading?: boolean;
+}) {
+ const tone = () => (props.loading ? 'active' : props.status.tone);
+ return (
+ <Badge
+ size="xs"
+ variant="ghost"
+ class={cn(
+ 'min-w-0 max-w-52',
+ tone() === 'success' && 'bg-success-bg text-success-ink',
+ tone() === 'failure' && 'bg-failure-bg text-failure-ink',
+ tone() === 'attention' && 'bg-warning-bg text-warning-ink',
+ (tone() === 'active' ||
+ tone() === 'neutral' ||
+ tone() === 'stopped' ||
+ tone() === 'tool') &&
+ 'bg-hover text-ink-muted'
)}
- </Show>
- </>
-);
-
-/**
- * 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 StatusRow: Component<{
- header?: MagicChipHeader;
- status: MagicChipActivity;
- tone: MagicChipTone;
- /** The reply preview, while the output row has nothing to offer. */
- preview?: string;
- onOpen?: () => void;
- onCollapse?: () => void;
-}> = (props) => (
- <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
>
- <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}
+ class="truncate"
+ classList={{
+ 'magic-chip-shimmer':
+ !props.loading && props.status.label === 'Thinking',
+ }}
>
- <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>
- <ActivityText activity={props.status} />
+ {props.loading ? 'Loading' : props.status.label}
</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>
- <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}
- >
- View session
- <ArrowUpRight class="size-3" />
- </button>
- </div>
- </Layer>
-);
+ </Badge>
+ );
+}
-/**
- * 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.
- */
+/** Fixed-height response card for a live agent session. */
export const MagicChipView: Component<{
agentSessionId: string;
presentation: MagicChipPresentation;
header?: MagicChipHeader;
+ loading?: boolean;
+ inDocument?: boolean;
+ selected?: boolean;
+ onSelect?: () => void;
onOpen?: () => void;
onCollapse?: () => void;
}> = (props) => {
- const status = createMemo(() => presentationStatus(props.presentation));
- const tone = createMemo(() => presentationTone(props.presentation));
+ const status = createMemo((): ChipStatus => {
+ const activity = presentationStatus(props.presentation);
+ const tone =
+ props.presentation.kind === 'settled'
+ ? 'success'
+ : props.presentation.kind === 'asking'
+ ? 'attention'
+ : (activity.tone ?? 'active');
+ return {
+ label: activity.label,
+ tone,
+ // Tool details (commands, paths, etc.) stay inside the session.
+ detail:
+ tone === 'failure' || tone === 'stopped'
+ ? activity.detail || activity.label
+ : undefined,
+ };
+ });
const line = createMemo(() => presentationLine(props.presentation));
-
- // While the output row has no prose, a reply to the message previews the
- // status row's line instead.
- const preview = () => {
- if (line()) return undefined;
- const current = status();
- const activity = `${current.label}${current.detail ? ` ${current.detail}` : ''}`;
- const agent = props.header?.agent;
- return agent ? `${agent} · ${activity}` : activity;
- };
-
- const onCardClick = (event: MouseEvent & { currentTarget: Element }) => {
- if (isControl(event.target, event.currentTarget)) return;
- props.onOpen?.();
- };
+ const preview = () => status().detail || line() || status().label;
return (
- <Layer depth={2}>
- <div
- 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();
- onCardClick(event);
- }}
- on:mousedown={(event) => {
- // The chip sits in a Lexical message; a press must not move the
- // 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?.();
- }}
+ <div
+ role="button"
+ tabIndex={0}
+ aria-label="Open agent session"
+ class="my-2 w-full min-w-0 max-w-full text-left"
+ data-magic-chip={props.agentSessionId}
+ data-magic-chip-preview
+ data-message-reply-preview={preview()}
+ data-lexical-interactive
+ on:click={(event) => {
+ event.stopPropagation();
+ if (
+ event.target instanceof Element &&
+ event.target.closest('button, a')
+ )
+ return;
+ if (props.onSelect) props.onSelect();
+ else props.onOpen?.();
+ }}
+ on:mousedown={(event) => event.preventDefault()}
+ on:keydown={(event) => {
+ if (
+ event.target !== event.currentTarget ||
+ (event.key !== 'Enter' && event.key !== ' ')
+ )
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ props.onOpen?.();
+ }}
+ >
+ <Card
+ depth={2}
+ variant={props.inDocument ? 'filled' : 'ghost'}
+ contentEditable={false}
+ data-magic-chip-card
+ aria-label={`${props.header?.agent ?? 'Agent'} session`}
+ aria-busy={props.loading}
+ class={cn(
+ '@container h-22 min-h-22 w-full min-w-0 shrink-0 overflow-hidden rounded-2xl border border-edge p-3 text-ink',
+ props.inDocument &&
+ props.selected &&
+ 'border-[color-mix(in_oklch,var(--color-edge)_80%,var(--color-ink))] ring-2 ring-edge-muted'
+ )}
>
- <StatusRow
- header={props.header}
- status={status()}
- tone={tone()}
- preview={preview()}
- onOpen={props.onOpen}
- onCollapse={props.onCollapse}
- />
+ <div class="flex h-6 min-w-0 items-center gap-2">
+ <MagicChipStatusIcon status={status()} loading={props.loading} />
+ <span class="min-w-0 truncate text-xs font-semibold">
+ {props.header?.agent ?? 'Agent'}
+ </span>
+ <Show when={props.header?.model}>
+ {(model) => (
+ <span
+ class="hidden max-w-40 min-w-0 truncate text-xs text-ink-muted @[600px]:block"
+ data-magic-chip-model
+ >
+ {model()}
+ </span>
+ )}
+ </Show>
+ <MagicChipStatusBadge status={status()} loading={props.loading} />
+ <div class="min-w-0 flex-1" />
+ <Show when={props.onCollapse}>
+ <Button
+ variant="plain"
+ size="icon-sm"
+ noTouchResize
+ aria-label="Collapse to mention"
+ on:click={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ props.onCollapse?.();
+ }}
+ >
+ <ArrowsIn />
+ </Button>
+ </Show>
+ <Button
+ variant="outline"
+ size="sm"
+ noTouchResize
+ class="aspect-square rounded-full bg-transparent p-0 font-normal @[600px]:aspect-auto @[600px]:px-2"
+ aria-label="Open session"
+ disabled={props.loading || !props.onOpen}
+ on:click={(event) => {
+ event.stopPropagation();
+ props.onOpen?.();
+ }}
+ >
+ <span class="hidden @[600px]:inline">Open session</span>
+ <ArrowUpRight aria-hidden="true" class="size-3" />
+ </Button>
+ </div>
<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
+ class="mt-1.5 flex h-8 min-w-0 items-center gap-2"
+ data-magic-chip-output-row
>
- <span class="min-w-0 flex-1 truncate" data-magic-chip-line>
+ <Show
+ when={!props.loading}
+ fallback={
+ <div
+ class="flex h-8 min-w-0 flex-1 items-center pl-7"
+ aria-hidden="true"
+ >
+ <span class="h-3 w-4/5 rounded bg-hover" />
+ </div>
+ }
+ >
<Show
- when={line()}
+ when={!status().detail && props.header?.pullRequestUrl}
fallback={
- <span class="text-ink-subtle italic">Nothing written yet</span>
+ <p
+ class="h-8 min-w-0 flex-1 truncate pl-7 text-sm leading-8"
+ classList={{
+ italic:
+ status().tone === 'failure' ||
+ Boolean(status().detail) ||
+ !line(),
+ }}
+ data-magic-chip-body
+ >
+ {status().detail || line() || 'Nothing written yet'}
+ </p>
}
>
- {(text) => <>{text()}</>}
+ {(url) => <MagicChipPullRequest url={url()} />}
</Show>
- </span>
- <Show when={props.header?.pullRequestUrl}>
- {(url) => (
- <div
- 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
- >
- <MagicChipPullRequest url={url()} />
- </div>
- )}
</Show>
</div>
- </div>
- </Layer>
+ </Card>
+ </div>
);
};
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
index c8236ae63e..7c99159d3d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
@@ -562,7 +562,7 @@ describe('createMagicChipModel', () => {
expect(presentation()).toEqual({
kind: 'working',
- activity: { label: 'Session disconnected', busy: false },
+ activity: { label: 'Session disconnected', busy: false, tone: 'stopped' },
});
dispose();
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.ts
index 7f95e70046..04870e38c4 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
@@ -106,7 +106,9 @@ export function createMagicChipModel(props: MagicChipData): {
presentation: Accessor<MagicChipPresentation>;
header: Accessor<MagicChipHeader | undefined>;
interactions: InteractionController;
+ loading: Accessor<boolean>;
} {
+ const [loading, setLoading] = createSignal(true);
const [messages, setMessages] = createSignal<FoldedMessage[]>([]);
const sessionQuery = useAgentSessionQuery(() => props.agentSessionId);
// Guard pending data so a cold query cannot suspend the surrounding editor.
@@ -134,17 +136,25 @@ export function createMagicChipModel(props: MagicChipData): {
// A chip scrolled out of a virtualized list mid-load releases the session,
// which rejects the load or the snapshot. That is not a fault.
let released = false;
- void live
- .load()
- .then(() => live.snapshot())
- .then((snapshot) => {
+ async function loadSession() {
+ try {
+ await live.load();
+ if (released) return;
+
+ const snapshot = await live.snapshot();
+ if (released) return;
+
setMessages(snapshot.messages);
setMetadata(snapshot.metadata);
- })
- .catch((error: unknown) => {
- if (released) return;
- console.error('[magic-chip] session log could not be folded', error);
- });
+ } catch (error: unknown) {
+ if (!released) {
+ console.error('[magic-chip] session log could not be folded', error);
+ }
+ } finally {
+ if (!released) setLoading(false);
+ }
+ }
+ void loadSession();
onCleanup(() => {
released = true;
@@ -226,5 +236,5 @@ export function createMagicChipModel(props: MagicChipData): {
: undefined;
});
- return { presentation, header, interactions };
+ return { presentation, header, interactions, loading };
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/magic-chip-morph.css b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/magic-chip-morph.css
new file mode 100644
index 0000000000..f500f44b18
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/magic-chip-morph.css
@@ -0,0 +1,30 @@
+/* Morph motion from https://loading.dev/spinners/morph (loading-dev, MIT).
+ Adapted to the chip's 20px icon slot; inherits its currentColor. */
+.magic-chip-morph {
+ width: 50%;
+ height: 50%;
+ background: currentColor;
+ border-radius: 1.25px;
+ animation: magic-chip-morph 2000ms ease-in-out infinite;
+}
+
+@keyframes magic-chip-morph {
+ 0% {
+ border-radius: 1.25px;
+ transform: rotate(0deg);
+ }
+ 50% {
+ border-radius: 50%;
+ transform: rotate(45deg);
+ }
+ 100% {
+ border-radius: 1.25px;
+ transform: rotate(90deg);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .magic-chip-morph {
+ animation: none;
+ }
+}
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 96775ac912..406713bce9 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
@@ -172,6 +172,7 @@ describe('deriveMagicChipPresentation', () => {
kind: 'working',
activity: {
label: 'Running command',
+ tone: 'tool',
detail: 'cargo test',
busy: true,
},
@@ -304,6 +305,7 @@ describe('deriveMagicChipPresentation', () => {
markdown: 'Let me check the tests.',
activity: {
label: 'Running command',
+ tone: 'tool',
detail: 'cargo test',
busy: true,
},
@@ -322,7 +324,7 @@ describe('deriveMagicChipPresentation', () => {
expect(presentation).toEqual({
kind: 'answering',
markdown: 'Half an ans',
- activity: { label: 'Stopped', busy: false },
+ activity: { label: 'Stopped', busy: false, tone: 'stopped' },
});
});
@@ -351,6 +353,7 @@ describe('deriveMagicChipPresentation', () => {
kind: 'working',
activity: {
label: 'Cursor usage limit reached',
+ tone: 'failure',
detail:
'Raise the spending limit in your Cursor dashboard, then send it again.',
busy: false,
@@ -375,6 +378,7 @@ describe('deriveMagicChipPresentation', () => {
kind: 'working',
activity: {
label: "Agent couldn't answer",
+ tone: 'failure',
detail:
"Cursor can't access macro-inc/macro. Connect the repository to Cursor's GitHub app, then prompt again.",
busy: false,
@@ -568,9 +572,9 @@ describe('flattenToLine', () => {
);
});
- it('drops fenced code entirely', () => {
+ it('keeps code content when flattening fences', () => {
expect(
flattenToLine('Run it:\n\n```sh\ncargo test\n```\n\nThen look.')
- ).toBe('Run it: Then look.');
+ ).toBe('Run it: cargo test 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 8cdc0b83a4..3169ef52e6 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 = {
label: string;
detail?: string;
busy: boolean;
+ tone?:
+ | 'neutral'
+ | 'active'
+ | 'tool'
+ | 'attention'
+ | 'success'
+ | 'failure'
+ | 'stopped';
};
/** Who is answering, for the chip's header: the persona and its model. */
@@ -171,7 +179,10 @@ function partActivity(part: MessagePart): MagicChipActivity {
detail: text.trim() || undefined,
busy: true,
}))
- .with({ kind: 'tool_use' }, toolActivity)
+ .with({ kind: 'tool_use' }, (part) => ({
+ ...toolActivity(part),
+ tone: 'tool' as const,
+ }))
.with({ kind: 'permission', outcome: { kind: 'cancelled' } }, () => ({
label: 'Permission cancelled',
busy: false,
@@ -183,6 +194,7 @@ function partActivity(part: MessagePart): MagicChipActivity {
.with({ kind: 'permission', outcome: { kind: 'pending' } }, () => ({
label: 'Permission needed',
busy: false,
+ tone: 'attention' as const,
}))
.with({ kind: 'permission', outcome: { kind: 'errored' } }, () => ({
label: 'Permission failed',
@@ -208,6 +220,7 @@ function partActivity(part: MessagePart): MagicChipActivity {
.with({ kind: 'elicitation', outcome: { kind: 'pending' } }, () => ({
label: 'Waiting for your input',
busy: false,
+ tone: 'attention' as const,
}))
.with({ kind: 'elicitation', outcome: { kind: 'accepted' } }, () => ({
label: 'Resuming work',
@@ -254,46 +267,49 @@ function turnEndedActivity(
): MagicChipActivity | undefined {
const stop = response?.stop;
if (!stop) return undefined;
- return (
- match(stop)
- .with({ kind: 'end_turn' }, () => ({
- // A clean end with prose settles before activity is consulted, so
- // reaching this arm means the agent closed the turn empty-handed.
- label: 'Agent finished without a response',
- busy: false,
- }))
- .with({ kind: 'cancelled' }, () => ({ label: 'Stopped', busy: false }))
- .with({ kind: 'refusal' }, () => ({
- label: 'Request refused',
- busy: false,
- }))
- .with({ kind: 'max_tokens' }, () => ({
- label: 'Response limit reached',
- busy: false,
- }))
- .with({ kind: 'max_turn_requests' }, () => ({
- label: 'Turn limit reached',
- busy: false,
- }))
- .with({ kind: 'other' }, ({ reason }) => ({ label: reason, busy: false }))
- // A failure the runtime wrote in the person's terms — a spent Cursor
- // budget — is shown in those terms; the link lives in the session,
- // which the chip opens.
- .with({ kind: 'failed', notice: P.nonNullable }, ({ notice }) => ({
- label: notice.title,
- detail: notice.body,
- busy: false,
- }))
- // The runtime errored the prompt. The label says that much; the
- // runtime's own message goes in the detail line, because some of these
- // are the user's to act on — a repository Cursor cannot reach, say.
- .with({ kind: 'failed' }, ({ message }) => ({
- label: "Agent couldn't answer",
- detail: message,
- busy: false,
- }))
- .exhaustive()
- );
+ const activity = match(stop)
+ .with({ kind: 'end_turn' }, () => ({
+ // A clean end with prose settles before activity is consulted, so
+ // reaching this arm means the agent closed the turn empty-handed.
+ label: 'Agent finished without a response',
+ busy: false,
+ }))
+ .with({ kind: 'cancelled' }, () => ({ label: 'Stopped', busy: false }))
+ .with({ kind: 'refusal' }, () => ({
+ label: 'Request refused',
+ busy: false,
+ }))
+ .with({ kind: 'max_tokens' }, () => ({
+ label: 'Response limit reached',
+ busy: false,
+ }))
+ .with({ kind: 'max_turn_requests' }, () => ({
+ label: 'Turn limit reached',
+ busy: false,
+ }))
+ .with({ kind: 'other' }, ({ reason }) => ({ label: reason, busy: false }))
+ // A failure the runtime wrote in the person's terms — a spent Cursor
+ // budget — is shown in those terms; the link lives in the session,
+ // which the chip opens.
+ .with({ kind: 'failed', notice: P.nonNullable }, ({ notice }) => ({
+ label: notice.title,
+ detail: notice.body,
+ busy: false,
+ }))
+ // The runtime errored the prompt. The label says that much; the
+ // runtime's own message goes in the detail line, because some of these
+ // are the user's to act on — a repository Cursor cannot reach, say.
+ .with({ kind: 'failed' }, ({ message }) => ({
+ label: "Agent couldn't answer",
+ detail: message,
+ busy: false,
+ }))
+ .exhaustive();
+ const tone = match(stop.kind)
+ .with('end_turn', () => 'success' as const)
+ .with('cancelled', () => 'stopped' as const)
+ .otherwise(() => 'failure' as const);
+ return { ...activity, tone };
}
/**
@@ -327,7 +343,11 @@ function turnInFlightActivity(
/** The session's persisted lifecycle, when the fold has nothing livelier. */
function statusActivity(status: MagicChipStatus): MagicChipActivity {
return match(status)
- .with('no_messages', () => ({ label: 'Starting session', busy: false }))
+ .with('no_messages', () => ({
+ label: 'Queued',
+ busy: false,
+ tone: 'neutral' as const,
+ }))
.with('booting', () => ({
label: 'Booting agent',
detail: 'Preparing workspace',
@@ -338,6 +358,7 @@ function statusActivity(status: MagicChipStatus): MagicChipActivity {
.with('disconnected', () => ({
label: 'Session disconnected',
busy: false,
+ tone: 'stopped' as const,
}))
.exhaustive();
}
@@ -371,24 +392,6 @@ 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.
*
@@ -404,7 +407,7 @@ export function presentationTone(
*/
export function flattenToLine(markdown: string): string {
return markdownToPlainText(markdown)
- .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/^\s*```[^\n]*$/gm, ' ')
.replace(/^\s{0,3}(?:[-*+]|\d+[.)])\s+/gm, '')
.replace(/^\s{0,3}#{1,6}\s+/gm, '')
.replace(/^\s{0,3}>\s?/gm, '')
@@ -431,11 +434,11 @@ export function presentationLine(
presentation: MagicChipPresentation
): string | undefined {
if (presentation.kind === 'asking') {
- const { request, action, detail } = presentation.asking;
+ const { request, action } = presentation.asking;
const asked =
request.kind === 'elicitation'
? request.message
- : [action, detail].filter(Boolean).join(' · ');
+ : action || 'Open session to respond';
return asked || undefined;
}
if (presentation.kind === 'working') return undefined;
@@ -482,7 +485,9 @@ export function deriveMagicChipPresentation(
turnEndedActivity(response) ??
liveEventActivity(latestEvent, 'disconnected') ??
turnInFlightActivity(response) ??
- (prompt ? { label: 'Waiting for agent', busy: true } : undefined) ??
+ (prompt
+ ? { label: 'Waiting for agent', busy: true, tone: 'neutral' as const }
+ : undefined) ??
liveEventActivity(latestEvent, 'acp_ready') ??
statusActivity(persistedStatus);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
index 379464d915..c56d9815a8 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
@@ -23,5 +23,6 @@
* Version 4.1 - Sep 2026. Expandable session mentions reuse Magic Chip with a null message lock for the latest turn.
* Version 4.2 - Sep 2026. ConnectAppNode: optional `target` (connections | harness) so the chip can connect Cursor.
* Version 4.3 - Sep 2026. ReplyTargetNode references a message parent (channel or document) instead of a channel id.
+ * Version 4.4 - Sep 2026. Expanded agent session mentions are block decorators with node selection.
*/
-export const MARKDOWN_VERSION_COUNTER = 4.3;
+export const MARKDOWN_VERSION_COUNTER = 4.4;
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index fc4b890945..ca71402f6e 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -138,17 +138,18 @@ 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 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.
+The reply renders a Magic Chip: a fixed 88px two-row card on desktop and mobile,
+including lazy loading. The header shows a leading status icon, agent name, model
+(hidden below 600px), an xs status badge, and an outlined **Open session** button
+(icon-only and circular on narrow cards). Working and tool calls use a slow Morph;
+lazy loading and queued states use a gray pulsing dot. Done uses a filled check circle,
+errors a warning circle, input requests a yellow question circle, and stopped a square.
+The lower row shows either a full-width PR preview with available line diff counts or
+one truncated line of agent output. Failure explanations replace that preview; tool
+commands and other secondary details stay inside the session. There are no tooltips.
+Click the card or **Open session** to read the full response or answer a question;
+click the PR to open its Macro split (GitHub until its entity has synced). Expanded
+session mentions retain their collapse control. 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:
@@ -184,12 +185,9 @@ PR status in an open Magic Chip updates from connection-gateway events after
webhook sync. Reconnecting refreshes active PR lookups to recover missed updates.
A late webhook does not require reloading the page.
-When the agent requests permission, the Magic Chip replaces its loading state
-with the action and `Allow once`, `Deny`, and `More options` controls. Permission
-requests and questions share the chip's pending-interaction state and apply only
-to its anchored turn. Session editors and owners can answer directly in the chip;
-viewers and commenters see a waiting notice. Answering clears the request in both
-the chip and the open session, and the chip follows the agent's next activity.
+When the agent requests permission or input, the Magic Chip displays the waiting
+status for its anchored turn. Open the session to answer; editors and owners can
+respond there. The chip follows the agent's next activity after the answer.
Coding agents use `macro_internal.set_pull_request` to register an existing or
new GitHub PR with their session. Macro Internal MCP is hosted by the harness
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 288db32a3d..6172811007 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -387,7 +387,11 @@ Enter) to open `/app/agent/<id>`.
It references an existing session; it does not invoke the persona, attach its
transcript to AI context, or grant access. Private/deleted sessions show an
unavailable label. Mounted references refresh every 30 seconds while the tab is
-active to update titles and check access.
+active to update titles and check access. Expanded session references are block-level
+Magic Chips with the same filled background as document cards. Click the card body
+to select its editor node (border and selection ring); use **Open session** to navigate.
+The collapse action returns the card to an inline session mention. Text before and
+after an expanded reference remains in separate paragraphs.
Hover a document reference chip to open its preview without navigating. With
the preview open, the compact header shows a tinted icon, title, and author/time
diff --git a/packages/lexical-core/nodes/AgentSessionMentionNode.ts b/packages/lexical-core/nodes/AgentSessionMentionNode.ts
index 0bcec18bd3..533ff7a5c5 100644
--- a/packages/lexical-core/nodes/AgentSessionMentionNode.ts
+++ b/packages/lexical-core/nodes/AgentSessionMentionNode.ts
@@ -1,5 +1,10 @@
+import { $insertNodeToNearestRootAtCaret } from '@lexical/utils';
import {
$applyNodeReplacement,
+ $createParagraphNode,
+ $getSiblingCaret,
+ $isParagraphNode,
+ $isRootOrShadowRoot,
DecoratorNode,
type DOMConversion,
type DOMConversionMap,
@@ -14,7 +19,7 @@ import {
import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';
import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
-const VERSION = 2;
+const VERSION = 3;
export type AgentSessionMentionInfo = {
id: string;
@@ -41,12 +46,43 @@ export class AgentSessionMentionNode extends DecoratorNode<
__mentionUuid: string | undefined;
__expanded: boolean;
+ __cachedDecoratorSignature?: string;
+ __cachedDecoratorComponent?: DecoratorComponent<AgentSessionMentionDecoratorProps>;
+
static getType() {
return 'agent-session-mention';
}
isInline(): boolean {
- return true;
+ return !this.__expanded;
+ }
+
+ static transform() {
+ return (node: LexicalNode) => {
+ if (!$isAgentSessionMentionNode(node)) return;
+ const parent = node.getParent();
+ if (!parent) return;
+ if (node.isExpanded() && !$isRootOrShadowRoot(parent)) {
+ $insertNodeToNearestRootAtCaret(
+ node,
+ $getSiblingCaret(node, 'previous')
+ );
+ // Splitting an otherwise empty paragraph must not add blank lines.
+ if ($isParagraphNode(parent)) {
+ for (const sibling of [
+ node.getPreviousSibling(),
+ node.getNextSibling(),
+ ]) {
+ if ($isParagraphNode(sibling) && sibling.isEmpty())
+ sibling.remove();
+ }
+ }
+ } else if (!node.isExpanded() && $isRootOrShadowRoot(parent)) {
+ const paragraph = $createParagraphNode();
+ node.replace(paragraph);
+ paragraph.append(node);
+ }
+ };
}
isKeyboardSelectable(): boolean {
@@ -54,13 +90,16 @@ export class AgentSessionMentionNode extends DecoratorNode<
}
static clone(node: AgentSessionMentionNode) {
- return new AgentSessionMentionNode(
+ const clone = new AgentSessionMentionNode(
node.__id,
node.__label,
node.__mentionUuid,
node.__key,
node.__expanded
);
+ clone.__cachedDecoratorSignature = node.__cachedDecoratorSignature;
+ clone.__cachedDecoratorComponent = node.__cachedDecoratorComponent;
+ return clone;
}
constructor(
@@ -110,13 +149,13 @@ export class AgentSessionMentionNode extends DecoratorNode<
}
createDOM(_config: EditorConfig): HTMLElement {
- const span = document.createElement('span');
+ const span = document.createElement(this.__expanded ? 'div' : 'span');
span.setAttribute('data-agent-session-mention', 'true');
return span;
}
- updateDOM(_prevNode: AgentSessionMentionNode, _dom: HTMLElement): boolean {
- return false;
+ updateDOM(prevNode: AgentSessionMentionNode, _dom: HTMLElement): boolean {
+ return prevNode.__expanded !== this.__expanded;
}
static importDOM(): DOMConversionMap<HTMLElement> | null {
@@ -148,6 +187,7 @@ export class AgentSessionMentionNode extends DecoratorNode<
};
return {
+ div: wrapInCheck({ conversion: convert, priority: 1 }),
span: wrapInCheck({ conversion: convert, priority: 1 }),
a: wrapInCheck({ conversion: convert, priority: 1 }),
};
@@ -164,7 +204,7 @@ export class AgentSessionMentionNode extends DecoratorNode<
}
exportDOM() {
- const element = document.createElement('span');
+ const element = document.createElement(this.__expanded ? 'div' : 'span');
const attrs = this.getDataAttrs();
for (const [k, v] of Object.entries(attrs)) {
if (v) {
@@ -194,6 +234,7 @@ export class AgentSessionMentionNode extends DecoratorNode<
setLabel(label: string | undefined) {
const self = this.getWritable();
self.__label = label;
+ self.__cachedDecoratorComponent = undefined;
}
isExpanded(): boolean {
@@ -201,7 +242,9 @@ export class AgentSessionMentionNode extends DecoratorNode<
}
setExpanded(expanded: boolean) {
- this.getWritable().__expanded = expanded;
+ const self = this.getWritable();
+ self.__expanded = expanded;
+ self.__cachedDecoratorComponent = undefined;
}
getMentionUuid(): string | undefined {
@@ -211,21 +254,30 @@ export class AgentSessionMentionNode extends DecoratorNode<
setMentionUuid(mentionUuid: string | undefined) {
const self = this.getWritable();
self.__mentionUuid = mentionUuid;
+ self.__cachedDecoratorComponent = undefined;
}
decorate(_: LexicalEditor, config: EditorConfig) {
+ const signature = JSON.stringify(this.exportComponentProps());
+ if (
+ this.__cachedDecoratorComponent &&
+ this.__cachedDecoratorSignature === signature
+ )
+ return this.__cachedDecoratorComponent;
+ this.__cachedDecoratorSignature = signature;
const Component = getDecorator<AgentSessionMentionDecoratorProps>(
AgentSessionMentionNode
);
if (!Component) return undefined;
- return () =>
+ this.__cachedDecoratorComponent = () =>
Component({
...this.exportComponentProps(),
key: this.getKey(),
theme: config.theme,
});
+ return this.__cachedDecoratorComponent;
}
}
diff --git a/packages/lexical-core/nodes/MagicChipNode.ts b/packages/lexical-core/nodes/MagicChipNode.ts
index c82ff7a657..50b0328e5c 100644
--- a/packages/lexical-core/nodes/MagicChipNode.ts
+++ b/packages/lexical-core/nodes/MagicChipNode.ts
@@ -95,18 +95,24 @@ export class MagicChipNode extends DecoratorNode<
__promptedMessage: MagicChipMessage | null;
__status: MagicChipStatus;
+ __cachedDecoratorSignature?: string;
+ __cachedDecoratorComponent?: DecoratorComponent<MagicChipDecoratorProps>;
+
static getType() {
return MAGIC_CHIP_NODE_TYPE;
}
static clone(node: MagicChipNode) {
- return new MagicChipNode(
+ const clone = new MagicChipNode(
node.__agentSessionId,
node.__channelId,
node.__promptedMessage,
node.__status,
node.__key
);
+ clone.__cachedDecoratorSignature = node.__cachedDecoratorSignature;
+ clone.__cachedDecoratorComponent = node.__cachedDecoratorComponent;
+ return clone;
}
constructor(
@@ -183,14 +189,22 @@ export class MagicChipNode extends DecoratorNode<
}
decorate(_: LexicalEditor, config: EditorConfig) {
+ const signature = JSON.stringify(this.exportComponentProps());
+ if (
+ this.__cachedDecoratorComponent &&
+ this.__cachedDecoratorSignature === signature
+ )
+ return this.__cachedDecoratorComponent;
+ this.__cachedDecoratorSignature = signature;
const decorator = getDecorator<MagicChipDecoratorProps>(MagicChipNode);
if (decorator) {
- return () =>
+ this.__cachedDecoratorComponent = () =>
decorator({
...this.exportComponentProps(),
key: this.getKey(),
theme: config.theme,
});
+ return this.__cachedDecoratorComponent;
}
}
}
diff --git a/packages/lexical-core/tests/agent-session-mention.test.ts b/packages/lexical-core/tests/agent-session-mention.test.ts
index a5d25acdac..f2f05b0e57 100644
--- a/packages/lexical-core/tests/agent-session-mention.test.ts
+++ b/packages/lexical-core/tests/agent-session-mention.test.ts
@@ -1,10 +1,17 @@
// @vitest-environment jsdom
import { createHeadlessEditor } from '@lexical/headless';
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
-import { $getRoot, $isParagraphNode } from 'lexical';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getNodeByKey,
+ $getRoot,
+ $isParagraphNode,
+} from 'lexical';
import { describe, expect, it } from 'vitest';
import { NodeReplacements, SupportedNodeTypes } from '../node-list';
import {
+ $createAgentSessionMentionNode,
$isAgentSessionMentionNode,
buildAgentSessionMentionMarkdown,
} from '../nodes/AgentSessionMentionNode';
@@ -26,7 +33,8 @@ describe('AgentSessionMentionNode', () => {
});
const state = markdownToSerializedEditorStateWithIds(expanded);
expect(state.root.children[0]).toMatchObject({
- children: [{ type: 'agent-session-mention', expanded: true }],
+ type: 'agent-session-mention',
+ expanded: true,
});
expect(serializedEditorStateToMarkdown(state)).toBe(expanded);
expect(extractChannelMentionsFromMarkdown(expanded)).toEqual([
@@ -103,10 +111,9 @@ describe('AgentSessionMentionNode', () => {
.clear()
.append(...nodes);
const paragraph = $getRoot().getFirstChild();
- expect($isParagraphNode(paragraph)).toBe(true);
const node = $isParagraphNode(paragraph)
? paragraph.getFirstChild()
- : null;
+ : paragraph;
expect($isAgentSessionMentionNode(node)).toBe(true);
if ($isAgentSessionMentionNode(node)) {
expect(node.getId()).toBe(info.id);
@@ -118,3 +125,53 @@ describe('AgentSessionMentionNode', () => {
}
);
});
+
+it('expands between text into a block and collapses back into an inline paragraph', () => {
+ const editor = createHeadlessEditor({
+ nodes: [...SupportedNodeTypes, ...NodeReplacements],
+ });
+ let key = '';
+ editor.update(
+ () => {
+ const node = $createAgentSessionMentionNode(info);
+ key = node.getKey();
+ $getRoot().append(
+ $createParagraphNode().append(
+ $createTextNode('Before'),
+ node,
+ $createTextNode('After')
+ )
+ );
+ node.setExpanded(true);
+ },
+ { discrete: true }
+ );
+ editor.getEditorState().read(() => {
+ const nodes = $getRoot().getChildren();
+ expect(nodes.map((node) => node.getType())).toEqual([
+ 'paragraph',
+ 'agent-session-mention',
+ 'paragraph',
+ ]);
+ expect(nodes.map((node) => node.getTextContent())).toEqual([
+ 'Before',
+ info.label,
+ 'After',
+ ]);
+ expect($getNodeByKey(key)?.isInline()).toBe(false);
+ });
+ editor.update(
+ () => {
+ const node = $getNodeByKey(key);
+ if ($isAgentSessionMentionNode(node)) node.setExpanded(false);
+ },
+ { discrete: true }
+ );
+ editor.getEditorState().read(() => {
+ const node = $getNodeByKey(key);
+ expect(node?.isInline()).toBe(true);
+ expect($isParagraphNode(node?.getParent())).toBe(true);
+ expect($getRoot().getTextContent()).toContain('Before');
+ expect($getRoot().getTextContent()).toContain('After');
+ });
+});
diff --git a/packages/lexical-core/tests/session-decorator-stability.test.ts b/packages/lexical-core/tests/session-decorator-stability.test.ts
new file mode 100644
index 0000000000..a2d6b0d7a3
--- /dev/null
+++ b/packages/lexical-core/tests/session-decorator-stability.test.ts
@@ -0,0 +1,74 @@
+// @vitest-environment jsdom
+import { createHeadlessEditor } from '@lexical/headless';
+import { $createParagraphNode, $getNodeByKey, $getRoot } from 'lexical';
+import { afterEach, expect, it } from 'vitest';
+import { clearDecorators, setDecorator } from '../decoratorRegistry';
+import { NodeReplacements, SupportedNodeTypes } from '../node-list';
+import {
+ $createAgentSessionMentionNode,
+ AgentSessionMentionNode,
+} from '../nodes/AgentSessionMentionNode';
+import { $createMagicChipNode, MagicChipNode } from '../nodes/MagicChipNode';
+
+afterEach(clearDecorators);
+
+it.each(['mention', 'magic'] as const)(
+ 'keeps the %s decorator mounted across adjacent paragraph edits',
+ (kind) => {
+ setDecorator(AgentSessionMentionNode, () => null);
+ setDecorator(MagicChipNode, () => null);
+ const editor = createHeadlessEditor({
+ nodes: [...SupportedNodeTypes, ...NodeReplacements],
+ });
+ let key = '';
+ let original: unknown;
+ editor.update(
+ () => {
+ const node =
+ kind === 'mention'
+ ? $createAgentSessionMentionNode({ id: 'session', expanded: true })
+ : $createMagicChipNode({
+ agentSessionId: 'session',
+ promptedMessage: null,
+ status: 'no_messages',
+ });
+ $getRoot().append(node);
+ key = node.getKey();
+ original = node.decorate(editor, editor._config);
+ },
+ { discrete: true }
+ );
+ for (const side of ['before', 'after'] as const) {
+ editor.update(
+ () => {
+ const node = $getNodeByKey(key);
+ if (
+ !(
+ node instanceof AgentSessionMentionNode ||
+ node instanceof MagicChipNode
+ )
+ )
+ throw new Error('Missing node');
+ if (side === 'before') node.insertBefore($createParagraphNode());
+ else node.insertAfter($createParagraphNode());
+ expect(node.getLatest().decorate(editor, editor._config)).toBe(
+ original
+ );
+ },
+ { discrete: true }
+ );
+ }
+ if (kind === 'mention') {
+ editor.update(
+ () => {
+ const node = $getNodeByKey<AgentSessionMentionNode>(key)!;
+ node.setLabel('Updated title');
+ expect(node.getLatest().decorate(editor, editor._config)).not.toBe(
+ original
+ );
+ },
+ { discrete: true }
+ );
+ }
+ }
+);
diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.ts
index 10dc1d60db..9b578e1ccc 100644
--- a/packages/lexical-core/transformers/index.ts
+++ b/packages/lexical-core/transformers/index.ts
@@ -22,6 +22,7 @@ import {
E_PR_MENTION,
E_TAG_MENTION,
E_USER_MENTION,
+ I_AGENT_SESSION_CARD,
I_AGENT_SESSION_MENTION,
I_CONNECT_APP,
I_CONTACT_MENTION,
@@ -76,6 +77,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_DOCUMENT_MENTION,
I_DOCUMENT_CARD,
I_PR_MENTION,
+ I_AGENT_SESSION_CARD,
I_AGENT_SESSION_MENTION,
I_CONTACT_MENTION,
I_DATE_MENTION,
@@ -163,6 +165,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [
I_DOCUMENT_CARD,
E_DOCUMENT_CARD,
I_PR_MENTION,
+ I_AGENT_SESSION_CARD,
I_AGENT_SESSION_MENTION,
E_AGENT_SESSION_MENTION,
E_PR_MENTION,
diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.ts
index eb81d06f8f..82f7074326 100644
--- a/packages/lexical-core/transformers/mentions.ts
+++ b/packages/lexical-core/transformers/mentions.ts
@@ -407,6 +407,19 @@ export const I_AGENT_SESSION_MENTION: TextMatchTransformer = {
},
};
+/** Expanded session references serialize as blocks while preserving their identity. */
+export const I_AGENT_SESSION_CARD: ElementTransformer = {
+ dependencies: [AgentSessionMentionNode],
+ type: 'element',
+ regExp: /$^/,
+ export: (node) => {
+ if (!(node instanceof AgentSessionMentionNode) || !node.isExpanded())
+ return null;
+ return buildAgentSessionMentionMarkdown(node.exportComponentProps());
+ },
+ replace: () => false,
+};
+
// External Agent Session Mentions
export const E_AGENT_SESSION_MENTION: ElementTransformer = {