Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

6.4 KB
Raw Blame
import assert from "node:assert/strict";
import test from "node:test";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { createInstance } from "i18next";
import { I18nextProvider } from "react-i18next";
import { catalogs } from "@pi-desktop/i18n";
import { createServer } from "vite";
import { fileURLToPath } from "node:url";

/*
 * Issue #449: assistant replies that emit TeX `\[ … \]` display delimiters used
 * to reach the transcript as raw text. These cases render the real
 * `Markdown.tsx` through Vite SSR, so the whole production chain runs:
 * block splitting, `remark-math`, the TeX bracket normalizer, `rehype-raw`,
 * `rehype-sanitize` and `rehype-katex`.
 */
test("TeX math and wrapped HTTP links render through the production Markdown pipeline", async () => {
  const server = await createServer({
    root: fileURLToPath(new URL("..", import.meta.url)),
    configFile: false,
    server: { middlewareMode: true, hmr: false, ws: false },
    esbuild: { jsx: "automatic" },
    appType: "custom",
    optimizeDeps: { noDiscovery: true, include: [] },
  });
  const originalDocument = globalThis.document;
  try {
    // `useThemeMode` reads the theme off the document during render.
    globalThis.document = { documentElement: { dataset: {} } };
    const { Markdown } = await server.ssrLoadModule(
      "/src/components/Markdown.tsx",
    );
    const i18n = createInstance();
    await i18n.init({
      lng: "en",
      resources: { en: { translation: catalogs.en } },
    });
    const render = (source, streaming = false) =>
      renderToStaticMarkup(
        createElement(
          I18nextProvider,
          { i18n },
          createElement(Markdown, { source, streaming }),
        ),
      );
    const display = (html) => html.includes("katex-display");
    const inline = (html) =>
      html.includes('class="katex"') && !html.includes("katex-display");

    for (const streaming of [false, true]) {
      for (const [source, body] of [
        ['这是**“重点内容”**,请查看。', '“重点内容”'],
        ['这是**重点。**后续内容。', '重点。'],
        ['这是**(重点)**后续内容。', '(重点)'],
      ]) {
        const html = render(source, streaming);
        assert.match(html, new RegExp(`<strong[^>]*>${body}</strong>`));
        assert.doesNotMatch(html, /\*\*/);
        assert.ok(html.includes(`data-source-end="${source.length}"`));
      }
    }

    // A nested linked-host destination must be normalized before the
    // production rehype sanitizer removes its invalid wrapper href.
    const wrappedLink = render(
      "[#1106](([github.com](https://github.com/vastsa/PI-Desktop/issues/1106)))",
    );
    assert.match(
      wrappedLink,
      /<a[^>]*href="https:\/\/github\.com\/vastsa\/PI-Desktop\/issues\/1106"/,
    );
    assert.match(wrappedLink, /target="_blank"/);

    // The issue's exact replies: a display formula on its own lines.
    const issueMultiline = render("\\[\nD \\leftrightarrow H\n\\]");
    assert.match(issueMultiline, /katex-display/);
    assert.doesNotMatch(issueMultiline, /\\\[/);
    const issueText = render(
      "\\[\n\\text{Data-RSI} \\leftrightarrow \\text{Harness-RSI}\n\\]",
    );
    assert.match(issueText, /katex-display/);
    // KaTeX keeps the TeX source in its MathML annotation, so only the bracket
    // delimiters (which used to leak as visible text) are checked here.
    assert.doesNotMatch(issueText, /\\\[|\\\]/);

    // TeX brackets are display math in every position, not only as a block:
    // `rehype-sanitize` has to keep `remark-math`'s math class for this to hold.
    for (const source of [
      "\\[a+b\\]",
      "Formally \\[ a+b \\] holds.",
      "Here is the mapping:\n\\[\nD \\leftrightarrow H\n\\]",
      "prose in between\n\n\\[\nX \\leftrightarrow Y\n\\]",
    ]) {
      assert.equal(display(render(source)), true, `expected display math: ${source}`);
    }

    // Inline code never turns into math. Fenced blocks and mermaid fences are
    // exercised at DOM level instead: `HighlightedCode` reads a browser-only
    // external store, so a fenced block cannot be server-rendered at all.
    const codeSpan = render("run `\\(inline\\)` now");
    assert.match(codeSpan, /<code[^>]*>\\\(inline\\\)<\/code>/);
    assert.doesNotMatch(codeSpan, /katex/);

    // Escaped and unmatched markers stay literal.
    assert.doesNotMatch(render("\\\\(escaped\\\\)"), /katex/);
    assert.doesNotMatch(render("text \\(unmatched"), /katex/);

    const largeMarkdown = "raw-source-".repeat(12_000);
    const largeMarkdownHtml = render(largeMarkdown);
    assert.match(largeMarkdownHtml, /role="status"/);
    assert.match(largeMarkdownHtml, /data-source-start="0"/);
    assert.match(largeMarkdownHtml, /data-source-end="132000"/);
    assert.match(largeMarkdownHtml, /<pre>raw-source-/);
    assert.doesNotMatch(largeMarkdownHtml, /<p>raw-source-/);

    const streamingMarkdownHtml = render(`# Settled\n\n${"large-tail-".repeat(3_000)}`, true);
    assert.match(streamingMarkdownHtml, /role="status"/);
    assert.match(streamingMarkdownHtml, /<pre># Settled/);
    assert.match(streamingMarkdownHtml, /large-tail-/);

    // Issue #541: display math whose body puts `=`, `-`, `+` or `*` on their
    // own lines used to be shredded by marked's block lexer (setext headings /
    // list markers), which left `\[` and `\]` in different blocks so the
    // delimiters escaped through as literal `[` / `]` and the equation body
    // rendered as prose. All four markers must now stay inside one math node.
    const setextEquals = render(
      "\\[\n\\mathbf{a}\n=\n\\frac{\\partial\\mathbf{u}}{\\partial t}\n\\]",
    );
    assert.match(setextEquals, /katex-display/);
    assert.doesNotMatch(setextEquals, /<h[1-6][ >]/);
    assert.doesNotMatch(setextEquals, /\\\[|\\\]/);

    const setextDash = render("\\[\nx\n-\ny\n\\]");
    assert.match(setextDash, /katex-display/);
    assert.doesNotMatch(setextDash, /<h[1-6][ >]/);

    const listPlus = render(
      "\\[\n\\boxed{\na\n+\nb\n+\nc\n}\n\\]",
    );
    assert.match(listPlus, /katex-display/);
    assert.doesNotMatch(listPlus, /<(ul|ol|li)[ >]/);
    assert.doesNotMatch(listPlus, /\\\[|\\\]/);

    const listStar = render("\\[\n*\na\n\\]");
    assert.match(listStar, /katex-display/);
    assert.doesNotMatch(listStar, /<(ul|ol|li)[ >]/);
  } finally {
    globalThis.document = originalDocument;
    await server.close();
  }
});