🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(markdown): preserve strong-wrapped autolink boundaries (#20557)
AmAzing-a7ff51d24736
diff --git a/package.json b/package.jsonindex d3f05a066d6..b90788af4db 100644--- a/package.json+++ b/package.json@@ -578,6 +578,7 @@"p-map": "^7.0.6","prettier": "^3.9.6","raw-loader": "^4.0.2",+ "remark-cjk-friendly": "^2.3.1","remark-cli": "^12.0.1","remark-frontmatter": "^5.0.0","remark-mdx": "^3.1.1",diff --git a/patches/[email protected] b/patches/[email protected]new file mode 100644index 00000000000..ce19732eff3--- /dev/null+++ b/patches/[email protected]@@ -0,0 +1,274 @@+diff --git a/dev/lib/syntax.js b/dev/lib/syntax.js+--- a/dev/lib/syntax.js++++ b/dev/lib/syntax.js+@@ -1,5 +1,5 @@+ /**+- * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types'++ * @import {Code, ConstructRecord, Event, Extension, Previous, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'+ */++ import {+@@ -16,6 +16,7 @@+ const domain = {tokenize: tokenizeDomain, partial: true}+ const path = {tokenize: tokenizePath, partial: true}+ const trail = {tokenize: tokenizeTrail, partial: true}++const strongEnd = {tokenize: tokenizeStrongEnd, partial: true}+ const emailDomainDotTrail = {+ tokenize: tokenizeEmailDomainDotTrail,+ partial: true+@@ -607,6 +608,9 @@+ * @type {Tokenizer}+ */+ function tokenizePath(effects, ok) {++ const self = this++ /** @type {boolean | undefined} */++ let strong+ let sizeOpen = 0+ let sizeClose = 0++@@ -656,7 +660,13 @@+ code === codes.underscore ||+ code === codes.tilde+ ) {+- return effects.check(trail, ok, pathAtPunctuation)(code)++ return effects.check(++ trail,++ ok,++ code === codes.asterisk && self.previous !== codes.asterisk++ ? effects.check(strongEnd, atStrongEnd, pathAtPunctuation)++ : pathAtPunctuation++ )(code)+ }++ if (+@@ -671,6 +681,13 @@+ return pathInside+ }+++ /** @type {State} */++ function atStrongEnd(code) {++ // Only resolve the prefix once a qualifying closing boundary is found.++ if (strong === undefined) strong = unmatchedStrong(self)++ return strong ? ok(code) : pathAtPunctuation(code)++ }+++ /**+ * In path, at potential trailing punctuation, that was not trailing.+ *+@@ -693,6 +710,94 @@+ }++ /**++ * Resolve a detached prefix to distinguish a fresh ** opener from a delimiter++ * already used as a closer. Use the tokenizer's actual resolver order, including++ * strikethrough, without mutating the live tokens or their positions.++ *++ * @param {TokenizeContext} context++ * @returns {boolean}++ */++function unmatchedStrong(context) {++ // The two current events enter literalAutolink and its protocol/www token.++ const before = context.events[context.events.length - 3]++ if (++ !before ||++ before[0] !== 'exit' ||++ before[1].type !== 'attentionSequence' ||++ !before[1]._open ||++ context.sliceSerialize(before[1]) !== '**'++ )++ return false++++ /** @type {Map<Token, Token>} */++ const copies = new Map()++ /** @type {Array<Event>} */++ const events = context.events.slice(0, -2).map(([kind, token, owner]) => {++ let copy = copies.get(token)++ if (!copy) {++ copy = {...token, start: {...token.start}, end: {...token.end}}++ copies.set(token, copy)++ }++ return [kind, copy, owner]++ })++ const opener = copies.get(before[1])++ // Private contract supplied by the pinned micromark core patch.++ const resolved =++ /** @type {TokenizeContext & {_resolveAll: (events: Array<Event>) => Array<Event>}} */ (++ context++ )._resolveAll(events)++ for (const [original, copy] of copies) {++ // An unresolved strike opener can match after the URL, changing the scope++ // in which emphasis pairs. Leave these ambiguous cases to upstream.++ if (++ original.type === 'strikethroughSequenceTemporary' &&++ original._open &&++ copy.type !== 'strikethroughSequence'++ )++ return false++ }++ return resolved.some(++ ([kind, token]) =>++ kind === 'exit' &&++ token === opener &&++ token.start.offset === before[1].start.offset &&++ token.end.offset === before[1].end.offset++ )++}++++/**++ * Let an adjacent ** opener close before non-ASCII punctuation without changing++ * bare URL boundaries. The lookahead leaves both stars for attention parsing.++ *++ * @this {TokenizeContext}++ * @type {Tokenizer}++ */++function tokenizeStrongEnd(effects, ok, nok) {++ const self = this++ // Use the active attention tokenizer, including CJK flanking rules, rather++ // than guessing whether this delimiter can close from punctuation alone.++ return effects.attempt(++ self.parser.constructs.text[codes.asterisk],++ after,++ nok++ )++++ /** @type {State} */++ function after(code) {++ const event = self.events[self.events.length - 1]++ return code !== codes.eof &&++ code > 127 &&++ unicodePunctuation(code) &&++ event[0] === 'exit' &&++ event[1].type === 'attentionSequence' &&++ event[1]._close &&++ self.sliceSerialize(event[1]) === '**'++ ? ok(code)++ : nok(code)++ }++}++++/**+ * Trail.+ *+ * This calls `ok` if this *is* the trail, followed by an end, which means+diff --git a/lib/syntax.js b/lib/syntax.js+--- a/lib/syntax.js++++ b/lib/syntax.js+@@ -1,5 +1,5 @@+ /**+- * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types'++ * @import {Code, ConstructRecord, Event, Extension, Previous, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'+ */++ import { asciiAlpha, asciiAlphanumeric, asciiControl, markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';+@@ -19,6 +19,10 @@+ tokenize: tokenizeTrail,+ partial: true+ };++const strongEnd = {++ tokenize: tokenizeStrongEnd,++ partial: true++};+ const emailDomainDotTrail = {+ tokenize: tokenizeEmailDomainDotTrail,+ partial: true+@@ -550,6 +554,9 @@+ * @type {Tokenizer}+ */+ function tokenizePath(effects, ok) {++ const self = this;++ /** @type {boolean | undefined} */++ let strong;+ let sizeOpen = 0;+ let sizeClose = 0;+ return pathInside;+@@ -582,7 +589,7 @@+ // followed by more trailing markers, and then followed+ // by an end.+ if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 63 || code === 93 || code === 95 || code === 126) {+- return effects.check(trail, ok, pathAtPunctuation)(code);++ return effects.check(trail, ok, code === 42 && self.previous !== 42 ? effects.check(strongEnd, atStrongEnd, pathAtPunctuation) : pathAtPunctuation)(code);+ }+ if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {+ return ok(code);+@@ -591,6 +598,13 @@+ return pathInside;+ }+++ /** @type {State} */++ function atStrongEnd(code) {++ // Only resolve the prefix once a qualifying closing boundary is found.++ if (strong === undefined) strong = unmatchedStrong(self);++ return strong ? ok(code) : pathAtPunctuation(code);++ }+++ /**+ * In path, at potential trailing punctuation, that was not trailing.+ *+@@ -608,6 +622,60 @@+ }+ effects.consume(code);+ return pathInside;++ }++}++++/**++ * Resolve a detached prefix to distinguish a fresh ** opener from a delimiter++ * already used as a closer. Use the tokenizer's actual resolver order, including++ * strikethrough, without mutating the live tokens or their positions.++ *++ * @param {TokenizeContext} context++ * @returns {boolean}++ */++function unmatchedStrong(context) {++ // The two current events enter literalAutolink and its protocol/www token.++ const before = context.events[context.events.length - 3];++ if (!before || before[0] !== 'exit' || before[1].type !== 'attentionSequence' || !before[1]._open || context.sliceSerialize(before[1]) !== '**') return false;++ /** @type {Map<Token, Token>} */++ const copies = new Map();++ /** @type {Array<Event>} */++ const events = context.events.slice(0, -2).map(([kind, token, owner]) => {++ let copy = copies.get(token);++ if (!copy) {++ copy = {...token, start: {...token.start}, end: {...token.end}};++ copies.set(token, copy);++ }++ return [kind, copy, owner];++ });++ const opener = copies.get(before[1]);++ // Private contract supplied by the pinned micromark core patch.++ const resolved = /** @type {TokenizeContext & {_resolveAll: (events: Array<Event>) => Array<Event>}} */ (context)._resolveAll(events);++ for (const [original, copy] of copies) {++ // An unresolved strike opener can match after the URL, changing the scope++ // in which emphasis pairs. Leave these ambiguous cases to upstream.++ if (original.type === 'strikethroughSequenceTemporary' && original._open && copy.type !== 'strikethroughSequence') return false;++ }++ return resolved.some(([kind, token]) => kind === 'exit' && token === opener && token.start.offset === before[1].start.offset && token.end.offset === before[1].end.offset);++}++++/**++ * Let an adjacent ** opener close before non-ASCII punctuation without changing++ * bare URL boundaries. The lookahead leaves both stars for attention parsing.++ *++ * @this {TokenizeContext}++ * @type {Tokenizer}++ */++function tokenizeStrongEnd(effects, ok, nok) {++ const self = this;++ // Use the active attention tokenizer, including CJK flanking rules, rather++ // than guessing whether this delimiter can close from punctuation alone.++ return effects.attempt(self.parser.constructs.text[42], after, nok);++++ /** @type {State} */++ function after(code) {++ const event = self.events[self.events.length - 1];++ return code !== null && code > 127 && unicodePunctuation(code) && event[0] === 'exit' && event[1].type === 'attentionSequence' && event[1]._close && self.sliceSerialize(event[1]) === '**' ? ok(code) : nok(code);+ }+ }++@@ -851,4 +919,4 @@+ events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;+ }+ return result;+-}+\ No newline at end of file++}diff --git a/patches/[email protected] b/patches/[email protected]new file mode 100644index 00000000000..1c2e6acd052--- /dev/null+++ b/patches/[email protected]@@ -0,0 +1,75 @@+diff --git a/dev/lib/create-tokenizer.js b/dev/lib/create-tokenizer.js+--- a/dev/lib/create-tokenizer.js++++ b/dev/lib/create-tokenizer.js+@@ -5,6 +5,7 @@+ * ConstructRecord,+ * Construct,+ * Effects,++ * Event,+ * InitialConstruct,+ * ParseContext,+ * Point,+@@ -101,9 +102,12 @@+ /**+ * State and tools for resolving and serializing.+ *+- * @type {TokenizeContext}++ * @type {TokenizeContext & {_resolveAll: (events: Array<Event>) => Array<Event>}}+ */+ const context = {++ // Private contract with the patched literal-autolink extension: resolve++ // detached events in registration order without replacing live events.++ _resolveAll: (events) => resolveAll(resolveAllConstructs, events, context),+ code: codes.eof,+ containerState: {},+ defineSkip,+@@ -150,7 +154,7 @@+ addResult(initialize, 0)++ // Otherwise, resolve, and exit.+- context.events = resolveAll(resolveAllConstructs, context.events, context)++ context.events = context._resolveAll(context.events)++ return context.events+ }+diff --git a/lib/create-tokenizer.js b/lib/create-tokenizer.js+--- a/lib/create-tokenizer.js++++ b/lib/create-tokenizer.js+@@ -5,6 +5,7 @@+ * ConstructRecord,+ * Construct,+ * Effects,++ * Event,+ * InitialConstruct,+ * ParseContext,+ * Point,+@@ -97,9 +98,12 @@+ /**+ * State and tools for resolving and serializing.+ *+- * @type {TokenizeContext}++ * @type {TokenizeContext & {_resolveAll: (events: Array<Event>) => Array<Event>}}+ */+ const context = {++ // Private contract with the patched literal-autolink extension: resolve++ // detached events in registration order without replacing live events.++ _resolveAll: events => resolveAll(resolveAllConstructs, events, context),+ code: null,+ containerState: {},+ defineSkip,+@@ -142,7 +146,7 @@+ addResult(initialize, 0);++ // Otherwise, resolve, and exit.+- context.events = resolveAll(resolveAllConstructs, context.events, context);++ context.events = context._resolveAll(context.events);+ return context.events;+ }++@@ -610,4 +614,4 @@+ result.push(value);+ }+ return result.join('');+-}+\ No newline at end of file++}diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex fd0656b89bf..c720e650d8f 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -70,6 +70,9 @@ overrides:drizzle-orm: ^0.45.2fast-xml-parser: 5.4.2lexical: 0.42.0+ # Keep the coupled core/autolink patches applied without a root lockfile.+ micromark: 4.0.3+ micromark-extension-gfm-autolink-literal: 2.1.0node-gyp: ^12.4.0pdfjs-dist: 5.4.530react: 19.2.7@@ -82,3 +85,5 @@ overrides:patchedDependencies:'@upstash/qstash': patches/@upstash__qstash.patch+ [email protected]: patches/[email protected]+ [email protected]: patches/[email protected]diff --git a/src/features/Conversation/Markdown/autolink.test.ts b/src/features/Conversation/Markdown/autolink.test.tsnew file mode 100644index 00000000000..7865a7a57ff--- /dev/null+++ b/src/features/Conversation/Markdown/autolink.test.ts@@ -0,0 +1,184 @@+import { remark } from 'remark';+import remarkCjkFriendly from 'remark-cjk-friendly';+import remarkGfm from 'remark-gfm';+import remarkHtml from 'remark-html';+import { describe, expect, it } from 'vitest';++describe.each([false, true])('GFM strong-emphasis boundaries (CJK plugin: %s)', (cjk) => {+ const render = (markdown: string) => {+ const processor = remark();+ if (cjk) processor.use(remarkCjkFriendly);+ return String(+ processor.use(remarkGfm, { singleTilde: false }).use(remarkHtml).processSync(markdown),+ );+ };++ it('keeps the closing emphasis and Chinese annotation outside the PR link', () => {+ expect(render('PR:**https://github.com/example/project/pull/123**(OPEN,base `main`)')).toBe(+ '<p>PR:<strong><a href="https://github.com/example/project/pull/123">https://github.com/example/project/pull/123</a></strong>(OPEN,base <code>main</code>)</p>\n',+ );+ });++ it.each([+ '(备注)',+ ',然后继续',+ '。下一句',+ ';另一项',+ '!完成',+ '?确认',+ '、下一项',+ '“说明”',+ '”然后继续',+ '‘说明’',+ '’然后继续',+ '…下一句',+ '……”然后继续',+ ])('closes directly wrapping strong emphasis before %s', (suffix) => {+ expect(render(`**https://example.com/path**${suffix}`)).toBe(+ `<p><strong><a href="https://example.com/path">https://example.com/path</a></strong>${suffix}</p>\n`,+ );+ });++ it.each([+ 'https://zh.wikipedia.org/wiki/三体(小说)',+ 'https://en.wikipedia.org/wiki/Schrödinger’s_cat',+ 'https://example.com/search?q=你好,世界&lang=zh',+ 'https://example。com/path',+ 'https://example.com/path?(查询值)',+ 'https://example.com/path**(备注)',+ 'https://example.com/path…下一句',+ ])('preserves the complete unwrapped URL %s', (url) => {+ const href = encodeURI(url).replaceAll('&', '&');+ expect(render(url)).toBe(`<p><a href="${href}">${url.replaceAll('&', '&')}</a></p>\n`);+ });++ it.each(['', ' '])(+ 'does not reuse an already closed strong opener (separator: %s)',+ (separator) => {+ expect(render(`**已闭合**${separator}https://example.com/path**(备注)`)).toBe(+ `<p><strong>已闭合</strong>${separator}<a href="https://example.com/path**%EF%BC%88%E5%A4%87%E6%B3%A8%EF%BC%89">https://example.com/path**(备注)</a></p>\n`,+ );+ },+ );++ it('allows a new strong-wrapped URL after already resolved emphasis', () => {+ expect(render('**标题**正文**https://example.com/path**(备注)')).toBe(+ '<p><strong>标题</strong>正文<strong><a href="https://example.com/path">https://example.com/path</a></strong>(备注)</p>\n',+ );+ });++ it('closes multiple strong-wrapped URLs in the same paragraph', () => {+ expect(+ render('**https://example.com/first**(一)正文**https://example.com/second**(二)'),+ ).toBe(+ '<p><strong><a href="https://example.com/first">https://example.com/first</a></strong>(一)正文<strong><a href="https://example.com/second">https://example.com/second</a></strong>(二)</p>\n',+ );+ });++ it('keeps an opener that the rule of three prevents from closing earlier emphasis', () => {+ expect(render('*前文**https://example.com/path**(备注)')).toBe(+ '<p>*前文<strong><a href="https://example.com/path">https://example.com/path</a></strong>(备注)</p>\n',+ );+ });++ it('does not reuse strong delimiters after resolving earlier strikethrough', () => {+ expect(render('~~x**one~~y**z**https://example.com/path**(备注)')).toBe(+ '<p><del>x**one</del>y<strong>z</strong><a href="https://example.com/path**%EF%BC%88%E5%A4%87%E6%B3%A8%EF%BC%89">https://example.com/path**(备注)</a></p>\n',+ );+ });++ it('recognizes a fresh opener after resolving earlier strikethrough', () => {+ expect(render('~~x**one~~y**https://example.com/path**(备注)')).toBe(+ '<p><del>x**one</del>y<strong><a href="https://example.com/path">https://example.com/path</a></strong>(备注)</p>\n',+ );+ });++ it('preserves upstream boundaries when a later strikethrough closer changes attention scope', () => {+ expect(render('~~q~~ **a~~b**c**https://example.com/path**(备注)~~')).toBe(+ '<p><del>q</del> **a<del>b<strong>c</strong><a href="https://example.com/path**%EF%BC%88%E5%A4%87%E6%B3%A8%EF%BC%89">https://example.com/path**(备注)</a></del></p>\n',+ );+ });++ it('recognizes a fresh opener after an explicit link', () => {+ expect(render('[**标题**](https://example.org)正文**https://example.com/path**(备注)')).toBe(+ '<p><a href="https://example.org"><strong>标题</strong></a>正文<strong><a href="https://example.com/path">https://example.com/path</a></strong>(备注)</p>\n',+ );+ });++ it('preserves pending-label fallback instead of creating nested links', () => {+ expect(render('[**https://example.com/path**(备注)](https://example.org)')).toBe(+ '<p><a href="https://example.org"><strong>https://example.com/path</strong>(备注)</a></p>\n',+ );+ });++ it('closes strong after a trailing slash with the active attention tokenizer', () => {+ expect(render('**https://example.com/path/**(备注)')).toBe(+ '<p><strong><a href="https://example.com/path/">https://example.com/path/</a></strong>(备注)</p>\n',+ );+ });++ it.each([+ ['**', '***(备注)'],+ ['***', '**(备注)'],+ ['**前文 ', '**(备注)'],+ ['**', '*(备注)'],+ ['**', '**suffix'],+ ])('does not reinterpret other delimiter contexts: %s URL %s', (prefix, suffix) => {+ const url = `https://example.com/path${suffix}`;+ expect(render(`${prefix}${url}`)).toBe(+ `<p>${prefix}<a href="${encodeURI(url)}">${url}</a></p>\n`,+ );+ });++ it('preserves the existing mdast fallback autolink boundaries', () => {+ expect(render('链接:www.example.com/path(备注)')).toBe(+ '<p>链接:<a href="http://www.example.com/path%EF%BC%88%E5%A4%87%E6%B3%A8%EF%BC%89">www.example.com/path(备注)</a></p>\n',+ );+ expect(render('[https://example.com/path(备注)]')).toBe(+ '<p>[<a href="https://example.com/path%EF%BC%88%E5%A4%87%E6%B3%A8%EF%BC%89">https://example.com/path(备注)</a>]</p>\n',+ );+ });++ it.each(['http://example.com', 'https://example.com', 'www.example.com/path'])(+ 'closes strong around %s',+ (url) => {+ expect(render(`**${url}**(备注)`)).toBe(+ `<p><strong><a href="${url.startsWith('www.') ? 'http://' : ''}${url}">${url}</a></strong>(备注)</p>\n`,+ );+ },+ );++ it('preserves punctuation inside a strongly wrapped URL', () => {+ expect(render('**https://example.com/path?(查询值)**(备注)')).toBe(+ '<p><strong><a href="https://example.com/path?%EF%BC%88%E6%9F%A5%E8%AF%A2%E5%80%BC%EF%BC%89">https://example.com/path?(查询值)</a></strong>(备注)</p>\n',+ );+ });++ it('preserves Unicode paths and balanced ASCII parentheses', () => {+ expect(render('https://example.com/中文_(page)?a=1&b=2')).toBe(+ '<p><a href="https://example.com/%E4%B8%AD%E6%96%87_(page)?a=1&b=2">https://example.com/中文_(page)?a=1&b=2</a></p>\n',+ );+ expect(render('https://example.com/a–b')).toBe(+ '<p><a href="https://example.com/a%E2%80%93b">https://example.com/a–b</a></p>\n',+ );+ });++ it('preserves punctuation explicitly included in link destinations', () => {+ expect(render('[文档](https://example.com/中文(说明))')).toBe(+ '<p><a href="https://example.com/%E4%B8%AD%E6%96%87%EF%BC%88%E8%AF%B4%E6%98%8E%EF%BC%89">文档</a></p>\n',+ );+ expect(render('https://example.com/a%EF%BC%88b%EF%BC%89')).toBe(+ '<p><a href="https://example.com/a%EF%BC%88b%EF%BC%89">https://example.com/a%EF%BC%88b%EF%BC%89</a></p>\n',+ );+ expect(render('[文档](https://example.com/a…b)')).toBe(+ '<p><a href="https://example.com/a%E2%80%A6b">文档</a></p>\n',+ );+ });++ it('leaves inline and fenced code unchanged', () => {+ const content = '**https://example.com/path**(备注)';+ expect(render(`\`${content}\`\n\n\`\`\`text\n${content}\n\`\`\``)).toBe(+ `<p><code>${content}</code></p>\n<pre><code class="language-text">${content}\n</code></pre>\n`,+ );+ });+});