// @vitest-environment node
import type { ComponentProps, ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import {
buildAgentMentionHref,
buildIssueReferenceHref,
buildProjectMentionHref,
buildRoutineMentionHref,
buildSkillMentionHref,
buildUserMentionHref,
appearanceForPalette,
} from "@paperclipai/shared";
import { ThemeProvider } from "../context/ThemeContext";
import { companyPathFromProtocolRelativeHref, MarkdownBody } from "./MarkdownBody";
import { StatusIcon } from "./StatusIcon";
import { taskStatusIconProps } from "../lib/task-status-presentation";
import type { IssueBlockerAttention } from "@paperclipai/shared";
import { MarkdownWordStreaming } from "./MarkdownWordStreaming";
import { queryKeys } from "../lib/queryKeys";
import type { WorkspaceFileAvailabilityTarget } from "../lib/workspace-file-availability";
/** Stands in for a server-confirmed openable reference in the issue's workspace. */
const OPENABLE_AUTO_TARGET: WorkspaceFileAvailabilityTarget = {
workspace: "auto",
projectId: null,
workspaceId: null,
projectName: null,
};
const mockIssuesApi = vi.hoisted(() => ({
get: vi.fn(),
}));
vi.mock("@/lib/router", () => ({
Link: ({
children,
to,
...props
}: { children: ReactNode; to: string } & React.ComponentProps<"a">) => (
{children}
),
useLocation: () => ({
pathname: "/PAP/issues/PAP-10306",
search: "",
hash: "",
state: null,
}),
}));
vi.mock("../api/issues", () => ({
issuesApi: mockIssuesApi,
}));
// Defaults to null (no provider) so the existing suite exercises the permissive
// path unchanged. Gating tests override the return value per-case.
const mockUseOptionalCompany = vi.hoisted(() => vi.fn<() => { companies: Array<{ issuePrefix: string }>; selectedCompanyId?: string } | null>(() => null));
vi.mock("../context/CompanyContext", () => ({
useOptionalCompany: mockUseOptionalCompany,
}));
afterEach(() => {
mockUseOptionalCompany.mockReturnValue(null);
});
function renderMarkdown(
children: string,
seededIssues: Array<{ identifier: string; status: string; title?: string; cacheKey?: string; blockerAttention?: IssueBlockerAttention }> = [],
props: Partial> = {},
streaming = false,
) {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
for (const issue of seededIssues) {
queryClient.setQueryData(queryKeys.issues.detail(issue.cacheKey ?? issue.identifier), {
id: issue.identifier,
identifier: issue.identifier,
status: issue.status,
title: issue.title,
...(issue.blockerAttention ? { blockerAttention: issue.blockerAttention } : {}),
});
}
return renderToStaticMarkup(
{children}
,
);
}
describe("MarkdownBody", () => {
it("renders a company link written as //PREFIX/... as that company path", () => {
mockUseOptionalCompany.mockReturnValue({ companies: [{ issuePrefix: "RUN" }] });
const html = renderMarkdown("[Failed run](//RUN/agents/agent-1/runs/run-1)");
expect(html).toContain('href="/RUN/agents/agent-1/runs/run-1"');
expect(html).not.toContain('href="//RUN');
expect(html).not.toContain('target="_blank"');
});
it("keeps the query and fragment of a normalized company link", () => {
expect(companyPathFromProtocolRelativeHref("//RUN/issues/RUN-1#document-plan", ["RUN"])).toBe("/RUN/issues/RUN-1#document-plan");
expect(companyPathFromProtocolRelativeHref("//RUN", ["RUN"])).toBe("/RUN");
expect(companyPathFromProtocolRelativeHref("/RUN/issues/RUN-1", ["RUN"])).toBe("/RUN/issues/RUN-1");
expect(companyPathFromProtocolRelativeHref("https://RUN/x", ["RUN"])).toBe("https://RUN/x");
});
it("leaves protocol-relative links to other hosts unchanged", () => {
mockUseOptionalCompany.mockReturnValue({ companies: [{ issuePrefix: "RUN" }] });
expect(renderMarkdown("[Docs](//docs.example.com/RUN/guide)")).toContain('href="//docs.example.com/RUN/guide"');
expect(renderMarkdown("[Other](//OTHER/agents/a/runs/r)")).toContain('href="//OTHER/agents/a/runs/r"');
mockUseOptionalCompany.mockReturnValue(null);
expect(renderMarkdown("[Unknown](//RUN/agents/a/runs/r)")).toContain('href="//RUN/agents/a/runs/r"');
});
it("preserves a saved document anchor in an explicit task link", () => {
// Hover/focus can resolve the issue to its plain identifier. Both the old
// fragment-bearing cache key and the corrected plain key model that load.
const html = renderMarkdown("[Saved document](/PAP/issues/PAP-1271#document-output)", [
{ identifier: "PAP-1271", status: "done" },
{ identifier: "PAP-1271", status: "done", cacheKey: "PAP-1271#document-output" },
], { linkIssueReferences: true });
expect(html).toContain('href="/PAP/issues/PAP-1271#document-output"');
expect(html).not.toContain("PAP-1271%23document-output");
});
it("renders markdown images without a resolver", () => {
const html = renderToStaticMarkup(
{""}
,
);
expect(html).toContain('
');
});
it("resolves relative image paths when a resolver is provided", () => {
const html = renderToStaticMarkup(
`/resolved/${src}`}>
{""}
,
);
expect(html).toContain('src="/resolved/images/org-chart.png"');
expect(html).toContain('alt="Org chart"');
});
it("renders decision images as inert references without resolving or preloading them", () => {
const resolveImageSrc = vi.fn((src: string) => `https://resolver.invalid/${src}`);
const html = renderMarkdown(
'# Plan\n\n**Keep this step.**\n\n\n\n\n\n',
[], { mediaMode: "reference", resolveImageSrc },
);
expect(html).toContain("Plan
");
expect(html).toContain("Keep this step.");
expect(html).toContain("Image: Evidence (https://provider.invalid/track.png)");
expect(html).toContain('title="Provider image"');
expect(html).toContain("Image: Relative (images/proof.png)");
expect(html).toContain("Image: Protocol relative (//provider.invalid/other.png)");
expect(html).not.toMatch(/<(?:img|link|iframe|video|audio)\b/);
expect(resolveImageSrc).not.toHaveBeenCalled();
});
it("keeps diagram source inert in decision media mode", () => {
const source = 'flowchart LR\n A@{ img: "https://provider.invalid/diagram.png" }';
const html = renderMarkdown(`\`\`\`mermaid\n${source}\n\`\`\``, [], { mediaMode: "reference" });
expect(html).toContain('class="language-mermaid"');
expect(html).toContain("https://provider.invalid/diagram.png");
expect(html).not.toContain('class="paperclip-mermaid"');
expect(html).not.toContain("Rendering Mermaid diagram");
});
it("renders user, agent, project, skill, and routine mentions as chips", () => {
const html = renderToStaticMarkup(
{`[@Taylor](${buildUserMentionHref("user-123")}) [@CodexCoder](${buildAgentMentionHref("agent-123", "code")}) [@Paperclip App](${buildProjectMentionHref("project-456", "#336699")}) [/release-changelog](${buildSkillMentionHref("skill-789", "release-changelog")}) [/routine:Weekly review](${buildRoutineMentionHref("routine-123")})`}
,
);
expect(html).toContain('href="/company/settings/access"');
expect(html).toContain('data-mention-kind="user"');
expect(html).toContain('href="/agents/agent-123"');
expect(html).toContain('data-mention-kind="agent"');
expect(html).toContain("--paperclip-mention-avatar-image");
expect(html).not.toContain("--paperclip-mention-icon-mask");
expect(html).toContain('href="/projects/project-456"');
expect(html).toContain('data-mention-kind="project"');
expect(html).toContain("--paperclip-mention-project-color:#336699");
expect(html).toContain('href="/skills/skill-789"');
expect(html).toContain('data-mention-kind="skill"');
expect(html).toContain('href="/routines/routine-123"');
expect(html).toContain('data-mention-kind="routine"');
});
it("sanitizes unsafe javascript markdown links", () => {
const html = renderMarkdown("[click me](javascript:alert(document.cookie))");
expect(html).toContain('click me");
expect(html).not.toContain("javascript:");
});
it("uses the current company agent appearance for an old saved mention", () => {
mockUseOptionalCompany.mockReturnValue({ companies: [{ issuePrefix: "PAP" }], selectedCompanyId: "company-1" });
const client = new QueryClient();
client.setQueryData(queryKeys.agents.list("company-1"), [
{ id: "agent-123", appearance: appearanceForPalette("electric-grove") },
]);
const html = renderToStaticMarkup(
{`[@CodexCoder](${buildAgentMentionHref("agent-123", "code")})`}
,
);
expect(html).toContain("/cap-v1/electric-grove/rest.png");
expect(html).not.toContain("mention-icon-mask");
});
it("renders raw HTML tags as escaped text", () => {
const html = renderMarkdown(
'\n\nPlain text
',
);
expect(html).not.toContain("