Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore(agents): expand session mentions into Magic Chips that follow the latest turn (#6357)
Wolf Mermelsteinefc833da5c62
diff --git a/apps/web/src/lib/core/component/DocumentPreview.tsx b/apps/web/src/lib/core/component/DocumentPreview.tsxindex ce23ab58d5..fda59ed0b4 100644--- a/apps/web/src/lib/core/component/DocumentPreview.tsx+++ b/apps/web/src/lib/core/component/DocumentPreview.tsx@@ -231,6 +231,7 @@ function PopupIconButton(props: {return (<Tooltip label={props.tooltip}><button+ aria-label={props.tooltip}onClick={(e) => {e.stopPropagation();props.onClick();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsxindex dddd841a32..7a34178a85 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx@@ -201,6 +201,12 @@ export const MarkdownShell: Component<)}on:keydown={(e) => e.stopPropagation()}on:click={(e) => {+ // Embedded controls own focus and need Solid's delegated clicks.+ if (+ e.target instanceof Element &&+ e.target.closest('[data-lexical-interactive]')+ )+ return;e.stopPropagation();if (!isMobile()) editor.focus();}}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsxindex c0706f5a53..69dc6e8d2b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx@@ -351,6 +351,12 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {e.stopPropagation();}}on:click={(e) => {+ // Embedded controls own focus and need Solid's delegated clicks.+ if (+ e.target instanceof Element &&+ e.target.closest('[data-lexical-interactive]')+ )+ return;e.stopPropagation();editor.focus();}}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex 069ea0336d..83f1b8615d 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -12,6 +12,7 @@ import type { TableCellNode, TableNode, TableRowNode } from '@lexical/table';import {$isClassedBlockNode,type AgentContextNode,+ type AgentSessionMentionNode,type AwaitNode,type ClassedBlockNode,type ConnectAppNode,@@ -77,6 +78,7 @@ import { theme as baseTheme, createTheme } from '../../theme';import { forceSingleLine, setEditorStateFromMarkdown } from '../../utils';import { StaticCodeBoxAccessory } from '../accessory/CodeBoxAccessory';import { AgentContext as AgentContextDecorator } from '../decorator/AgentContext';+import { AgentSessionMention as AgentSessionMentionDecorator } from '../decorator/AgentSessionMention';import { Await as AwaitDecorator } from '../decorator/Await';import { ConnectApp as ConnectAppDecorator } from '../decorator/ConnectApp';import { ContactMention as ContactMentionDecorator } from '../decorator/ContactMention';@@ -237,6 +239,7 @@ function getTextClassName(| TextNode| UserMentionNode| DocumentMentionNode+ | AgentSessionMentionNode| ContactMentionNode| DateMentionNode| WatermarkNode,@@ -397,6 +400,20 @@ const DocumentMention: TypedRenderableEntity<DocumentMentionNode> = {},};+const AgentSessionMention: TypedRenderableEntity<AgentSessionMentionNode> = {+ guard: (node: LexicalNode): node is AgentSessionMentionNode =>+ node.__type === 'agent-session-mention',+ render: (props) => (+ <span class={getTextClassName(props.node, props.theme)}>+ {AgentSessionMentionDecorator({+ ...props.node.exportComponentProps(),+ key: props.node.getKey(),+ theme: props.theme,+ })}+ </span>+ ),+};+const ThemeMention: TypedRenderableEntity<ThemeMentionNode> = {guard: (node: LexicalNode): node is ThemeMentionNode =>node.__type === 'theme-mention',@@ -549,11 +566,7 @@ const MagicChip: TypedRenderableEntity<MagicChipNode> = {node.__type === 'magic-chip',render: (props) => (<div class="min-w-0 max-w-full overflow-x-hidden">- <MagicChipDecorator- {...props.node.exportComponentProps()}- key={props.node.getKey()}- theme={props.theme}- />+ <MagicChipDecorator {...props.node.exportComponentProps()} /></div>),};@@ -906,6 +919,7 @@ const InlineEntities: RenderableEntity[] = [eraseRenderableEntity(LineBreak),eraseRenderableEntity(UserMention),eraseRenderableEntity(DocumentMention),+ eraseRenderableEntity(AgentSessionMention),eraseRenderableEntity(DocumentCard),eraseRenderableEntity(ContactMention),eraseRenderableEntity(DateMention),diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentSessionMention.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentSessionMention.test.tsxindex 7794ae47d2..249c7abae1 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentSessionMention.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentSessionMention.test.tsx@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({query: { isSuccess: true, isError: false, data: {} as unknown },open: vi.fn(),+ magic: vi.fn(),subscribe: vi.fn(() => () => {}),}));vi.mock('@components/app/split-layout/layout', () => ({@@ -20,6 +21,19 @@ vi.mock('@queries/agent-session/mentions', () => ({vi.mock('@queries/agent-session/session-fold', () => ({subscribeAgentSessionLog: mocks.subscribe,}));+vi.mock('./MagicChip', () => ({+ MagicChip: (props: unknown) => {+ mocks.magic(props);+ return <span data-magic-chip>Latest session response</span>;+ },+}));+vi.mock('@core/component/DocumentPreview', () => ({+ PopupPreview: () => null,+}));+vi.mock('@core/component/HoverCard', () => ({+ HoverCard: (props: { trigger: import('solid-js').JSX.Element }) =>+ props.trigger,+}));vi.mock('../../plugins', () => ({ autoRegister: vi.fn() }));import { AgentSessionMention } from './AgentSessionMention';@@ -40,6 +54,41 @@ beforeEach(() => {});describe('agent session mention rendering', () => {+ it('mounts the shared Magic Chip with a null message lock only when expanded', () => {+ const view = render(() => (+ <AgentSessionMention+ id="session"+ label="Saved title"+ key="node"+ theme={{}}+ expanded+ />+ ));+ expect(view.container.querySelector('[data-magic-chip]')).not.toBeNull();+ expect(mocks.magic).toHaveBeenCalledWith(+ expect.objectContaining({+ agentSessionId: 'session',+ promptedMessage: null,+ })+ );+ });+ it.each(['no_access', 'does_not_exist'])(+ 'does not mount expanded session content for %s',+ (access) => {+ mocks.query.data = { access };+ render(() => (+ <AgentSessionMention+ id="session"+ label="Secret"+ key="node"+ theme={{}}+ expanded+ />+ ));+ expect(mocks.magic).not.toHaveBeenCalled();+ }+ );+it('shows only the agent icon and underlined title, and opens the agent block', () => {const view = render(() => (<AgentSessionMention@@ -58,6 +107,7 @@ describe('agent session mention rendering', () => {screen.getByText('Fix mentions').classList.contains('underline')).toBe(true);expect(mocks.subscribe).not.toHaveBeenCalled();+ expect(mocks.magic).not.toHaveBeenCalled();fireEvent.click(screen.getByText('Fix mentions'));expect(mocks.open).toHaveBeenCalledWith({ type: 'agent', id: 'session' },@@ -81,6 +131,7 @@ describe('agent session mention rendering', () => {fireEvent.click(view.container.firstElementChild!);expect(mocks.open).not.toHaveBeenCalled();expect(mocks.subscribe).not.toHaveBeenCalled();+ expect(mocks.magic).not.toHaveBeenCalled();});it('does not read pending query data or suspend the editor', () => {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.tsxindex 0bd4362c58..4790f2137d 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@@ -1,13 +1,23 @@import { useSplitLayout } from '@components/app/split-layout/layout';+import { PopupPreview } from '@core/component/DocumentPreview';+import { HoverCard } from '@core/component/HoverCard';import { openInNewSplitForMention } from '@core/util/openInNewSplit';import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';-import type { AgentSessionMentionDecoratorProps } from '@macro-inc/lexical-core';+import {+ $isAgentSessionMentionNode,+ type AgentSessionMentionDecoratorProps,+} from '@macro-inc/lexical-core';import { useAgentSessionMentionPreview } from '@queries/agent-session/mentions';-import { COMMAND_PRIORITY_NORMAL, KEY_ENTER_COMMAND } from 'lexical';-import { useContext } from 'solid-js';+import {+ $getNodeByKey,+ COMMAND_PRIORITY_NORMAL,+ KEY_ENTER_COMMAND,+} from 'lexical';+import { Show, Suspense, useContext } from 'solid-js';import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';import { autoRegister } from '../../plugins';import { AgentSessionMentionLabel } from './AgentSessionMentionLabel';+import { MagicChip } from './MagicChip';export function AgentSessionMention(props: AgentSessionMentionDecoratorProps) {const wrapper = useContext(LexicalWrapperContext);@@ -60,17 +70,69 @@ export function AgentSessionMention(props: AgentSessionMentionDecoratorProps) {event.stopPropagation();open(event);});+ const canExpand = () => Boolean(session() && wrapper?.isInteractable());+ const setExpanded = (expanded: boolean) => {+ if (!canExpand()) return;+ wrapper?.editor.update(() => {+ const node = $getNodeByKey(props.key);+ if ($isAgentSessionMentionNode(node)) node.setExpanded(expanded);+ });+ };+return (- <span- data-agent-session-mention="true"- data-agent-session-id={props.id}- data-agent-session-label={label()}- class="py-0.5 rounded-xs hover:bg-hover focus:bg-active"- classList={{ 'bg-active': selected() }}- title={label()}- {...navigation}+ <Show+ when={props.expanded && session()}+ fallback={+ <HoverCard+ disabled={!session()}+ trigger={+ <span+ data-agent-session-mention="true"+ data-agent-session-id={props.id}+ data-agent-session-label={label()}+ class="py-0.5 rounded-xs hover:bg-hover focus:bg-active"+ classList={{ 'bg-active': selected() }}+ title={label()}+ {...navigation}+ >+ <AgentSessionMentionLabel label={label()} />+ </span>+ }+ content={+ <Suspense>+ <PopupPreview+ mouseEnter={() => {}}+ mouseLeave={() => {}}+ documentInfo={{+ id: props.id,+ type: 'agent',+ params: {},+ isOpenable: true,+ }}+ previewInfo={{+ isPreviewable: false,+ showPreview: canExpand(),+ handlePreviewToggle: () => setExpanded(true),+ }}+ />+ </Suspense>+ }+ />+ }>- <AgentSessionMentionLabel label={label()} />- </span>+ <span+ class="inline-block w-full align-top my-2"+ data-agent-session-expanded="true"+ >+ <Suspense>+ <MagicChip+ agentSessionId={props.id}+ promptedMessage={null}+ status="no_messages"+ onCollapse={canExpand() ? () => setExpanded(false) : undefined}+ />+ </Suspense>+ </span>+ </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.tsxindex d1a8d72261..f883906dab 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,11 +1,13 @@import { useSplitLayout } from '@components/app/split-layout/layout';-import type { MagicChipDecoratorProps } from '@macro-inc/lexical-core';+import type { MagicChipData } from '@macro-inc/lexical-core';import type { Component } from 'solid-js';import { createMagicChipModel } from './create-magic-chip-model';import { MagicChipView } from './MagicChipView';-/** Lexical decorator for a `<m-magic-chip>` node in a channel message. */-export const MagicChip: Component<MagicChipDecoratorProps> = (props) => {+/** Shared session response surface, optionally anchored to one turn. */+export const MagicChip: Component<+ MagicChipData & { onCollapse?: () => void }+> = (props) => {const { insertSplit } = useSplitLayout();const model = createMagicChipModel(props);@@ -14,6 +16,7 @@ export const MagicChip: Component<MagicChipDecoratorProps> = (props) => {agentSessionId={props.agentSessionId}presentation={model.presentation()}header={model.header()}+ onCollapse={props.onCollapse}answer={{answering: model.elicitation.answering(),respond: model.elicitation.respond,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsxindex f42a1c217b..74effdc423 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx@@ -98,6 +98,25 @@ beforeEach(() => {onOpen.mockReset();});+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(() => (diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsxindex 8dede74aa3..374c7d0796 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@@ -15,6 +15,7 @@ import {import { channelTheme } from '@core/component/LexicalMarkdown/theme';import { PulsingStar } from '@entity/components/PulsingStar';import ArrowUpRight from '@phosphor/arrow-up-right.svg';+import ArrowsIn from '@phosphor/arrows-in.svg';import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';import { Button, Layer } from '@ui';import {@@ -187,6 +188,7 @@ const ChipHeader: Component<{/** The reply preview, while the answer area has nothing to offer. */preview?: string;onOpen?: () => void;+ onCollapse?: () => void;}> = (props) => (<divclass="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"@@ -226,6 +228,22 @@ const ChipHeader: Component<{</Show><ActivityText activity={props.status} /></button>+ <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><Buttonvariant="ghost"size="icon-xs"@@ -324,6 +342,7 @@ export const MagicChipView: Component<{/** 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(() =>@@ -393,7 +412,9 @@ export const MagicChipView: Component<{class="my-2 flex w-full min-w-0 max-w-full flex-col overflow-hidden rounded-lg border border-edge-muted bg-surface"data-magic-chip={props.agentSessionId}data-magic-chip-preview- onMouseDown={(event) => {+ data-lexical-interactive+ onClick={(event) => event.stopPropagation()}+ 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();@@ -404,6 +425,7 @@ export const MagicChipView: Component<{status={status()}preview={preview()}onOpen={props.onOpen}+ onCollapse={props.onCollapse}/><divrole="button"@@ -413,10 +435,11 @@ export const MagicChipView: Component<{classList={{ 'h-41': !expanded() }}data-magic-chip-answeronClick={onAreaClick}- onKeyDown={(event) => {+ 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?.();}}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.tsindex 04ea1c9d40..9f091275f9 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@@ -104,6 +104,78 @@ describe('createMagicChipModel', () => {serviceClient.control.mockResolvedValue({ isErr: () => false });});+ it('follows the latest turn and streaming updates without rewinding for late patches', async () => {+ let model!: ReturnType<typeof createMagicChipModel>;+ const release = vi.fn();+ sessionFold.acquireAgentSessionFold.mockResolvedValue({+ messages: [prompt, response],+ metadata: metadata(null),+ release,+ });+ const dispose = createRoot((dispose) => {+ model = createMagicChipModel({ ...props, promptedMessage: null });+ return dispose;+ });+ await settle();+ expect(model.presentation()).toEqual({ kind: 'settled', markdown: 'Hi!' });+ const callbacks = sessionFold.acquireAgentSessionFold.mock.calls[0]![0];+ callbacks.onChange([{ ...prompt, turn: 3 }]);+ expect(model.presentation()).not.toMatchObject({ markdown: 'Hi!' });+ callbacks.onChange([+ {+ ...openResponse,+ turn: 3,+ parts: [{ kind: 'text', text: 'Newest stream' }],+ },+ ]);+ expect(model.presentation()).toMatchObject({+ kind: 'answering',+ markdown: 'Newest stream',+ });+ callbacks.onChange([+ {+ ...response,+ turn: 1,+ parts: [{ kind: 'text', text: 'Late old patch' }],+ },+ ]);+ expect(model.presentation()).toMatchObject({ markdown: 'Newest stream' });+ callbacks.onChange([+ {+ ...response,+ turn: 3,+ parts: [{ kind: 'text', text: 'Newest answer' }],+ },+ ]);+ expect(model.presentation()).toEqual({+ kind: 'settled',+ markdown: 'Newest answer',+ });+ callbacks.onMetadata(metadata({ ...question, turn: 4 }));+ expect(model.presentation()).toMatchObject({+ kind: 'asking',+ asking: { question: { turn: 4 } },+ });+ dispose();+ expect(release).toHaveBeenCalledOnce();+ });++ it('keeps an explicit message lock when later turns arrive', async () => {+ let model!: ReturnType<typeof createMagicChipModel>;+ const dispose = createRoot((dispose) => {+ model = createMagicChipModel(props);+ return dispose;+ });+ await settle();+ const callbacks = sessionFold.acquireAgentSessionFold.mock.calls[0]![0];+ callbacks.onChange([+ { ...response, turn: 3, parts: [{ kind: 'text', text: 'New turn' }] },+ ]);+ callbacks.onMetadata(metadata({ ...question, turn: 3 }));+ expect(model.presentation()).toEqual({ kind: 'settled', markdown: 'Hi!' });+ dispose();+ });+it('settles after the attached turn completes despite stale acp_ready status', async () => {let presentation!: ReturnType<typeof createMagicChipModel>['presentation'];const dispose = createRoot((rootDispose) => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.tsindex 09c9ec6dc1..9441206d4c 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@@ -10,7 +10,7 @@ import {import { useUserId } from '@core/context/user';import {MAGIC_CHIP_STATUSES,- type MagicChipDecoratorProps,+ type MagicChipData,type MagicChipStatus,} from '@macro-inc/lexical-core';import {@@ -86,7 +86,7 @@ function modelName(* row names its owner, and {@link ElicitationController} sends the answer.* The header names the persona and model from the session row and the fold.*/-export function createMagicChipModel(props: MagicChipDecoratorProps): {+export function createMagicChipModel(props: MagicChipData): {presentation: Accessor<MagicChipPresentation>;header: Accessor<MagicChipHeader | undefined>;elicitation: ElicitationController;@@ -176,11 +176,19 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {release?.();});- // This chip is one turn's surface; only a question asked in that turn is- // its to offer.+ // Fold patches can arrive out of order. Follow the highest turn, including+ // a pending question whose metadata arrives before its message patch.+ const turn = () =>+ props.promptedMessage?.turn ??+ messages().reduce(+ (latest, message) => Math.max(latest, message.turn),+ pendingElicitation()?.turn ?? 0+ );++ // A locked chip only offers questions from its anchored turn.const questionForTurn = () => {const question = pendingElicitation();- return question?.turn === props.promptedMessage.turn ? question : undefined;+ return question?.turn === turn() ? question : undefined;};const elicitation = createElicitationController({sessionId: () => props.agentSessionId,@@ -201,9 +209,9 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {// Memoized: the view reads these from many places per flush, and a fold// pushes a frame per streamed chunk.const presentation = createMemo(() => {- const turn = props.promptedMessage.turn;+ const currentTurn = turn();const messagesForTurn = messages().filter(- (message) => message.turn === turn+ (message) => message.turn === currentTurn);return deriveMagicChipPresentation({persistedStatus: persistedStatus(),diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/agent-session-mention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/agent-session-mention.tsxindex 440dcb01bd..f9e4247861 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/agent-session-mention.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/agent-session-mention.tsx@@ -1,30 +1,90 @@import '@app/index.css';-import { createSignal } from 'solid-js';+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';+import { PosthogProvider } from '@app/lib/analytics/posthog';+import { buildAgentSessionMentionMarkdown } from '@macro-inc/lexical-core';+import { agentSessionKeys } from '@queries/agent-session/keys';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { For, onCleanup } from 'solid-js';import { render } from 'solid-js/web';-import { AgentSessionMentionLabel } from '../AgentSessionMentionLabel';+import {+ createLexicalWrapper,+ LexicalWrapperContext,+} from '../../../context/LexicalWrapperContext';+import { channelTheme } from '../../../theme';+import {+ StaticMarkdown,+ StaticMarkdownContext,+} from '../../core/StaticMarkdown';++const id = 'session-mention-fixture';+const label = 'Fix mentions';+const mention = buildAgentSessionMentionMarkdown({ id, label });function Fixture() {- const [privateSession, setPrivateSession] = createSignal(false);- return (- <main class="p-4 text-ink bg-page">- <p class="w-80 border border-edge-muted p-2">- Open{' '}- <span- data-testid="chip"- class="py-0.5 rounded-xs hover:bg-hover focus:bg-active"- >- <AgentSessionMentionLabel- label={- privateSession()- ? 'Private agent session'- : 'Fix mentions in documents and channel editors'+ const client = new QueryClient();+ const wrapper = createLexicalWrapper({+ type: 'chat',+ namespace: 'session-mention-fixture',+ isInteractable: () => false,+ });+ onCleanup(() => {+ wrapper.cleanup();+ client.clear();+ });+ const setAccess = (accessible: boolean) => {+ for (const graphql of [false, true]) {+ client.setQueryData(+ agentSessionKeys.preview(id, graphql).queryKey,+ accessible+ ? {+ access: 'access',+ data: {+ id,+ name: label,+ ownerId: 'fixture-owner',+ botId: 'fixture-bot',+ status: { kind: 'disconnected' },+ createdAt: '',+ updatedAt: '',+ },}- />- </span>{' '}- to continue.- </p>- <button onClick={() => setPrivateSession(true)}>Revoke access</button>- </main>+ : { access: 'no_access' }+ );+ }+ };+ setAccess(true);+ return (+ <AnalyticsContextProvider>+ <PosthogProvider>+ <QueryClientProvider client={client}>+ <LexicalWrapperContext.Provider+ value={{ ...wrapper, skipPreviewFetch: true }}+ >+ <StaticMarkdownContext theme={channelTheme}>+ <main class="p-4 text-ink bg-page space-y-4">+ <For+ each={[+ mention,+ `${mention} followed by text`,+ `Before ${mention} after`,+ ]}+ >+ {(markdown) => (+ <div+ data-testid="sent-message"+ class="w-96 border border-edge-muted p-2"+ >+ <StaticMarkdown markdown={markdown} target="internal" />+ </div>+ )}+ </For>+ <button onClick={() => setAccess(false)}>Revoke access</button>+ </main>+ </StaticMarkdownContext>+ </LexicalWrapperContext.Provider>+ </QueryClientProvider>+ </PosthogProvider>+ </AnalyticsContextProvider>);}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex 675729a9d6..3cc759863c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -13,8 +13,6 @@ import { useDateSearch } from '@core/util/dateSearch/useDateSearch';import { debouncedDependent } from '@core/util/debounce';import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';import type { EmailEntity } from '@entity';-import { searchAgentSessionMentions } from '@queries/agent-session/mention-types';-import { useRecentAgentSessionMentions } from '@queries/agent-session/mentions';import type { HistoryItem as Item } from '@queries/history/history';import { createLazyMemo } from '@solid-primitives/memo';import { createVirtualizer } from '@tanstack/solid-virtual';@@ -101,26 +99,19 @@ function MentionsMenuInner(props: MentionsMenuProps) {const sessionsEnabled = () =>!hasCustomEntities() &&(!props.sources || props.sources.includes('agentSessions'));- const sessionQuery = useRecentAgentSessionMentions(- () => props.menu.isOpen() && sessionsEnabled()- );- const agentSessions = createLazyMemo((): AgentSessionMentionItem[] => {- if (!sessionsEnabled() || !sessionQuery.isSuccess) return [];- return searchAgentSessionMentions(sessionQuery.data, searchTerm()).map(- (data) => ({- kind: 'agentSession',- id: data.id,- data,- searchText: `${data.name} ${data.bot?.name ?? ''}`,- timestamps: {- createdAt: new Date(data.createdAt),- updatedAt: new Date(data.updatedAt),- },- })- );+ const quickAccess = hasCustomEntities() ? undefined : useQuickAccess();+ const sessionList = quickAccess?.useList({+ buckets: ['agent_session'],+ searchTerm: activeSearchTerm,+ enabled: sessionsEnabled,});+ const agentSessions = createLazyMemo((): AgentSessionMentionItem[] =>+ (sessionList?.items() ?? []).map((item) => ({+ ...item,+ kind: 'agentSession',+ }))+ );- const quickAccess = hasCustomEntities() ? undefined : useQuickAccess();const allItems = props.entities ?? quickAccess!.useList().items;const { isKeypressActive } = useIsKeyPressActive();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/agent-session-selection.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/agent-session-selection.test.tsindex 39180c3821..00ba7ab31d 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/agent-session-selection.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/agent-session-selection.test.ts@@ -22,16 +22,19 @@ import { sortMobileMentions } from './mobileSort';const item: AgentSessionMentionItem = {kind: 'agentSession',+ bucket: 'agent_session',+ sortTimestamp: 0,id: 'session',searchText: 'Ada Fix mentions',timestamps: { createdAt: new Date(), updatedAt: new Date() },data: {+ type: 'agent_session',id: 'session',name: 'Fix mentions',ownerId: 'owner',botId: 'bot',bot: { id: 'bot', name: 'Ada' },- status: { kind: 'no_messages' },+ status: 'no_messages',createdAt: '',updatedAt: '',},diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.tsindex 711d8f2355..5fcd9f3b84 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts@@ -14,6 +14,7 @@ export function getBlockNameFromEntity(.with('channel', () => 'channel' as const).with('dm', () => 'channel' as const).with('email', () => 'email' as const)+ .with('agent_session', () => 'agent' as const).with('chat', () => 'chat' as const).with('project', () => 'project' as const).with('task', () => 'task' as const)diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.tsindex d877420b54..f91cb42ceb 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts@@ -1,11 +1,11 @@import type { BlockAlias, BlockName } from '@core/block';import { fileTypeToBlockName } from '@core/constant/allBlocks';-import type { QuickAccessItem } from '@core/context/quickAccess';+import type { EntityItem, QuickAccessItem } from '@core/context/quickAccess';import { trackMention } from '@core/signal/mention';import type { ChannelWithParticipants, IUser } from '@core/user';import type { ParsedDate } from '@core/util/dateParser';import type { DateOption } from '@core/util/dateSearch/useDateSearch';-import type { EmailEntity } from '@entity';+import type { AgentSessionEntity, EmailEntity } from '@entity';import type { HistoryItem as Item } from '@queries/history/history';import { waitBulkUploadStatus } from '@service-connection/bulkUpload';import type { DocumentMentionMetadata } from '@service-notification/client';@@ -384,13 +384,10 @@ export type GroupMentionItem = {* MentionItem = QuickAccessItem + Date + Group.* Used in MentionsMenu to unify all mentionable item types.*/-export type AgentSessionMentionItem = {- kind: 'agentSession';- id: string;- data: import('@queries/agent-session/mention-types').AgentSessionMentionData;- searchText: string;- timestamps: { createdAt: Date; updatedAt: Date };-};+export type AgentSessionMentionItem = Omit<+ EntityItem<AgentSessionEntity>,+ 'kind'+> & { kind: 'agentSession' };export type MentionItem =| QuickAccessItemdiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.tsindex cd3298c958..74588480c2 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts@@ -20,5 +20,6 @@* Version 3.0 - Sep 2026. Added ReplyTargetNode.* Version 4.0 - Sep 2026. Added AgentSessionMentionNode.* Version 3.1 - Sep 2026. Added ConnectAppNode (agent "connect this app" chip).+ * Version 4.1 - Sep 2026. Expandable session mentions reuse Magic Chip with a null message lock for the latest turn.*/-export const MARKDOWN_VERSION_COUNTER = 4.0;+export const MARKDOWN_VERSION_COUNTER = 4.1;diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsxindex 0f6fffcdf2..4836af15af 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx@@ -23,6 +23,7 @@ import {import { queryReadyGate } from '@queries/gate';import { materializeCachedGraphqlHistoryItems } from '@queries/history/graphql';import { type HistoryItem, useHistoryQuery } from '@queries/history/history';+import { useQuickAccessAgentSessionsQuery } from '@queries/soup/quick-access-agent-sessions';import { useQuickAccessCrmCompaniesQuery } from '@queries/soup/quick-access-crm-companies';import { useQuickAccessSkillsQuery } from '@queries/soup/quick-access-skills';import { useQuickAccessSnippetsQuery } from '@queries/soup/quick-access-snippets';@@ -330,6 +331,9 @@ export function createQuickAccessValue(): QuickAccessContextValue {const { query: skillsQuery, skills: skillsAccessor } =useQuickAccessSkillsQuery();+ const { query: agentSessionsQuery, sessions: agentSessionsAccessor } =+ useQuickAccessAgentSessionsQuery();+// globally hidden idsconst [hiddenIds, setHiddenIds] = createSignal<Set<string>>(new Set());@@ -700,6 +704,41 @@ export function createQuickAccessValue(): QuickAccessContextValue {return sortIndexEntries(allEntries);});+ const agentSessionEntries = createLazyMemo(() => {+ const viewedAtMap = soupViewedAtMap();+ const hidden = hiddenIds();+ const entries: IndexEntry[] = [];+ for (const session of agentSessionsAccessor()) {+ if (hidden.has(session.id)) continue;+ const viewedAt = viewedAtMap.get(session.id) ?? session.viewedAt;+ const sortTimestamp =+ toTimestamp(viewedAt) || toTimestamp(session.updatedAt);+ const entity = { ...session, viewedAt };+ const version = JSON.stringify(entity);+ const cached = itemCache.get(session.id);+ if (!cached || cached.version !== version) {+ itemCache.set(session.id, {+ version,+ item: {+ kind: 'entity',+ id: session.id,+ bucket: 'agent_session',+ searchText: `${session.name} ${session.bot?.name ?? ''}`,+ sortTimestamp,+ timestamps: {+ viewedAt,+ updatedAt: session.updatedAt,+ createdAt: session.createdAt,+ },+ data: entity,+ },+ });+ }+ entries.push({ id: session.id, bucket: 'agent_session', sortTimestamp });+ }+ return sortIndexEntries(entries);+ });+const processedData = createLazyMemo(() => {const allEntries = mergeMultipleSortedIndices([historyEntries().entries,@@ -708,6 +747,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {crmCompanyEntries(),snippetEntries(),skillEntries(),+ agentSessionEntries(),]);const seenIds = new Set(allEntries.map((entry) => entry.id));@@ -982,6 +1022,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {crmCompaniesQuery.refetch();snippetsQuery.refetch();skillsQuery.refetch();+ void agentSessionsQuery.refetch();};return {diff --git a/apps/web/src/lib/core/context/quickAccess/types.ts b/apps/web/src/lib/core/context/quickAccess/types.tsindex 1449e410ee..6657a44423 100644--- a/apps/web/src/lib/core/context/quickAccess/types.ts+++ b/apps/web/src/lib/core/context/quickAccess/types.ts@@ -1,6 +1,7 @@import type { IUser } from '@core/user/types';import type { DateValue } from '@core/util/date';import type {+ AgentSessionEntity,ChannelEntity,ChatEntity,CrmCompanyEntity,@@ -30,7 +31,8 @@ export type Bucket =| 'chat'| 'project'| 'email'- | 'crm_company';+ | 'crm_company'+ | 'agent_session';export type EntityBucket = Exclude<Bucket, 'person'>;@@ -47,6 +49,7 @@ const ALL_BUCKETS: Bucket[] = ['project','email','crm_company',+ 'agent_session',];export type BucketCombination = 'all' | 'channels' | 'documents';@@ -131,6 +134,7 @@ export type BucketItemMap = {project: EntityItem<ProjectEntity>;email: EntityItem<EmailEntity>;crm_company: EntityItem<CrmCompanyEntity>;+ agent_session: EntityItem<AgentSessionEntity>;person: UserItem;};diff --git a/apps/web/src/lib/queries/agent-session/keys.ts b/apps/web/src/lib/queries/agent-session/keys.tsindex 33d38b9760..2ac37d0e92 100644--- a/apps/web/src/lib/queries/agent-session/keys.ts+++ b/apps/web/src/lib/queries/agent-session/keys.ts@@ -1,6 +1,5 @@import { createQueryKeys } from '@lukemorales/query-key-factory';export const agentSessionKeys = createQueryKeys('agentSessionMentions', {- recent: (graphql: boolean) => ({ queryKey: [graphql] }),preview: (id: string, graphql: boolean) => ({ queryKey: [id, graphql] }),});diff --git a/apps/web/src/lib/queries/agent-session/mention-fetchers.test.ts b/apps/web/src/lib/queries/agent-session/mention-fetchers.test.tsindex 24bf436a70..e68e5c38df 100644--- a/apps/web/src/lib/queries/agent-session/mention-fetchers.test.ts+++ b/apps/web/src/lib/queries/agent-session/mention-fetchers.test.ts@@ -1,15 +1,9 @@-import { err, ok } from 'neverthrow';+import { ok } from 'neverthrow';import { beforeEach, describe, expect, it, vi } from 'vitest';const clients = vi.hoisted(() => ({graphql: vi.fn(),preview: vi.fn(),- soup: vi.fn(),- bots: vi.fn(),- bot: vi.fn(),-}));-vi.mock('@app/features/next-soup/filters/query-filters', () => ({- QUERY_FILTERS_BASE: { document_filters: { document_ids: ['excluded'] } },}));vi.mock('@service-storage/agent-session-mentions', () => ({fetchGraphqlAgentSessionMentions: clients.graphql,@@ -17,23 +11,10 @@ vi.mock('@service-storage/agent-session-mentions', () => ({vi.mock('@service-agent-harness/client', () => ({agentHarnessServiceClient: { preview: clients.preview },}));-vi.mock('@service-storage/client', () => ({- storageServiceClient: {- getSoupItems: clients.soup,- getBots: clients.bots,- getBot: clients.bot,- },-}));-vi.mock('../client', () => ({- queryClient: {- ensureQueryData: ({ queryFn }: { queryFn: () => unknown }) => queryFn(),- },-}));import {agentSessionMentionInput,fetchAgentSessionMentionPreviews,- fetchRecentAgentSessionMentions,} from './mention-fetchers';beforeEach(() => vi.clearAllMocks());@@ -79,7 +60,6 @@ describe('mention transport adapters', () => {},});expect(clients.preview).not.toHaveBeenCalled();- expect(clients.bot).not.toHaveBeenCalled();});it('uses REST to distinguish inaccessible and deleted GraphQL omissions', async () => {clients.graphql.mockResolvedValue([session]);@@ -98,7 +78,6 @@ describe('mention transport adapters', () => {expect(clients.preview).toHaveBeenCalledWith(['private', 'deleted']);expect(result.get('private')).toEqual({ access: 'no_access' });expect(result.get('deleted')).toEqual({ access: 'does_not_exist' });- expect(clients.bot).not.toHaveBeenCalled();});it('hydrates REST previews with persona metadata and normalized timestamps', async () => {clients.preview.mockResolvedValue(@@ -113,9 +92,6 @@ describe('mention transport adapters', () => {],}));- clients.bot.mockResolvedValue(- ok({ id: 'bot', name: 'Ada', avatar_url: 'avatar' })- );const result = await fetchAgentSessionMentionPreviews(['one'], false);expect(result.get('one')).toMatchObject({access: 'access',@@ -123,156 +99,4 @@ describe('mention transport adapters', () => {});expect(clients.graphql).not.toHaveBeenCalled();});- it('hydrates REST discovery through permission-checked previews', async () => {- clients.soup.mockResolvedValue(- ok({ items: [{ tag: 'agentSession', data: session }] })- );- clients.preview.mockResolvedValue(- ok({- previews: [- {- ...session,- type: 'access',- modifiedAt: '',- status: { kind: 'no_messages' },- },- ],- })- );- expect(await fetchRecentAgentSessionMentions(false)).toMatchObject([- { id: 'one', bot: { name: 'Ada' } },- ]);- expect(clients.bot).not.toHaveBeenCalled();- expect(clients.soup).toHaveBeenCalledWith({- params: {},- body: {- document_filters: { document_ids: ['excluded'] },- agent_session_filters: { include: true },- limit: 500,- sort_method: 'updated_at',- },- });- });- it('resolves a persona from botId when the REST preview omits bot metadata', async () => {- clients.soup.mockResolvedValue(- ok({- items: [{ tag: 'agentSession', data: { ...session, bot: undefined } }],- })- );- clients.preview.mockResolvedValue(- ok({- previews: [- {- ...session,- bot: undefined,- type: 'access',- modifiedAt: '',- status: { kind: 'no_messages' },- },- ],- })- );- clients.bots.mockResolvedValue(- ok([{ id: 'bot', name: 'cursor', avatar_url: null }])- );- expect(await fetchRecentAgentSessionMentions(false)).toMatchObject([- { id: 'one', bot: { id: 'bot', name: 'cursor' } },- ]);- expect(clients.bots).toHaveBeenCalledOnce();- });-- it('resolves missing GraphQL persona metadata from the same cached bot list', async () => {- clients.graphql.mockResolvedValue([{ ...session, bot: null }]);- clients.bots.mockResolvedValue(- ok([{ id: 'bot', name: 'cursor', avatar_url: null }])- );- expect(await fetchRecentAgentSessionMentions(true)).toMatchObject([- { id: 'one', bot: { name: 'cursor' } },- ]);- expect(clients.preview).not.toHaveBeenCalled();- });-- it.each([false, true])(- 'resolves built-in personas without the manageable bots list (GraphQL: %s)',- async (graphql) => {- const sessions = [- {- ...session,- id: 'cursor',- botId: '00000000-0000-0000-0000-00000000c5c5',- bot: undefined,- },- {- ...session,- id: 'macro-new',- botId: '00000000-0000-0000-0000-00000000a2a2',- bot: undefined,- },- ];- clients.graphql.mockResolvedValue(sessions);- clients.soup.mockResolvedValue(- ok({ items: sessions.map((data) => ({ tag: 'agentSession', data })) })- );- clients.preview.mockResolvedValue(- ok({- previews: sessions.map((data) => ({- ...data,- type: 'access',- modifiedAt: '',- status: { kind: 'no_messages' },- })),- })- );- expect(await fetchRecentAgentSessionMentions(graphql)).toMatchObject([- { id: 'cursor', bot: { name: 'Cursor' } },- { id: 'macro-new', bot: { name: 'macro(new)' } },- ]);- expect(clients.bots).not.toHaveBeenCalled();- }- );-- it('preserves API names and built-in names when custom persona lookup fails', async () => {- clients.graphql.mockResolvedValue([- {- ...session,- id: 'renamed',- botId: '00000000-0000-0000-0000-00000000c5c5',- bot: {- id: '00000000-0000-0000-0000-00000000c5c5',- name: 'API persona',- },- },- {- ...session,- id: 'macro-new',- botId: '00000000-0000-0000-0000-00000000a2a2',- bot: null,- },- { ...session, bot: null },- ]);- clients.bots.mockResolvedValue(err(new Error('unavailable')));- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- try {- expect(await fetchRecentAgentSessionMentions(true)).toMatchObject([- { id: 'renamed', bot: { name: 'API persona' } },- { id: 'macro-new', bot: { name: 'macro(new)' } },- { id: 'one', bot: null },- ]);- } finally {- warn.mockRestore();- }- });-- it('keeps sessions visible when the optional persona lookup fails', async () => {- clients.graphql.mockResolvedValue([{ ...session, bot: null }]);- clients.bots.mockResolvedValue(err(new Error('unavailable')));- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- try {- expect(await fetchRecentAgentSessionMentions(true)).toMatchObject([- { id: 'one', bot: null },- ]);- } finally {- warn.mockRestore();- }- });});diff --git a/apps/web/src/lib/queries/agent-session/mention-fetchers.ts b/apps/web/src/lib/queries/agent-session/mention-fetchers.tsindex b86e823ada..e8723083df 100644--- a/apps/web/src/lib/queries/agent-session/mention-fetchers.ts+++ b/apps/web/src/lib/queries/agent-session/mention-fetchers.ts@@ -1,18 +1,12 @@-import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';import { throwOnErr } from '@core/util/result';import { agentHarnessServiceClient } from '@service-agent-harness/client';import { fetchGraphqlAgentSessionMentions } from '@service-storage/agent-session-mentions';-import { storageServiceClient } from '@service-storage/client';import type {GraphqlAgentSessionExpr,SoupInput,} from '@service-storage/graphql/generated/graphql';-import { botsQueryOptions } from '../bots/bots';-import { firstPartyBotName } from '../bots/first-party-bot-name';-import { queryClient } from '../client';import { buildGraphqlEntitySoupInput } from '../soup/graphql/entity-input';import {- type AgentSessionMentionData,type AgentSessionMentionPreview,normalizeAgentSessionStatus,} from './mention-types';@@ -48,81 +42,6 @@ export function agentSessionMentionInput(ids?: string[]): SoupInput {};}-/** Older preview responses may identify the persona only by botId. */-async function withSessionPersonaNames(- sessions: AgentSessionMentionData[]-): Promise<AgentSessionMentionData[]> {- const namedSessions = sessions.map((session) => {- if (session.bot?.name) return session;- const name = firstPartyBotName(session.botId);- return name- ? { ...session, bot: { ...session.bot, id: session.botId, name } }- : session;- });- if (namedSessions.every((session) => session.bot?.name)) return namedSessions;- try {- const bots = await queryClient.ensureQueryData(botsQueryOptions());- const byId = new Map(bots.map((bot) => [bot.id, bot]));- return namedSessions.map((session) => {- if (session.bot?.name) return session;- const bot = byId.get(session.botId);- if (!bot) return session;- return {- ...session,- bot: { id: bot.id, name: bot.name, avatarUrl: bot.avatar_url },- };- });- } catch (error) {- console.warn('Failed to load agent session persona names', error);- return namedSessions;- }-}--export async function fetchRecentAgentSessionMentions(- graphql: boolean-): Promise<AgentSessionMentionData[]> {- if (graphql) {- const items = await fetchGraphqlAgentSessionMentions(- agentSessionMentionInput()- );- return withSessionPersonaNames(- items.map((item) => ({- ...item,- status: normalizeAgentSessionStatus(item.status),- }))- );- }- const page = await throwOnErr(() =>- storageServiceClient.getSoupItems({- params: {},- body: {- ...QUERY_FILTERS_BASE,- agent_session_filters: { include: true },- limit: 500,- sort_method: 'updated_at',- },- })- );- const ids = page.items.flatMap((item) =>- item.tag === 'agentSession' ? [item.data.id] : []- );- const batches: Promise<Map<string, AgentSessionMentionPreview>>[] = [];- for (let start = 0; start < ids.length; start += 50) {- batches.push(- fetchAgentSessionMentionPreviews(ids.slice(start, start + 50), false)- );- }- const previews = new Map(- (await Promise.all(batches)).flatMap((batch) => [...batch])- );- return withSessionPersonaNames(- ids.flatMap((id) => {- const preview = previews.get(id);- return preview?.access === 'access' ? [preview.data] : [];- })- );-}-export async function fetchAgentSessionMentionPreviews(ids: string[],graphql: booleandiff --git a/apps/web/src/lib/queries/agent-session/mention-types.test.ts b/apps/web/src/lib/queries/agent-session/mention-types.test.tsindex b04594f688..701a073483 100644--- a/apps/web/src/lib/queries/agent-session/mention-types.test.ts+++ b/apps/web/src/lib/queries/agent-session/mention-types.test.ts@@ -1,9 +1,5 @@import { describe, expect, it } from 'vitest';-import {- type AgentSessionMentionData,- normalizeAgentSessionStatus,- searchAgentSessionMentions,-} from './mention-types';+import { normalizeAgentSessionStatus } from './mention-types';describe('agent session mention data', () => {it('normalizes GraphQL/Soup statuses without losing unfamiliar events', () => {@@ -18,21 +14,4 @@ describe('agent session mention data', () => {event: 'session/end',});});- it('searches both persona and session names, preserving recency order', () => {- const item: AgentSessionMentionData = {- id: '1',- name: 'Fix the menu',- ownerId: 'owner',- botId: 'bot',- bot: { id: 'bot', name: 'Ada' },- status: { kind: 'no_messages' },- createdAt: '',- updatedAt: '',- };- expect(searchAgentSessionMentions([item], 'ADA menu')).toEqual([item]);- expect(searchAgentSessionMentions([item], 'missing')).toEqual([]);- expect(- searchAgentSessionMentions([{ ...item, bot: null }], 'fix')- ).toHaveLength(1);- });});diff --git a/apps/web/src/lib/queries/agent-session/mention-types.ts b/apps/web/src/lib/queries/agent-session/mention-types.tsindex eb1716a43f..756687f848 100644--- a/apps/web/src/lib/queries/agent-session/mention-types.ts+++ b/apps/web/src/lib/queries/agent-session/mention-types.ts@@ -25,15 +25,3 @@ export function normalizeAgentSessionStatus(return { kind: status };return { kind: 'event', event: status };}--/** Menu discovery deliberately searches only the 500 most recently updated sessions. */-export function searchAgentSessionMentions(- items: AgentSessionMentionData[],- search: string-) {- const terms = search.toLocaleLowerCase().trim().split(/\s+/).filter(Boolean);- return items.filter((item) => {- const text = `${item.name} ${item.bot?.name ?? ''}`.toLocaleLowerCase();- return terms.every((term) => text.includes(term));- });-}diff --git a/apps/web/src/lib/queries/agent-session/mentions.ts b/apps/web/src/lib/queries/agent-session/mentions.tsindex c81bcb60a3..87256377ab 100644--- a/apps/web/src/lib/queries/agent-session/mentions.ts+++ b/apps/web/src/lib/queries/agent-session/mentions.ts@@ -4,10 +4,7 @@ import { useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import { agentSessionKeys } from './keys';import { createAgentSessionMentionBatcher } from './mention-batcher';-import {- fetchAgentSessionMentionPreviews,- fetchRecentAgentSessionMentions,-} from './mention-fetchers';+import { fetchAgentSessionMentionPreviews } from './mention-fetchers';const restPreview = createAgentSessionMentionBatcher((ids) =>fetchAgentSessionMentionPreviews(ids, false)@@ -16,16 +13,6 @@ const graphqlPreview = createAgentSessionMentionBatcher((ids) =>fetchAgentSessionMentionPreviews(ids, true));-export function useRecentAgentSessionMentions(enabled: Accessor<boolean>) {- const flag = useFeatureFlag(enableGraphqlSoup);- return useQuery(() => ({- queryKey: agentSessionKeys.recent(flag().enabled).queryKey,- queryFn: () => fetchRecentAgentSessionMentions(flag().enabled),- enabled: enabled(),- staleTime: 60_000,- }));-}-export function useAgentSessionMentionPreview(id: Accessor<string>,enabled: Accessor<boolean>diff --git a/apps/web/src/lib/queries/agent-session/mutations.ts b/apps/web/src/lib/queries/agent-session/mutations.tsindex 613f3cd070..c3958203bd 100644--- a/apps/web/src/lib/queries/agent-session/mutations.ts+++ b/apps/web/src/lib/queries/agent-session/mutations.ts@@ -5,12 +5,16 @@ import type {CreateAgentSessionRequest,} from '@service-agent-harness/generated/schemas';import { useMutation } from '@tanstack/solid-query';+import { invalidateAllSoup } from '../soup/cache';export function useCreateAgentSessionMutation() {return useMutation(() => ({retry: false,mutationFn: (request: CreateAgentSessionRequest) =>throwOnErr(() => agentHarnessServiceClient.create(request)),+ onSuccess: () => {+ invalidateAllSoup();+ },}));}diff --git a/apps/web/src/lib/queries/client.ts b/apps/web/src/lib/queries/client.tsindex 0826ba19b4..6a004c641d 100644--- a/apps/web/src/lib/queries/client.ts+++ b/apps/web/src/lib/queries/client.ts@@ -8,7 +8,7 @@ import { onlineManager } from '@tanstack/query-core';import { QueryClient } from '@tanstack/solid-query';import { setupQueryPersistence } from './persistence';import { createQueryPersistenceScopes } from './persistence-scopes';-import { initSoupNormalizer } from './soup/cache';+import { initSoupNormalizer } from './soup/normalized-cache/normalizer';export const queryClient = new QueryClient({defaultOptions: {diff --git a/apps/web/src/lib/queries/soup/quick-access-agent-sessions.ts b/apps/web/src/lib/queries/soup/quick-access-agent-sessions.tsnew file mode 100644index 0000000000..1091d863ee--- /dev/null+++ b/apps/web/src/lib/queries/soup/quick-access-agent-sessions.ts@@ -0,0 +1,41 @@+import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';+import type { AgentSessionEntity } from '@entity';+import { useBotsQuery } from '../bots/bots';+import { firstPartyBotName } from '../bots/first-party-bot-name';+import { useSoupItemsQuery } from './items';++/** Shared discovery feed; starts with Quick Access, before a mention menu opens. */+export function useQuickAccessAgentSessionsQuery() {+ const query = useSoupItemsQuery(+ () => ({+ params: { limit: 500, sort_method: 'updated_at' },+ body: {+ ...QUERY_FILTERS_BASE,+ agent_session_filters: { include: true },+ },+ }),+ () => ({ staleTime: 60_000 })+ );+ const botsQuery = useBotsQuery();+ // Optional persona enrichment never holds up the session list or other entities.+ const sessions = (): AgentSessionEntity[] => {+ if (!query.isSuccess) return [];+ const bots = new Map(+ (botsQuery.isSuccess ? botsQuery.data : []).map((bot) => [bot.id, bot])+ );+ return query.data+ .filter((entity) => entity.type === 'agent_session')+ .map((session) => {+ if (session.bot?.name) return session;+ const bot = bots.get(session.botId);+ const name = firstPartyBotName(session.botId) ?? bot?.name;+ return name+ ? {+ ...session,+ bot: { id: session.botId, name, avatarUrl: bot?.avatar_url },+ }+ : session;+ });+ };+ return { query, sessions };+}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 3408e67d42..4ccbf1376c 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -160,6 +160,18 @@ Other participants can copy a link for people who already have access, butcannot grant access. Copying a link alone never changes permissions. New,unsaved session drafts do not offer sharing.+Agent sessions in the `@` menu use the shared Quick Access feed, loaded when the app opens. Search matches session titles and persona names. The initial feed covers the 500 most recently updated accessible sessions; it does not load transcripts.++### Expanded session mentions++Hover an accessible inline `@` session mention in an editable document or+composer and choose **Convert to Card View**. The card is the same Magic Chip used+for agent responses and follows the session's latest turn as it streams. Use+**Collapse to mention** in its header to restore the compact underlined title.+The display choice survives reload and copying; expansion still references the+same session and does not invoke a bot. Compact mentions do not load transcripts.+Existing announcement chips remain locked to the turn they announced.+### Transcript navigationAgent sessions reuse the channel's TanStack `ThreadList`. Opening a session landsdiff --git a/packages/lexical-core/nodes/AgentSessionMentionNode.ts b/packages/lexical-core/nodes/AgentSessionMentionNode.tsindex 927725abb8..0bcec18bd3 100644--- a/packages/lexical-core/nodes/AgentSessionMentionNode.ts+++ b/packages/lexical-core/nodes/AgentSessionMentionNode.ts@@ -14,12 +14,13 @@ import {import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';-const VERSION = 1;+const VERSION = 2;export type AgentSessionMentionInfo = {id: string;label?: string;mentionUuid?: string;+ expanded?: boolean;};export type SerializedAgentSessionMentionNode = Spread<@@ -38,6 +39,7 @@ export class AgentSessionMentionNode extends DecoratorNode<__id: string;__label: string | undefined;__mentionUuid: string | undefined;+ __expanded: boolean;static getType() {return 'agent-session-mention';@@ -56,15 +58,23 @@ export class AgentSessionMentionNode extends DecoratorNode<node.__id,node.__label,node.__mentionUuid,- node.__key+ node.__key,+ node.__expanded);}- constructor(id: string, label?: string, mentionUuid?: string, key?: NodeKey) {+ constructor(+ id: string,+ label?: string,+ mentionUuid?: string,+ key?: NodeKey,+ expanded = false+ ) {super(key);this.__id = id;this.__label = label;this.__mentionUuid = mentionUuid;+ this.__expanded = expanded;}static importJSON(serializedNode: SerializedAgentSessionMentionNode) {@@ -72,6 +82,7 @@ export class AgentSessionMentionNode extends DecoratorNode<id: serializedNode.id,label: serializedNode.label,mentionUuid: serializedNode.mentionUuid,+ expanded: serializedNode.expanded,});$applyIdFromSerialized(node, serializedNode);return node;@@ -83,6 +94,7 @@ export class AgentSessionMentionNode extends DecoratorNode<id: this.__id,label: this.__label,mentionUuid: this.__mentionUuid,+ ...(this.__expanded ? { expanded: true } : {}),type: AgentSessionMentionNode.getType(),version: VERSION,};@@ -93,6 +105,7 @@ export class AgentSessionMentionNode extends DecoratorNode<id: this.__id,label: this.__label,mentionUuid: this.__mentionUuid,+ ...(this.__expanded ? { expanded: true } : {}),};}@@ -116,7 +129,13 @@ export class AgentSessionMentionNode extends DecoratorNode<if (id) {return {- node: $createAgentSessionMentionNode({ id, label, mentionUuid }),+ node: $createAgentSessionMentionNode({+ id,+ label,+ mentionUuid,+ expanded:+ domNode.getAttribute('data-agent-session-expanded') === 'true',+ }),};}@@ -140,6 +159,7 @@ export class AgentSessionMentionNode extends DecoratorNode<'data-agent-session-id': this.__id,'data-agent-session-label': this.__label || '','data-mention-uuid': this.__mentionUuid || '',+ ...(this.__expanded ? { 'data-agent-session-expanded': 'true' } : {}),};}@@ -176,6 +196,14 @@ export class AgentSessionMentionNode extends DecoratorNode<self.__label = label;}+ isExpanded(): boolean {+ return this.__expanded;+ }++ setExpanded(expanded: boolean) {+ this.getWritable().__expanded = expanded;+ }+getMentionUuid(): string | undefined {return this.__mentionUuid;}@@ -214,7 +242,9 @@ export function $createAgentSessionMentionNode(const node = new AgentSessionMentionNode(params.id,params.label,- params.mentionUuid+ params.mentionUuid,+ undefined,+ params.expanded);return $applyNodeReplacement(node);}diff --git a/packages/lexical-core/nodes/MagicChipNode.ts b/packages/lexical-core/nodes/MagicChipNode.tsindex 81a236bd92..c82ff7a657 100644--- a/packages/lexical-core/nodes/MagicChipNode.ts+++ b/packages/lexical-core/nodes/MagicChipNode.ts@@ -13,7 +13,7 @@ import {import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';-const VERSION = 4;+const VERSION = 5;export const MAGIC_CHIP_NODE_TYPE = 'magic-chip';@@ -47,7 +47,8 @@ export type MagicChipMessage = {export type MagicChipData = {agentSessionId: string;channelId?: string;- promptedMessage: MagicChipMessage;+ /** Null follows the latest turn; a message anchors the chip to that turn. */+ promptedMessage: MagicChipMessage | null;status: MagicChipStatus;};@@ -91,7 +92,7 @@ export class MagicChipNode extends DecoratorNode<> {__agentSessionId: string;__channelId?: string;- __promptedMessage: MagicChipMessage;+ __promptedMessage: MagicChipMessage | null;__status: MagicChipStatus;static getType() {@@ -111,7 +112,7 @@ export class MagicChipNode extends DecoratorNode<constructor(agentSessionId: string,channelId: string | undefined,- promptedMessage: MagicChipMessage,+ promptedMessage: MagicChipMessage | null,status: MagicChipStatus,key?: NodeKey) {diff --git a/packages/lexical-core/tests/agent-session-mention.test.ts b/packages/lexical-core/tests/agent-session-mention.test.tsindex 2574eb229a..a5d25acdac 100644--- a/packages/lexical-core/tests/agent-session-mention.test.ts+++ b/packages/lexical-core/tests/agent-session-mention.test.ts@@ -19,6 +19,25 @@ const info = { id: 'session-1', label: 'Fix the menu' };const markdown = buildAgentSessionMentionMarkdown(info);describe('AgentSessionMentionNode', () => {+ it('preserves expansion and session-reference semantics through Markdown', () => {+ const expanded = buildAgentSessionMentionMarkdown({+ ...info,+ expanded: true,+ });+ const state = markdownToSerializedEditorStateWithIds(expanded);+ expect(state.root.children[0]).toMatchObject({+ children: [{ type: 'agent-session-mention', expanded: true }],+ });+ expect(serializedEditorStateToMarkdown(state)).toBe(expanded);+ expect(extractChannelMentionsFromMarkdown(expanded)).toEqual([+ { entityType: 'agent_session', entityId: info.id },+ ]);+ expect(markdownToPlainText(expanded)).toBe(info.label);+ expect(markdownToEmbeddingText(expanded)).toBe(+ '[Fix the menu](agent_session:session-1)'+ );+ });+it('round-trips Markdown and serialized state', () => {const state = markdownToSerializedEditorStateWithIds(markdown);expect(state.root.children[0]).toMatchObject({@@ -54,36 +73,48 @@ describe('AgentSessionMentionNode', () => {]);});- it('preserves identity when copied as HTML and pasted', () => {- const editor = createHeadlessEditor({- nodes: [...SupportedNodeTypes, ...NodeReplacements],- });- editor.setEditorState(- editor.parseEditorState(markdownToSerializedEditorStateWithIds(markdown))- );- const html = editor- .getEditorState()- .read(() => $generateHtmlFromNodes(editor));- expect(html).toContain('data-agent-session-id="session-1"');- editor.update(- () => {- const nodes = $generateNodesFromDOM(- editor,- new DOMParser().parseFromString(html, 'text/html')- );- $getRoot()- .clear()- .append(...nodes);- const paragraph = $getRoot().getFirstChild();- expect($isParagraphNode(paragraph)).toBe(true);- const node = $isParagraphNode(paragraph)- ? paragraph.getFirstChild()- : null;- expect($isAgentSessionMentionNode(node)).toBe(true);- if ($isAgentSessionMentionNode(node))- expect(node.getId()).toBe(info.id);- },- { discrete: true }- );- });+ it.each([false, true])(+ 'preserves identity and expansion through HTML (expanded: %s)',+ (expanded) => {+ const editor = createHeadlessEditor({+ nodes: [...SupportedNodeTypes, ...NodeReplacements],+ });+ editor.setEditorState(+ editor.parseEditorState(+ markdownToSerializedEditorStateWithIds(+ buildAgentSessionMentionMarkdown({+ ...info,+ ...(expanded ? { expanded: true } : {}),+ })+ )+ )+ );+ const html = editor+ .getEditorState()+ .read(() => $generateHtmlFromNodes(editor));+ expect(html).toContain('data-agent-session-id="session-1"');+ editor.update(+ () => {+ const nodes = $generateNodesFromDOM(+ editor,+ new DOMParser().parseFromString(html, 'text/html')+ );+ $getRoot()+ .clear()+ .append(...nodes);+ const paragraph = $getRoot().getFirstChild();+ expect($isParagraphNode(paragraph)).toBe(true);+ const node = $isParagraphNode(paragraph)+ ? paragraph.getFirstChild()+ : null;+ expect($isAgentSessionMentionNode(node)).toBe(true);+ if ($isAgentSessionMentionNode(node)) {+ expect(node.getId()).toBe(info.id);+ expect(node.isExpanded()).toBe(expanded);+ }+ },+ { discrete: true }+ );+ }+ );});diff --git a/packages/lexical-core/tests/magic-chip.test.ts b/packages/lexical-core/tests/magic-chip.test.tsindex 1bf1622567..0ef877be35 100644--- a/packages/lexical-core/tests/magic-chip.test.ts+++ b/packages/lexical-core/tests/magic-chip.test.ts@@ -8,6 +8,17 @@ const markdown ='<m-magic-chip>{"agentSessionId":"session-1","channelId":"channel-1","promptedMessage":{"turn":1,"author":"user"},"status":"booting"}</m-magic-chip>';describe('MagicChipNode', () => {+ it('round-trips an unlocked chip without turning null into a pinned turn', () => {+ const latest =+ '<m-magic-chip>{"agentSessionId":"session-1","promptedMessage":null,"status":"acp_ready"}</m-magic-chip>';+ const state = markdownToSerializedEditorStateWithIds(latest);+ expect(state.root.children[0]).toMatchObject({+ type: 'magic-chip',+ promptedMessage: null,+ });+ expect(serializedEditorStateToMarkdown(state)).toBe(latest);+ });+it('round-trips its typed static status through internal markdown', () => {const state = markdownToSerializedEditorStateWithIds(markdown);diff --git a/packages/lexical-core/transformers/magicChip.ts b/packages/lexical-core/transformers/magicChip.tsindex 6502c9954f..e87aad1ed4 100644--- a/packages/lexical-core/transformers/magicChip.ts+++ b/packages/lexical-core/transformers/magicChip.ts@@ -2,13 +2,16 @@ import type { ElementTransformer } from '@lexical/markdown';import type { ElementNode, LexicalNode } from 'lexical';import {$createMagicChipNode,- isMagicChipMessage,$isMagicChipNode,+ isMagicChipMessage,isMagicChipStatus,type MagicChipData,MagicChipNode,} from '../nodes/MagicChipNode';-import { replaceElementWithUnknownMention, UnknownMentionNode } from './unknownFallback';+import {+ replaceElementWithUnknownMention,+ UnknownMentionNode,+} from './unknownFallback';function isMagicChipData(value: unknown): value is MagicChipData {if (!value || typeof value !== 'object') return false;@@ -16,7 +19,8 @@ function isMagicChipData(value: unknown): value is MagicChipData {return (typeof data.agentSessionId === 'string' &&(data.channelId === undefined || typeof data.channelId === 'string') &&- isMagicChipMessage(data.promptedMessage) &&+ (data.promptedMessage === null ||+ isMagicChipMessage(data.promptedMessage)) &&isMagicChipStatus(data.status));}diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.tsindex fc6cc18386..1de85f0ece 100644--- a/packages/lexical-core/transformers/mentions.ts+++ b/packages/lexical-core/transformers/mentions.ts@@ -4,6 +4,7 @@ import type {} from '@lexical/markdown';import type { ElementNode, LexicalNode, TextNode } from 'lexical';import {+ $createAgentSessionMentionNode,AgentSessionMentionNode,buildAgentSessionMentionMarkdown,} from '../nodes/AgentSessionMentionNode';@@ -379,6 +380,7 @@ export const I_AGENT_SESSION_MENTION: TextMatchTransformer = {id: node.getId(),label: node.getLabel(),mentionUuid: node.getMentionUuid(),+ ...(node.isExpanded() ? { expanded: true } : {}),});},replace: (node: TextNode, match: RegExpMatchArray) => {@@ -387,12 +389,15 @@ export const I_AGENT_SESSION_MENTION: TextMatchTransformer = {if (!('id' in data) || typeof data.id !== 'string') {throw new Error('Missing field id');}- const prMentionNode = new AgentSessionMentionNode(- data.id,- typeof data.label === 'string' ? data.label : undefined,- typeof data.mentionUuid === 'string' ? data.mentionUuid : undefined+ node.replace(+ $createAgentSessionMentionNode({+ id: data.id,+ label: typeof data.label === 'string' ? data.label : undefined,+ mentionUuid:+ typeof data.mentionUuid === 'string' ? data.mentionUuid : undefined,+ expanded: data.expanded === true,+ }));- node.replace(prMentionNode);} catch (e) {console.error('Error in I_AGENT_SESSION_MENTION replace:', e);replaceTextWithUnknownMention(node, 'Unknown Agent Session');