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.

fix(agents): hide incomplete mentions after replies stop (#8989)

Wolf Mermelstein65703d8fef26
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index c4c1e31412..251110efc1 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -587,6 +587,10 @@ desktop and mobile.
Keep Responding bound to the notification turn, including rejection and noop.
The backend-free desktop/mobile check is
`bunx playwright test --config src/features/block-agent/browser-test/playwright.config.ts`.
+The same suite covers stopping and reloading an agent reply inside a mention:
+keep incomplete trailing Macro XML hidden in settled agent prose, preserve
+completed chips and literal tag examples in Markdown code, and leave user prompts
+unchanged.
Set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` when using the Nix Chrome binary.
Reuse the responsive import review for Notion, Linear and Jira; scope report
diff --git a/apps/web/src/features/block-agent/browser-test/mentions.browser.e2e.ts b/apps/web/src/features/block-agent/browser-test/mentions.browser.e2e.ts
new file mode 100644
index 0000000000..c05e7100bc
--- /dev/null
+++ b/apps/web/src/features/block-agent/browser-test/mentions.browser.e2e.ts
@@ -0,0 +1,64 @@
+import { expect, test } from '@playwright/test';
+
+test.setTimeout(60_000);
+
+test('stopping and reloading a reply keeps complete chips and hides partial XML', async ({
+ page,
+}) => {
+ await page.goto('/mentions.html');
+ const reply = page.getByRole('region', { name: 'Agent reply' });
+ await expect(reply).toContainText('Project notes', { timeout: 30_000 });
+ await expect(reply.locator('[data-agent-session-mention]')).toHaveAttribute(
+ 'data-agent-session-label',
+ 'Project notes'
+ );
+ await expect(reply).toContainText('The next reference is');
+ await expect(reply).not.toContainText('unfinished');
+
+ await page.getByRole('button', { name: 'Stop response' }).click();
+ await expect(
+ page.getByRole('button', { name: 'Stopped', exact: true })
+ ).toBeVisible();
+ await expect(reply.locator('[data-agent-session-mention]')).toHaveAttribute(
+ 'data-agent-session-label',
+ 'Project notes'
+ );
+ await expect(reply).not.toContainText('unfinished');
+ await expect(reply).not.toContainText('<m-');
+
+ await page.reload();
+ await expect(reply).toContainText('Project notes');
+ await expect(reply.locator('[data-agent-session-mention]')).toHaveAttribute(
+ 'data-agent-session-label',
+ 'Project notes'
+ );
+ await expect(reply).toContainText('The next reference is');
+ await expect(reply).not.toContainText('unfinished');
+ await expect(reply).not.toContainText('<m-');
+});
+
+test('literal mention examples stay code when stopped and reloaded', async ({
+ page,
+}) => {
+ await page.goto('/mentions.html?literal');
+ const reply = page.getByRole('region', { name: 'Agent reply' });
+ await expect(reply.locator('.md-inline-code')).toHaveText(
+ '<m-document-mention>',
+ {
+ timeout: 30_000,
+ }
+ );
+ await expect(reply).toContainText('as the tag name.');
+
+ await page.getByRole('button', { name: 'Stop response' }).click();
+ await expect(reply.locator('.md-inline-code')).toHaveText(
+ '<m-document-mention>'
+ );
+ await expect(reply).toContainText('as the tag name.');
+
+ await page.reload();
+ await expect(reply.locator('.md-inline-code')).toHaveText(
+ '<m-document-mention>'
+ );
+ await expect(reply).toContainText('as the tag name.');
+});
diff --git a/apps/web/src/features/block-agent/browser-test/mentions.html b/apps/web/src/features/block-agent/browser-test/mentions.html
new file mode 100644
index 0000000000..07d7c77ad8
--- /dev/null
+++ b/apps/web/src/features/block-agent/browser-test/mentions.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Stopped agent mentions</title></head>
+ <body><div id="root"></div><script type="module" src="./mentions.tsx"></script></body>
+</html>
diff --git a/apps/web/src/features/block-agent/browser-test/mentions.tsx b/apps/web/src/features/block-agent/browser-test/mentions.tsx
new file mode 100644
index 0000000000..8cef047689
--- /dev/null
+++ b/apps/web/src/features/block-agent/browser-test/mentions.tsx
@@ -0,0 +1,117 @@
+import '@app/index.css';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import {
+ createLexicalWrapper,
+ LexicalWrapperContext,
+} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
+import { channelTheme } from '@core/component/LexicalMarkdown/theme';
+import { buildAgentSessionMentionMarkdown } from '@macro-inc/lexical-core';
+import { agentSessionKeys } from '@queries/agent-session/keys';
+import type { FoldedMessage } from '@service-agent-fold/generated/types';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { createSignal, onCleanup } from 'solid-js';
+import { render } from 'solid-js/web';
+import { Message } from '../component/AgentMessage';
+
+const SESSION_ID = 'session-mention-fixture';
+const LABEL = 'Project notes';
+const MENTION = buildAgentSessionMentionMarkdown({
+ id: SESSION_ID,
+ label: LABEL,
+});
+
+function Fixture() {
+ const [stopped, setStopped] = createSignal(
+ new URLSearchParams(location.search).has('stopped')
+ );
+ const literal = new URLSearchParams(location.search).has('literal');
+ const reply = (): FoldedMessage => ({
+ agentSessionId: 'fixture',
+ turn: 1,
+ author: { kind: 'agent' },
+ parts: [
+ {
+ kind: 'text',
+ text: literal
+ ? 'Use `<m-document-mention>` as the tag name.'
+ : `Here is ${MENTION}. The next reference is <m-document-mention>{"documentId":"unfinished`,
+ },
+ ],
+ stop: stopped() ? { kind: 'cancelled' } : null,
+ requestId: null,
+ pending: false,
+ postedAt: null,
+ segments: [],
+ phase: null,
+ });
+ 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(SESSION_ID, graphql).queryKey,
+ accessible
+ ? {
+ access: 'access',
+ data: {
+ id: SESSION_ID,
+ name: LABEL,
+ ownerId: 'fixture-owner',
+ botId: 'fixture-bot',
+ status: { kind: 'disconnected' },
+ createdAt: '',
+ updatedAt: '',
+ },
+ }
+ : { access: 'no_access' }
+ );
+ }
+ };
+ setAccess(true);
+ return (
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <QueryClientProvider client={client}>
+ <LexicalWrapperContext.Provider
+ value={{ ...wrapper, skipPreviewFetch: true }}
+ >
+ <StaticMarkdownContext theme={channelTheme}>
+ <main class="p-6 text-ink bg-page min-h-screen">
+ <div class="max-w-2xl mx-auto space-y-6">
+ <h1 class="text-lg font-medium">Agent reply</h1>
+ <section aria-label="Agent reply">
+ <Message message={reply()} inFlight={!stopped()} />
+ </section>
+ <button
+ type="button"
+ disabled={stopped()}
+ onClick={() => {
+ const params = new URLSearchParams(location.search);
+ params.set('stopped', '');
+ history.replaceState(null, '', `?${params}`);
+ setStopped(true);
+ }}
+ >
+ {stopped() ? 'Stopped' : 'Stop response'}
+ </button>
+ </div>
+ </main>
+ </StaticMarkdownContext>
+ </LexicalWrapperContext.Provider>
+ </QueryClientProvider>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
+ );
+}
+
+render(() => <Fixture />, document.getElementById('root')!);
diff --git a/apps/web/src/features/block-agent/browser-test/session.ts b/apps/web/src/features/block-agent/browser-test/session.ts
index 30e9c8b349..4164e0b41b 100644
--- a/apps/web/src/features/block-agent/browser-test/session.ts
+++ b/apps/web/src/features/block-agent/browser-test/session.ts
@@ -28,6 +28,7 @@ export const session = {
turn: () => metadata().turn,
};
export const useOptionalAgentSession = () => session;
+export const useAgentSession = () => session;
export function receiveDecision() {
setMetadata((value) => ({
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
index 3024f461da..e2ae08dd16 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
@@ -7,7 +7,7 @@ import type {
MessagePart,
} from '@service-agent-fold/generated/types';
import { cleanup, render } from '@solidjs/testing-library';
-import { createSignal, type JSX, onMount } from 'solid-js';
+import { createSignal, type JSX } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Message } from './AgentMessage';
@@ -47,19 +47,16 @@ vi.mock('@ui', () => ({
<div data-testid="bubble">{props.children}</div>
),
}));
-vi.mock('./parts/TextPart', () => ({
- TextPart: (props: {
- text: string;
- observeRender?: (element: HTMLElement) => void;
- }) => {
- let element!: HTMLParagraphElement;
- onMount(() => props.observeRender?.(element));
- return (
- <p ref={element} data-testid="text">
- {props.text}
- </p>
- );
- },
+vi.mock(
+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',
+ () => ({
+ StaticMarkdown: (props: { markdown: string }) => (
+ <p data-testid="text">{props.markdown}</p>
+ ),
+ })
+);
+vi.mock('@core/component/LexicalMarkdown/theme', () => ({
+ channelTheme: {},
}));
vi.mock('./parts/ToolCallPart', () => ({
ToolCallPart: (props: {
@@ -178,6 +175,49 @@ const message = (
stop,
});
+describe('Message incomplete mentions', () => {
+ const partial = 'See <m-document-mention>{"documentId":"unfinished';
+
+ it('keeps a cancelled reply clean when stopping and after remount', () => {
+ const [reply, setReply] = createSignal(message([text(partial)], null));
+ const [inFlight, setInFlight] = createSignal(true);
+ const view = render(() => (
+ <Message message={reply()} inFlight={inFlight()} />
+ ));
+ expect(view.getByTestId('text').textContent).toBe('See ');
+
+ setReply(message([text(partial)], { kind: 'cancelled' }));
+ setInFlight(false);
+ expect(view.getByTestId('text').textContent).toBe('See ');
+ view.unmount();
+
+ const restored = render(() => (
+ <Message message={reply()} inFlight={false} />
+ ));
+ expect(restored.getByTestId('text').textContent).toBe('See ');
+ });
+
+ it('hides an interrupted reply without a recorded stop reason', () => {
+ const view = render(() => (
+ <Message message={message([text(partial)], null)} inFlight={false} />
+ ));
+ expect(view.getByTestId('text').textContent).toBe('See ');
+ });
+
+ it('preserves unfinished markup in user prompts', () => {
+ const view = render(() => (
+ <Message
+ message={{
+ ...message([text(partial)]),
+ author: { kind: 'user', userId: null },
+ }}
+ inFlight={false}
+ />
+ ));
+ expect(view.getByTestId('text').textContent).toBe(partial);
+ });
+});
+
describe('Message tool grouping', () => {
it('observes only agent answer DOM on the existing session and matching turn', () => {
renderTelemetry.context.mockReturnValue({
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index ce2c747fbc..2a1de23ffa 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -80,6 +80,7 @@ function AgentMessagePart(props: {
<TextPart
text={part().text}
inFlight={props.inFlight}
+ hideIncompleteXml={props.message.author.kind === 'agent'}
observeRender={
props.message.author.kind === 'agent'
? (element) =>
diff --git a/apps/web/src/features/block-agent/component/parts/TextPart.test.tsx b/apps/web/src/features/block-agent/component/parts/TextPart.test.tsx
index 41416ceae0..283b7ba7f5 100644
--- a/apps/web/src/features/block-agent/component/parts/TextPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/TextPart.test.tsx
@@ -6,9 +6,9 @@
* each re-render rebuilds its DOM, reloading every image in it.
*/
-import { render } from '@solidjs/testing-library';
+import { cleanup, render } from '@solidjs/testing-library';
import { createEffect, createSignal } from 'solid-js';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { TextPart } from './TextPart';
const parses = vi.hoisted((): string[] => []);
@@ -28,7 +28,35 @@ vi.mock('@core/component/LexicalMarkdown/theme', () => ({
channelTheme: {},
}));
+afterEach(cleanup);
+
describe('TextPart', () => {
+ it('keeps an unfinished agent chip hidden when the stream settles', () => {
+ parses.length = 0;
+ const [inFlight, setInFlight] = createSignal(true);
+ render(() => (
+ <TextPart
+ text={'See <m-document-mention>{"documentId":"unfinished'}
+ hideIncompleteXml
+ inFlight={inFlight()}
+ />
+ ));
+ setInFlight(false);
+ expect(parses).toEqual(['See ']);
+ });
+
+ it('preserves complete chips and surrounding text in settled replies', () => {
+ parses.length = 0;
+ const complete =
+ '<m-document-mention>{"documentId":"abc","documentName":"Notes","blockName":"md","blockParams":{}}</m-document-mention>';
+ render(() => (
+ <TextPart
+ text={`Before ${complete} after. Next <m-user-mention>{"userId":`}
+ hideIncompleteXml
+ />
+ ));
+ expect(parses).toEqual([`Before ${complete} after. Next `]);
+ });
it('hands mounted markdown DOM to its observer and cleans up when unmounted', () => {
const stop = vi.fn();
const observe = vi.fn((element: HTMLElement) => {
diff --git a/apps/web/src/features/block-agent/component/parts/TextPart.tsx b/apps/web/src/features/block-agent/component/parts/TextPart.tsx
index fe147f2c4e..96a5162dd2 100644
--- a/apps/web/src/features/block-agent/component/parts/TextPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/TextPart.tsx
@@ -8,12 +8,16 @@ import { hideIncompleteMacroXml } from './hideIncompleteMacroXml';
export function TextPart(props: {
text: string;
inFlight?: boolean;
+ /** Agent prose stays truncated after a stop, interruption, or reload. */
+ hideIncompleteXml?: boolean;
observeRender?: (element: HTMLElement) => (() => void) | undefined;
}) {
// Memoized so an `inFlight` flip that leaves the text unchanged does not
// rebuild the markdown DOM and reload its images.
const markdown = createMemo(() =>
- props.inFlight ? hideIncompleteMacroXml(props.text) : props.text
+ props.inFlight || props.hideIncompleteXml
+ ? hideIncompleteMacroXml(props.text)
+ : props.text
);
let content!: HTMLDivElement;
onMount(() => {
diff --git a/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.test.ts b/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.test.ts
index c00755e5fb..fc5cfe8fa0 100644
--- a/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.test.ts
+++ b/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.test.ts
@@ -15,10 +15,57 @@ describe('hideIncompleteMacroXml', () => {
).toBe('See ');
});
+ it('keeps completed chips and surrounding prose before an unfinished chip', () => {
+ expect(
+ hideIncompleteMacroXml(
+ `Before ${complete} after. Next <m-document-mention>{"documentId":"partial`
+ )
+ ).toBe(`Before ${complete} after. Next `);
+ });
+
+ it.each([
+ '<m-document-ment',
+ '<m-document-mention>',
+ '<m-document-mention>{"documentId":"partial',
+ '<m-document-mention>{"documentId":"abc"}</m-document-',
+ '<m-user-mention>{"userId":"partial',
+ '<m-agent-session-mention>{"id":"partial',
+ ])('hides a response cut off at %s', (partial) => {
+ expect(hideIncompleteMacroXml(`See ${partial}`)).toBe('See ');
+ });
+
it('strips a trailing bare open prefix', () => {
expect(hideIncompleteMacroXml('See <m-document-ment')).toBe('See ');
});
+ it.each([
+ 'Use `<m-document-mention>` as the tag name.',
+ 'Use ``<m-document-mention>`` as the tag name.',
+ 'Example:\n```xml\n<m-document-mention>{"documentId":"example"}\n```\nAfter.',
+ 'Example:\n```xml\n<m-document-mention>{"documentId":"unfinished',
+ 'Example:\n````xml\n```\n<m-document-mention>\n````\nAfter.',
+ ])('preserves literal Macro XML in code: %s', (text) => {
+ expect(hideIncompleteMacroXml(text)).toBe(text);
+ });
+
+ it('still hides an unfinished chip after a closed code example', () => {
+ const before = 'Use `<m-document-mention>` as the tag name. See ';
+ expect(
+ hideIncompleteMacroXml(`${before}<m-document-mention>{"documentId":`)
+ ).toBe(before);
+ const fenced = '```xml\n<m-document-mention>\n```\nSee ';
+ expect(hideIncompleteMacroXml(`${fenced}<m-user-mention>{"userId":`)).toBe(
+ fenced
+ );
+ });
+
+ it('does not treat an escaped backtick or an unclosed inline span as code', () => {
+ expect(hideIncompleteMacroXml('Use \\`<m-document-mention>')).toBe(
+ 'Use \\`'
+ );
+ expect(hideIncompleteMacroXml('Use `<m-document-mention>')).toBe('Use `');
+ });
+
it('leaves text with no mention markup alone', () => {
expect(hideIncompleteMacroXml('plain reply')).toBe('plain reply');
});
diff --git a/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.ts b/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.ts
index 7073b27160..2134b111d1 100644
--- a/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.ts
+++ b/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.ts
@@ -1,13 +1,46 @@
/**
- * Hide a trailing unclosed Macro mention tag so streaming text does not
- * flash raw `<m-document-mention>` XML. Complete tags stay intact.
+ * Hide a trailing unclosed Macro mention tag so agent text does not
+ * flash raw `<m-document-mention>` XML. Complete tags and code stay intact.
*/
export function hideIncompleteMacroXml(text: string): string {
const open = text.lastIndexOf('<m-');
if (open === -1) return text;
+ if (isInCode(text, open)) return text;
const after = text.slice(open);
if (/^<m-[a-zA-Z0-9_-]+>[\s\S]*<\/m-[a-zA-Z0-9_-]+>/.test(after)) {
return text;
}
return text.slice(0, open);
}
+
+/** Follow Lexical's backtick fences, including fences still being streamed. */
+function isInCode(text: string, position: number): boolean {
+ let closingFence: RegExp | undefined;
+ let offset = 0;
+ for (const line of text.split('\n')) {
+ const containsPosition = position < offset + line.length + 1;
+ if (closingFence) {
+ if (containsPosition) return true;
+ if (closingFence.test(line.trimEnd())) closingFence = undefined;
+ } else {
+ const fence = /^[ \t]*(`{3,})/.exec(line);
+ if (fence) {
+ if (containsPosition) return true;
+ const length = fence[1].length;
+ const rest = line.trimEnd().slice(fence[0].length);
+ if (!new RegExp(`\`{${length},}$`).test(rest)) {
+ closingFence = new RegExp(`^[ \\t]*\`{${length},}$`);
+ }
+ } else if (containsPosition) {
+ for (const span of line.matchAll(/(^|[^\\`])(`+)(.*?)\2(?!`)/g)) {
+ const start = offset + span.index + span[1].length;
+ const end = offset + span.index + span[0].length;
+ if (position >= start && position < end) return true;
+ }
+ return false;
+ }
+ }
+ offset += line.length + 1;
+ }
+ return false;
+}
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index fd34dd1cd7..629df9be80 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -688,6 +688,13 @@ icons instead of flashing back to loading placeholders. Check an answer with
multiple mentions while more text arrives and when generation finishes, in both
chat and agent sessions. A newly encountered mention may load once.
+If an agent reply stops inside a Macro mention chip, its unfinished trailing
+markup stays hidden after stopping and after reload, on desktop and mobile.
+Completed chips, literal tag examples in Markdown code, and the prose before
+the unfinished chip remain visible. Verify
+with a reply containing a completed mention followed by a partial mention: stop
+it, then reload. User-authored markup remains unchanged.
+
On mobile, only the AI/Agents view has a floating AI composer above the bottom
dock. Its input fills the row with no separate create button. Other views keep
their right-aligned creation action: **+ Email**, **+ Task**, **+ Document**,