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
feat(text-paste): smart paste for GitHub pull request URLs (#7956)
Jacob Beckerman89ddf2bda091
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsxindex 60aae002ec..5b924c0071 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx@@ -17,6 +17,12 @@ vi.mock('../decorator/AgentSessionMention', () => ({},}));+vi.mock('../decorator/PullRequestMention', () => ({+ PullRequestMention: (props: { id: string; url?: string; label?: string }) => (+ <span data-pr-chip={props.id || props.url}>{props.label}</span>+ ),+}));+vi.mock('@service-connection/websocket', () => ({ws: { send() {}, addEventListener() {}, removeEventListener() {} },state: () => 'closed',@@ -163,3 +169,30 @@ describe('static agent session previews', () => {rendered.unmount();});});++describe('static pull request mentions', () => {+ it.each([+ [+ 'a Macro id',+ '<m-pr-mention>{"id":"foreign-1","label":"macro-inc/macro#7956"}</m-pr-mention>',+ 'foreign-1',+ ],+ [+ 'a GitHub URL',+ '<m-pr-mention>{"url":"https://github.com/macro-inc/macro/pull/7956","label":""}</m-pr-mention>',+ 'https://github.com/macro-inc/macro/pull/7956',+ ],+ ])('renders a PR chip from %s', (_, markdown, target) => {+ const rendered = render(() => (+ <StaticMarkdownContext>+ <StaticMarkdown markdown={markdown} target="internal" lazy={false} />+ </StaticMarkdownContext>+ ));+ expect(+ rendered.container+ .querySelector('[data-pr-chip]')+ ?.getAttribute('data-pr-chip')+ ).toBe(target);+ rendered.unmount();+ });+});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 952442e0d6..bde32609e4 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@@ -31,6 +31,7 @@ import {type MagicChipNode,normalizedLanguage,type PasteNode,+ type PullRequestMentionNode,type ReplyTargetNode,type SnapshotNode,SupportedNodeTypes,@@ -101,6 +102,7 @@ import { MagicChip as MagicChipDecorator } from '../decorator/MagicChip';import { MarkdownImage as ImageDecorator } from '../decorator/MarkdownImage';import { MarkdownVideo as VideoDecorator } from '../decorator/MarkdownVideo';import { PasteNode as PasteNodeDecorator } from '../decorator/PasteNode';+import { PullRequestMention as PullRequestMentionDecorator } from '../decorator/PullRequestMention';import { ReplyTarget as ReplyTargetDecorator } from '../decorator/ReplyTarget';import { Snapshot as SnapshotDecorator } from '../decorator/Snapshot';import { TagMention as TagMentionDecorator } from '../decorator/TagMention';@@ -246,6 +248,7 @@ function getTextClassName(| UserMentionNode| DocumentMentionNode| AgentSessionMentionNode+ | PullRequestMentionNode| ContactMentionNode| DateMentionNode| WatermarkNode,@@ -420,6 +423,20 @@ const AgentSessionMention: TypedRenderableEntity<AgentSessionMentionNode> = {),};+const PullRequestMention: TypedRenderableEntity<PullRequestMentionNode> = {+ guard: (node: LexicalNode): node is PullRequestMentionNode =>+ node.__type === 'pr-mention',+ render: (props) => (+ <span class={getTextClassName(props.node, props.theme)}>+ <PullRequestMentionDecorator+ {...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',@@ -974,6 +991,7 @@ const InlineEntities: RenderableEntity[] = [eraseRenderableEntity(UserMention),eraseRenderableEntity(DocumentMention),eraseRenderableEntity(AgentSessionMention),+ eraseRenderableEntity(PullRequestMention),eraseRenderableEntity(DocumentCard),eraseRenderableEntity(ContactMention),eraseRenderableEntity(DateMention),diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsxindex d48d0d731a..3983f2b06a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx@@ -1,6 +1,12 @@+import {+ parseGithubPrUrl,+ prDisplayName,+ toGithubKey,+} from '@app/features/block-pr/util/prKey';import { useSplitLayout } from '@components/app/split-layout/layout';import { HoverCard } from '@core/component/HoverCard';import { openInNewSplitForMention } from '@core/util/openInNewSplit';+import { openExternalUrl } from '@core/util/url';import {useNativeSplitNavigationHandler,useSplitNavigationHandler,@@ -8,6 +14,7 @@ import {import {$isPullRequestMentionNode,HISTORIC_TAG,+ isGithubPullRequestUrl,type PullRequestMentionDecoratorProps,SKIP_DOM_SELECTION_TAG,SKIP_SCROLL_INTO_VIEW_TAG,@@ -16,7 +23,10 @@ import OpenIcon from '@phosphor/arrows-out.svg';import ChatCircle from '@phosphor/chat-circle.svg';import GitMerge from '@phosphor/git-merge.svg';import GitPullRequest from '@phosphor/git-pull-request.svg';-import { usePrMentionQuery } from '@queries/storage/pr-mention';+import {+ usePrMentionQuery,+ usePullRequestByGithubKeyQuery,+} from '@queries/storage/pr-mention';import type {ForeignEntity,GithubPullRequestCheckRun,@@ -29,6 +39,7 @@ import {KEY_ENTER_COMMAND,} from 'lexical';import {+ type Accessor,createEffect,createMemo,type JSX,@@ -92,6 +103,14 @@ function pullRequestLabel(return title ?? displayName ?? refLabel;}+function pullRequestUrl(entity: ForeignEntity | undefined): string | undefined {+ if (!entity || entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {+ return undefined;+ }+ const url = optionalString(metadataRecord(entity.metadata).url);+ return url && isGithubPullRequestUrl(url) ? url : undefined;+}+function pullRequestStatus(entity: ForeignEntity | undefined): string {if (!entity || entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {return 'open';@@ -366,30 +385,108 @@ export function PullRequestPreviewCard(props: {);}+function githubKeyFromUrl(url: string | undefined): string | undefined {+ const ref = url ? parseGithubPrUrl(url) : null;+ return ref ? toGithubKey(ref) : undefined;+}++/** The label to show before a mention's entity resolves. */+function mentionFallbackLabel(+ props: Pick<PullRequestMentionDecoratorProps, 'label' | 'url'>+): string | undefined {+ if (props.label) return props.label;+ const ref = props.url ? parseGithubPrUrl(props.url) : null;+ return ref ? prDisplayName(ref) : undefined;+}++/**+ * Resolve a GitHub-URL-only mention (one an agent wrote without the Macro id)+ * to its synced pull request. Settles to `undefined` while loading and when+ * Macro has not synced the PR, without suspending.+ */+function useGithubUrlMentionEntity(+ props: Pick<PullRequestMentionDecoratorProps, 'id' | 'url'>,+ enabled: Accessor<boolean>+): Accessor<ForeignEntity | undefined> {+ const query = usePullRequestByGithubKeyQuery(+ () => (props.id ? undefined : githubKeyFromUrl(props.url)),+ enabled+ );+ return () => (query.isSuccess ? (query.data ?? undefined) : undefined);+}++/** Hover preview for a GitHub URL mention Macro has not synced. */+function UnsyncedPullRequestPreviewCard(props: {+ label: string;+ url?: string;+}) {+ return (+ <div class="select-none w-80 text-ink">+ <Surface depth={3} class="glass bg-menu-glass rounded-xl">+ <div class="flex items-center justify-between gap-2 p-2">+ <div class="flex items-center gap-2 min-w-0">+ <span class="relative size-4 shrink-0 inline-flex">+ <PullRequestStatusIcon status="unknown" />+ </span>+ <span class="text-sm font-semibold truncate">{props.label}</span>+ </div>+ <Show when={props.url}>+ {(url) => (+ <a+ href={url()}+ target="_blank"+ rel="noreferrer"+ class="shrink-0 text-link hover:text-link-hover visited:text-link-visited"+ onClick={(e) => e.stopPropagation()}+ >+ <OpenIcon class="size-4" />+ </a>+ )}+ </Show>+ </div>+ </Surface>+ </div>+ );+}+function PullRequestMentionContent(props: PullRequestMentionDecoratorProps) {const lexicalWrapper = useContext(LexicalWrapperContext);const editor = lexicalWrapper?.editor;+ const fetchEnabled = () => !lexicalWrapper?.skipPreviewFetch;- const query = usePrMentionQuery(- () => props.id,- () => !lexicalWrapper?.skipPreviewFetch- );+ const query = usePrMentionQuery(() => props.id, fetchEnabled);+ const urlEntity = useGithubUrlMentionEntity(props, fetchEnabled);+ // Only an id mention reads `query.data`, which suspends until it loads.+ const entity = () => (props.id ? query.data : urlEntity());const label = createMemo(- () => pullRequestLabel(query.data) ?? fallbackLabel(props.label)+ () =>+ pullRequestLabel(entity()) ?? fallbackLabel(mentionFallbackLabel(props)));- const parts = createMemo(() => pullRequestParts(query.data, props.label));- const status = createMemo(() => pullRequestStatus(query.data));+ const parts = createMemo(() =>+ pullRequestParts(entity(), mentionFallbackLabel(props))+ );+ // An unresolved GitHub URL mention has no known state yet.+ const status = createMemo(() => {+ const resolved = entity();+ return resolved || props.id ? pullRequestStatus(resolved) : 'unknown';+ });+ // Keep the node's label and GitHub URL current, so the Markdown this editor+ // sends (an agent prompt, a message) names the PR and links it.createEffect(() => {- const nextLabel = pullRequestLabel(query.data);- if (!editor || !nextLabel || nextLabel === props.label) return;+ const resolved = entity();+ const nextLabel = pullRequestLabel(resolved);+ const nextUrl = props.url ? undefined : pullRequestUrl(resolved);+ const labelChanged = !!nextLabel && nextLabel !== props.label;+ if (!editor || (!labelChanged && !nextUrl)) return;editor.update(() => {const node = $getNodeByKey(props.key);if ($isPullRequestMentionNode(node)) {- node.setLabel(nextLabel);+ if (labelChanged) node.setLabel(nextLabel);+ if (nextUrl) node.setUrl(nextUrl);}},{@@ -433,9 +530,21 @@ export function PullRequestMention(props: PullRequestMentionDecoratorProps) {return sel.type === 'node' && sel.nodeKeys.has(props.key);};+ const urlEntity = useGithubUrlMentionEntity(+ props,+ () => !lexicalWrapper?.skipPreviewFetch+ );+ const entityId = () => props.id || urlEntity()?.id;+const open = (e: MouseEvent | KeyboardEvent | null) => {+ const id = entityId();+ if (!id) {+ // A PR Macro has not synced has no split to open; fall back to GitHub.+ if (props.url) openExternalUrl(props.url);+ return;+ }openWithSplit(- { type: 'pr', id: props.id },+ { type: 'pr', id },{ preferNewSplit: openInNewSplitForMention(e?.shiftKey, e != null) });};@@ -484,7 +593,22 @@ export function PullRequestMention(props: PullRequestMentionDecoratorProps) {</span>}content={- <PullRequestPreviewCard id={props.id} fallbackLabel={props.label} />+ <Show+ when={entityId()}+ fallback={+ <UnsyncedPullRequestPreviewCard+ label={fallbackLabel(mentionFallbackLabel(props))}+ url={props.url}+ />+ }+ >+ {(id) => (+ <PullRequestPreviewCard+ id={id()}+ fallbackLabel={mentionFallbackLabel(props)}+ />+ )}+ </Show>}/>);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SkillsMenu/SkillsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SkillsMenu/SkillsMenu.tsxindex bee34f0da7..c606fbd99c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SkillsMenu/SkillsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SkillsMenu/SkillsMenu.tsx@@ -225,6 +225,7 @@ function SkillsMenuInner(props: SkillsMenuProps) {props.editor.dispatchCommand(INSERT_PR_MENTION_COMMAND, {id: item.id,label: `${item.metadata.owner}/${item.metadata.repo}#${item.metadata.number}`,+ url: item.metadata.url || undefined,});};diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex e617b2377d..18f69cdace 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -184,6 +184,11 @@ function $isMentionNode();}+/** A PR mention authored from a GitHub URL alone has no entity to track. */+function $isUntrackedPullRequestMention(node: LexicalNode): boolean {+ return $isPullRequestMentionNode(node) && !node.getId();+}+function $mentionItemFromNode(node: MentionNode): ItemMention {if ($isDocumentMentionNode(node)) {let fileType = '';@@ -398,7 +403,7 @@ function registerMentionsPlugin(const mentions: ItemMention[] = [];editor.read(() => {$traverseNodes($getRoot(), (node) => {- if ($isMentionNode(node)) {+ if ($isMentionNode(node) && !$isUntrackedPullRequestMention(node)) {mentions.push($mentionItemFromNode(node));}});@@ -1034,7 +1039,7 @@ function registerMentionsPlugin(nodeKey) as PullRequestMentionNode | null;- if (!node) continue;+ if (!node || $isUntrackedPullRequestMention(node)) continue;if (mutation === 'destroyed') {const mentionUuid = node.getMentionUuid();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/githubPullRequestPaste.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/githubPullRequestPaste.test.tsnew file mode 100644index 0000000000..7339a678c8--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/githubPullRequestPaste.test.ts@@ -0,0 +1,198 @@+import { $isLinkNode, LinkNode } from '@lexical/link';+import {+ $isPullRequestMentionNode,+ PullRequestMentionNode,+} from '@macro-inc/lexical-core';+import {+ fetchPullRequestByGithubKey,+ getCachedPullRequestByGithubKey,+} from '@queries/storage/pr-mention';+import type { ForeignEntity } from '@service-storage/generated/schemas';+import {+ $createParagraphNode,+ $getRoot,+ $isElementNode,+ COMMAND_PRIORITY_EDITOR,+ createEditor,+ type LexicalEditor,+ type LexicalNode,+ PASTE_COMMAND,+} from 'lexical';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { INSERT_PR_MENTION_COMMAND } from '../mentions';+import { textPastePlugin } from './textPastePlugin';++// Keep the paste tests independent of application boot and editor UI wiring.+vi.mock('@core/internal/BlockLoader', () => ({}));+vi.mock('../../utils', () => ({}));+vi.mock('../mentions', async () => {+ const { createCommand } = await import('lexical');+ return {+ INSERT_DOCUMENT_MENTION_COMMAND: createCommand('INSERT_DOCUMENT_MENTION'),+ INSERT_PR_MENTION_COMMAND: createCommand('INSERT_PR_MENTION'),+ INSERT_THEME_MENTION_COMMAND: createCommand('INSERT_THEME_MENTION'),+ };+});+vi.mock('@queries/storage/pr-mention', () => ({+ fetchPullRequestByGithubKey: vi.fn(),+ getCachedPullRequestByGithubKey: vi.fn(),+}));++const PR_URL = 'https://github.com/macro-inc/macro/pull/7870';+const ENTITY = {+ id: '019507e8-14a3-7bc1-8610-419f16bd03a8',+ foreignEntitySource: 'github_pull_request',+ foreignEntityId: 'macro-inc/macro/pull/7870',+} as ForeignEntity;++class TestClipboardEvent extends Event {+ clipboardData: DataTransfer;+ constructor(text: string) {+ super('paste');+ this.clipboardData = {+ getData: (type: string) => (type === 'text/plain' ? text : ''),+ } as DataTransfer;+ }+}++let editor: LexicalEditor;+let unregister: () => void;++function paste(text: string): boolean {+ let handled = false;+ editor.update(+ () => {+ handled = editor.dispatchCommand(+ PASTE_COMMAND,+ new TestClipboardEvent(text) as ClipboardEvent+ );+ },+ { discrete: true }+ );+ return handled;+}++function $paragraphChildren(): LexicalNode[] {+ const paragraph = $getRoot().getFirstChild();+ return $isElementNode(paragraph) ? paragraph.getChildren() : [];+}++function readParagraph(fn: (children: LexicalNode[]) => void) {+ editor.getEditorState().read(() => fn($paragraphChildren()));+}++async function flushLookup() {+ await new Promise((resolve) => setTimeout(resolve, 0));+}++beforeEach(() => {+ vi.stubGlobal('ClipboardEvent', TestClipboardEvent);+ editor = createEditor({+ nodes: [LinkNode, PullRequestMentionNode],+ onError: (error) => {+ throw error;+ },+ });+ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ $getRoot().append(paragraph);+ paragraph.select();+ },+ { discrete: true }+ );+ unregister = textPastePlugin()(editor);+});++afterEach(() => {+ unregister();+ vi.unstubAllGlobals();+ vi.mocked(fetchPullRequestByGithubKey).mockReset();+ vi.mocked(getCachedPullRequestByGithubKey).mockReset();+});++describe('GitHub pull request smart paste', () => {+ it('inserts a link and upgrades it to a PR mention once the PR resolves', async () => {+ vi.mocked(fetchPullRequestByGithubKey).mockResolvedValue(ENTITY);++ expect(paste(PR_URL)).toBe(true);+ expect(fetchPullRequestByGithubKey).toHaveBeenCalledWith(+ 'macro-inc/macro/pull/7870'+ );+ await flushLookup();++ readParagraph((children) => {+ expect(children).toHaveLength(1);+ const [mention] = children;+ expect($isPullRequestMentionNode(mention)).toBe(true);+ if (!$isPullRequestMentionNode(mention)) return;+ expect(mention.getId()).toBe(ENTITY.id);+ expect(mention.getLabel()).toBe('macro-inc/macro#7870');+ expect(mention.getUrl()).toBe(PR_URL);+ });+ });++ it('inserts the mention directly when the PR is already cached', () => {+ vi.mocked(getCachedPullRequestByGithubKey).mockReturnValue(ENTITY);+ const insertMention = vi.fn(() => true);+ const unregisterInsert = editor.registerCommand(+ INSERT_PR_MENTION_COMMAND,+ insertMention,+ COMMAND_PRIORITY_EDITOR+ );++ expect(paste(`${PR_URL}/files`)).toBe(true);+ unregisterInsert();++ expect(insertMention).toHaveBeenCalledWith(+ { id: ENTITY.id, label: 'macro-inc/macro#7870', url: PR_URL },+ editor+ );+ expect(fetchPullRequestByGithubKey).not.toHaveBeenCalled();+ });++ it('keeps the link when Macro has not synced the PR', async () => {+ vi.mocked(fetchPullRequestByGithubKey).mockResolvedValue(null);++ paste(PR_URL);+ await flushLookup();++ readParagraph((children) => {+ expect(children).toHaveLength(1);+ const [link] = children;+ expect($isLinkNode(link)).toBe(true);+ if (!$isLinkNode(link)) return;+ expect(link.getURL()).toBe(PR_URL);+ expect(link.getTextContent()).toBe(PR_URL);+ });+ });++ it('leaves the link alone if it was edited before the PR resolved', async () => {+ let resolveLookup!: (entity: ForeignEntity) => void;+ vi.mocked(fetchPullRequestByGithubKey).mockReturnValue(+ new Promise((resolve) => {+ resolveLookup = resolve;+ })+ );++ paste(PR_URL);+ editor.update(+ () => {+ const [link] = $paragraphChildren();+ if ($isLinkNode(link)) link.setURL('https://example.com');+ },+ { discrete: true }+ );+ resolveLookup(ENTITY);+ await flushLookup();++ readParagraph((children) => {+ expect(children.some($isPullRequestMentionNode)).toBe(false);+ });+ });++ it('does not handle non-PR GitHub links', () => {+ expect(paste('https://github.com/macro-inc/macro/issues/1')).toBe(false);+ expect(fetchPullRequestByGithubKey).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.test.tsindex 4a12a8791c..1a3ec653e4 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.test.ts@@ -1,10 +1,15 @@import { describe, expect, it, vi } from 'vitest';-import { parseMacroAppUrl, resolvePastedMacroAppUrl } from './textPastePlugin';+import {+ parseMacroAppUrl,+ parsePastedGithubPrUrl,+ resolvePastedMacroAppUrl,+} from './textPastePlugin';// Keep the parser tests independent of application boot and editor UI wiring.vi.mock('@core/internal/BlockLoader', () => ({}));vi.mock('../../utils', () => ({}));vi.mock('../mentions', () => ({}));+vi.mock('@queries/storage/pr-mention', () => ({}));const sessionId = '019507e8-14a3-7bc1-8610-419f16bd03a8';@@ -126,3 +131,34 @@ describe('route-aware paste resolver', () => {).toBeUndefined();});});++describe('parsePastedGithubPrUrl', () => {+ it.each([+ 'https://github.com/macro-inc/macro/pull/7870',+ 'https://www.github.com/macro-inc/macro/pull/7870',+ ' https://github.com/macro-inc/macro/pull/7870\n',+ 'https://github.com/macro-inc/macro/pull/7870/files',+ 'https://github.com/macro-inc/macro/pull/7870/files?w=1#diff-abc',+ 'http://github.com/macro-inc/macro/pull/7870',+ ])('recognizes %s', (url) => {+ expect(parsePastedGithubPrUrl(url)).toEqual({+ owner: 'macro-inc',+ repo: 'macro',+ number: 7870,+ });+ });++ it.each([+ 'https://github.com/macro-inc/macro/issues/7870',+ 'https://github.com/macro-inc/macro/pull/',+ 'https://github.com/macro-inc/macro/pull/0',+ 'https://github.com/macro-inc/macro/pull/7870abc',+ 'https://github.example.com/macro-inc/macro/pull/7870',+ 'https://gist.github.com/macro-inc/macro/pull/7870',+ 'see https://github.com/macro-inc/macro/pull/7870',+ 'https://github.com/macro-inc/macro/pull/7870 and more',+ 'github.com/macro-inc/macro/pull/7870',+ ])('ignores %s', (text) => {+ expect(parsePastedGithubPrUrl(text)).toBeNull();+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.tsindex 6db7505e6b..c635a57cf9 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts@@ -1,3 +1,9 @@+import {+ type PrRef,+ prDisplayName,+ prHtmlUrl,+ toGithubKey,+} from '@app/features/block-pr/util/prKey';import {type BlockAlias,BlockAliasRegistry,@@ -5,15 +11,31 @@ import {BlockRegistry,} from '@core/block';import { isValidMacroAppHostname } from '@core/util/macroAppUrl';-import { mergeRegister } from '@lexical/utils';-import { $createPasteNode, PasteNode } from '@macro-inc/lexical-core';+import { $isCodeNode } from '@lexical/code';+import { $createLinkNode, $isLinkNode, LinkNode } from '@lexical/link';+import { $findMatchingParent, mergeRegister } from '@lexical/utils';+import {+ $createPasteNode,+ $createPullRequestMentionNode,+ $isCustomCodeNode,+ HISTORY_MERGE_TAG,+ PasteNode,+ PullRequestMentionNode,+} from '@macro-inc/lexical-core';+import {+ fetchPullRequestByGithubKey,+ getCachedPullRequestByGithubKey,+} from '@queries/storage/pr-mention';import { convertThemev2v3 } from '@theme/utils/themeMigrations';import {parseThemeV2Json,parseThemeV3Json,} from '@theme/utils/themeValidation';import {+ $createTextNode,+ $getNodeByKey,$getSelection,+ $insertNodes,$isRangeSelection,COMMAND_PRIORITY_HIGH,type LexicalEditor,@@ -129,6 +151,106 @@ export function resolvePastedMacroAppUrl(return legacy.isValid ? legacy : resolveAppLink?.(text);}+const GITHUB_HOSTNAMES = new Set(['github.com', 'www.github.com']);+const GITHUB_PR_PATH_PATTERN =+ /^\/([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)\/pull\/([1-9][0-9]*)(?:\/.*)?$/;++/**+ * Parse a pasted github.com pull request URL, including its subpages such as+ * `/files`. Text with anything besides the URL is not a PR link paste.+ */+export function parsePastedGithubPrUrl(text: string): PrRef | null {+ const trimmed = text.trim();+ if (!trimmed || /\s/.test(trimmed)) return null;++ let url: URL;+ try {+ url = new URL(trimmed);+ } catch {+ return null;+ }+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;+ if (!GITHUB_HOSTNAMES.has(url.hostname)) return null;++ const match = url.pathname.match(GITHUB_PR_PATH_PATTERN);+ if (!match) return null;+ return { owner: match[1], repo: match[2], number: Number(match[3]) };+}++function $isSelectionInCode(): boolean {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return false;+ return (+ $findMatchingParent(+ selection.anchor.getNode(),+ (node) => $isCodeNode(node) || $isCustomCodeNode(node)+ ) !== null+ );+}++/**+ * Insert a pasted GitHub pull request URL as a PR mention. A PR already in the+ * cache becomes a mention immediately; otherwise the URL is inserted as a link+ * and upgraded once the lookup finds a synced PR. PRs Macro has not synced+ * stay links.+ */+function $insertPastedGithubPullRequest(+ editor: LexicalEditor,+ url: string,+ ref: PrRef+) {+ const githubKey = toGithubKey(ref);+ const label = prDisplayName(ref);+ // The canonical URL, not a pasted subpage, so agents reading the mention+ // get the pull request itself.+ const prUrl = prHtmlUrl(ref);++ const cached = getCachedPullRequestByGithubKey(githubKey);+ if (cached) {+ editor.dispatchCommand(INSERT_PR_MENTION_COMMAND, {+ id: cached.id,+ label,+ url: prUrl,+ });+ return;+ }++ const placeholder = editor.hasNode(LinkNode)+ ? $createLinkNode(url).append($createTextNode(url))+ : $createTextNode(url);+ $insertNodes([placeholder]);+ const placeholderKey = placeholder.getKey();++ void fetchPullRequestByGithubKey(githubKey).then((entity) => {+ if (!entity) return;+ editor.update(+ () => {+ const node = $getNodeByKey(placeholderKey);+ if (!node || !node.isAttached() || node.getTextContent() !== url) {+ return;+ }+ if ($isLinkNode(node) && node.getURL() !== url) return;++ const selection = $getSelection();+ const caretInPlaceholder =+ $isRangeSelection(selection) &&+ selection.isCollapsed() &&+ (selection.anchor.key === placeholderKey ||+ node.isParentOf(selection.anchor.getNode()));++ const mention = $createPullRequestMentionNode({+ id: entity.id,+ label,+ url: prUrl,+ });+ node.replace(mention);+ if (caretInPlaceholder) mention.selectEnd();+ },+ { tag: HISTORY_MERGE_TAG }+ );+ });+}+function registerTextPastePlugin(editor: LexicalEditor,resolveAppLink?: MentionLinkResolver@@ -161,6 +283,22 @@ function registerTextPastePlugin(return true;}+ const githubPr = parsePastedGithubPrUrl(pastedText);+ if (githubPr && editor.hasNode(PullRequestMentionNode)) {+ const selection = $getSelection();+ if (+ !$isRangeSelection(selection) ||+ !selection.isCollapsed() ||+ $isSelectionInCode()+ ) {+ return false;+ }++ event.preventDefault();+ $insertPastedGithubPullRequest(editor, pastedText.trim(), githubPr);+ return true;+ }+const parsedMacroAppUrl = resolvePastedMacroAppUrl(pastedText,resolveAppLinkdiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.tsindex 2e9abe5316..e81bcc1411 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts@@ -31,5 +31,7 @@* Version 7.0 - Oct 2026. Added TaskListNode: replaces ListNode at runtime, serializes as* `task-list` with the `list` wire shape plus optional `$.taskListView` node state* (persisted check-list task filters).+ * Version 7.1 - Oct 2026. PullRequestMentionNode: optional GitHub `url`; `id` may be empty+ * when an agent mentions a PR by URL, and the decorator resolves the synced PR.*/-export const MARKDOWN_VERSION_COUNTER = 7.0;+export const MARKDOWN_VERSION_COUNTER = 7.1;diff --git a/apps/web/src/lib/queries/storage/pr-mention.ts b/apps/web/src/lib/queries/storage/pr-mention.tsindex 3d4c7f979d..8ffe98b17e 100644--- a/apps/web/src/lib/queries/storage/pr-mention.ts+++ b/apps/web/src/lib/queries/storage/pr-mention.ts@@ -1,4 +1,5 @@import { ThrownResultError, throwOnErr } from '@core/util/result';+import { queryClient } from '@queries/client';import { storageServiceClient } from '@service-storage/client';import type { ForeignEntity } from '@service-storage/generated/schemas';import { useQuery } from '@tanstack/solid-query';@@ -60,6 +61,42 @@ function pullRequestByGithubKeyQueryOptions(githubKey: string) {};}+/** The cached pull request for a GitHub key, if a lookup already resolved it. */+export function getCachedPullRequestByGithubKey(+ githubKey: string+): ForeignEntity | undefined {+ return (+ queryClient.getQueryData<ForeignEntity | null>(+ pullRequestMentionKeys.byGithubKey(githubKey).queryKey+ ) ?? undefined+ );+}++/**+ * Resolve a pull request by GitHub key outside a component. The result shares+ * the `byGithubKey` cache and seeds the mention query, so a chip created from+ * it renders without a second request. Resolves `null` when the pull request+ * has not been synced or the lookup fails.+ */+export async function fetchPullRequestByGithubKey(+ githubKey: string+): Promise<ForeignEntity | null> {+ try {+ const entity = await queryClient.fetchQuery(+ pullRequestByGithubKeyQueryOptions(githubKey)+ );+ if (entity) {+ queryClient.setQueryData(+ pullRequestMentionKeys.foreignEntity(entity.id).queryKey,+ entity+ );+ }+ return entity;+ } catch {+ return null;+ }+}+export function usePullRequestByGithubKeyQuery(githubKey: Accessor<string | undefined>,enabled?: EnabledInputdiff --git a/crates/mention_utils/src/parse.rs b/crates/mention_utils/src/parse.rsindex 68ad3ab247..a87d5a0fc4 100644--- a/crates/mention_utils/src/parse.rs+++ b/crates/mention_utils/src/parse.rs@@ -166,10 +166,35 @@ impl<'de> XmlTaggedParsed<'de> for ParsedAgentSessionMention<'de> {#[serde(rename_all = "camelCase")]#[non_exhaustive]pub struct ParsedPullRequestMention<'a> {- #[serde(borrow)]+ /// The Macro foreign entity id. Empty when an agent mentioned the PR by+ /// its GitHub `url` alone.+ #[serde(borrow, default)]pub id: Cow<'a, str>,#[serde(borrow, default)]pub label: Option<Cow<'a, str>>,+ /// The pull request's github.com URL.+ #[serde(borrow, default)]+ pub url: Option<Cow<'a, str>>,+}++impl ParsedPullRequestMention<'_> {+ /// `owner/repo#123` from the mention's GitHub URL, if it has one.+ pub fn github_ref(&self) -> Option<String> {+ let url = self.url.as_deref()?;+ let path = url+ .strip_prefix("https://")+ .or_else(|| url.strip_prefix("http://"))?;+ let path = path.strip_prefix("www.").unwrap_or(path);+ let mut parts = path.strip_prefix("github.com/")?.split('/');+ let (owner, repo, pull, number) =+ (parts.next()?, parts.next()?, parts.next()?, parts.next()?);+ let number = number+ .split(['?', '#'])+ .next()+ .filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))?;+ (pull == "pull" && !owner.is_empty() && !repo.is_empty())+ .then(|| format!("{owner}/{repo}#{number}"))+ }}impl<'de> XmlTaggedParsed<'de> for ParsedPullRequestMention<'de> {@@ -436,14 +461,14 @@ impl XmlFormatter for PlainTextFormatter {pr: &ParsedPullRequestMention<'_>,f: &mut Formatter<'_>,) -> std::fmt::Result {- write!(- f,- "{}",- pr.label- .as_deref()- .filter(|label| !label.is_empty())- .unwrap_or("Pull request")- )+ match pr.label.as_deref().filter(|label| !label.is_empty()) {+ Some(label) => write!(f, "{label}"),+ None => write!(+ f,+ "{}",+ pr.github_ref().as_deref().unwrap_or("Pull request")+ ),+ }}}diff --git a/crates/mention_utils/src/tests.rs b/crates/mention_utils/src/tests.rsindex 3fbb13c6fd..cea9db2730 100644--- a/crates/mention_utils/src/tests.rs+++ b/crates/mention_utils/src/tests.rs@@ -791,7 +791,7 @@ fn parse_pull_request_mention() {assert_eq!(rendered, "macro/macro#123");let out = ParsedXmlText::parse(input).unwrap();assert_matches!(out.0, [- TextSegment::Xml(XmlTag::PullRequest(ParsedPullRequestMention { id, label })),+ TextSegment::Xml(XmlTag::PullRequest(ParsedPullRequestMention { id, label, .. })),] => {assert_eq!(id.as_ref(), "foreign-1");assert_eq!(label.as_deref(), Some("macro/macro#123"));@@ -806,6 +806,39 @@ fn parse_pull_request_mention_without_label() {assert_eq!(rendered, "Pull request");}+#[test]+fn parse_pull_request_mention_by_github_url() {+ let input = r#"See <m-pr-mention>{"url":"https://github.com/macro-inc/macro/pull/7945","label":""}</m-pr-mention>."#;+ let rendered = PlainTextFormatter::format_xml_text(ParsedXmlText::parse(input).unwrap()).0;+ assert_eq!(rendered, "See macro-inc/macro#7945.");+ let out = ParsedXmlText::parse(input).unwrap();+ assert_matches!(&out.0[..], [+ TextSegment::Plain("See "),+ TextSegment::Xml(XmlTag::PullRequest(ParsedPullRequestMention { id, url, .. })),+ TextSegment::Plain("."),+ ] => {+ assert!(id.is_empty());+ assert_eq!(url.as_deref(), Some("https://github.com/macro-inc/macro/pull/7945"));+ });+}++#[test]+fn pull_request_github_ref_ignores_non_pull_urls() {+ for url in [+ "https://github.com/macro-inc/macro/issues/7945",+ "https://example.com/macro-inc/macro/pull/7945",+ "https://github.com/macro-inc/macro/pull/79x",+ ] {+ let input = format!(r#"<m-pr-mention>{{"url":"{url}"}}</m-pr-mention>"#);+ let rendered = PlainTextFormatter::format_xml_text(ParsedXmlText::parse(&input).unwrap()).0;+ assert_eq!(rendered, "Pull request", "{url}");+ }+ let input =+ r#"<m-pr-mention>{"url":"https://www.github.com/a/b/pull/12/files#x"}</m-pr-mention>"#;+ let rendered = PlainTextFormatter::format_xml_text(ParsedXmlText::parse(input).unwrap()).0;+ assert_eq!(rendered, "a/b#12");+}+// =============================================================================// Unknown / unrecognized tag tests// =============================================================================diff --git a/crates/prompt/src/document_content_links.rs b/crates/prompt/src/document_content_links.rsindex 765c5b1ee7..2186d74390 100644--- a/crates/prompt/src/document_content_links.rs+++ b/crates/prompt/src/document_content_links.rs@@ -29,6 +29,8 @@ For Markdown document content, link to other Macro documents, channels, chats, pThe same Markdown parser also renders the other in-app chip tags: `<m-date-mention>` for a day or time, `<m-agent-session-mention>` for an agent session (add `"expanded":true` for the card that follows the latest turn), `<m-user-mention>` / `<m-contact-mention>` / `<m-group-mention>` for people and groups, and `<m-pr-mention>` for a pull request. Use those tags in document content the same way you would in a chat reply.+Reference a GitHub pull request with a PR chip rather than a Markdown link or bare URL: `<m-pr-mention>{"url":"https://github.com/{owner}/{repo}/pull/{number}","label":""}</m-pr-mention>`. Put the PR's github.com URL in `url`; no Macro id is needed. This applies to Markdown document content and to `SendChannelMessage` content, which uses the same Markdown syntax. The chip shows the PR's number, title, and live status and opens it in Macro, so leave `label` empty and do not repeat the number or title beside it. Issues, commits, and other GitHub pages stay Markdown links. Your own chat replies to the MCP client still link pull requests as plain Markdown URLs.+This holds true even when `CreateDocument` is called through the MCP server, where you are otherwise told to link items in your own chat replies as plain Markdown URLs — that rule is about your conversational responses to the MCP client, not about content you write into a Macro document. Do NOT use plain Markdown links or bare URLs to reference other Macro items inside document content; only `<m-document-mention>` tags (and the other chip tags above) render as working links there.The same applies to `EditDocument`: when its `instructions` ask for a mention chip (person, date/time, document, agent session, and so on) or a document-card, include the referenced item's ids and details so the editing worker can construct the correct in-app markup itself. Date chips need an ISO datetime and displayFormat; they do not need a looked-up id.@@ -36,7 +38,8 @@ The same applies to `EditDocument`: when its `instructions` ask for a mention chstatic INTENT: &str = "Content written into Markdown documents via CreateDocument or EditDocument \links other Macro items with `<m-document-mention>` XML tags and the other in-app chip tags \-(dates, agent sessions, people) — never plain Markdown URLs — \+(dates, agent sessions, people, and `<m-pr-mention>` by URL for GitHub pull requests, also in \+SendChannelMessage content) — never plain Markdown URLs — \regardless of whether the tool call arrived in-app or over MCP, while non-Markdown documents carry \no Markdown syntax or mention tags at all.";diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rsindex d185eca8a6..34ff2490ae 100644--- a/crates/prompt/src/lib.rs+++ b/crates/prompt/src/lib.rs@@ -290,6 +290,16 @@ mod tests {assert!(document_content_links::PROMPT.instructions.contains(TAG));}+ #[test]+ fn mentions_and_document_content_links_share_the_github_pr_mention_tag() {+ // GitHub PRs are mentioned by URL in-app and over MCP alike; the two+ // sections must hand the model the same tag shape.+ const TAG: &str = r#"<m-pr-mention>{"url":"https://github.com/{owner}/{repo}/pull/{number}","label":""}</m-pr-mention>"#;+ assert!(mentions::PROMPT.instructions.contains(TAG));+ assert!(document_content_links::PROMPT.instructions.contains(TAG));+ assert!(mcp_instructions("https://macro.com").contains(TAG));+ }+#[test]fn agent_session_preamble_tells_the_model_to_emit_mention_tags() {let preamble = agent_session::PROMPT.to_string();diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rsindex 1127935727..9db6cf51d1 100644--- a/crates/prompt/src/mentions.rs+++ b/crates/prompt/src/mentions.rs@@ -61,10 +61,12 @@ These use their own tags — never wrap them in `<m-document-mention>`:- Group: `<m-group-mention>{"groupAlias":"{alias}"}</m-group-mention>`- Date/time: `<m-date-mention>{"date":"{iso_datetime}","displayFormat":"{label}"}</m-date-mention>`- Agent session: `<m-agent-session-mention>{"id":"{session_id}","label":""}</m-agent-session-mention>`-- Pull request: `<m-pr-mention>{"id":"{id}","label":""}</m-pr-mention>`+- GitHub pull request: `<m-pr-mention>{"url":"https://github.com/{owner}/{repo}/pull/{number}","label":""}</m-pr-mention>`, or `<m-pr-mention>{"id":"{id}","label":""}</m-pr-mention>` when a tool returned the PR's Macro idDate/time chips do not need a looked-up id. `date` is an ISO 8601 datetime; `displayFormat` is the chip label the user sees (e.g. "Mon, Dec 1, 2025", "Today", "Tomorrow", "3:00 PM"). Prefer a date chip over typing a date as plain text when you are naming a specific day or time.+Reference a GitHub pull request with a PR chip, never a Markdown link or bare URL, whenever you name one: a PR a tool returned, one you opened, or one in a list. Put its github.com pull request URL in `url` (a `/files` or other subpage URL works too); you do not need to look up a Macro id. The chip shows the PR's number, title, and live status, opens it in Macro, and falls back to GitHub when Macro has not synced the PR, so leave `label` empty and do not repeat the number or title beside it. Issues, commits, repositories, and other GitHub pages stay Markdown links. A PR chip in a message you receive carries the pull request's GitHub URL in `url` (and its `owner/repo#number` in `label`); use them to read or work on that PR.+Agent session chips reference an existing session by id from a tool result. An empty `label` is fine. Set `"expanded":true` to insert the card (Magic Chip) that follows the session's latest turn instead of the compact underlined title. Do not invent session ids.If a tool result tells you an app is not connected for the person you are working for and hands you a `<m-connect-app>{"appSlug":"...","name":"..."}</m-connect-app>` tag, include that tag verbatim in your reply: it renders as a button that connects the app. Never invent one; only repeat the tag a tool result gave you. In agent sessions, where `DiscoverConnectors` is available, the button resumes the conversation after a successful connection; tell the user to connect to continue, without asking for a separate confirmation message. In other hosts, ask them to let you know once they have connected the app so you can try again.@@ -81,8 +83,8 @@ If no inline or node ids are present:static INTENT: &str = "Entities, people, dates, agent sessions, and other chips are referenced \with the matching XML mention tag (m-document-mention with the right blockName/blockParams, \-m-user-mention, m-date-mention, m-agent-session-mention, and the other listed chip tags) \-across every Markdown surface (AI chat replies, agent session replies, channel messages, \+m-user-mention, m-date-mention, m-agent-session-mention, m-pr-mention for GitHub pull \+requests by URL, and the other listed chip tags) across every Markdown surface (AI chat replies, agent session replies, channel messages, \email bodies, and Markdown documents) — never inside non-Markdown documents, and never for \ids outside the listed types (a calendar id from ListCalendars is not mentionable; \only individual events are).";diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 9127858017..3e053c24e2 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -1960,6 +1960,13 @@ not the workspace path or pane-local search state. A copied multi-pane URLentity, the URL remains an ordinary link. Project task comment targets, Home PRs,and agent chat links also convert to their respective entity mentions.+Pasting a bare GitHub pull request URL (`github.com/<owner>/<repo>/pull/<n>`,+including subpages such as `/files`) inserts a link that becomes a PR mention+once Macro finds the synced PR, usually within a moment. Hovering the mention+shows its status, diff size, comments, and checks; clicking opens the PR in a+split. A PR Macro has not synced stays an ordinary link, and pasting inside a+code block or over a selection keeps the default behavior.+1. `Create` → `Document D`. The app navigates to `/app/md/<uuid>` with the **title fieldfocused**.2. `type_text` the title, then `submitKey: "Enter"` to drop into the body.diff --git a/packages/lexical-core/nodes/PullRequestMentionNode.ts b/packages/lexical-core/nodes/PullRequestMentionNode.tsindex 9584586063..c7043615d7 100644--- a/packages/lexical-core/nodes/PullRequestMentionNode.ts+++ b/packages/lexical-core/nodes/PullRequestMentionNode.ts@@ -17,11 +17,25 @@ import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';const VERSION = 1;export type PullRequestMentionInfo = {+ /**+ * The Macro foreign entity id. Empty when the mention was authored from a+ * GitHub URL alone; the decorator then resolves the PR from `url`.+ */id: string;label?: string;mentionUuid?: string;+ /** The pull request's github.com URL. */+ url?: string;};+const GITHUB_PR_URL_PATTERN =+ /^https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9._-]+\/pull\/[1-9][0-9]*(?:[/?#]\S*)?$/;++/** Whether `url` is a github.com pull request URL a PR mention can carry. */+export function isGithubPullRequestUrl(url: string): boolean {+ return GITHUB_PR_URL_PATTERN.test(url);+}+export type SerializedPullRequestMentionNode = Spread<PullRequestMentionInfo,SerializedLexicalNode@@ -38,6 +52,7 @@ export class PullRequestMentionNode extends DecoratorNode<__id: string;__label: string | undefined;__mentionUuid: string | undefined;+ __url: string | undefined;static getType() {return 'pr-mention';@@ -56,15 +71,23 @@ export class PullRequestMentionNode extends DecoratorNode<node.__id,node.__label,node.__mentionUuid,+ node.__url,node.__key);}- constructor(id: string, label?: string, mentionUuid?: string, key?: NodeKey) {+ constructor(+ id: string,+ label?: string,+ mentionUuid?: string,+ url?: string,+ key?: NodeKey+ ) {super(key);this.__id = id;this.__label = label;this.__mentionUuid = mentionUuid;+ this.__url = url;}static importJSON(serializedNode: SerializedPullRequestMentionNode) {@@ -72,6 +95,7 @@ export class PullRequestMentionNode extends DecoratorNode<id: serializedNode.id,label: serializedNode.label,mentionUuid: serializedNode.mentionUuid,+ url: serializedNode.url,});$applyIdFromSerialized(node, serializedNode);return node;@@ -83,6 +107,7 @@ export class PullRequestMentionNode extends DecoratorNode<id: this.__id,label: this.__label,mentionUuid: this.__mentionUuid,+ url: this.__url,type: PullRequestMentionNode.getType(),version: VERSION,};@@ -93,6 +118,7 @@ export class PullRequestMentionNode extends DecoratorNode<id: this.__id,label: this.__label,mentionUuid: this.__mentionUuid,+ url: this.__url,};}@@ -112,10 +138,16 @@ export class PullRequestMentionNode extends DecoratorNode<const label = domNode.getAttribute('data-pr-label') || undefined;const mentionUuid =domNode.getAttribute('data-mention-uuid') || undefined;+ const url = domNode.getAttribute('data-pr-url') || undefined;- if (id) {+ if (id || (url && isGithubPullRequestUrl(url))) {return {- node: $createPullRequestMentionNode({ id, label, mentionUuid }),+ node: $createPullRequestMentionNode({+ id: id ?? '',+ label,+ mentionUuid,+ url,+ }),};}@@ -139,6 +171,7 @@ export class PullRequestMentionNode extends DecoratorNode<'data-pr-id': this.__id,'data-pr-label': this.__label || '','data-mention-uuid': this.__mentionUuid || '',+ 'data-pr-url': this.__url || '',};}@@ -170,6 +203,15 @@ export class PullRequestMentionNode extends DecoratorNode<return this.__label;}+ getUrl(): string | undefined {+ return this.__url;+ }++ setUrl(url: string | undefined) {+ const self = this.getWritable();+ self.__url = url;+ }+setLabel(label: string | undefined) {const self = this.getWritable();self.__label = label;@@ -204,7 +246,8 @@ export function $createPullRequestMentionNode(params: PullRequestMentionInfo) {const node = new PullRequestMentionNode(params.id,params.label,- params.mentionUuid+ params.mentionUuid,+ params.url);return $applyNodeReplacement(node);}diff --git a/packages/lexical-core/tests/mentions.test.ts b/packages/lexical-core/tests/mentions.test.tsindex 834310b07e..491e0487a9 100644--- a/packages/lexical-core/tests/mentions.test.ts+++ b/packages/lexical-core/tests/mentions.test.ts@@ -119,6 +119,12 @@ describe('parsePullRequestMentions', () => {expect(parsePullRequestMentions(input)).toBe('foreign-1');});+ it('falls back to the GitHub reference for a URL-only mention', () => {+ const input =+ '<m-pr-mention>{"url":"https://github.com/macro-inc/macro/pull/7945","label":""}</m-pr-mention>';+ expect(parsePullRequestMentions(input)).toBe('macro-inc/macro#7945');+ });+it('returns empty string for invalid JSON', () => {const input = '<m-pr-mention>???</m-pr-mention>';expect(parsePullRequestMentions(input)).toBe('');diff --git a/packages/lexical-core/tests/pr-mention.test.ts b/packages/lexical-core/tests/pr-mention.test.tsnew file mode 100644index 0000000000..4ad3a7f6a1--- /dev/null+++ b/packages/lexical-core/tests/pr-mention.test.ts@@ -0,0 +1,68 @@+// @vitest-environment jsdom+import { describe, expect, it } from 'vitest';+import { isGithubPullRequestUrl } from '../nodes/PullRequestMentionNode';+import {+ markdownToSerializedEditorStateWithIds,+ serializedEditorStateToMarkdown,+} from '../utils/markdown-state';+import { markdownToEmbeddingText, markdownToPlainText } from '../utils/parsers';++const PR_URL = 'https://github.com/macro-inc/macro/pull/7945';++describe('PullRequestMentionNode', () => {+ it('round-trips a Macro id mention', () => {+ const markdown =+ '<m-pr-mention>{"id":"foreign-1","label":"macro-inc/macro#7945"}</m-pr-mention>';+ const state = markdownToSerializedEditorStateWithIds(markdown);+ expect(state.root.children[0]).toMatchObject({+ children: [{ type: 'pr-mention', id: 'foreign-1' }],+ });+ expect(serializedEditorStateToMarkdown(state)).toBe(markdown);+ });++ it('accepts a GitHub URL in place of the Macro id', () => {+ const markdown = `<m-pr-mention>{"url":"${PR_URL}","label":""}</m-pr-mention>`;+ const state = markdownToSerializedEditorStateWithIds(markdown);+ expect(state.root.children[0]).toMatchObject({+ children: [{ type: 'pr-mention', id: '', url: PR_URL }],+ });++ const exported = serializedEditorStateToMarkdown(state);+ expect(markdownToSerializedEditorStateWithIds(exported).root).toMatchObject(+ {+ children: [{ children: [{ type: 'pr-mention', id: '', url: PR_URL }] }],+ }+ );+ expect(markdownToPlainText(markdown)).toBe('macro-inc/macro#7945');+ expect(markdownToEmbeddingText(markdown)).toBe(+ `[macro-inc/macro#7945](${PR_URL})`+ );+ });++ it('rejects a mention with neither an id nor a GitHub PR URL', () => {+ const markdown =+ '<m-pr-mention>{"url":"https://example.com/pull/1","label":""}</m-pr-mention>';+ const state = markdownToSerializedEditorStateWithIds(markdown);+ expect(JSON.stringify(state)).not.toContain('"type":"pr-mention"');+ });+});++describe('isGithubPullRequestUrl', () => {+ it.each([+ PR_URL,+ `${PR_URL}/files`,+ `${PR_URL}#issuecomment-1`,+ 'https://www.github.com/macro-inc/macro/pull/7945',+ ])('accepts %s', (url) => {+ expect(isGithubPullRequestUrl(url)).toBe(true);+ });++ it.each([+ 'https://github.com/macro-inc/macro/issues/7945',+ 'https://github.com/macro-inc/macro/pull/7945abc',+ 'https://evil.example/github.com/macro-inc/macro/pull/7945',+ 'javascript:alert(1)//github.com/a/b/pull/1',+ ])('rejects %s', (url) => {+ expect(isGithubPullRequestUrl(url)).toBe(false);+ });+});diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.tsindex 82f7074326..846aca02cb 100644--- a/packages/lexical-core/transformers/mentions.ts+++ b/packages/lexical-core/transformers/mentions.ts@@ -20,7 +20,10 @@ import { DateMentionNode } from '../nodes/DateMentionNode';import { DocumentCardNode } from '../nodes/DocumentCardNode';import { DocumentMentionNode } from '../nodes/DocumentMentionNode';import { GroupMentionNode } from '../nodes/GroupMentionNode';-import { PullRequestMentionNode } from '../nodes/PullRequestMentionNode';+import {+ isGithubPullRequestUrl,+ PullRequestMentionNode,+} from '../nodes/PullRequestMentionNode';import { TagMentionNode } from '../nodes/TagMentionNode';import { ThemeMentionNode } from '../nodes/ThemeMentionNode';import { UserMentionNode } from '../nodes/UserMentionNode';@@ -318,19 +321,28 @@ export const I_PR_MENTION: TextMatchTransformer = {id: node.getId(),label: node.getLabel(),mentionUuid: node.getMentionUuid(),+ url: node.getUrl(),});return `<m-pr-mention>${data}</m-pr-mention>`;},replace: (node: TextNode, match: RegExpMatchArray) => {try {const data = JSON.parse(match[1]);- if (!('id' in data) || typeof data.id !== 'string') {- throw new Error('Missing field id');+ // Agents often know only a PR's GitHub URL; the decorator resolves the+ // Macro entity from it, so either field identifies the PR.+ const id = typeof data.id === 'string' ? data.id : '';+ const url =+ typeof data.url === 'string' && isGithubPullRequestUrl(data.url)+ ? data.url+ : undefined;+ if (!id && !url) {+ throw new Error('Missing field id or url');}const prMentionNode = new PullRequestMentionNode(- data.id,+ id,typeof data.label === 'string' ? data.label : undefined,- typeof data.mentionUuid === 'string' ? data.mentionUuid : undefined+ typeof data.mentionUuid === 'string' ? data.mentionUuid : undefined,+ url);node.replace(prMentionNode);} catch (e) {@@ -350,9 +362,12 @@ export const E_PR_MENTION: ElementTransformer = {if (!(node instanceof PullRequestMentionNode)) return null;const id = node.getId();- if (!id) return null;-const label = node.getLabel() || 'Pull request';+ if (!id) {+ const url = node.getUrl();+ return url ? `[${label}](${url})` : null;+ }+const hostname = currentBrowserHostname();if (!hostname) return label;diff --git a/packages/lexical-core/transformers/xml/codecs.ts b/packages/lexical-core/transformers/xml/codecs.tsindex e1fb098ef3..cdb68f45f1 100644--- a/packages/lexical-core/transformers/xml/codecs.ts+++ b/packages/lexical-core/transformers/xml/codecs.ts@@ -376,6 +376,7 @@ export function serializeNode(node: SerNode): FxpNode {nodeAttrs(n, {...(n.id && { prId: n.id }),...(n.label && { label: n.label }),+ ...(n.url && { url: n.url }),})))diff --git a/packages/lexical-core/transformers/xml/nodes.ts b/packages/lexical-core/transformers/xml/nodes.tsindex d20d83b89a..00ef8ab404 100644--- a/packages/lexical-core/transformers/xml/nodes.ts+++ b/packages/lexical-core/transformers/xml/nodes.ts@@ -206,6 +206,7 @@ export type PullRequestMentionNode = Id & {version: number;id: string;label: string;+ url?: string;};export type ThemeMentionNode = Id & {diff --git a/packages/lexical-core/utils/parsers.ts b/packages/lexical-core/utils/parsers.tsindex dfae18e9c6..0d7cec0dfc 100644--- a/packages/lexical-core/utils/parsers.ts+++ b/packages/lexical-core/utils/parsers.ts@@ -82,13 +82,26 @@ export function parsePullRequestMentions(text: string): string {return text.replace(/<m-pr-mention>(.*?)<\/m-pr-mention>/g, (_, json) => {try {const data = JSON.parse(json);- return data.label || data.id || '';+ return (+ data.label ||+ data.id ||+ (typeof data.url === 'string' ? githubPullRequestRef(data.url) : '') ||+ ''+ );} catch {return '';}});}+/** `owner/repo#123` for a github.com pull request URL. */+function githubPullRequestRef(url: string): string | undefined {+ const match = url.match(+ /github\.com\/([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)\/pull\/([1-9][0-9]*)/+ );+ return match ? `${match[1]}/${match[2]}#${match[3]}` : undefined;+}+/** `<m-connect-app>` chips read as their call to action. */export function parseConnectApps(text: string): string {return text.replace(/<m-connect-app>(.*?)<\/m-connect-app>/g, (_, json) => {@@ -400,11 +413,13 @@ export function markdownToEmbeddingText(markdown: string): string {);text = replaceJsonTag(text, 'm-document-mention', documentRefToEmbeddingText);text = replaceJsonTag(text, 'm-document-card', documentRefToEmbeddingText);- text = replaceJsonTag(text, 'm-pr-mention', (data) =>- data.id- ? `[${data.label || 'Pull request'}](pr:${data.id})`- : data.label || ''- );+ text = replaceJsonTag(text, 'm-pr-mention', (data) => {+ if (data.id) return `[${data.label || 'Pull request'}](pr:${data.id})`;+ if (data.url) {+ return `[${data.label || githubPullRequestRef(data.url) || 'Pull request'}](${data.url})`;+ }+ return data.label || '';+ });text = replaceJsonTag(text, 'm-link', (data) =>data.url ? `[${data.text || data.url}](${data.url})` : data.text || '');