// @vitest-environment jsdom import { act as reactAct, type ReactNode } from "react"; import { flushSync } from "react-dom"; import { createRoot, type Root } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, describe, expect, it, vi } from "vitest"; import { ThemeProvider } from "../context/ThemeContext"; import { TooltipProvider } from "./ui/tooltip"; import { ActorProfileIdentity, CommentKvLabelsBar, resolveActorProfileAttribution, } from "./CommentStructuredMeta"; import { MarkdownBody } from "./MarkdownBody"; import { extractFencedSchemaBlocks, getUnfencedSchemaBlocks, hasMatchingSchemaBlock, SchemaBlockCard, StandaloneSchemaBlockList, } from "./SchemaBlockCard"; import { resolveIssueChatHumanAuthor } from "../lib/issue-chat-human-author"; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; vi.mock("@/lib/router", () => ({ Link: ({ to, children, className }: { to: string; children: ReactNode; className?: string }) => ( {children} ), useCaseHref: () => () => "#", })); let container: HTMLDivElement | null = null; let root: Root | null = null; async function act(callback: () => void | Promise) { if (typeof reactAct === "function") { await reactAct(callback); return; } let result: void | Promise = undefined; flushSync(() => { result = callback(); }); await result; await new Promise((resolve) => setTimeout(resolve, 0)); } async function renderNode(node: ReactNode) { const queryClient = new QueryClient(); container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); await act(() => { root!.render( {node} , ); }); return container; } afterEach(async () => { if (root) { await act(() => { root?.unmount(); }); root = null; } container?.remove(); container = null; }); describe("SchemaBlockCard and MarkdownBody schema fences", () => { it("renders built-in finding@1, test-report@1, git-commit@1, pull-request@1, and custom schemas with JSON toggle", async () => { const markdown = [ "```json schema=finding@1", JSON.stringify({ severity: "critical", title: "Missing CSRF check on token endpoint", path: "server/src/routes/auth.ts", line: 88, recommendation: "Require Origin validation before issuing session cookie.", }), "```", "", "```json schema=test-report@1", JSON.stringify({ passed: false, total: 10, failed: 1, skipped: 1, durationMs: 1450, failures: [{ name: "rejects cross-origin POST", message: "Expected 403, got 200" }], }), "```", "", "```json schema=git-commit@1", JSON.stringify({ sha: "abcdef1234567890", branch: "fix/csrf", message: "fix(auth): enforce csrf check", filesChanged: 2, insertions: 18, deletions: 3, }), "```", "", "```json schema=pull-request@1", JSON.stringify({ number: 901, state: "open", title: "Enforce CSRF origin check", head: "fix/csrf", base: "master", url: "https://github.com/paperclipai/paperclip/pull/901", }), "```", "", "```json schema=deploy-receipt@2", JSON.stringify({ environment: "staging", healthy: true, }), "```", ].join("\n"); const dom = await renderNode({markdown}); const cards = dom.querySelectorAll('[data-testid="schema-block-card"]'); expect(cards).toHaveLength(5); expect(dom.textContent).toContain("finding@1"); expect(dom.textContent).toContain("Missing CSRF check on token endpoint"); expect(dom.textContent).toContain("server/src/routes/auth.ts:88"); expect(dom.textContent).toContain("test-report@1"); expect(dom.textContent).toContain("rejects cross-origin POST"); expect(dom.textContent).toContain("git-commit@1"); expect(dom.textContent).toContain("abcdef1"); expect(dom.textContent).toContain("+18"); expect(dom.textContent).toContain("pull-request@1"); expect(dom.textContent).toContain("fix/csrf -> master"); const prLink = dom.querySelector('a[href="https://github.com/paperclipai/paperclip/pull/901"]'); expect(prLink).not.toBeNull(); expect(dom.textContent).toContain("deploy-receipt@2"); expect(dom.textContent).toContain("staging"); // Toggle first card to JSON view const jsonToggle = cards[0]!.querySelectorAll("button")[1]!; expect(jsonToggle.textContent).toBe("JSON"); await act(() => { jsonToggle.click(); }); expect(cards[0]!.querySelector("pre")?.textContent).toContain( '"title": "Missing CSRF check on token endpoint"', ); }); it("rejects non-https URLs in pull-request@1 and falls back to code block on malformed JSON", async () => { const markdown = [ "```json schema=finding@1", "{ not valid json", "```", ].join("\n"); const dom = await renderNode( <> {markdown} , ); // Malformed JSON falls back to standard code block expect(dom.querySelectorAll('[data-testid="schema-block-card"]')).toHaveLength(1); expect(dom.querySelector(".paperclip-markdown-codeblock")?.textContent).toContain( "{ not valid json", ); // Unsafe URL is never rendered as an anchor href expect(dom.querySelector('a[href^="javascript:"]')).toBeNull(); }); it("deduplicates standalone schemaBlocks already rendered in markdown fences", async () => { const block = { schema: "finding", version: 1, data: { severity: "low", title: "Minor lint note" }, }; const fencedMd = `Summary\n\n\`\`\`json schema=finding@1\n${JSON.stringify(block.data, null, 2)}\n\`\`\``; expect(getUnfencedSchemaBlocks(fencedMd, [block])).toHaveLength(0); expect(getUnfencedSchemaBlocks("Plain text body", [block])).toHaveLength(1); const dom = await renderNode(
{fencedMd}
, ); expect(dom.querySelectorAll('[data-testid="schema-block-card"]')).toHaveLength(2); // Ensure deeply nested objects neither blow the stack nor collide when leaf values differ let deepNestedA: Record = { leaf: "alpha" }; let deepNestedB: Record = { leaf: "beta" }; for (let i = 0; i < 40; i += 1) { deepNestedA = { child: deepNestedA }; deepNestedB = { child: deepNestedB }; } const deepBlockA = { schema: "deep-test", version: 1, data: deepNestedA }; const deepBlockB = { schema: "deep-test", version: 1, data: deepNestedB }; const deepMd = `\`\`\`json schema=deep-test@1\n${JSON.stringify(deepNestedA)}\n\`\`\``; expect(getUnfencedSchemaBlocks(deepMd, [deepBlockA])).toHaveLength(0); expect(getUnfencedSchemaBlocks(deepMd, [deepBlockB])).toEqual([deepBlockB]); }); it("scans thousands of repeated unterminated ```json lines in linear time without backtracking", () => { const craftedUnterminated = "```json schema=finding@1\n".repeat(5_000); const startMs = performance.now(); const blocks = extractFencedSchemaBlocks(craftedUnterminated); const matched = hasMatchingSchemaBlock("finding@1", { markdownBodies: [craftedUnterminated], }); const elapsedMs = performance.now() - startMs; expect(blocks).toEqual([]); expect(matched).toBe(false); expect(elapsedMs).toBeLessThan(100); }); it("matches schema fences after >64 ordinary JSON fences and marks oversized bodies unverified instead of missing", async () => { const { checkMatchingSchemaBlock } = await import("../lib/schema-block-utils"); const ordinaryFences = '```json\n{"plain":true}\n```\n'.repeat(80); const trailingResult = '```json schema=test-report@1\n{"passed":true}\n```'; expect( checkMatchingSchemaBlock("test-report@1", { markdownBodies: [`${ordinaryFences}\n${trailingResult}`], }), ).toBe("matched"); const hugePrefix = "x".repeat(600 * 1024); expect( checkMatchingSchemaBlock("test-report@1", { markdownBodies: [`${hugePrefix}\n${trailingResult}`], }), ).toBe("unverified"); // Ensure a 512 KiB cutoff landing right after ``` on a line with trailing text // does not accept an incomplete line as a closing fence. const openFenceAndJson = '```json schema=test-report@1\n{"passed":true}\n'; const padBeforeCutLine = "p".repeat(512 * 1024 - openFenceAndJson.length - 4) + "\n"; const cutNonClosingLine = `${padBeforeCutLine}${openFenceAndJson}\`\`\`not-a-closing-fence\n`; expect(extractFencedSchemaBlocks(cutNonClosingLine)).toEqual([]); expect( checkMatchingSchemaBlock("test-report@1", { markdownBodies: [cutNonClosingLine], }), ).toBe("unverified"); }); }); describe("Comment profile attribution and key-value chips", () => { it("renders --as profile attribution (delegated user vs local-board) and comment kv_labels chips", async () => { const userLabelMap = new Map([["user-julian", "julian"]]); const delegated = resolveActorProfileAttribution({ actorProfile: "claude", authorUserId: "user-julian", userLabelMap, }); const localProfile = resolveActorProfileAttribution({ actorProfile: "ci-bot", authorUserId: "local-board", userLabelMap, }); expect(delegated).toEqual({ profile: "claude", viaUserLabel: "julian", isEphemeralProfile: false, }); expect(localProfile).toEqual({ profile: "ci-bot", viaUserLabel: null, isEphemeralProfile: true, }); // Ensure profile comments on local-board are NOT treated as the viewer's own blue bubble expect( resolveIssueChatHumanAuthor({ authorUserId: "local-board", actorProfile: "ci-bot", currentUserId: "local-board", }), ).toEqual({ isCurrentUser: false, authorName: "ci-bot", avatarUrl: null, }); const dom = await renderNode(
, ); expect(dom.textContent).toContain("claude"); expect(dom.textContent).toContain("via julian"); expect(dom.textContent).toContain("ci-bot"); expect(dom.textContent).toContain("profile"); expect(dom.textContent).not.toContain("local-board"); expect(dom.querySelector('[data-testid="comment-kv-labels"]')?.textContent).toContain( "status=fixed", ); }); });