The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep source-anchored citation markers through markdown preprocessing
liuhao10249ab86e65845c
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.test.ts b/apps/desktop/src/components/assistant-ui/markdown-text.test.tsindex ed6834017ee..85135134341 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.test.ts+++ b/apps/desktop/src/components/assistant-ui/markdown-text.test.ts@@ -197,6 +197,32 @@ describe('preprocessMarkdown', () => {expect(output).toContain('`items[0]`')})+ it('keeps citation markers anchored by a numbered source list', () => {+ const input = [+ 'Ice floats because it is less dense than liquid water.[1][2]',+ '',+ '## Sources',+ '',+ '[1] https://example.com/a',+ '[2] https://example.com/b'+ ].join('\n')++ const output = preprocessMarkdown(input)++ expect(output).toContain('water.[1][2]')+ expect(output).toMatch(/\[1\][^\n]*example\.com\/a/)+ expect(output).toMatch(/\[2\][^\n]*example\.com\/b/)+ })++ it('strips a citation marker whose number is absent from the source list', () => {+ const input = 'A claim[1] and another[7].\n\n## Sources\n\n[1] https://example.com/a'++ const output = preprocessMarkdown(input)++ expect(output).toContain('claim[1]')+ expect(output).not.toContain('another[7]')+ })+it('demotes title/url blocks wrapped in malformed inline fences', () => {const input = ['**π’ TOMORROW (Fajardo, crystal clear cays, pickup avail):**',diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.tsindex e36256690b3..eb55868267b 100644--- a/apps/desktop/src/lib/markdown-preprocess.ts+++ b/apps/desktop/src/lib/markdown-preprocess.ts@@ -194,6 +194,24 @@ const CITATION_MARKER_RE = /(?<=[\p{L}\p{N})\].,!?:;"'ββ])\[(?:\d+(?:\s*,\s*const CITATION_TRANSPORT_MARKER_RE =/\uE200(?:cite)?(?:\uE202?turn\d+search\d+)+\uE201?|citeturn\d+search\d+(?:turn\d+search\d+)*/gu+// The `Sources` section header the bundled grounded-citations skill renders β+// `## Sources` (ATX, 1-6 hashes) or plain `Sources:`, case-insensitive,+// optionally bolded, colon optional. Mirrors the skill's own header pattern+// (`_SOURCES_HEADER_RE` in scripts/sources.py) so only the section shape it+// actually emits is recognized.+const SOURCES_HEADER_RE = /^[ \t]*(?:#{1,6}[ \t]*)?(?:\*\*)?sources:?(?:\*\*)?[ \t]*\r?$/i+// Numbered source-list entries inside a `Sources` section β a `[3] https://β¦`+// line (optionally behind a list marker or a `-`/`β`/`:` separator), as the+// bundled grounded-citations skill renders its entries. Such an entry anchors+// the bare `[3]` marker in prose: the marker cites a listed source, so it+// must survive the orphan-marker strip (#110370). Entries only count after+// the LAST `Sources` header and never inside a fenced block, so ordinary+// `[7] todo` lines or fenced examples can't anchor anything.+const SOURCE_LIST_ENTRY_RE = /^[ \t]*(?:[-*+][ \t]+)?\[((?:\d+(?:\s*,\s*\d+)*))\][ \t]*(?:[-β:][ \t]*)?https?:\/\/\S/+// Any fence line toggles code-block state while scanning for the `Sources`+// section β the same toggle the bundled skill uses to drop fenced code from+// a draft's prose.+const FENCE_TOGGLE_RE = /^[ \t]*(?:```|~~~)/// Markdown links whose target is a filesystem path on the agent's machine:// `[report](/home/user/report.md)`, `[notes](file:///srv/notes.txt)`,// `[todo](~/todo.md)`, `[log](C:\logs\run.txt)`. Negative lookbehind keeps@@ -440,13 +458,78 @@ function routeFileLinksToPreview(text: string): string {})}-function rewriteProseSegment(segment: string): string {+// Mirror of the bundled grounded-citations skill's `_split_draft()`: find the+// LAST `Sources` header, then collect entry ids only from the section that+// header opens (fenced code excluded). A marker survives only when this+// response actually lists a corresponding `[n] url` entry.+function collectSourceListIds(text: string): Set<string> {+ const ids = new Set<string>()+ const lines = text.split('\n')+ let inFence = false+ let headerIndex = -1++ for (let index = 0; index < lines.length; index += 1) {+ const line = lines[index]++ if (FENCE_TOGGLE_RE.test(line)) {+ inFence = !inFence++ continue+ }++ if (!inFence && SOURCES_HEADER_RE.test(line)) {+ headerIndex = index+ }+ }++ if (headerIndex === -1) {+ return ids+ }++ inFence = false++ for (let index = headerIndex + 1; index < lines.length; index += 1) {+ const line = lines[index]++ if (FENCE_TOGGLE_RE.test(line)) {+ inFence = !inFence++ continue+ }++ if (inFence) {+ continue+ }++ const match = line.match(SOURCE_LIST_ENTRY_RE)++ if (match) {+ for (const id of match[1].split(',')) {+ ids.add(id.trim())+ }+ }+ }++ return ids+}++function rewriteProseSegment(segment: string, sourceListIds: Set<string>): string {return linkifySessionRefs(escapeLoneTildes(autoLinkRawUrls(routeFileLinksToPreview(escapeUnknownHtmlLikeTags(- segment.replace(/`{3,}/g, '').replace(CITATION_TRANSPORT_MARKER_RE, '').replace(CITATION_MARKER_RE, '')+ segment+ .replace(/`{3,}/g, '')+ .replace(CITATION_TRANSPORT_MARKER_RE, '')+ .replace(CITATION_MARKER_RE, marker => {+ const ids = marker+ .slice(1, -1)+ .split(',')+ .map(id => id.trim())++ return ids.every(id => sourceListIds.has(id)) ? marker : ''+ }))))@@ -483,7 +566,7 @@ export function shieldDirectiveLines(text: string): string {* `startsWith('$')` test, so a prose segment that merely opens with a stray* dollar can't be mistaken for math.*/-function normalizeVisibleProse(text: string): string {+function normalizeVisibleProse(text: string, sourceListIds: Set<string>): string {return text.split(INLINE_CODE_SPLIT_RE).map(part =>@@ -491,7 +574,7 @@ function normalizeVisibleProse(text: string): string {? part: part.split(MATH_SPAN_SPLIT_RE)- .map((segment, index) => (index % 2 === 1 ? segment : rewriteProseSegment(segment)))+ .map((segment, index) => (index % 2 === 1 ? segment : rewriteProseSegment(segment, sourceListIds))).join('')).join('')@@ -982,6 +1065,10 @@ export function preprocessMarkdown(text: string): string {const scrubbed = scrubBacktickNoise(cleaned)const normalizedFences = normalizeFenceBlocks(scrubbed)const strippedEmptyFences = stripEmptyFenceBlocks(normalizedFences)+ // Anchors come from the response's `Sources` section only: a marker+ // survives the orphan strip exactly when this response lists a matching+ // `[n] url` entry there (see collectSourceListIds).+ const sourceListIds = collectSourceListIds(strippedEmptyFences)return strippedEmptyFences.split(CODE_FENCE_SPLIT_RE)@@ -998,7 +1085,7 @@ export function preprocessMarkdown(text: string): string {// Directive lines are shielded last, after the prose rewrites have had// their look, so nothing re-introduces markdown into them.return shieldDirectiveLines(- clampHtmlNestingDepth(normalizeVisibleProse(stripPreviewTargets(normalizeProseMath(part))))+ clampHtmlNestingDepth(normalizeVisibleProse(stripPreviewTargets(normalizeProseMath(part)), sourceListIds)))}).join('')