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): render Cursor `<system_notification>` events as cards in agent transcripts (#7239)
Wolf Mermelstein6f33cb9a6225
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsxindex aec49079c5..70ab316fa4 100644--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx@@ -633,6 +633,26 @@ describe('Message prompt attribution', () => {expect(view.queryByTestId('prompt-author')).toBeNull();expect(view.getByTestId('bubble')).toBeTruthy();});++ it('renders a notification Cursor wrote full-width, not as a prompt', () => {+ const notification = [+ '<system_notification source="github" conclusion="success" checks="27" subscriptionType="github:ci:branch">',+ 'All 27 CI checks completed without failures.',+ '</system_notification>',+ ].join('\n');+ const view = render(() => (+ <Message+ message={{+ ...message([text(notification)]),+ author: { kind: 'user', userId: 'macro|[email protected]' },+ }}+ inFlight={false}+ />+ ));+ expect(view.queryByTestId('bubble')).toBeNull();+ expect(view.queryByTestId('prompt-author')).toBeNull();+ expect(view.getByTestId('text').textContent).toBe(notification);+ });});describe('Message failed turns', () => {diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsxindex 853af9fd03..5b7c93bdbf 100644--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx@@ -21,6 +21,7 @@ import { UserMessageBubble } from '@ui';import { For, Index, type JSX, Match, Show, Switch } from 'solid-js';import { match } from 'ts-pattern';import { isControlMessage } from '../state/control-message';+import { isNotificationMessage } from '../state/notification-message';import { thoughtIsStreaming } from '../state/thought-streaming';import { segmentParts } from '../state/tool-groups';import {@@ -281,9 +282,14 @@ export function Message(props: {props.message.stop?.kind === 'failed' ? props.message.stop : undefined;return (+ // A control and an event notification are both user-authored by the+ // fold's account and neither is a prompt: they take the full-width+ // treatment, where the notification renders as its own card.<Showwhen={- props.message.author.kind === 'user' && !isControlMessage(props.message)+ props.message.author.kind === 'user' &&+ !isControlMessage(props.message) &&+ !isNotificationMessage(props.message)}fallback={<div class="flex flex-col gap-1 min-w-0">diff --git a/apps/web/src/features/block-agent/state/notification-message.test.ts b/apps/web/src/features/block-agent/state/notification-message.test.tsnew file mode 100644index 0000000000..784f7fcc93--- /dev/null+++ b/apps/web/src/features/block-agent/state/notification-message.test.ts@@ -0,0 +1,81 @@+import type { FoldedMessage } from '@service-agent-fold/generated/types';+import { describe, expect, it } from 'vitest';+import { isNotificationMessage } from './notification-message';++const NOTIFICATION = [+ '<system_notification source="github" repo="github.com/macro-inc/macro" conclusion="success" checks="27" subscriptionType="github:ci:branch">',+ 'All 27 CI checks completed without failures.',+ '</system_notification>',+].join('\n');++const message = (+ author: 'user' | 'agent',+ parts: FoldedMessage['parts']+): FoldedMessage =>+ ({+ turn: 1,+ author:+ author === 'user' ? { kind: 'user', userId: null } : { kind: 'agent' },+ parts,+ stop: null,+ }) as unknown as FoldedMessage;++describe('isNotificationMessage', () => {+ it('recognises a prompt Cursor wrote from a subscription event', () => {+ expect(+ isNotificationMessage(+ message('user', [{ kind: 'text', text: `\n${NOTIFICATION}\n` }])+ )+ ).toBe(true);+ });++ it('recognises several notifications delivered as one prompt', () => {+ expect(+ isNotificationMessage(+ message('user', [+ { kind: 'text', text: `${NOTIFICATION}\n\n${NOTIFICATION}` },+ ])+ )+ ).toBe(true);+ });++ it('leaves a prompt a person typed around a pasted notification as theirs', () => {+ expect(+ isNotificationMessage(+ message('user', [+ { kind: 'text', text: `Look at this:\n${NOTIFICATION}` },+ ])+ )+ ).toBe(false);+ expect(+ isNotificationMessage(+ message('user', [+ { kind: 'text', text: NOTIFICATION },+ { kind: 'text', text: 'and fix it' },+ ])+ )+ ).toBe(false);+ });++ it('never reads an agent reply or an empty message as a notification', () => {+ expect(+ isNotificationMessage(+ message('agent', [{ kind: 'text', text: NOTIFICATION }])+ )+ ).toBe(false);+ expect(isNotificationMessage(message('user', []))).toBe(false);+ });++ it.each([+ `${NOTIFICATION}\nPlease fix this\n${NOTIFICATION}`,+ `<system_notification source="github">${NOTIFICATION}</system_notification>`,+ `\`\`\`xml\n${NOTIFICATION}\n\`\`\``,+ ])(+ 'keeps mixed, nested, or code-fenced content in a prompt bubble',+ (text) => {+ expect(+ isNotificationMessage(message('user', [{ kind: 'text', text }]))+ ).toBe(false);+ }+ );+});diff --git a/apps/web/src/features/block-agent/state/notification-message.ts b/apps/web/src/features/block-agent/state/notification-message.tsnew file mode 100644index 0000000000..58b6fcf376--- /dev/null+++ b/apps/web/src/features/block-agent/state/notification-message.ts@@ -0,0 +1,29 @@+/**+ * Telling an event notification apart from a prompt.+ *+ * A Cursor run that subscribes to something outside the conversation — a CI+ * run, a thread, a timer — gets told about it by a prompt Cursor writes+ * itself, wrapped in `<system_notification …>` (see `CursorSystemNotificationNode`+ * in lexical-core). The fold records it as a user message like any other, so+ * by author it is indistinguishable from something a person typed. It is+ * not: nobody sent it, so it should not sit in a prompt bubble under+ * someone's name.+ */++import type { FoldedMessage } from '@service-agent-fold/generated/types';++const NOTIFICATION_ONLY =+ /^\s*(?:<system_notification\b[^>]*>(?:(?!<\/?system_notification\b)[\s\S])*<\/system_notification>\s*)+$/;++/**+ * Every part is a notification Cursor wrote: the message is an event, not a+ * prompt. A prompt a person typed around a pasted notification stays theirs.+ */+export function isNotificationMessage(message: FoldedMessage): boolean {+ if (message.author.kind !== 'user' || message.parts.length === 0) {+ return false;+ }+ return message.parts.every(+ (part) => part.kind === 'text' && NOTIFICATION_ONLY.test(part.text)+ );+}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 83f1b8615d..47d69cc964 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@@ -17,6 +17,7 @@ import {type ClassedBlockNode,type ConnectAppNode,type ContactMentionNode,+ type CursorSystemNotificationNode,type DateMentionNode,DEFAULT_LANGUAGE,type DocumentCardNode,@@ -82,6 +83,7 @@ import { AgentSessionMention as AgentSessionMentionDecorator } from '../decoratoimport { Await as AwaitDecorator } from '../decorator/Await';import { ConnectApp as ConnectAppDecorator } from '../decorator/ConnectApp';import { ContactMention as ContactMentionDecorator } from '../decorator/ContactMention';+import { CursorSystemNotification as CursorSystemNotificationDecorator } from '../decorator/CursorSystemNotification';import { DateMention as DateMentionDecorator } from '../decorator/DateMention';import { DocumentCard as DocumentCardDecorator } from '../decorator/DocumentCard';import {@@ -561,6 +563,19 @@ const ReplyTarget: TypedRenderableEntity<ReplyTargetNode> = {),};+const CursorSystemNotification: TypedRenderableEntity<CursorSystemNotificationNode> =+ {+ guard: (node: LexicalNode): node is CursorSystemNotificationNode =>+ node.__type === 'system-notification',+ render: (props) => (+ <CursorSystemNotificationDecorator+ {...props.node.exportComponentProps()}+ key={props.node.getKey()}+ theme={props.theme}+ />+ ),+ };+const MagicChip: TypedRenderableEntity<MagicChipNode> = {guard: (node: LexicalNode): node is MagicChipNode =>node.__type === 'magic-chip',@@ -927,6 +942,7 @@ const InlineEntities: RenderableEntity[] = [eraseRenderableEntity(Await),eraseRenderableEntity(AgentContext),eraseRenderableEntity(ReplyTarget),+ eraseRenderableEntity(CursorSystemNotification),eraseRenderableEntity(MagicChip),eraseRenderableEntity(Snapshot),eraseRenderableEntity(Image),diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/CursorSystemNotification.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/CursorSystemNotification.test.tsxnew file mode 100644index 0000000000..659c05ac78--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/CursorSystemNotification.test.tsx@@ -0,0 +1,165 @@+/**+ * @vitest-environment jsdom+ */++import { fireEvent, render } from '@solidjs/testing-library';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ CursorSystemNotification,+ conclusionTone,+ details,+ kindLabel,+ sourceLabel,+} from './CursorSystemNotification';++const mocks = vi.hoisted(() => ({ openExternalUrl: vi.fn() }));+vi.mock('@core/util/url', () => ({ openExternalUrl: mocks.openExternalUrl }));++const ci = {+ key: 'k',+ theme: {},+ source: 'github',+ text: 'All 27 CI checks completed without failures.',+ attributes: {+ repo: 'github.com/macro-inc/macro',+ commit: 'ca515d369476de0a33eef36b21724175e2f6bed3',+ branch: 'cursor/settings-menu-search-1f17',+ conclusion: 'success',+ checks: '27',+ subscriptionId: 'sub_7a13eaab-eee7-4339-a8d3-31c3182150b2',+ subscriptionType: 'github:ci:branch',+ },+};++beforeEach(() => {+ mocks.openExternalUrl.mockReset();+});++describe('CursorSystemNotification', () => {+ it('reads a CI result as a GitHub card with its summary and a pass pill', () => {+ const view = render(() => <CursorSystemNotification {...ci} />);+ const card = view.getByRole('region', { name: 'GitHub notification' });+ expect(card.textContent).toContain('GitHub');+ expect(card.textContent).toContain('CI checks');+ expect(card.textContent).toContain(+ 'All 27 CI checks completed without failures.'+ );+ expect(card.querySelector('[data-tone]')?.getAttribute('data-tone')).toBe(+ 'success'+ );+ expect(card.textContent).toContain('Success');+ });++ it('shows the repository, branch, short commit and check count, and hides the subscription id', () => {+ const view = render(() => <CursorSystemNotification {...ci} />);+ const card = view.getByRole('region');+ expect(card.textContent).toContain('macro-inc/macro');+ expect(card.textContent).toContain('cursor/settings-menu-search-1f17');+ expect(card.textContent).toContain('ca515d3');+ expect(card.textContent).not.toContain(+ 'ca515d369476de0a33eef36b21724175e2f6bed3'+ );+ expect(card.textContent).toContain('27 checks');+ expect(card.textContent).not.toContain('sub_7a13eaab');+ expect(card.textContent).not.toContain('github:ci:branch');+ });++ it('opens the commit on GitHub from its chip', () => {+ const view = render(() => <CursorSystemNotification {...ci} />);+ fireEvent.click(view.getByText('ca515d3'));+ expect(mocks.openExternalUrl).toHaveBeenCalledWith(+ 'https://github.com/macro-inc/macro/commit/ca515d369476de0a33eef36b21724175e2f6bed3'+ );+ fireEvent.click(view.getByText('macro-inc/macro'));+ expect(mocks.openExternalUrl).toHaveBeenCalledWith(+ 'https://github.com/macro-inc/macro'+ );+ });++ it('lists attributes it has no face for as name: value chips', () => {+ const view = render(() => (+ <CursorSystemNotification+ key="k"+ theme={{}}+ source="linear"+ text="Issue moved to In Progress."+ attributes={{+ issue: 'MAC-123',+ subscriptionType: 'linear:issue',+ subscriptionId: 'sub_x',+ }}+ />+ ));+ const card = view.getByRole('region', { name: 'Linear notification' });+ expect(card.textContent).toContain('Issue update');+ expect(card.textContent).toContain('issue: MAC-123');+ expect(card.textContent).not.toContain('sub_x');+ expect(card.querySelector('[data-tone]')).toBeNull();+ });++ it.each([+ 'javascript:alert(1)',+ 'javascript://example.com/%0aalert(1)',+ 'data:text/html,<script>alert(1)</script>',+ 'file:///etc/passwd',+ 'https://',+ ])('does not render actionable links for %s', (url) => {+ const view = render(() => (+ <CursorSystemNotification+ {...ci}+ attributes={{ repo: url, commit: ci.attributes.commit, url }}+ />+ ));+ expect(view.queryAllByRole('link')).toHaveLength(0);+ fireEvent.click(view.getByText('ca515d3'));+ expect(mocks.openExternalUrl).not.toHaveBeenCalled();+ expect(+ details({ repository: url, link: url, sha: ci.attributes.commit }).every(+ (detail) => detail.href === undefined+ )+ ).toBe(true);+ });++ it.each(['http://example.com/event', 'https://example.com/event'])(+ 'opens an HTTP event link: %s',+ (url) => {+ const view = render(() => (+ <CursorSystemNotification {...ci} attributes={{ link: url }} />+ ));+ fireEvent.click(view.getByRole('link', { name: 'Open' }));+ expect(mocks.openExternalUrl).toHaveBeenCalledWith(url);+ }+ );+});++describe('labels', () => {+ it('names known sources and title-cases the rest', () => {+ expect(sourceLabel('github')).toBe('GitHub');+ expect(sourceLabel('slack')).toBe('Slack');+ expect(sourceLabel('jira')).toBe('Jira');+ expect(sourceLabel('')).toBe('System');+ });++ it('reads a subscription type as words', () => {+ expect(kindLabel('github:ci:branch')).toBe('CI checks');+ expect(kindLabel('slack:thread')).toBe('Thread reply');+ expect(kindLabel('timer')).toBe('Timer');+ expect(kindLabel('github:release_published')).toBe('Release published');+ expect(kindLabel(undefined)).toBe('Notification');+ });++ it('colours a conclusion by outcome', () => {+ expect(conclusionTone('success')).toBe('success');+ expect(conclusionTone('failure')).toBe('failure');+ expect(conclusionTone('timed_out')).toBe('failure');+ expect(conclusionTone('neutral')).toBe('neutral');+ expect(conclusionTone(undefined)).toBe('neutral');+ });++ it('links a commit only when it knows the repository', () => {+ expect(details({ commit: 'abcdef0123456789' })).toEqual([+ expect.objectContaining({ label: 'abcdef0', href: undefined }),+ ]);+ expect(details({ checks: '1' })[0]?.label).toBe('1 check');+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/CursorSystemNotification.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/CursorSystemNotification.tsxnew file mode 100644index 0000000000..9af5d2117f--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/CursorSystemNotification.tsx@@ -0,0 +1,282 @@+/**+ * The card a Cursor `<system_notification>` renders as: an event that+ * happened to the session — a CI run finishing, a thread reply, a timer —+ * rather than something a person typed. Cursor writes these into the prompt+ * stream when a run subscribes to something outside the conversation; see+ * `CursorSystemNotificationNode` for the wire shape.+ *+ * The attributes Cursor sends are not a fixed schema, so the card knows the+ * handful worth a face (repository, branch, commit, checks, a status word)+ * and lists whatever else it carried as plain `name: value` chips, hiding+ * only the subscription bookkeeping nobody reads.+ */++import { openExternalUrl } from '@core/util/url';+import type { CursorSystemNotificationDecoratorProps } from '@macro-inc/lexical-core';+import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';+import BellIcon from '@phosphor/bell.svg';+import CheckCircleIcon from '@phosphor/check-circle.svg';+import GitBranchIcon from '@phosphor/git-branch.svg';+import GitCommitIcon from '@phosphor/git-commit.svg';+import GithubLogoIcon from '@phosphor/github-logo.svg';+import SlackLogoIcon from '@phosphor/slack-logo.svg';+import TimerIcon from '@phosphor/timer.svg';+import XCircleIcon from '@phosphor/x-circle.svg';+import { cn } from '@ui/utils/classname';+import { type Component, For, Show } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import { match } from 'ts-pattern';++/** How the source names itself in the card's header. */+export function sourceLabel(source: string): string {+ return match(source.toLowerCase())+ .with('github', () => 'GitHub')+ .with('slack', () => 'Slack')+ .with('linear', () => 'Linear')+ .with('timer', () => 'Timer')+ .otherwise(() =>+ source ? source.charAt(0).toUpperCase() + source.slice(1) : 'System'+ );+}++function sourceIcon(source: string): Component<{ class?: string }> {+ return match(source.toLowerCase())+ .with('github', () => GithubLogoIcon)+ .with('slack', () => SlackLogoIcon)+ .with('timer', () => TimerIcon)+ .otherwise(() => BellIcon);+}++/**+ * What kind of event this was, from Cursor's `subscriptionType`+ * (`github:ci:branch`, `slack:thread`, `linear:issue`, `timer`). Unknown+ * types read as their words.+ */+export function kindLabel(subscriptionType: string | undefined): string {+ if (!subscriptionType) return 'Notification';+ return match(subscriptionType)+ .with('github:ci', 'github:ci:branch', 'github:ci:pr', () => 'CI checks')+ .with('github:pr', () => 'Pull request')+ .with('slack:thread', () => 'Thread reply')+ .with('slack:channel', () => 'Channel message')+ .with('linear:issue', () => 'Issue update')+ .with('linear:comment', () => 'Issue comment')+ .with('timer', () => 'Timer')+ .otherwise((type) => {+ const words = type.split(/[:_-]+/).filter(Boolean);+ const label = words.slice(1).join(' ') || words.join(' ');+ return label.charAt(0).toUpperCase() + label.slice(1);+ });+}++type Tone = 'success' | 'failure' | 'neutral';++/** The tone a status word carries: green for a pass, red for anything that went wrong. */+export function conclusionTone(conclusion: string | undefined): Tone {+ return match(conclusion?.toLowerCase())+ .with('success', 'passed', 'completed', 'merged', () => 'success' as const)+ .with(+ 'failure',+ 'failed',+ 'error',+ 'cancelled',+ 'canceled',+ 'timed_out',+ 'action_required',+ () => 'failure' as const+ )+ .otherwise(() => 'neutral' as const);+}++function conclusionLabel(conclusion: string): string {+ const words = conclusion.replace(/[_-]+/g, ' ').toLowerCase();+ return words.charAt(0).toUpperCase() + words.slice(1);+}++function safeHttpUrl(value: string): string | undefined {+ try {+ const url = new URL(value);+ return url.protocol === 'https:' || url.protocol === 'http:'+ ? url.href+ : undefined;+ } catch {+ return undefined;+ }+}++/** A repository as Cursor spells it (`github.com/org/repo`, sometimes with a scheme) as a URL. */+function repositoryUrl(repo: string): string | undefined {+ const value = repo.trim();+ return safeHttpUrl(+ /^[a-z][a-z\d+.-]*:/i.test(value) ? value : `https://${value}`+ );+}++/** `github.com/org/repo` reads as `org/repo`; anything else is left alone. */+function repositoryName(repo: string): string {+ return repo.replace(/^(?:[a-z]+:\/\/)?(?:www\.)?github\.com\//i, '');+}++/** Attributes the card renders with their own face, or deliberately not at all. */+const FEATURED = new Set([+ 'repo',+ 'repository',+ 'branch',+ 'commit',+ 'sha',+ 'checks',+ 'conclusion',+ 'status',+ 'url',+ 'link',+ 'subscriptionId',+ 'subscriptionType',+]);++type Detail = {+ label: string;+ icon?: Component<{ class?: string }>;+ href?: string;+ title?: string;+};++/** The footer chips, in reading order. */+export function details(attributes: Record<string, string>): Detail[] {+ const repo = attributes.repo ?? attributes.repository;+ const sha = attributes.commit ?? attributes.sha;+ const repoHref = repo ? repositoryUrl(repo) : undefined;+ const chips: Detail[] = [];+ if (repo) {+ chips.push({+ label: repositoryName(repo),+ icon: GithubLogoIcon,+ href: repoHref,+ });+ }+ if (attributes.branch) {+ chips.push({ label: attributes.branch, icon: GitBranchIcon });+ }+ if (sha) {+ chips.push({+ label: sha.slice(0, 7),+ icon: GitCommitIcon,+ title: sha,+ href: repoHref+ ? `${repoHref.replace(/\/$/, '')}/commit/${encodeURIComponent(sha)}`+ : undefined,+ });+ }+ if (attributes.checks) {+ const count = Number(attributes.checks);+ chips.push({+ label: Number.isFinite(count)+ ? `${count} ${count === 1 ? 'check' : 'checks'}`+ : attributes.checks,+ });+ }+ const link = attributes.url ?? attributes.link;+ if (link) {+ const href = safeHttpUrl(link);+ if (href) chips.push({ label: 'Open', icon: ArrowUpRightIcon, href });+ }+ for (const [name, value] of Object.entries(attributes)) {+ if (FEATURED.has(name) || !value) continue;+ chips.push({ label: `${name}: ${value}` });+ }+ return chips;+}++function DetailChip(props: { detail: Detail }) {+ const href = () => props.detail.href;+ return (+ <Dynamic+ component={href() ? 'a' : 'span'}+ href={href()}+ title={props.detail.title ?? href()}+ class={cn(+ 'inline-flex max-w-full items-center gap-1 rounded-md border border-edge-muted px-1.5 py-0.5 text-xs text-ink-muted',+ href() &&+ 'pointer-events-auto no-underline outline-none transition-colors hover:border-edge hover:text-ink focus-visible:text-ink'+ )}+ // The card sits in an editor: a click is an action, not a caret target.+ onMouseDown={(event: MouseEvent) => {+ if (href()) event.preventDefault();+ }}+ onClick={(event: MouseEvent) => {+ const target = href();+ if (!target) return;+ event.preventDefault();+ openExternalUrl(target);+ }}+ >+ <Show when={props.detail.icon}>+ {(icon) => <Dynamic component={icon()} class="size-3 shrink-0" />}+ </Show>+ <span class="truncate">{props.detail.label}</span>+ </Dynamic>+ );+}++export function CursorSystemNotification(+ props: CursorSystemNotificationDecoratorProps+) {+ const conclusion = () =>+ props.attributes.conclusion ?? props.attributes.status;+ const tone = () => conclusionTone(conclusion());+ const chips = () => details(props.attributes);++ return (+ <section+ data-system-notification={props.source}+ aria-label={`${sourceLabel(props.source)} notification`}+ class="my-1.5 min-w-0 max-w-full overflow-hidden rounded-xl border border-edge-muted bg-panel text-ink"+ >+ <div class="flex items-start gap-3 px-3 pt-3">+ <div class="flex size-7 shrink-0 items-center justify-center rounded-lg bg-accent-bg text-ink-muted">+ <Dynamic component={sourceIcon(props.source)} class="size-4" />+ </div>+ <div class="min-w-0 flex-1">+ <div class="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs leading-5 text-ink-muted">+ <span class="font-medium text-ink">+ {sourceLabel(props.source)}+ </span>+ <span aria-hidden="true">·</span>+ <span>{kindLabel(props.attributes.subscriptionType)}</span>+ <Show when={conclusion()}>+ {(word) => (+ <span+ data-tone={tone()}+ class={cn(+ 'ml-auto inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium',+ match(tone())+ .with('success', () => 'bg-success-bg text-success-ink')+ .with('failure', () => 'bg-failure-bg text-failure-ink')+ .with('neutral', () => 'bg-accent-bg text-ink-muted')+ .exhaustive()+ )}+ >+ {match(tone())+ .with('success', () => <CheckCircleIcon class="size-3.5" />)+ .with('failure', () => <XCircleIcon class="size-3.5" />)+ .with('neutral', () => null)+ .exhaustive()}+ {conclusionLabel(word())}+ </span>+ )}+ </Show>+ </div>+ <Show when={props.text}>+ <p class="mt-0.5 whitespace-pre-wrap text-sm leading-5 [overflow-wrap:anywhere]">+ {props.text}+ </p>+ </Show>+ </div>+ </div>+ <Show when={chips().length > 0}>+ <div class="flex flex-wrap gap-1.5 px-3 pb-3 pt-2">+ <For each={chips()}>{(detail) => <DetailChip detail={detail} />}</For>+ </div>+ </Show>+ </section>+ );+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts b/apps/web/src/lib/core/component/LexicalMarkdown/init.tsindex ef2c4c03e8..44f9f78b65 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts@@ -4,6 +4,7 @@ import {AwaitNode,ConnectAppNode,ContactMentionNode,+ CursorSystemNotificationNode,DateMentionNode,DiffInsertNode,DocumentCardNode,@@ -34,6 +35,7 @@ import { AgentSessionMention } from './component/decorator/AgentSessionMention';import { Await } from './component/decorator/Await';import { ConnectApp } from './component/decorator/ConnectApp';import { ContactMention } from './component/decorator/ContactMention';+import { CursorSystemNotification } from './component/decorator/CursorSystemNotification';import { DateMention } from './component/decorator/DateMention';import { DiffInsert } from './component/decorator/DiffInsert';import { DocumentCard } from './component/decorator/DocumentCard';@@ -86,5 +88,6 @@ export function initializeLexical() {setDecorator(WatermarkNode, Watermark);setDecorator(AwaitNode, Await);setDecorator(MagicChipNode, MagicChip);+ setDecorator(CursorSystemNotificationNode, CursorSystemNotification);registerDiffNodeFactory();}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.tsindex c56d9815a8..a5bfc8becb 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts@@ -24,5 +24,6 @@* 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.+ * Version 5.0 - Sep 2026. Added CursorSystemNotificationNode (Cursor `<system_notification>` event cards).*/-export const MARKDOWN_VERSION_COUNTER = 4.4;+export const MARKDOWN_VERSION_COUNTER = 5.0;diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex e627a34fc9..9ac289ec48 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -676,6 +676,20 @@ answer: screenshots as images, recordings as video players, and `.txt` / `.log`files as an inline `txt` code block (not a download link). Larger or non-UTF-8text stays a link.+When a Cursor run subscribes to something outside the conversation (a CI run,+a pull request, a Slack thread, a Linear issue, a timer), Cursor feeds the+event back as a prompt wrapped in `<system_notification …>`. The transcript+renders that as a full-width event card, not a prompt bubble: a source header+(e.g. **GitHub · CI checks**), a pass/fail pill when the event carries a+`conclusion`, the summary line, and chips for the repository, branch, short+commit and check count (repository and commit chips open GitHub). Attributes+the card has no face for appear as `name: value` chips; the subscription id+is hidden. The same tag renders as the same card anywhere internal markdown+is shown; a tag inside a code fence stays code. Text between notification+blocks keeps the message in its author's prompt bubble. Card links accept+only HTTP or HTTPS URLs; invalid repository links stay as plain chips and+invalid event links are omitted.+On mobile the composer (and any queued prompts above it) floats in the bottomaccessory region above the dock — same placement as channel and AI chat — so itstays tappable and clear of the home indicator. The box is full width; the textdiff --git a/packages/lexical-core/decoratorRegistry.ts b/packages/lexical-core/decoratorRegistry.tsindex b3cdb02ea6..ed10d16fb7 100644--- a/packages/lexical-core/decoratorRegistry.ts+++ b/packages/lexical-core/decoratorRegistry.ts@@ -16,6 +16,10 @@ import type {ContactMentionDecoratorProps,ContactMentionNode,} from './nodes/ContactMentionNode';+import type {+ CursorSystemNotificationDecoratorProps,+ CursorSystemNotificationNode,+} from './nodes/CursorSystemNotificationNode';import type {DateMentionDecoratorProps,DateMentionNode,@@ -195,6 +199,10 @@ export interface NodeDecoratorMap {klass: typeof MagicChipNode;props: MagicChipDecoratorProps;};+ CursorSystemNotificationNode: {+ klass: typeof CursorSystemNotificationNode;+ props: CursorSystemNotificationDecoratorProps;+ };}const decoratorRegistry = new Map<diff --git a/packages/lexical-core/index.ts b/packages/lexical-core/index.tsindex 1eb8bf283e..c578139e3a 100644--- a/packages/lexical-core/index.ts+++ b/packages/lexical-core/index.ts@@ -10,6 +10,7 @@ export * from './nodes/CommentNode';export * from './nodes/CompletionNode';export * from './nodes/ConnectAppNode';export * from './nodes/ContactMentionNode';+export * from './nodes/CursorSystemNotificationNode';export * from './nodes/CustomCodeNode';export * from './nodes/DateMentionNode';export * from './nodes/DecoratorBlockNode';diff --git a/packages/lexical-core/node-list.ts b/packages/lexical-core/node-list.tsindex 87bfa56b0e..2753dcea3d 100644--- a/packages/lexical-core/node-list.ts+++ b/packages/lexical-core/node-list.ts@@ -21,6 +21,7 @@ import { CommentNode } from './nodes/CommentNode';import { CompletionNode } from './nodes/CompletionNode';import { ConnectAppNode } from './nodes/ConnectAppNode';import { ContactMentionNode } from './nodes/ContactMentionNode';+import { CursorSystemNotificationNode } from './nodes/CursorSystemNotificationNode';import { CustomCodeNode } from './nodes/CustomCodeNode';import { DateMentionNode } from './nodes/DateMentionNode';import { DiffDeleteNode } from './nodes/DiffDeleteNode';@@ -118,6 +119,7 @@ export const SupportedNodeTypes = [AwaitNode,MagicChipNode,AgentContextNode,+ CursorSystemNotificationNode,] as const;export const NodeReplacements: LexicalNodeReplacement[] = [diff --git a/packages/lexical-core/nodes/CursorSystemNotificationNode.ts b/packages/lexical-core/nodes/CursorSystemNotificationNode.tsnew file mode 100644index 0000000000..eb5e8f3a29--- /dev/null+++ b/packages/lexical-core/nodes/CursorSystemNotificationNode.ts@@ -0,0 +1,225 @@+import {+ $applyNodeReplacement,+ DecoratorNode,+ type DOMConversionMap,+ type DOMExportOutput,+ type EditorConfig,+ type EditorThemeClasses,+ type LexicalEditor,+ type LexicalNode,+ type NodeKey,+ type SerializedLexicalNode,+ type Spread,+} from 'lexical';+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';++const VERSION = 1;++export const CURSOR_SYSTEM_NOTIFICATION_NODE_TYPE = 'system-notification';++/**+ * The tag Cursor's cloud agents wrap an event notification in. When a run+ * subscribes to something outside the conversation — a CI check, a pull+ * request, a Slack thread, a Linear issue, a timer — the event arrives as a+ * prompt Cursor writes itself, shaped like+ *+ * ```+ * <system_notification source="github" repo="github.com/org/repo" conclusion="success" checks="27" subscriptionType="github:ci:branch">+ * All 27 CI checks completed without failures.+ * </system_notification>+ * ```+ *+ * Unlike the `<m-*>` tags this package owns, the attributes ride on the+ * opening tag rather than as a JSON body, and the body is the human-readable+ * summary. Nothing in Macro writes one; they only arrive through the Cursor+ * transport, so the node exists to read them.+ */+export const CURSOR_SYSTEM_NOTIFICATION_TAG = 'system_notification';++/** What one notification carries. */+export type CursorSystemNotificationData = {+ /** Who raised the event: `github`, `slack`, `linear`, `timer`, … */+ source: string;+ /** Every attribute on the opening tag except `source`, in tag order. */+ attributes: Record<string, string>;+ /** The human-readable summary between the tags, trimmed. */+ text: string;+};++/** Return whether a value is a system-notification payload. */+export function isCursorSystemNotificationData(+ value: unknown+): value is CursorSystemNotificationData {+ if (!value || typeof value !== 'object') return false;+ const data = value as Record<string, unknown>;+ return (+ typeof data.source === 'string' &&+ typeof data.text === 'string' &&+ !!data.attributes &&+ typeof data.attributes === 'object' &&+ Object.values(data.attributes as Record<string, unknown>).every(+ (attribute) => typeof attribute === 'string'+ )+ );+}++export type SerializedCursorSystemNotificationNode = Spread<+ CursorSystemNotificationData & {+ type: typeof CURSOR_SYSTEM_NOTIFICATION_NODE_TYPE;+ },+ SerializedLexicalNode+>;++export type CursorSystemNotificationDecoratorProps =+ CursorSystemNotificationData & {+ key: NodeKey;+ theme: EditorThemeClasses;+ };++/**+ * A block-level card for one event notification a Cursor run received. Reads+ * as an event that happened to the session rather than as something a person+ * typed.+ */+export class CursorSystemNotificationNode extends DecoratorNode<+ DecoratorComponent<CursorSystemNotificationDecoratorProps> | undefined+> {+ __source: string;+ __attributes: Record<string, string>;+ __text: string;++ static getType(): typeof CURSOR_SYSTEM_NOTIFICATION_NODE_TYPE {+ return CURSOR_SYSTEM_NOTIFICATION_NODE_TYPE;+ }++ static clone(+ node: CursorSystemNotificationNode+ ): CursorSystemNotificationNode {+ return new CursorSystemNotificationNode(+ node.__source,+ node.__attributes,+ node.__text,+ node.__key+ );+ }++ constructor(+ source: string,+ attributes: Record<string, string>,+ text: string,+ key?: NodeKey+ ) {+ super(key);+ this.__source = source;+ this.__attributes = { ...attributes };+ this.__text = text;+ }++ static importJSON(+ serializedNode: SerializedCursorSystemNotificationNode+ ): CursorSystemNotificationNode {+ if (!isCursorSystemNotificationData(serializedNode)) {+ throw new Error('invalid system notification data');+ }+ const node = $createCursorSystemNotificationNode(serializedNode);+ $applyIdFromSerialized(node, serializedNode);+ return node;+ }++ exportJSON(): SerializedCursorSystemNotificationNode {+ return {+ ...super.exportJSON(),+ ...this.exportComponentProps(),+ type: CURSOR_SYSTEM_NOTIFICATION_NODE_TYPE,+ version: VERSION,+ };+ }++ exportComponentProps(): CursorSystemNotificationData {+ return {+ source: this.__source,+ attributes: { ...this.__attributes },+ text: this.__text,+ };+ }++ getSource(): string {+ return this.__source;+ }++ getAttributes(): Record<string, string> {+ return { ...this.__attributes };+ }++ getText(): string {+ return this.__text;+ }++ isInline(): false {+ return false;+ }++ isKeyboardSelectable(): true {+ return true;+ }++ createDOM(_config: EditorConfig): HTMLElement {+ const element = document.createElement('div');+ element.setAttribute('data-system-notification', this.__source);+ return element;+ }++ updateDOM(): false {+ return false;+ }++ exportDOM(): DOMExportOutput {+ const element = document.createElement('div');+ element.setAttribute('data-system-notification', this.__source);+ element.textContent = this.__text;+ return { element };+ }++ /** Nothing pastes one of these; they only arrive through the transformer. */+ static importDOM(): DOMConversionMap | null {+ return null;+ }++ getTextContent(): string {+ return this.__text;+ }++ getSearchText(): string {+ return this.__text;+ }++ decorate(_: LexicalEditor, config: EditorConfig) {+ const decorator = getDecorator<CursorSystemNotificationDecoratorProps>(+ CursorSystemNotificationNode+ );+ if (!decorator) return;+ return () =>+ decorator({+ ...this.exportComponentProps(),+ key: this.getKey(),+ theme: config.theme,+ });+ }+}++/** Create a system notification card. */+export function $createCursorSystemNotificationNode(+ data: CursorSystemNotificationData+): CursorSystemNotificationNode {+ return $applyNodeReplacement(+ new CursorSystemNotificationNode(data.source, data.attributes, data.text)+ );+}++/** Return whether a Lexical node is a system notification. */+export function $isCursorSystemNotificationNode(+ node: LexicalNode | null | undefined+): node is CursorSystemNotificationNode {+ return node instanceof CursorSystemNotificationNode;+}diff --git a/packages/lexical-core/tests/cursor-system-notification.test.ts b/packages/lexical-core/tests/cursor-system-notification.test.tsnew file mode 100644index 0000000000..85156c5d3b--- /dev/null+++ b/packages/lexical-core/tests/cursor-system-notification.test.ts@@ -0,0 +1,172 @@+import {+ $convertFromMarkdownString,+ $convertToMarkdownString,+} from '@lexical/markdown';+import { $getRoot, $isParagraphNode, createEditor } from 'lexical';+import { describe, expect, it } from 'vitest';+import { SupportedNodeTypes } from '../node-list';+import {+ $isCursorSystemNotificationNode,+ CursorSystemNotificationNode,+} from '../nodes/CursorSystemNotificationNode';+import { ALL_TRANSFORMERS, EXTERNAL_TRANSFORMERS } from '../transformers';+import { markdownToPlainText } from '../utils/parsers';++const CI_NOTIFICATION = [+ '<system_notification source="github" repo="github.com/macro-inc/macro" commit="ca515d369476de0a33eef36b21724175e2f6bed3" branch="cursor/settings-menu-search-1f17" conclusion="success" checks="27" subscriptionId="sub_7a13eaab-eee7-4339-a8d3-31c3182150b2" subscriptionType="github:ci:branch">',+ 'All 27 CI checks completed without failures.',+ '</system_notification>',+].join('\n');++function editorWith(markdown: string, transformers = ALL_TRANSFORMERS) {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError: (error) => {+ throw error;+ },+ });+ editor.update(+ () => {+ $convertFromMarkdownString(markdown, transformers);+ },+ { discrete: true }+ );+ return editor;+}++function topLevel(editor: ReturnType<typeof createEditor>) {+ return editor.getEditorState().read(() => $getRoot().getChildren());+}++function topLevelText(editor: ReturnType<typeof createEditor>) {+ return editor.getEditorState().read(() =>+ $getRoot()+ .getChildren()+ .map((node) => node.getTextContent())+ );+}++function exported(editor: ReturnType<typeof createEditor>) {+ return editor+ .getEditorState()+ .read(() => $convertToMarkdownString(ALL_TRANSFORMERS));+}++describe('system notification', () => {+ it('reads the CI notification Cursor writes into a prompt', () => {+ const editor = editorWith(CI_NOTIFICATION);+ const [node] = topLevel(editor);+ expect(node).toBeInstanceOf(CursorSystemNotificationNode);+ if (!$isCursorSystemNotificationNode(node)) throw new Error('unreachable');+ expect(node.getSource()).toBe('github');+ expect(node.getText()).toBe('All 27 CI checks completed without failures.');+ expect(node.getAttributes()).toEqual({+ repo: 'github.com/macro-inc/macro',+ commit: 'ca515d369476de0a33eef36b21724175e2f6bed3',+ branch: 'cursor/settings-menu-search-1f17',+ conclusion: 'success',+ checks: '27',+ subscriptionId: 'sub_7a13eaab-eee7-4339-a8d3-31c3182150b2',+ subscriptionType: 'github:ci:branch',+ });+ });++ it('round-trips through internal markdown unchanged', () => {+ const editor = editorWith(CI_NOTIFICATION);+ expect(exported(editor)).toBe(CI_NOTIFICATION);+ });++ it('keeps the prose around it', () => {+ const editor = editorWith(+ `Waiting on CI.\n\n${CI_NOTIFICATION}\n\nThat green result is for the merge commit.`+ );+ const nodes = topLevel(editor);+ expect(nodes.map((node) => node.getType())).toEqual([+ 'paragraph',+ 'system-notification',+ 'paragraph',+ ]);+ expect(topLevelText(editor)).toEqual([+ 'Waiting on CI.',+ 'All 27 CI checks completed without failures.',+ 'That green result is for the merge commit.',+ ]);+ });++ it('accepts a notification written on one line and a multi-line body', () => {+ const oneLine = editorWith(+ '<system_notification source="timer" subscriptionType="timer">Timer fired.</system_notification>'+ );+ const [single] = topLevel(oneLine);+ if (!$isCursorSystemNotificationNode(single))+ throw new Error('expected a card');+ expect(single.getSource()).toBe('timer');+ expect(single.getText()).toBe('Timer fired.');++ const multi = editorWith(+ '<system_notification source="slack" channel="#eng">\nFirst line.\n\nSecond paragraph.\n</system_notification>'+ );+ const [card] = topLevel(multi);+ if (!$isCursorSystemNotificationNode(card))+ throw new Error('expected a card');+ expect(card.getText()).toBe('First line.\n\nSecond paragraph.');+ });++ it('reads a tag that went through a markdown export as plain text', () => {+ // Underscores escaped and the bare repository host autolinked, the way+ // an editor exports a notification someone pasted in as text.+ const escaped = [+ '<system\\_notification source="github" repo="<m-link>{"url":"https://github.com/macro-inc/macro","text":"github.com/macro-inc/macro","title":""}</m-link>" subscriptionId="sub\\_7a13" subscriptionType="github:ci:branch">',+ 'All 27 CI checks completed without failures.',+ '</system\\_notification>',+ ].join('\n');+ const [node] = topLevel(editorWith(escaped));+ if (!$isCursorSystemNotificationNode(node))+ throw new Error('expected a card');+ expect(node.getAttributes()).toMatchObject({+ repo: 'github.com/macro-inc/macro',+ subscriptionId: 'sub_7a13',+ });+ });++ it('leaves a tag without a source, or without a close, as text', () => {+ const noSource = editorWith(+ '<system_notification kind="x">\nBody.\n</system_notification>'+ );+ expect(topLevel(noSource).every($isParagraphNode)).toBe(true);+ expect(topLevel(noSource).some($isCursorSystemNotificationNode)).toBe(+ false+ );++ const unclosed = editorWith(+ '<system_notification source="github">\nStill streaming'+ );+ expect(topLevel(unclosed).some($isCursorSystemNotificationNode)).toBe(+ false+ );+ expect(topLevelText(unclosed).join('\n')).toContain(+ '<system_notification source="github">'+ );+ });++ it('leaves a tag quoted inside a code fence as code', () => {+ const editor = editorWith(+ ['```', ...CI_NOTIFICATION.split('\n'), '```'].join('\n')+ );+ const nodes = topLevel(editor);+ expect(nodes).toHaveLength(1);+ expect(nodes[0]!.getType()).toBe('code');+ expect(nodes.some($isCursorSystemNotificationNode)).toBe(false);+ });++ it('is an internal-format node; external markdown leaves it as text', () => {+ const editor = editorWith(CI_NOTIFICATION, EXTERNAL_TRANSFORMERS);+ expect(topLevel(editor).some($isCursorSystemNotificationNode)).toBe(false);+ });++ it('reads as its summary in plain text', () => {+ expect(markdownToPlainText(`Heads up:\n${CI_NOTIFICATION}`)).toBe(+ 'Heads up:\nAll 27 CI checks completed without failures.'+ );+ });+});diff --git a/packages/lexical-core/transformers/cursorSystemNotification.ts b/packages/lexical-core/transformers/cursorSystemNotification.tsnew file mode 100644index 0000000000..c57f711419--- /dev/null+++ b/packages/lexical-core/transformers/cursorSystemNotification.ts@@ -0,0 +1,111 @@+import type { MultilineElementTransformer } from '@lexical/markdown';+import type { LexicalNode } from 'lexical';+import {+ $createCursorSystemNotificationNode,+ $isCursorSystemNotificationNode,+ CURSOR_SYSTEM_NOTIFICATION_TAG,+ type CursorSystemNotificationData,+ CursorSystemNotificationNode,+} from '../nodes/CursorSystemNotificationNode';++// Attributes are quoted `name="value"` pairs; the quotes are what let a value+// carry `>` without ending the tag. An autolinked `<m-link>` payload inside a+// value carries quotes of its own, so it is consumed whole.+const ATTRIBUTE_SOURCE = String.raw`([A-Za-z_\\][\w.:\\-]*)\s*=\s*"((?:<m-link>.*?</m-link>|[^"])*)"`;+// The opening tag, and nothing past it: what follows on the same line is+// body, so a one-line notification still finds its closing tag. The `\\?_`+// tolerates the `\_` a markdown exporter leaves behind when the tag has been+// through an editor as plain text.+const OPEN_TAG = new RegExp(+ String.raw`^<system\\?_notification((?:\s+${ATTRIBUTE_SOURCE})*)\s*>`+);+const CLOSE_TAG = /<\/system\\?_notification>\s*$/;+const ATTRIBUTE = new RegExp(ATTRIBUTE_SOURCE, 'g');+const INTERNAL_LINK = /<m-link>(.*?)<\/m-link>/gs;++/** Undo what a markdown pass may have done to a name or value. */+function unescapeAttribute(value: string): string {+ return value+ .replaceAll('\\_', '_')+ .replaceAll('"', '"')+ .replaceAll('&', '&')+ .replace(INTERNAL_LINK, (whole, json: string) => {+ // A bare `github.com/org/repo` autolinks in an editor and exports as an+ // internal link tag; the value the notification carried is its text.+ try {+ const link: unknown = JSON.parse(json);+ if (link && typeof link === 'object') {+ const { text, url } = link as Record<string, unknown>;+ if (typeof text === 'string' && text) return text;+ if (typeof url === 'string') return url;+ }+ } catch {+ // Not a link payload after all: leave it as it was written.+ }+ return whole;+ });+}++function escapeAttribute(value: string): string {+ return value.replaceAll('&', '&').replaceAll('"', '"');+}++/** The attributes on an opening tag, in the order written. */+export function parseCursorSystemNotificationAttributes(+ tag: string+): Record<string, string> {+ const attributes: Record<string, string> = {};+ for (const [, name, value] of tag.matchAll(ATTRIBUTE)) {+ attributes[unescapeAttribute(name!)] = unescapeAttribute(value!);+ }+ return attributes;+}++/** The notification a tag and its body describe, or `undefined` when the tag names no source. */+export function readCursorSystemNotification(+ openingTag: string,+ body: string+): CursorSystemNotificationData | undefined {+ const { source, ...attributes } =+ parseCursorSystemNotificationAttributes(openingTag);+ if (!source) return undefined;+ return { source, attributes, text: body.trim() };+}++/** The tag as Cursor writes it, so a notification survives a save unchanged. */+export function buildCursorSystemNotificationMarkdown(+ data: CursorSystemNotificationData+): string {+ const attributes = Object.entries({ source: data.source, ...data.attributes })+ .map(([name, value]) => `${name}="${escapeAttribute(value)}"`)+ .join(' ');+ return `<${CURSOR_SYSTEM_NOTIFICATION_TAG} ${attributes}>\n${data.text}\n</${CURSOR_SYSTEM_NOTIFICATION_TAG}>`;+}++/**+ * Internal markdown transformer for the event notifications Cursor's cloud+ * agents receive (see {@link CursorSystemNotificationNode}).+ *+ * A tag with no `source`, or with no closing tag, is left as the text it was:+ * the format is Cursor's, and anything else spelled like it is more likely+ * someone writing about the format than an event.+ */+export const I_CURSOR_SYSTEM_NOTIFICATION: MultilineElementTransformer = {+ dependencies: [CursorSystemNotificationNode],+ type: 'multiline-element',+ regExpStart: OPEN_TAG,+ regExpEnd: CLOSE_TAG,+ export: (node: LexicalNode) => {+ if (!$isCursorSystemNotificationNode(node)) return null;+ return buildCursorSystemNotificationMarkdown(node.exportComponentProps());+ },+ replace: (rootNode, children, startMatch, _endMatch, linesInBetween) => {+ if ((children?.length ?? 0) > 0) return false;+ const data = readCursorSystemNotification(+ startMatch[1] ?? '',+ linesInBetween?.join('\n') ?? ''+ );+ if (!data) return false;+ rootNode.append($createCursorSystemNotificationNode(data));+ },+};diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.tsindex 9b578e1ccc..605e6af290 100644--- a/packages/lexical-core/transformers/index.ts+++ b/packages/lexical-core/transformers/index.ts@@ -2,6 +2,7 @@ import type { Transformer } from '@lexical/markdown';import { I_AGENT_CONTEXT } from './agentContext';import { I_AWAIT_NODE } from './await';import { HTML_BLOCKQUOTE, I_MACRO_QUOTE } from './classedBlock';+import { I_CURSOR_SYSTEM_NOTIFICATION } from './cursorSystemNotification';import { CUSTOM_TRANSFORMERS } from './customTransformers';import { I_HTML_RENDER } from './htmlRender';import { I_IMAGE_CONSTRAINED, IMAGE } from './image';@@ -94,6 +95,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [I_CONNECT_APP,I_WATERMARK,...CUSTOM_TRANSFORMERS,+ I_CURSOR_SYSTEM_NOTIFICATION, // After the code fence so a tag quoted in one stays textUNKNOWN_MENTION, // Must be last to act as fallback for unrecognized XML tags];@@ -191,5 +193,6 @@ export const ALL_TRANSFORMERS: Transformer[] = [E_INLINE_EQUATION_NODE,...HTML_ENTITY_TRANSFORMERS,...CUSTOM_TRANSFORMERS,+ I_CURSOR_SYSTEM_NOTIFICATION, // After the code fence so a tag quoted in one stays textUNKNOWN_MENTION, // Must be last to act as fallback for unrecognized XML tags];diff --git a/packages/lexical-core/utils/parsers.ts b/packages/lexical-core/utils/parsers.tsindex dcb6ac7cb8..57c46ec446 100644--- a/packages/lexical-core/utils/parsers.ts+++ b/packages/lexical-core/utils/parsers.ts@@ -102,6 +102,14 @@ export function parseConnectApps(text: string): string {});}+/** A Cursor `<system_notification …>` block reads as its summary line. */+export function parseCursorSystemNotifications(text: string): string {+ return text.replace(+ /<system_notification\b[^>]*>(.*?)<\/system_notification>/gs,+ (_, body: string) => body.trim()+ );+}+export function parseTagMentions(text: string): string {return text.replace(/<m-tag>(.*?)<\/m-tag>/g, (_, json) => {try {@@ -216,6 +224,7 @@ export function stripAgentContext(text: string): string {* - Group mentions: @groupAlias (e.g., @here)* - Links: text (fallback to url)* - Reply targets: displayText+ * - Cursor system notifications: the summary between the tags*/export function markdownToPlainText(markdown: string): string {const transforms: Array<(text: string) => string> = [@@ -228,6 +237,7 @@ export function markdownToPlainText(markdown: string): string {parseAgentSessionMentions,parseTagMentions,parseConnectApps,+ parseCursorSystemNotifications,parseSnapshots,parseDocumentCards,parseLinks,