Skip to content

The agent that grows with you

4.9 KB
Raw Blame
import remarkGfm from 'remark-gfm'
import remarkParse from 'remark-parse'
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
 * hands the paragraph over as ONE text node; the moment an attribute value
 * reads as markdown the paragraph splits into element children and the raw
 * directive paints as the user's message. These are the shapes that leaked.
 */

// The paragraph's children as the renderer will see them, after preprocess.
function paragraphChildren(markdown: string) {
  const tree = unified().use(remarkParse).use(remarkGfm).parse(preprocessMarkdown(markdown)) as {
    children: { children?: { type: string; value?: string }[] }[]
  }

  return tree.children[0]?.children ?? []
}

const briefs = [
  'Track monarch sightings *by week* and plot them',
  'Track a_b and c_d values across runs',
  'Sync ~/notes to ~/backup nightly',
  'Wrap the `run` command with retries',
  'Compare <before> and <after> snapshots',
  'Parse [id] tokens and \\n escapes'
]

describe('preprocessMarkdown / directive lines', () => {
  it.each(briefs)('stays one text node with brief: %s', brief => {
    const line = `::onboarding{step="handoff" task="Tracker" brief="${brief}" plan="build"}`
    const children = paragraphChildren(line)

    expect(children.map(child => child.type)).toEqual(['text'])
    // The parser eats the escapes, so the directive arrives as written.
    expect(children[0]?.value).toBe(line)
  })

  it('leaves the surrounding prose to markdown', () => {
    const text = 'Perfect, that is *all* I needed.\n\n::onboarding{step="handoff" task="T" brief="a_b" plan="build"}'

    const tree = unified().use(remarkParse).use(remarkGfm).parse(preprocessMarkdown(text)) as {
      children: { children?: { type: string }[] }[]
    }

    expect(tree.children[0]?.children?.map(child => child.type)).toEqual(['text', 'emphasis', 'text'])
    expect(tree.children[1]?.children?.map(child => child.type)).toEqual(['text'])
  })

  it('does not touch a directive inside a code fence', () => {
    const text = '```\n::onboarding{step="handoff" brief="a_b"}\n```'

    expect(preprocessMarkdown(text)).toBe(text)
  })

  it('does not touch prose that merely contains ::', () => {
    // The `::` itself is never structure, but `<int>` is an unknown html-like
    // token: escaping it to entities is the #53953 behavior (the renderer
    // would otherwise swallow it), and it paints identically as literal text.
    const text = 'Use std::vector<int> for *speed*.'

    expect(preprocessMarkdown(text)).toBe('Use std::vector&lt;int&gt; 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 })
  })

  it('keeps an explicit markdown link inside directive-like text clickable', () => {
    const children = rendered('::example{\nSee [docs](https://example.com)\n}').children[0]?.children ?? []

    expect(children.filter(child => child.type === 'link').map(child => child.url)).toEqual(['https://example.com'])
  })
})

function directiveAttrs(text: string) {
  const segment = segmentTranscriptDirectives(text)?.find(part => part.kind === 'directive')

  return segment?.kind === 'directive' ? segment.directive.attrs : null
}