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
fix(markdown): recognize bare URLs across message imports (#8601)
gbirman14c6cfbe548d
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex e36fc0bfd1..b8e2801213 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -132,6 +132,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.### General+- Share URL recognition with `packages/lexical-core/utils/auto-link.ts`; preserve explicit unlink markers when saving and rendering messages. See `packages/lexical-core/README.md` at the repository root.- Empty human DMs use the shared centered conversations graphic and explain email delivery to nonusers; keep this state out of agent DMs, loading/error states, and populated timelines.- Enable persisted email/calendar review controls only for the review’s saved acting account; historical reviews fall back to the session owner. Require session edit access on desktop and mobile.- Email draft reads compare server generations before choosing cached delivery state over a restored working copy; only a definitive first-submission rejection permits local send recovery without server cancellation.diff --git a/apps/web/package.json b/apps/web/package.jsonindex 951114b0e9..9255001adf 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -151,7 +151,6 @@"katex": "^0.16.22","lexical": "0.45.0","libheif-js": "^1.19.8",- "linkify-it": "^5.0.0","livekit-client": "^2.18.0","loro-crdt": "catalog:","nanoid": "^3.3.7",@@ -197,7 +196,6 @@"@types/d3-shape": "^3.1.8","@types/facebook-pixel": "^0.0.31","@types/gtag.js": "^0.0.20",- "@types/linkify-it": "^5.0.0","@types/lodash": "^4.17.20","@types/node": "^24.8.0","@types/papaparse": "^5.5.2",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 15c8282e93..fafc727441 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@@ -5,7 +5,7 @@import type { CodeNode } from '@lexical/code';import { PrismTokenizer } from '@lexical/code';-import type { LinkNode } from '@lexical/link';+import { $isAutoLinkNode, type LinkNode } from '@lexical/link';import { $getListDepth, type ListItemNode, type ListNode } from '@lexical/list';import type { HeadingNode, QuoteNode } from '@lexical/rich-text';import type { TableCellNode, TableNode, TableRowNode } from '@lexical/table';@@ -350,7 +350,8 @@ function eraseRenderableElement<T extends ElementNode>(}const Text: TypedRenderableEntity<TextNode> = {- guard: (node: LexicalNode): node is TextNode => node.__type === 'text',+ guard: (node: LexicalNode): node is TextNode =>+ node.__type === 'text' || node.__type === 'unlinked-text',render: (props) => {return (<span class={getTextClassName(props.node, props.theme)}>@@ -875,16 +876,21 @@ const HorizontalRule: TypedRenderableEntity<HorizontalRuleNode> = {};const Link: TypedRenderableElement<LinkNode> = {- guard: (node: LexicalNode): node is LinkNode => node.__type === 'link',- render: (props) => (- <LinkWithPreview- url={props.node.__url}- class={props.theme.link}- title={props.node.__title ?? props.node.__url}- >- {props.children}- </LinkWithPreview>- ),+ guard: (node: LexicalNode): node is LinkNode =>+ node.__type === 'link' || node.__type === 'autolink',+ render: (props) => {+ if ($isAutoLinkNode(props.node) && props.node.getIsUnlinked())+ return props.children;+ return (+ <LinkWithPreview+ url={props.node.__url}+ class={props.theme.link}+ title={props.node.__title ?? props.node.__url}+ >+ {props.children}+ </LinkWithPreview>+ );+ },};const Mark: TypedRenderableElement<MarkNode> = {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.mdindex f8f740407d..48e131f4f2 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md@@ -20,3 +20,15 @@ not authenticated app navigation or a VoiceOver session.Screenshots from the verified fixture: [desktop](proof/desktop.png) and[phone](proof/mobile.png).++## Message links++`links.browser.e2e.ts` mounts the production Markdown parser, renderer, composer,+and link menu over the original App Store message. It checks pointer/keyboard+navigation, encoded URLs, Markdown punctuation, literal code, and Remove link →+save → reopen on desktop, tablet touch, and phone touch. Network requests outside+the local fixture are intercepted. Run just this case by adding+`links.browser.e2e.ts` to the command above.++Screenshots: [desktop](proof/autolinks-desktop.png) and+[phone](proof/autolinks-mobile.png).diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.browser.e2e.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.browser.e2e.tsnew file mode 100644index 0000000000..9fb00554e9--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.browser.e2e.ts@@ -0,0 +1,79 @@+import { expect, test } from '@playwright/test';++test('agent URLs navigate and removed links survive save and reopen', async ({+ page,+ context,+}, testInfo) => {+ await context.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (+ url.hostname === 'localhost' &&+ !url.pathname.includes('/__macro_dev/')+ ) {+ await route.continue();+ } else {+ await route.fulfill({+ status:+ url.pathname.includes('unfurl') || url.hostname === 'apps.apple.com'+ ? 200+ : 401,+ contentType: 'application/json',+ body: JSON.stringify({ responses: [] }),+ });+ }+ });+ await page.routeWebSocket('**/*', (socket) => socket.close());+ const errors: string[] = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.goto(+ '/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.html'+ );+ const url = 'https://apps.apple.com/us/app/macro-app/id6743133649';+ const link = page+ .getByTestId('original')+ .getByRole('link', { name: url, exact: true });+ await expect(link).toHaveAttribute('href', url, { timeout: 30_000 });+ await expect(page.getByTestId('explicit').getByRole('link')).toHaveAttribute(+ 'href',+ url+ );+ const cases = page.getByTestId('cases');+ await expect(cases.getByRole('link')).toHaveCount(2);+ await expect(cases.getByRole('link').first()).toHaveAttribute(+ 'href',+ 'https://example.com/a%20b?q=x%2Fy#part'+ );+ await expect(cases.getByRole('link').last()).toHaveAttribute(+ 'href',+ 'https://example.com/a~~b~~c'+ );+ await expect(cases).toContainText('https://example.com/removed');+ const popupPromise = page.waitForEvent('popup');+ if (testInfo.project.use.hasTouch) await link.tap();+ else {+ await link.focus();+ await page.keyboard.press('Enter');+ }+ const popup = await popupPromise;+ await expect(popup).toHaveURL(url);+ await popup.close();++ const editor = page.getByRole('textbox', { name: 'Message' });+ await editor.locator('a').click();+ await page.getByRole('button', { name: 'Remove link' }).click();+ await expect(editor.locator('a')).toHaveCount(0);+ await page.getByRole('button', { name: 'Save message', exact: true }).click();+ await expect(page.getByTestId('saved')).toHaveText(url);+ await expect(page.getByTestId('saved').locator('a')).toHaveCount(0);+ await page.getByRole('button', { name: 'Reopen saved message' }).click();+ await expect(editor).toHaveText(url);+ await expect(editor.locator('a')).toHaveCount(0);+ expect(errors).toEqual([]);+ await page.locator('main').evaluate((element) => {+ element.scrollTop = 0;+ });+ await page.screenshot({+ path: testInfo.outputPath('links.png'),+ fullPage: true,+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.html b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.htmlnew file mode 100644index 0000000000..838b1776a0--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Message links</title></head>+ <body><div id="root"></div><script type="module" src="./links.tsx"></script></body>+</html>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.tsxnew file mode 100644index 0000000000..790030e8b3--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.tsx@@ -0,0 +1,89 @@+import '@app/index.css';+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';+import { PosthogProvider } from '@app/lib/analytics/posthog';+import { UserContextProvider } from '@core/context/user';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { createSignal, onCleanup } from 'solid-js';+import { render } from 'solid-js/web';+import { buildConfig } from '../../../builder/MarkdownConfigBuilder';+import { ComposerEditor } from '../../ComposerEditor';+import { StaticMarkdown, StaticMarkdownContext } from '../StaticMarkdown';++const url = 'https://apps.apple.com/us/app/macro-app/id6743133649';+const original = `hey! can you rate the Macro app on the App Store (5 stars if you're feeling it) and leave a quick review if you can? takes 30 seconds:\n${url}\n\n(sent by @macro on behalf of Jacob)`;++function Fixture() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ onCleanup(() => client.clear());+ const [saved, setSaved] = createSignal('');+ const editor = buildConfig('chat')+ .namespace('links-fixture')+ .withLinks({ floatingMenu: true, autoLinkMatchMode: 'common-tlds' });+ return (+ <AnalyticsContextProvider>+ <PosthogProvider>+ <QueryClientProvider client={client}>+ <UserContextProvider>+ <StaticMarkdownContext>+ <main class="bg-page text-ink h-dvh overflow-y-auto p-6 space-y-6 max-w-3xl mx-auto">+ <h1 class="text-xl font-medium">Message links</h1>+ <section+ data-testid="original"+ class="border border-edge rounded p-4"+ >+ <p class="font-medium mb-3">Macro · Agent</p>+ <StaticMarkdown markdown={original} />+ </section>+ <section+ data-testid="explicit"+ class="border border-edge rounded p-4"+ >+ <StaticMarkdown+ markdown={`here's the clickable link: [Rate Macro on the App Store](${url})`}+ />+ </section>+ <section+ data-testid="cases"+ class="border border-edge rounded p-4"+ >+ <StaticMarkdown+ markdown={+ 'Encoded path: https://example.com/a%20b?q=x%2Fy#part\n\nURL punctuation: https://example.com/a~~b~~c\n\nLiteral code: `https://example.com/code`\n\nRemoved link: <m-link>{"url":"https://example.com/removed","text":"https://example.com/removed","unlinked":true}</m-link>'+ }+ />+ </section>+ <section class="border border-edge rounded p-4 space-y-3">+ <h2>Edit and save a link</h2>+ <ComposerEditor+ config={editor}+ initialValue={url}+ ariaLabel="Message"+ />+ <button+ class="border border-edge rounded px-3 py-1"+ onClick={() => setSaved(editor.controls.getMarkdown())}+ >+ Save message+ </button>+ <div data-testid="saved">+ <StaticMarkdown markdown={saved()} />+ </div>+ <button+ class="border border-edge rounded px-3 py-1"+ onClick={() => editor.controls.setMarkdown(saved())}+ >+ Reopen saved message+ </button>+ </section>+ </main>+ </StaticMarkdownContext>+ </UserContextProvider>+ </QueryClientProvider>+ </PosthogProvider>+ </AnalyticsContextProvider>+ );+}++render(() => <Fixture />, document.getElementById('root')!);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/autolinks-desktop.png b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/autolinks-desktop.pngnew file mode 100644index 0000000000..5ff4236139Binary files /dev/null and b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/autolinks-desktop.png differdiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/autolinks-mobile.png b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/autolinks-mobile.pngnew file mode 100644index 0000000000..eeb3fa45b8Binary files /dev/null and b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/autolinks-mobile.png differdiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/autoLink.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/autoLink.tsindex db08942a05..743d328b4d 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/autoLink.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/autoLink.ts@@ -1,108 +1,6 @@-import linkify, { type Match } from 'linkify-it';--export const strictLinkifier = new linkify(undefined, {- fuzzyLink: false,-});--const commonTldLinkifier = new linkify(undefined, {- fuzzyLink: true,-}).tlds(- [- 'app',- 'biz',- 'ca',- 'co',- 'com',- 'dev',- 'edu',- 'gov',- 'info',- 'io',- 'me',- 'net',- 'org',- 'shop',- 'site',- 'store',- 'tv',- 'uk',- 'us',- 'xyz',- ],- false-);--const fuzzyLinkifier = new linkify(undefined, {- fuzzyLink: true,-});--export type AutoLinkMatchMode = 'protocol' | 'common-tlds' | 'fuzzy';--function getAutoLinkifier(mode: AutoLinkMatchMode) {- switch (mode) {- case 'common-tlds':- return commonTldLinkifier;- case 'fuzzy':- return fuzzyLinkifier;- case 'protocol':- return strictLinkifier;- }-}--const ALLOWED_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);-const URL_SCHEME_PATTERN = /^([a-z][a-z\d+.-]*):/i;--/**- * Normalize user-entered links and reject protocols that links must not open.- * Bare hosts retain the existing behavior of defaulting to HTTPS.- */-export function normalizeLinkUrl(input: string): string | null {- const trimmed = input.trim();- if (!trimmed) return null;-- // The URL parser ignores ASCII tabs and newlines in protocols. Use the same- // view when detecting a scheme so values such as `java\nscript:` cannot be- // mistaken for a bare host and rewritten as HTTPS.- const schemeProbe = trimmed.replace(/[\t\n\r]/g, '');- const schemeMatch = URL_SCHEME_PATTERN.exec(schemeProbe);- const scheme = schemeMatch?.[1]?.toLowerCase();- const remainder = schemeMatch ? schemeProbe.slice(schemeMatch[0].length) : '';- const isHostWithPort =- scheme !== undefined &&- (scheme === 'localhost' || scheme.includes('.')) &&- /^\d+(?:[/?#]|$)/.test(remainder);- const candidate = scheme && !isHostWithPort ? trimmed : `https://${trimmed}`;-- try {- const parsed = new URL(candidate);- if (!ALLOWED_LINK_PROTOCOLS.has(parsed.protocol)) return null;-- if (parsed.protocol === 'mailto:') return trimmed;-- const [basePath, ...queryParts] = candidate.split(/([#?])/);- const encodedBase = basePath- .split('/')- .map((segment) => (segment.includes(':') ? segment : encodeURI(segment)))- .join('/');- return encodedBase + queryParts.join('');- } catch {- return null;- }-}--export function findNextAutoLinkMatch(- text: string,- mode: AutoLinkMatchMode = 'protocol'-): Match | null {- const linkifier = getAutoLinkifier(mode);- if (!linkifier.test(text)) return null;- const match = linkifier.match(text);- if (!match) return null;- const firstMatch = match[0];- const url = normalizeLinkUrl(- firstMatch.schema === '' ? firstMatch.raw : firstMatch.url- );- if (!url) return null;- firstMatch.url = url;- return firstMatch;-}+export {+ type AutoLinkMatchMode,+ findNextAutoLinkMatch,+ normalizeLinkUrl,+ strictLinkifier,+} from '@macro-inc/lexical-core/utils/auto-link';diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.tsindex 3a24e8ec66..93ec91ddaf 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts@@ -1,6 +1,28 @@+import { $isAutoLinkNode, $isLinkNode } from '@lexical/link';+import {+ $convertFromMarkdownString,+ $convertToMarkdownString,+} from '@lexical/markdown';+import {+ ALL_TRANSFORMERS,+ INTERNAL_TRANSFORMERS,+ SupportedNodeTypes,+} from '@macro-inc/lexical-core';+import { $isUnlinkedTextNode } from '@macro-inc/lexical-core/nodes/UnlinkedTextNode';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ createEditor,+} from 'lexical';import { describe, expect, it } from 'vitest';-import { findNextAutoLinkMatch, normalizeLinkUrl } from './linksPlugin';+import {+ findNextAutoLinkMatch,+ linksPlugin,+ normalizeLinkUrl,+ UNLINK_COMMAND,+} from './linksPlugin';describe('normalizeLinkUrl', () => {it('normalizes bare hosts to HTTPS', () => {@@ -70,3 +92,133 @@ describe('findNextAutoLinkMatch', () => {);});});++describe('composer link persistence', () => {+ it('removes an entire formatted label when multiple children are selected', () => {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError(error) {+ throw error;+ },+ });+ const cleanup = linksPlugin({})(editor);+ editor.update(+ () =>+ $convertFromMarkdownString(+ '[**click** here](https://example.com)',+ ALL_TRANSFORMERS+ ),+ { discrete: true }+ );+ editor.update(+ () => {+ const [first, last] = $getRoot().getAllTextNodes();+ const selection = first.select(0);+ selection.focus.set(last.getKey(), last.getTextContentSize(), 'text');+ expect(editor.dispatchCommand(UNLINK_COMMAND, undefined)).toBe(true);+ },+ { discrete: true }+ );+ const markdown = editor.getEditorState().read(() => {+ expect($getRoot().getTextContent()).toBe('click here');+ for (const node of $getRoot().getAllTextNodes()) {+ expect($isLinkNode(node.getParent())).toBe(false);+ }+ return $convertToMarkdownString(INTERNAL_TRANSFORMERS);+ });+ expect(markdown).toBe('**click** here');+ cleanup();+ });++ it('keeps escaped URLs literal when imported into a live editor', () => {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError(error) {+ throw error;+ },+ });+ const cleanup = linksPlugin({ autoLinkMatchMode: 'common-tlds' })(editor);+ editor.update(+ () =>+ $convertFromMarkdownString(+ 'https\\://example\\.com then https://example.com/linked',+ ALL_TRANSFORMERS+ ),+ { discrete: true }+ );+ editor.getEditorState().read(() => {+ const nodes = $getRoot().getAllTextNodes();+ expect($isUnlinkedTextNode(nodes[0])).toBe(true);+ expect(nodes[0].getTextContent()).toBe('https://example.com');+ expect($isLinkNode(nodes[0].getParent())).toBe(false);+ expect($isLinkNode(nodes[2].getParent())).toBe(true);+ });+ cleanup();+ });++ it.each([+ { kind: 'typed', url: 'https://example.com/a%20b', protocol: false },+ { kind: 'imported', url: 'https://example.com/a%20b', protocol: false },+ { kind: 'typed', url: 'example.com', protocol: false },+ { kind: 'imported', url: 'example.com', protocol: false },+ { kind: 'imported', url: 'example.com', protocol: true },+ ])(+ 'keeps a $kind $url link removed after saving and opening the editor again',+ ({ kind, url, protocol }) => {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError(error) {+ throw error;+ },+ });+ const cleanup = linksPlugin({+ autoLinkMatchMode: protocol ? 'protocol' : 'common-tlds',+ })(editor);+ editor.update(+ () => {+ if (kind === 'typed') {+ $getRoot().append(+ $createParagraphNode().append(+ $createTextNode(url).setFormat('bold')+ )+ );+ } else {+ $convertFromMarkdownString(`**${url}**`, ALL_TRANSFORMERS);+ }+ },+ { discrete: true }+ );+ editor.getEditorState().read(() => {+ const node = $getRoot().getAllTextNodes()[0];+ expect(node.hasFormat('bold')).toBe(true);+ const parent = node.getParent();+ expect($isLinkNode(parent) && parent.getURL()).toBe(+ url.includes('://') ? url : `https://${url}`+ );+ });+ editor.update(+ () => {+ $getRoot().getAllTextNodes()[0].select();+ editor.dispatchCommand(UNLINK_COMMAND, undefined);+ },+ { discrete: true }+ );+ const markdown = editor+ .getEditorState()+ .read(() => $convertToMarkdownString(INTERNAL_TRANSFORMERS));+ editor.update(+ () => $convertFromMarkdownString(markdown, ALL_TRANSFORMERS),+ { discrete: true }+ );+ editor.getEditorState().read(() => {+ const node = $getRoot().getAllTextNodes()[0];+ expect($isUnlinkedTextNode(node)).toBe(true);+ expect(node.hasFormat('bold')).toBe(true);+ expect(node.getTextContent()).toBe(url);+ expect($isLinkNode(node.getParent())).toBe(false);+ expect($isAutoLinkNode(node.getParent())).toBe(false);+ });+ cleanup();+ }+ );+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.tsindex 865eb38b81..ab46019198 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts@@ -169,21 +169,20 @@ function $matchAndCreateAutoLink(}const linkNode = $createAutoLinkNode(matchedLink.url);- linkNode.append($createTextNode(matchedLink.text));matchedNode.replace(linkNode);+ linkNode.append(matchedNode);}function $convertAutoLinkToLinkNode(node: AutoLinkNode): LinkNode {const url = node.getURL();- const text = node.getTextContent();const linkNode = $createLinkNode(url);- linkNode.append($createTextNode(text));+ const children = node.getChildren();node.replace(linkNode);+ linkNode.append(...children);return linkNode;}-// TODO (seamus): Improve this logic. This function should correctly dissolve any links that-// are touched by the selection while maintaining all children and text formatting.+// Dissolve touched links while preserving their labels and text formatting.function $unlinkSelection(): boolean {const selection = $getSelection();let unlinkSuccess = false;@@ -205,7 +204,7 @@ function $unlinkSelection(): boolean {// Process all selected nodesnodes.forEach((node) => {const parent = node.getParent();- if (!node || !parent) return;+ if (!parent?.isAttached()) return;if ($isAutoLinkNode(parent)) {parent.setIsUnlinked(true);@@ -216,20 +215,17 @@ function $unlinkSelection(): boolean {if ($isLinkNode(parent)) {unlinkSuccess = true;- let newNode;- let text = node.getTextContent();- if (strictLinkifier.test(text)) {- newNode = $createUnlinkedTextNode(text);- } else {- newNode = $createTextNode(text);+ // Preserve the explicit removal even when the current editor's URL+ // policy is narrower than the importer, and retain the whole label.+ for (const child of parent.getChildren()) {+ const unlinked = $isTextNode(child)+ ? $createUnlinkedTextNode().updateFromJSON(child.exportJSON())+ : child;+ if (child.getKey() === anchor.key) anchor.key = unlinked.getKey();+ if (child.getKey() === focus.key) focus.key = unlinked.getKey();+ parent.insertBefore(unlinked);}- if (node.getKey() === anchor.key) {- anchor.key = newNode.getKey();- }- if (node.getKey() === focus.key) {- focus.key = newNode.getKey();- }- parent.replace(newNode);+ parent.remove();}});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.tsindex fcac388bd4..737a45668e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts@@ -35,5 +35,6 @@* when an agent mentions a PR by URL, and the decorator resolves the synced PR.* Version 8.0 - Oct 2026. Added BookingLinkMentionNode for Macro `/app/book/…` URLs.* Version 9.0 - Oct 2026. Added AgentActivityNode: the steps of an agent's reply between two passages, with a snapshot of its rows and live rendering where the session is readable.+ * Version 9.1 - Oct 2026. Markdown m-link payloads preserve explicit unlinking; bare URLs import as links.*/-export const MARKDOWN_VERSION_COUNTER = 9.0;+export const MARKDOWN_VERSION_COUNTER = 9.1;diff --git a/bun.lock b/bun.lockindex c9ef283aa4..b6dbdbc3e5 100644--- a/bun.lock+++ b/bun.lock@@ -145,7 +145,6 @@"katex": "^0.16.22","lexical": "0.45.0","libheif-js": "^1.19.8",- "linkify-it": "^5.0.0","livekit-client": "^2.18.0","loro-crdt": "catalog:","nanoid": "^3.3.7",@@ -191,7 +190,6 @@"@types/d3-shape": "^3.1.8","@types/facebook-pixel": "^0.0.31","@types/gtag.js": "^0.0.20",- "@types/linkify-it": "^5.0.0","@types/lodash": "^4.17.20","@types/node": "^24.8.0","@types/papaparse": "^5.5.2",@@ -337,6 +335,7 @@"fast-xml-parser": "^4.5.6","flat": "^6.0.1","lexical": "0.45.0",+ "linkify-it": "^5.0.0","loro-crdt": "catalog:","nanoid": "^5.1.5","p-queue": "^9.3.0",@@ -348,6 +347,7 @@"@types/bun": "^1.3.14","@types/diff": "^8.0.0","@types/flat": "^5.0.5",+ "@types/linkify-it": "^5.0.0","@types/yargs": "^17.0.35",},},diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex c0f403508c..20697fa135 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -9,6 +9,20 @@ the message text, including link labels and mention names, once per preview.Verify wide and narrow rows and channel/thread cards; links and mentions remaininteractive inside the opened conversation.+## Message links++Bare URLs, common bare domains, and email addresses are clickable in opened+messages, including agent/API messages and older messages. Explicit Markdown+links still use their label. Inline code, code blocks, and escaped URLs stay+literal. Removing a link in the composer remains effective after sending and+reopening the message for editing.++Verify a bare App Store URL on desktop and mobile, a percent-encoded URL, a URL+containing Markdown punctuation, and Remove link → send → reopen. Channel and+Home previews remain display-only as described above. The backend-free browser+check is in+`apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md`.+## Empty direct messagesAn empty human DM shows the centered conversations illustration and “Say hello”diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 7e49a5be2a..5c79e79063 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -2352,6 +2352,9 @@ nodes — use the snapshot itself to verify content. For formatting checks, runBody placeholder advertises: `/` for block commands, `@` to reference files, `;` for snippets.Markdown auto-format works while typing (`#` heading, `[]` checklist, `>` quote).+Imported Markdown recognizes bare URLs with the same shared matcher as messages;+code and escaped URLs remain literal. Remove link persists through Markdown and+editor-state saves. See [message links](channels.md#message-links) for verification.Every top-level checklist shows a completed count and progress meter on a thinline above its items, left-aligned with the checkboxes. Checklists containingdiff --git a/packages/lexical-core/AGENTS.md b/packages/lexical-core/AGENTS.mdnew file mode 100644index 0000000000..2eeb9fa321--- /dev/null+++ b/packages/lexical-core/AGENTS.md@@ -0,0 +1,33 @@+# Lexical core++## What it is++Shared Lexical nodes and Markdown conversion for web editors, message renderers,+and backend document transformations.++## Start here++- `transformers/index.ts`: internal, external, and combined import/export sets.+- `utils/auto-link.ts` and `transformers/auto-link.ts`: shared URL matching and+ its adapter to Lexical's inline importer.+- `README.md`: persisted link and explicit-unlink behavior.++## Boundaries++Keep runtime code independent of the web app and browser-only modules. The web+composer imports the URL matcher from this package; do not duplicate it.++## Checks++- From `apps/web`: `bun run test --project lexical-core`.+- Run `bunx @biomejs/biome ci <changed-files>` from this directory for its+ format/lint rules; include untracked files before the first commit.+- Link changes also run `bun run test --project core linksPlugin.test.ts+ StaticMarkdown.test.tsx` in `apps/web`, and the browser check documented in+ `apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md`.++## Gotchas++Keep URLs protected from inline formatting during import; matching rendered+text is too late. Preserve code, mention payloads, existing links, and escaped+literal URLs. Keep unlink state through both Markdown and Lexical JSON saves.diff --git a/packages/lexical-core/CLAUDE.md b/packages/lexical-core/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/packages/lexical-core/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/packages/lexical-core/README.md b/packages/lexical-core/README.mdindex ec52faebbd..72410db32f 100644--- a/packages/lexical-core/README.md+++ b/packages/lexical-core/README.md@@ -1,7 +1,36 @@# Lexical Core-`lexical core` defines the nodes, plugins, and transformers that are required for interoperability between our-front end Lexical editors and the back end document transformation features. All files in this package-should ONLY import from lexical or from other files in this package.++Shared Lexical nodes, Markdown transformers, and utilities for web editors,+static message rendering, and backend document conversion. Keep this package+independent of web components and browser-only imports; runtime-neutral libraries+such as `linkify-it` supply shared parsing behavior.++## Links++All Markdown import formats recognize bare URLs, common bare domains, email+addresses, and angle-bracket URLs with the shared matcher in+`utils/auto-link.ts`. URL matching runs during inline parsing so formatting+characters inside a URL remain literal. Code, existing links, mention payloads,+and escaped URL text retain their own syntax. Existing bare URLs become clickable+when imported; their source Markdown is not rewritten in storage.++The editor and parser share URL validation and normalization. Preserve existing+percent escapes, use the HTTP/HTTPS/mailto allowlist, and continue past rejected+matches to find later valid links.++Internal Markdown persists an explicit removal as+`<m-link>{"url":"https://example.com","text":"https://example.com","title":"","unlinked":true,"format":0}</m-link>`.+The optional `unlinked` field imports as the existing `UnlinkedTextNode`; `format`+preserves its text formatting. Older clients ignore these fields and render a+normal link using the normalized URL. Removed labels that contain no URL export+as ordinary formatted text. Ordinary link payloads are unchanged. External Markdown exports+removed links as escaped literal text.++Before this marker existed, removed links could be saved as plain URL text or as+ordinary link payloads. Their original intent cannot be recovered; legacy bare+URLs follow the automatic-linking policy.++## Canvas text`canvas-text.ts` shares bounded Lexical JSON validation, plain-text seeds andextraction between Canvas and its headless AI worker. Geometry, typography anddiff --git a/packages/lexical-core/nodes/UnlinkedTextNode.ts b/packages/lexical-core/nodes/UnlinkedTextNode.tsindex 33fe3d826e..44649a4640 100644--- a/packages/lexical-core/nodes/UnlinkedTextNode.ts+++ b/packages/lexical-core/nodes/UnlinkedTextNode.ts@@ -1,5 +1,5 @@/**- * Unlinked text nodes are basic text nodes that serialize and deserialize to plain text.+ * Unlinked text nodes preserve an explicit choice to keep URL-shaped text inert.* They basically flag off the the auto link listener. you cannot unlink a url shaped string* while the auto linker is listening without some sort of flag.*/@@ -55,9 +55,7 @@ export class UnlinkedTextNode extends TextNode {};}static importJSON(serializedNode: SerializedUnlinkedTextNode) {- super.importJSON(serializedNode);- const node = $createUnlinkedTextNode(serializedNode.text);- return node;+ return $createUnlinkedTextNode().updateFromJSON(serializedNode);}}diff --git a/packages/lexical-core/package.json b/packages/lexical-core/package.jsonindex d5c4077d14..35f53e5f9f 100644--- a/packages/lexical-core/package.json+++ b/packages/lexical-core/package.json@@ -38,6 +38,7 @@"fast-xml-parser": "^4.5.6","flat": "^6.0.1","lexical": "0.45.0",+ "linkify-it": "^5.0.0","loro-crdt": "catalog:","nanoid": "^5.1.5","p-queue": "^9.3.0",@@ -49,6 +50,7 @@"@types/bun": "^1.3.14","@types/diff": "^8.0.0","@types/flat": "^5.0.5",+ "@types/linkify-it": "^5.0.0","@types/yargs": "^17.0.35"}}diff --git a/packages/lexical-core/tests/auto-link.test.ts b/packages/lexical-core/tests/auto-link.test.tsnew file mode 100644index 0000000000..0e7f178c69--- /dev/null+++ b/packages/lexical-core/tests/auto-link.test.ts@@ -0,0 +1,284 @@+import { $createAutoLinkNode, $isLinkNode } from '@lexical/link';+import {+ $convertFromMarkdownString,+ $convertToMarkdownString,+ type Transformer,+} from '@lexical/markdown';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $isElementNode,+ createEditor,+ type LexicalNode,+} from 'lexical';+import { describe, expect, it } from 'vitest';+import { SupportedNodeTypes } from '../node-list';+import {+ $createUnlinkedTextNode,+ $isUnlinkedTextNode,+} from '../nodes/UnlinkedTextNode';+import {+ ALL_TRANSFORMERS,+ EXTERNAL_TRANSFORMERS,+ INTERNAL_TRANSFORMERS,+} from '../transformers';+import { findNextAutoLinkMatch, normalizeLinkUrl } from '../utils/auto-link';++function parse(+ markdown: string,+ transformers: Transformer[] = ALL_TRANSFORMERS+) {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError(error) {+ throw error;+ },+ });+ editor.update(() => $convertFromMarkdownString(markdown, transformers), {+ discrete: true,+ });+ return editor;+}++function links(node: LexicalNode): { text: string; url: string }[] {+ const own = $isLinkNode(node)+ ? [{ text: node.getTextContent(), url: node.getURL() }]+ : [];+ return [+ ...own,+ ...($isElementNode(node) ? node.getChildren().flatMap(links) : []),+ ];+}++const appStore = 'https://apps.apple.com/us/app/macro-app/id6743133649';++describe('Markdown URL imports', () => {+ it.each([+ { transformers: ALL_TRANSFORMERS },+ { transformers: INTERNAL_TRANSFORMERS },+ { transformers: EXTERNAL_TRANSFORMERS },+ ])(+ 'links the original agent message through every import format',+ ({ transformers }) => {+ const message = `hey! can you rate the Macro app on the App Store (5 stars if you're feeling it) and leave a quick review if you can? takes 30 seconds:\n${appStore}\n\n(sent by @macro on behalf of Jacob)`;+ const editor = parse(message, transformers);+ editor.getEditorState().read(() => {+ expect(links($getRoot())).toEqual([{ text: appStore, url: appStore }]);+ expect($getRoot().getTextContent()).toContain(+ '(sent by @macro on behalf of Jacob)'+ );+ });+ }+ );+ it.each([+ [+ 'Visit https://example.com/a%20b?q=x%2Fy#part.',+ 'https://example.com/a%20b?q=x%2Fy#part',+ ],+ ['Visit (https://example.com/a(b)).', 'https://example.com/a(b)'],+ ['https://example.com/a~~b~~c', 'https://example.com/a~~b~~c'],+ [+ 'https://example.com/?q=*abc*&next=1',+ 'https://example.com/?q=*abc*&next=1',+ ],+ ['<https://example.com/path>', 'https://example.com/path'],+ ['Go to example.com/path', 'https://example.com/path'],+ ['Email [email protected].', 'mailto:[email protected]'],+ ])('keeps the URL intact in %s', (markdown, url) => {+ parse(markdown)+ .getEditorState()+ .read(() =>+ expect(links($getRoot()).map((link) => link.url)).toEqual([url])+ );+ });+ it('preserves bold around a URL without formatting punctuation inside it', () => {+ parse('**https://example.com/a~~b~~c**')+ .getEditorState()+ .read(() => {+ expect(links($getRoot())).toEqual([+ {+ text: 'https://example.com/a~~b~~c',+ url: 'https://example.com/a~~b~~c',+ },+ ]);+ expect($getRoot().getAllTextNodes()[0].hasFormat('bold')).toBe(true);+ expect($getRoot().getAllTextNodes()[0].hasFormat('strikethrough')).toBe(+ false+ );+ });+ });+ it('links multiple URLs, including those after unsupported schemes', () => {+ parse(+ 'ftp://files.example.com https://one.example.com, https://two.example.com.'+ )+ .getEditorState()+ .read(() => {+ expect(links($getRoot()).map((link) => link.url)).toEqual([+ 'https://one.example.com',+ 'https://two.example.com',+ ]);+ });+ });+ it.each([+ '`https://example.com`',+ '```text\nhttps://example.com\n```',+ 'Open main.rs or parser.ts',+ 'javascript:alert(1)',+ 'https\\://example\\.com',+ 'https://example\\.com',+ '<m-user-mention>{"userId":"u1","email":"[email protected]","displayName":"https://example.com"}</m-user-mention>',+ '',+ ])('keeps protected content inert: %s', (markdown) => {+ parse(markdown)+ .getEditorState()+ .read(() => expect(links($getRoot())).toEqual([]));+ });+ it('does not nest links inside explicit Markdown or internal links', () => {+ parse(+ '[https://label.example.com](https://target.example.com) <m-link>{"url":"https://xml.example.com","text":"https://label.example.com"}</m-link>'+ )+ .getEditorState()+ .read(() => {+ expect(links($getRoot())).toEqual([+ {+ text: 'https://label.example.com',+ url: 'https://target.example.com',+ },+ { text: 'https://label.example.com', url: 'https://xml.example.com' },+ ]);+ });+ });+ it('retains URL destinations through repeated save and reload', () => {+ let editor = parse(`${appStore} https://example.com/a%2Fb?q=%25`);+ for (let i = 0; i < 3; i++) {+ const markdown = editor+ .getEditorState()+ .read(() => $convertToMarkdownString(INTERNAL_TRANSFORMERS));+ editor = parse(markdown);+ editor+ .getEditorState()+ .read(() =>+ expect(links($getRoot()).map((link) => link.url)).toEqual([+ appStore,+ 'https://example.com/a%2Fb?q=%25',+ ])+ );+ }+ });+});++describe('explicitly removed links', () => {+ it('stores a normalized destination for older clients of an unlinked bare host', () => {+ const editor = parse('');+ editor.update(+ () => {+ $getRoot()+ .clear()+ .append(+ $createParagraphNode().append(+ $createUnlinkedTextNode('example.com')+ )+ );+ },+ { discrete: true }+ );+ const markdown = editor+ .getEditorState()+ .read(() => $convertToMarkdownString(INTERNAL_TRANSFORMERS));+ expect(markdown).toContain('"url":"https://example.com"');+ const legacyMarkdown = markdown.replace(',"unlinked":true,"format":0', '');+ parse(legacyMarkdown)+ .getEditorState()+ .read(() =>+ expect(links($getRoot())).toEqual([+ { text: 'example.com', url: 'https://example.com' },+ ])+ );+ });++ it.each(['text', 'autolink'])(+ 'keeps an unlinked %s URL inert after save and reload',+ (kind) => {+ const editor = parse('');+ editor.update(+ () => {+ const text = $createTextNode(appStore).setFormat('bold');+ const node =+ kind === 'text'+ ? $createUnlinkedTextNode(appStore).setFormat('bold')+ : $createAutoLinkNode(appStore, { isUnlinked: true }).append(+ text+ );+ $getRoot().clear().append($createParagraphNode().append(node));+ },+ { discrete: true }+ );+ const markdown = editor+ .getEditorState()+ .read(() => $convertToMarkdownString(INTERNAL_TRANSFORMERS));+ const restored = parse(markdown);+ restored.getEditorState().read(() => {+ expect(links($getRoot())).toEqual([]);+ const node = $getRoot().getAllTextNodes()[0];+ expect($isUnlinkedTextNode(node)).toBe(true);+ expect(node.getTextContent()).toBe(appStore);+ expect(node.hasFormat('bold')).toBe(true);+ });+ const savedAgain = restored+ .getEditorState()+ .read(() => $convertToMarkdownString(INTERNAL_TRANSFORMERS));+ expect(savedAgain).toBe(markdown);+ }+ );+ it('preserves text and formatting through serialized editor state', () => {+ const editor = parse('');+ editor.update(+ () => {+ $getRoot().append(+ $createParagraphNode().append(+ $createUnlinkedTextNode(appStore).setFormat('italic')+ )+ );+ },+ { discrete: true }+ );+ editor.parseEditorState(editor.getEditorState().toJSON()).read(() => {+ const node = $getRoot().getAllTextNodes()[0];+ expect(node.hasFormat('italic')).toBe(true);+ expect($isUnlinkedTextNode(node)).toBe(true);+ });+ });+ it('exports literal text to external Markdown without internal tags or links', () => {+ const editor = parse(+ `<m-link>{"url":"${appStore}","text":"${appStore}","unlinked":true}</m-link>`+ );+ const markdown = editor+ .getEditorState()+ .read(() => $convertToMarkdownString(EXTERNAL_TRANSFORMERS));+ expect(markdown).not.toContain('<m-link>');+ parse(markdown, EXTERNAL_TRANSFORMERS)+ .getEditorState()+ .read(() => {+ expect(links($getRoot())).toEqual([]);+ expect($getRoot().getTextContent()).toBe(appStore);+ });+ });+});++describe('shared URL recognition', () => {+ it.each([+ 'https://example.com/a%20b',+ 'https://example.com/a%2Fb?q=x%25#y',+ 'https://example.com/a%2520b',+ ])('normalizes encoded URLs idempotently: %s', (url) => {+ expect(normalizeLinkUrl(url)).toBe(url);+ expect(normalizeLinkUrl(normalizeLinkUrl(url) ?? '')).toBe(url);+ });+ it('continues past an unsupported URL to find an allowed URL', () => {+ expect(+ findNextAutoLinkMatch('ftp://example.com then https://example.com/ok')+ ?.url+ ).toBe('https://example.com/ok');+ });+});diff --git a/packages/lexical-core/transformers/auto-link.ts b/packages/lexical-core/transformers/auto-link.tsnew file mode 100644index 0000000000..f7d39993d7--- /dev/null+++ b/packages/lexical-core/transformers/auto-link.ts@@ -0,0 +1,95 @@+import { $createLinkNode, $isLinkNode, LinkNode } from '@lexical/link';+import type { TextMatchTransformer } from '@lexical/markdown';+import { $findMatchingParent } from '@lexical/utils';+import { $createTextNode } from 'lexical';+import {+ $createUnlinkedTextNode,+ UnlinkedTextNode,+} from '../nodes/UnlinkedTextNode';+import { findAutoLinkMatches } from '../utils/auto-link';+import type { ConversionOnlyTransformer } from './transformers';++// Lexical's import API takes a RegExp. Adapt the shared URL matcher to that+// interface so URL boundaries are determined by linkify-it in both editors and+// imports, before Markdown formatting can consume characters inside a URL.+class AutoLinkRegExp extends RegExp {+ override exec(text: string): RegExpExecArray | null {+ const link = findAutoLinkMatches(text, 'common-tlds').find(+ (candidate) =>+ // Escaped Markdown is literal, including a URL whose escaped dot made+ // the recognizer stop at a partial hostname (https://example\\.com).+ !candidate.raw.includes('\\') &&+ text[candidate.lastIndex] !== '\\' &&+ text[candidate.index - 1] !== '\\'+ );+ if (!link) return null;+ const bracketed =+ text[link.index - 1] === '<' && text[link.lastIndex] === '>';+ const start = bracketed ? link.index - 1 : link.index;+ const end = bracketed ? link.lastIndex + 1 : link.lastIndex;+ const groups: [string, string, string] = [+ text.slice(start, end),+ link.url,+ link.text,+ ];+ return Object.assign(groups, {+ index: start,+ input: text,+ });+ }+}++// Preserve source offsets while decoding Markdown escapes so the importer can+// replace exactly the escaped URL, not a neighboring literal or markup tag.+class EscapedAutoLinkRegExp extends RegExp {+ override exec(source: string): RegExpExecArray | null {+ if (!source.includes('\\')) return null;+ const offsets: number[] = [];+ let decoded = '';+ for (let i = 0; i < source.length; i++) {+ offsets.push(i);+ if (source[i] === '\\' && /[!-/:-@[-`{-~]/.test(source[i + 1] ?? '')) i++;+ decoded += source[i];+ }+ offsets.push(source.length);+ for (const link of findAutoLinkMatches(decoded, 'common-tlds')) {+ const start = offsets[link.index];+ const raw = source.slice(start, offsets[link.lastIndex]);+ if (raw === link.text) continue;+ const groups: [string, string] = [raw, link.text];+ return Object.assign(groups, { index: start, input: source });+ }+ return null;+ }+}++export const ESCAPED_AUTO_LINK: ConversionOnlyTransformer<TextMatchTransformer> =+ {+ dependencies: [UnlinkedTextNode],+ importRegExp: new EscapedAutoLinkRegExp(''),+ regExp: new EscapedAutoLinkRegExp(''),+ replace: (textNode, match) => {+ if ($findMatchingParent(textNode, $isLinkNode)) return;+ textNode.replace(+ $createUnlinkedTextNode(match[1]).setFormat(textNode.getFormat())+ );+ },+ type: 'text-match',+ conversionOnly: true,+ };++export const AUTO_LINK: ConversionOnlyTransformer<TextMatchTransformer> = {+ dependencies: [LinkNode],+ importRegExp: new AutoLinkRegExp(''),+ regExp: new AutoLinkRegExp(''),+ replace: (textNode, match) => {+ if ($findMatchingParent(textNode, $isLinkNode)) return;+ const link = $createLinkNode(match[1]);+ link.append($createTextNode(match[2]).setFormat(textNode.getFormat()));+ textNode.replace(link);+ // Do not return the label for further Markdown parsing: URL punctuation+ // is literal, even when it resembles emphasis or strikethrough.+ },+ type: 'text-match',+ conversionOnly: true,+};diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.tsindex 703b7ee9d6..b55cbffc75 100644--- a/packages/lexical-core/transformers/index.ts+++ b/packages/lexical-core/transformers/index.ts@@ -1,6 +1,7 @@import type { Transformer } from '@lexical/markdown';import { I_AGENT_ACTIVITY } from './agentActivity';import { I_AGENT_CONTEXT } from './agentContext';+import { AUTO_LINK, ESCAPED_AUTO_LINK } from './auto-link';import { I_AWAIT_NODE } from './await';import { HTML_BLOCKQUOTE, I_MACRO_QUOTE } from './classedBlock';import { I_CURSOR_SYSTEM_NOTIFICATION } from './cursorSystemNotification';@@ -53,6 +54,7 @@ import {MARK_XML,PRESERVE_LINES,SEARCH_MATCH,+ UNLINKED_TEXT,} from './transformers';import { UNKNOWN_MENTION } from './unknownMention';import { I_VIDEO, VIDEO_LINK } from './video';@@ -104,6 +106,8 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [I_CONNECT_APP,I_WATERMARK,...CUSTOM_TRANSFORMERS,+ ESCAPED_AUTO_LINK,+ AUTO_LINK,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];@@ -112,6 +116,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [* External transformers for converting Lexical to and from to GitHub Flavored (ish) Markdown.*/export const EXTERNAL_TRANSFORMERS: Transformer[] = [+ UNLINKED_TEXT,I_DATABASE_QUERY_BLOCK,I_DATABASE_QUERY,HR,@@ -148,6 +153,8 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [E_SNAPSHOT_NODE,...HTML_ENTITY_TRANSFORMERS,...CUSTOM_TRANSFORMERS,+ ESCAPED_AUTO_LINK,+ AUTO_LINK,UNKNOWN_MENTION, // Must be last to act as fallback for unrecognized XML tags];@@ -213,6 +220,8 @@ export const ALL_TRANSFORMERS: Transformer[] = [E_INLINE_EQUATION_NODE,...HTML_ENTITY_TRANSFORMERS,...CUSTOM_TRANSFORMERS,+ ESCAPED_AUTO_LINK,+ AUTO_LINK,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/transformers/transformers.ts b/packages/lexical-core/transformers/transformers.tsindex 076c50c815..37afad9ee9 100644--- a/packages/lexical-core/transformers/transformers.ts+++ b/packages/lexical-core/transformers/transformers.ts@@ -20,9 +20,11 @@ import {$createTextNode,$isDecoratorNode,$isParagraphNode,+ $isTextNode,type LexicalNode,LineBreakNode,ParagraphNode,+ type TextNode,} from 'lexical';import {$createHorizontalRuleNode,@@ -33,6 +35,12 @@ import {$createSearchMatchNode,SearchMatchNode,} from '../nodes/SearchMatchNode';+import {+ $createUnlinkedTextNode,+ $isUnlinkedTextNode,+ UnlinkedTextNode,+} from '../nodes/UnlinkedTextNode';+import { findNextAutoLinkMatch } from '../utils/auto-link';import { HTML_ENTITIES } from '../utils/html-entities';import {replaceTextWithUnknownMention,@@ -152,10 +160,35 @@ function escapeUrl(url: string): string {return url.replace(/\(/g, '%28').replace(/\)/g, '%29');}+function exportUnlinkedText(+ node: TextNode,+ exportFormat: (node: TextNode, text: string) => string+): string {+ const text = node.getTextContent();+ const link = findNextAutoLinkMatch(text, 'common-tlds');+ if (!link) return exportFormat(node, text);+ return wrapXml('m-link', {+ url: link.url,+ text,+ title: '',+ unlinked: true,+ format: node.getFormat(),+ });+}+export const LINK_XML: TextMatchTransformer = {- dependencies: [LinkNode, UnknownMentionNode],- export: (node: LexicalNode) => {- if (!($isLinkNode(node) || $isAutoLinkNode(node))) return null;+ dependencies: [LinkNode, UnlinkedTextNode, UnknownMentionNode],+ export: (node, _exportChildren, exportFormat) => {+ if ($isUnlinkedTextNode(node))+ return exportUnlinkedText(node, exportFormat);+ if ($isAutoLinkNode(node) && node.getIsUnlinked()) {+ return node+ .getChildren()+ .filter($isTextNode)+ .map((text) => exportUnlinkedText(text, exportFormat))+ .join('');+ }+ if (!$isLinkNode(node)) return null;const text = node.getTextContent();return wrapXml('m-link', {url: escapeUrl(node.getURL()),@@ -171,6 +204,15 @@ export const LINK_XML: TextMatchTransformer = {for (const field of ['url', 'text']) {if (!(field in res)) throw new Error(`Missing field ${field}`);}+ if (res.unlinked === true) {+ const format = typeof res.format === 'number' ? res.format : 0;+ textNode.replace(+ $createUnlinkedTextNode(res.text).setFormat(+ format | textNode.getFormat()+ )+ );+ return;+ }const linkNode = $createLinkNode(res.url, { title: res.title });const linkTextNode = $createTextNode(res.text);linkTextNode.setFormat(textNode.getFormat());@@ -184,6 +226,26 @@ export const LINK_XML: TextMatchTransformer = {type: 'text-match',};+/** Preserve explicit unlinking when exporting to ordinary Markdown. */+export const UNLINKED_TEXT: TextMatchTransformer = {+ ...LINK_XML,+ export: (node, _exportChildren, exportFormat) => {+ if (+ !$isUnlinkedTextNode(node) &&+ !($isAutoLinkNode(node) && node.getIsUnlinked())+ )+ return null;+ const texts = $isUnlinkedTextNode(node)+ ? [node]+ : node.getChildren().filter($isTextNode);+ return texts+ .map((text) =>+ exportFormat(text, text.getTextContent()).replace(/[:.@/]/g, '\\$&')+ )+ .join('');+ },+};+export const MARK_XML: TextMatchTransformer = {dependencies: [MarkNode],export: (_: LexicalNode) => {diff --git a/packages/lexical-core/utils/auto-link.ts b/packages/lexical-core/utils/auto-link.tsnew file mode 100644index 0000000000..0e4ac519a7--- /dev/null+++ b/packages/lexical-core/utils/auto-link.ts@@ -0,0 +1,118 @@+import linkify, { type Match } from 'linkify-it';+import { match } from 'ts-pattern';++export const strictLinkifier = new linkify(undefined, {+ fuzzyLink: false,+});++const commonTldLinkifier = new linkify(undefined, {+ fuzzyLink: true,+}).tlds(+ [+ 'app',+ 'biz',+ 'ca',+ 'co',+ 'com',+ 'dev',+ 'edu',+ 'gov',+ 'info',+ 'io',+ 'me',+ 'net',+ 'org',+ 'shop',+ 'site',+ 'store',+ 'tv',+ 'uk',+ 'us',+ 'xyz',+ ],+ false+);++const fuzzyLinkifier = new linkify(undefined, {+ fuzzyLink: true,+});++export type AutoLinkMatchMode = 'protocol' | 'common-tlds' | 'fuzzy';++function getAutoLinkifier(mode: AutoLinkMatchMode) {+ return match(mode)+ .with('common-tlds', () => commonTldLinkifier)+ .with('fuzzy', () => fuzzyLinkifier)+ .with('protocol', () => strictLinkifier)+ .exhaustive();+}++const ALLOWED_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);+const URL_SCHEME_PATTERN = /^([a-z][a-z\d+.-]*):/i;++/**+ * Normalize user-entered links and reject protocols that links must not open.+ * Bare hosts retain the existing behavior of defaulting to HTTPS.+ */+export function normalizeLinkUrl(input: string): string | null {+ const trimmed = input.trim();+ if (!trimmed) return null;++ // The URL parser ignores ASCII tabs and newlines in protocols. Use the same+ // view when detecting a scheme so values such as `java\nscript:` cannot be+ // mistaken for a bare host and rewritten as HTTPS.+ const schemeProbe = trimmed.replace(/[\t\n\r]/g, '');+ const schemeMatch = URL_SCHEME_PATTERN.exec(schemeProbe);+ const scheme = schemeMatch?.[1]?.toLowerCase();+ const remainder = schemeMatch ? schemeProbe.slice(schemeMatch[0].length) : '';+ const isHostWithPort =+ scheme !== undefined &&+ (scheme === 'localhost' || scheme.includes('.')) &&+ /^\d+(?:[/?#]|$)/.test(remainder);+ const candidate = scheme && !isHostWithPort ? trimmed : `https://${trimmed}`;++ try {+ const parsed = new URL(candidate);+ if (!ALLOWED_LINK_PROTOCOLS.has(parsed.protocol)) return null;++ if (parsed.protocol === 'mailto:') return trimmed;++ const [basePath, ...queryParts] = candidate.split(/([#?])/);+ const encodedBase = basePath+ .split('/')+ .map((segment) =>+ segment.includes(':')+ ? segment+ : encodeURI(segment).replace(/%25([\da-f]{2})/gi, '%$1')+ )+ .join('/');+ return encodedBase + queryParts.join('');+ } catch {+ return null;+ }+}++export function findAutoLinkMatches(+ text: string,+ mode: AutoLinkMatchMode = 'protocol'+): Match[] {+ const linkifier = getAutoLinkifier(mode);+ if (!linkifier.test(text)) return [];+ const match = linkifier.match(text);+ if (!match) return [];+ const matches: Match[] = [];+ for (const candidate of match) {+ const url = normalizeLinkUrl(+ candidate.schema === '' ? candidate.raw : candidate.url+ );+ if (url) matches.push({ ...candidate, url });+ }+ return matches;+}++export function findNextAutoLinkMatch(+ text: string,+ mode: AutoLinkMatchMode = 'protocol'+): Match | null {+ return findAutoLinkMatches(text, mode)[0] ?? null;+}