Skip to content

The agent that grows with you

fix(desktop): plugin directives whose attributes hold a URL render as cards

Tekniumd9de072af401
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.tsx
index 93906148d1a..01b4039bcbf 100644
--- a/apps/desktop/src/components/assistant-ui/markdown-text.tsx
+++ b/apps/desktop/src/components/assistant-ui/markdown-text.tsx
@@ -39,6 +39,7 @@ import {
import { previewTargetFromMarkdownHref } from '@/lib/preview-targets'
import { remarkSoftBreaks } from '@/lib/remark-soft-breaks'
import { sessionRefFromMarkdownHref } from '@/lib/session-refs'
+import { remarkTranscriptDirectives } from '@/lib/transcript-directives'
import { cn } from '@/lib/utils'
import { useForcedTextDirection } from '@/store/text-direction'
@@ -97,7 +98,7 @@ function useCodePlugin(): CodePlugin | null {
return plugin
}
-const REMARK_PLUGINS = [...Object.values(defaultRemarkPlugins), remarkSoftBreaks]
+const REMARK_PLUGINS = [...Object.values(defaultRemarkPlugins), remarkTranscriptDirectives, remarkSoftBreaks]
// Replaces Streamdown's `parseIncompleteMarkdown` (full-text remend per
// flush) with a tail-bounded repair. Must stay module-scope so the prop
diff --git a/apps/desktop/src/lib/markdown-preprocess.directives.test.ts b/apps/desktop/src/lib/markdown-preprocess.directives.test.ts
index 748e4ba9ded..5351dad085d 100644
--- a/apps/desktop/src/lib/markdown-preprocess.directives.test.ts
+++ b/apps/desktop/src/lib/markdown-preprocess.directives.test.ts
@@ -4,6 +4,7 @@ import { unified } from 'unified'
import { describe, expect, it } from 'vitest'
import { preprocessMarkdown } from './markdown-preprocess'
+import { remarkTranscriptDirectives, segmentTranscriptDirectives } from './transcript-directives'
/**
* A transcript directive (`::onboarding{...}`) is a card only while the parser
@@ -66,3 +67,46 @@ describe('preprocessMarkdown / directive lines', () => {
expect(preprocessMarkdown(text)).toBe('Use std::vector<int> for *speed*.')
})
})
+
+describe('preprocessMarkdown / directive attributes holding URLs', () => {
+ // A signed CDN URL: `_`, `~`, `*`, `&` in the query, exactly what the prose
+ // rewrites (autolinker, tilde/currency escaping) and the parser each read
+ // as markup.
+ const url =
+ 'https://assets.example.com/t/01a/model.glb?Expires=1761000000&Signature=ab~cd_ef-gh__ij*k&Key-Pair-Id=K2X_Y'
+
+ // The renderer's pipeline: preprocess, parse with GFM, then the directive fold.
+ function rendered(markdown: string) {
+ const processor = unified().use(remarkParse).use(remarkGfm).use(remarkTranscriptDirectives)
+
+ return processor.runSync(processor.parse(preprocessMarkdown(markdown))) as unknown as {
+ children: { children?: { type: string; url?: string; value?: string }[] }[]
+ }
+ }
+
+ it.each([
+ `::meshy-model{url="${url}" title="Fox_v2" task="01a"}`,
+ `Here it is: ::meshy-model{url="${url}" title="Fox_v2" task="01a"}`
+ ])('reaches the directive parser exactly as written: %s', line => {
+ const children = rendered(line).children[0]?.children ?? []
+
+ expect(children.map(child => child.type)).toEqual(['text'])
+ expect(directiveAttrs(children[0]?.value ?? '')).toEqual({ url, title: 'Fox_v2', task: '01a' })
+ })
+
+ it('still autolinks a URL in the prose around it', () => {
+ const tree = rendered(`See https://example.com/a_b and [docs](https://ex.com/d).\n\n::meshy-model{url="${url}"}`)
+
+ expect(tree.children[0]?.children?.filter(child => child.type === 'link').map(child => child.url)).toEqual([
+ 'https://example.com/a_b',
+ 'https://ex.com/d'
+ ])
+ expect(directiveAttrs(tree.children[1]?.children?.[0]?.value ?? '')).toEqual({ url })
+ })
+})
+
+function directiveAttrs(text: string) {
+ const segment = segmentTranscriptDirectives(text)?.find(part => part.kind === 'directive')
+
+ return segment?.kind === 'directive' ? segment.directive.attrs : null
+}
diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.ts
index 203cd1df8ec..0e8a4cbc598 100644
--- a/apps/desktop/src/lib/markdown-preprocess.ts
+++ b/apps/desktop/src/lib/markdown-preprocess.ts
@@ -6,6 +6,7 @@ import { mediaKind, mediaMarkdownHref } from '@/lib/media'
import { previewMarkdownHref } from '@/lib/preview-targets'
import { stripPreviewTargets } from '@/lib/preview-targets'
import { linkifySessionRefs } from '@/lib/session-refs'
+import { DIRECTIVE_WITH_BODY_RE } from '@/lib/transcript-directives'
// Same tag set as agent/think_scrubber.py THINK_TAG_NAMES, plus desktop-only
// `scratchpad`/`analysis`.
@@ -113,10 +114,6 @@ const URL_LIKE_SPLIT_RE = /(<https?:\/\/[^>\s]+>|https?:\/\/[^\s<>"'`*]+[^\s<>"'
// literal tilde, so CJK ranges (`1~10`) and approximation prefixes (`~¥0.089`)
// no longer pair up into a GFM strikethrough span.
const LONE_TILDE_RE = /(?<![\\~])~(?!~)/g
-// Same shape as DIRECTIVE_LINE_RE, anchored to a single line: escapeLoneTildes
-// tests one line at a time and must not carry the shared regex's `g` flag
-// (stateful lastIndex would skip every other directive line).
-const DIRECTIVE_LINE_ONLY_RE = /^[ \t]*::[a-z][a-z0-9-]{0,63}\{[^{}\n]{0,1024}\}[ \t]*$/
// HTML-shaped prose tokens (`<tool_call>`, `<observation>`...) that are NOT
// real inline elements get swallowed by the HTML-aware renderer (parse5 sees
// an unclosed tag and consumes the rest of the message). Match unknown tag-like
@@ -224,14 +221,17 @@ const FENCE_TOGGLE_RE = /^[ \t]*(?:```|~~~)/
const FILE_LINK_RE =
/(?<!!)\[(?<label>[^\]\n]+)\]\((?<target>(?:<(?:file:\/\/|\/|~\/|[a-z]:[\\/])[^>]*>)|(?:file:\/\/|\/|~\/|[a-z]:[\\/])[^)\s]*)\)/gi
-// A transcript directive on its own line: `::name{...}`. Attribute values are
-// prose the model wrote (a task brief, a question) and read as markdown to the
-// parser — `*by week*` becomes <em>, `a_b c_d` becomes <em>, `~/x` opens
-// strikethrough. Any of those splits the paragraph into element children, the
-// directive stops being text-only, and the raw line paints as the user's
-// message. Same shape as lib/transcript-directives.ts DIRECTIVE_RE.
-const DIRECTIVE_LINE_RE = /^([ \t]*)(::[a-z][a-z0-9-]{0,63}\{[^{}\n]{0,1024}\})[ \t]*$/gm
-const MARKDOWN_INLINE_META_RE = /[\\`*_~[\]<>]/g
+// Transcript directives (`::name{...}`) carry DATA in their attributes: a task
+// brief, a signed URL with `_`/`~`/`&` in its query. Every prose rewrite here
+// corrupts them (the URL autolinker wraps `url="https://…"` in `<…>`, currency
+// escaping leaves `\$`), and the parser reads what survives as markdown
+// (`*by week*` → <em>, `~/x` → strikethrough), splitting the paragraph so the
+// card is never claimed. So directives are lifted out before the rewrites and
+// put back with every inline metachar backslash-escaped; the parser consumes
+// the escapes and the renderer sees the directive byte-for-byte.
+const MARKDOWN_INLINE_META_RE = /[\\`*_~[\]<>$&]/g
+const DIRECTIVE_SLOT_RE = /\uE000(\d+)\uE001/g
+const DIRECTIVE_OR_CODE_RE = new RegExp(`(${DIRECTIVE_WITH_BODY_RE.source})|${INLINE_CODE_SPLIT_RE.source}`, 'g')
/**
* Returns true when `body` contains a line that's exactly `marker` (modulo
@@ -485,16 +485,7 @@ function escapeLoneTildes(text: string): string {
return part
}
- // Directive lines are shielded verbatim further down the pipeline:
- // shieldDirectiveLines backslash-escapes every inline metachar (`~`
- // included) so the card value arrives as ONE text node. Escaping a `~`
- // here would leave `\\~` after the shield doubles the backslash, and the
- // parser then emits the stray `\` into the directive's rendered value
- // (#50871 follow-up: `brief="Sync ~/notes to ~/backup nightly"`).
- return part
- .split('\n')
- .map(line => (DIRECTIVE_LINE_ONLY_RE.test(line) ? line : line.replace(LONE_TILDE_RE, '\\~')))
- .join('\n')
+ return part.replace(LONE_TILDE_RE, '\\~')
})
.join('')
}
@@ -609,19 +600,31 @@ function rewriteProseSegment(segment: string, sourceListIds: Set<string>): strin
}
/**
- * Backslash-escape markdown inline syntax inside directive lines so the parser
- * yields one text node. The escapes are consumed by the parser, so the
- * directive the renderer sees is byte-for-byte what the model wrote.
+ * Lift every directive outside inline code out of `text`, leaving a slot the
+ * prose rewrites cannot match. `restore` puts each back shielded: inline
+ * markdown backslash-escaped so the parser yields it as plain text.
*/
-export function shieldDirectiveLines(text: string): string {
- if (!text.includes('::')) {
- return text
+function liftDirectives(text: string): { text: string; restore: (rewritten: string) => string } {
+ const lifted: string[] = []
+
+ if (text.includes('::') && !text.includes('\uE000')) {
+ // One leftmost-wins scan: a code span that opens first keeps a directive
+ // inside it as code; a directive that opens first keeps the backticks in
+ // its attribute values (`brief="wrap the `run` command"`) as data.
+ text = text.replace(DIRECTIVE_OR_CODE_RE, (match, directive?: string) =>
+ directive ? `\uE000${lifted.push(directive) - 1}\uE001` : match
+ )
}
- return text.replace(
- DIRECTIVE_LINE_RE,
- (_match, indent: string, directive: string) => indent + directive.replace(MARKDOWN_INLINE_META_RE, '\\$&')
- )
+ return {
+ text,
+ restore: rewritten =>
+ lifted.length === 0
+ ? rewritten
+ : rewritten.replace(DIRECTIVE_SLOT_RE, (_slot, index: string) =>
+ lifted[Number(index)].replace(MARKDOWN_INLINE_META_RE, '\\$&')
+ )
+ }
}
/**
@@ -1152,10 +1155,11 @@ export function preprocessMarkdown(text: string): string {
// blocks stay intact. The HTML-depth clamp belongs here for the same
// reason: a fenced block renders as code and never reaches rehype-raw,
// so escaping tags inside one would corrupt the listing for nothing.
- // 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)), sourceListIds))
+ // Directives sit out the rewrites entirely (see liftDirectives).
+ const { text: prose, restore } = liftDirectives(part)
+
+ return restore(
+ clampHtmlNestingDepth(normalizeVisibleProse(stripPreviewTargets(normalizeProseMath(prose)), sourceListIds))
)
})
.join('')
diff --git a/apps/desktop/src/lib/transcript-directives.test.ts b/apps/desktop/src/lib/transcript-directives.test.ts
index b579dea5620..1b949f5ee02 100644
--- a/apps/desktop/src/lib/transcript-directives.test.ts
+++ b/apps/desktop/src/lib/transcript-directives.test.ts
@@ -43,3 +43,15 @@ describe('segmentTranscriptDirectives', () => {
expect(segmentTranscriptDirectives(`::x{${'a="b" '.repeat(1000)}}`)).toBeNull()
})
})
+
+describe('segmentTranscriptDirectives / long attribute values', () => {
+ it('parses a directive carrying two signed URLs', () => {
+ // Signed CDN URLs run 500-1,000 chars; a model card names a model and its thumbnail.
+ const signed = (name: string) => `https://cdn.example.com/${name}?Signature=${'s'.repeat(800)}&Key-Pair-Id=K`
+ const text = `::model{url="${signed('m.glb')}" thumb="${signed('t.png')}" title="Fox"}`
+
+ expect(directive(text)).toMatchObject({
+ directive: { attrs: { url: signed('m.glb'), thumb: signed('t.png'), title: 'Fox' } }
+ })
+ })
+})
diff --git a/apps/desktop/src/lib/transcript-directives.ts b/apps/desktop/src/lib/transcript-directives.ts
index a70919e88dc..0ce4d9de236 100644
--- a/apps/desktop/src/lib/transcript-directives.ts
+++ b/apps/desktop/src/lib/transcript-directives.ts
@@ -51,9 +51,108 @@ export interface ParsedTranscriptDirective {
export type TranscriptParagraphSegment =
{ kind: 'prose'; text: string } | { kind: 'directive'; directive: ParsedTranscriptDirective }
+// Brace-body cap. A signed CDN URL alone runs 500–1,000+ chars (Meshy's are
+// ~520), and a directive must fit two of them plus a title. Still a bound, so
+// the attr scan stays linear on adversarial input.
+export const DIRECTIVE_BODY_MAX = 2048
+
// `::name` or `::name{...}`, anywhere a word can start — so `std::vector` is
-// never a directive. Length caps bound the attr scan on adversarial input.
-const SEGMENT_RE = /(?<=^|\s)::([a-z][a-z0-9-]{0,63})(?:\{([^{}]{0,1024})\})?/g
+// never a directive.
+const SEGMENT_RE = new RegExp(
+ String.raw`(?<=^|\s)::([a-z][a-z0-9-]{0,63})(?:\{([^{}]{0,${DIRECTIVE_BODY_MAX}})\})?`,
+ 'g'
+)
+
+/** A directive with a brace body on one line: the span markdown preprocessing
+ * must hand to the parser untouched (its attributes are data, not prose). */
+export const DIRECTIVE_WITH_BODY_RE = new RegExp(
+ String.raw`(?<=^|\s)::[a-z][a-z0-9-]{0,63}\{[^{}\n]{0,${DIRECTIVE_BODY_MAX}}\}`,
+ 'g'
+)
+
+// A text node that opens a directive brace it never closes.
+const OPEN_DIRECTIVE_RE = /(?<=^|\s)::[a-z][a-z0-9-]{0,63}\{[^{}]*$/
+
+interface MdNode {
+ children?: MdNode[]
+ type: string
+ value?: string
+}
+
+function inlineText(node: MdNode): string | null {
+ if (node.type === 'text') {
+ return node.value ?? ''
+ }
+
+ // A GFM literal autolink keeps its source verbatim, backslash escapes
+ // included (preprocess escapes `_`/`&`/`~` inside directives); a URL never
+ // holds a literal `\`, so drop the CommonMark escapes to get it as written.
+ if (node.type === 'link' && node.children?.every(child => child.type === 'text')) {
+ return node.children.map(child => (child.value ?? '').replace(/\\([!-/:-@[-`{-~])/g, '$1')).join('')
+ }
+
+ return null
+}
+
+function foldDirectiveRuns(node: MdNode) {
+ const kids = node.children
+
+ if (!kids) {
+ return
+ }
+
+ const out: MdNode[] = []
+
+ for (let i = 0; i < kids.length; i += 1) {
+ const child = kids[i]
+
+ if (child.type === 'text' && OPEN_DIRECTIVE_RE.test(child.value ?? '')) {
+ let merged = child.value ?? ''
+ let closed = -1
+
+ for (let j = i + 1; j < kids.length && merged.length <= 4800; j += 1) {
+ const piece = inlineText(kids[j])
+
+ if (piece === null) {
+ break
+ }
+
+ merged += piece
+
+ if (piece.includes('}')) {
+ closed = j
+
+ break
+ }
+ }
+
+ if (closed !== -1) {
+ // Re-scan the folded node: its tail may open the next directive.
+ kids[closed] = { type: 'text', value: merged }
+ i = closed - 1
+
+ continue
+ }
+ }
+
+ foldDirectiveRuns(child)
+ out.push(child)
+ }
+
+ node.children = out
+}
+
+/**
+ * remark plugin. GFM links every bare URL in a text node — including one
+ * inside a directive attribute (`url="https://…"`) — and that link element
+ * splits the paragraph, so it is no longer text-only and the card is never
+ * claimed. Fold a run that opens a directive brace in a text node and closes
+ * it within text/link siblings back into one text node; the link's text is
+ * the URL as written, so the directive comes back byte-for-byte.
+ */
+export function remarkTranscriptDirectives() {
+ return (tree: MdNode) => foldDirectiveRuns(tree)
+}
// `key="value"` pairs; single quotes accepted for model sloppiness.
const ATTR_RE = /([a-z][\w-]{0,63})=(?:"([^"]*)"|'([^']*)')/gi
@@ -62,7 +161,8 @@ function parseAttrs(body: string | undefined): ParsedTranscriptDirective['attrs'
const attrs: Record<string, string> = {}
for (const pair of (body ?? '').matchAll(ATTR_RE)) {
- attrs[pair[1].toLowerCase()] = pair[2] ?? pair[3] ?? ''
+ // Models copy the `<https://…>` autolink form into attributes too.
+ attrs[pair[1].toLowerCase()] = (pair[2] ?? pair[3] ?? '').replace(/^<(https?:\/\/[^<>\s]+)>$/i, '$1')
}
return attrs