Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatMarkdown.test.tsx

784 lines28.1 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import { act, type ComponentProps, type ReactNode } from "react";
3import { renderToStaticMarkup } from "react-dom/server";
4import { create, type ReactTestRenderer } from "react-test-renderer";
5import { describe, expect, it, vi } from "vite-plus/test";
6​
7import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
8import { Button } from "./ui/button";
9import { setMarkdownTaskChecked } from "./files/filePreviewMode";
10​
11vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
12vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
13vi.mock("../hooks/useSettings", async (importOriginal) => {
14 const actual = await importOriginal<typeof import("../hooks/useSettings")>();
15 const settings = actual.getClientSettings();
16 return {
17 ...actual,
18 useClientSettings: (select?: (value: typeof settings) => unknown) =>
19 select ? select(settings) : settings,
20 };
21});
22vi.mock("./ui/tooltip", async () => {
23 const { cloneElement, isValidElement } = await import("react");
24 return {
25 Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
26 TooltipTrigger({
27 render,
28 children,
29 }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
30 if (!isValidElement(render)) return <>{children}</>;
31 return children === undefined ? render : cloneElement(render, undefined, children);
32 },
33 TooltipPopup: () => null,
34 };
35});
36vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
37vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
38vi.mock("../state/session", async (importOriginal) => ({
39 ...(await importOriginal<typeof import("../state/session")>()),
40 usePreparedConnection: () => ({ _tag: "Loading" }),
41}));
42vi.mock("../state/entities", () => ({
43 readThreadShell: () => null,
44 useProjects: () => [],
45}));
46vi.mock("../remoteOpen", () => ({
47 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
48}));
49vi.mock("../editorPreferences", () => ({
50 useOpenInPreferredEditor: () => vi.fn(),
51 usePreferredEditor: () => [null, vi.fn()],
52}));
53vi.mock("~/lib/openPullRequestLink", () => ({
54 findProjectForChangeRequest: () => undefined,
55 matchesLinkedPullRequestUrl: () => false,
56 parseChangeRequestUrl: () => null,
57 useOpenChangeRequestLink: () => vi.fn(),
58}));
59​
60import ChatMarkdown, {
61 canUseMarkdownFileShellActions,
62 hasMarkdownFilePrimaryAction,
63 orderedListGutterStyle,
64 shouldUseMarkdownFileBrowserPrimaryAction,
65} from "./ChatMarkdown";
66​
67function codeButton(renderer: ReactTestRenderer, label: string) {
68 const button = renderer.root
69 .findAllByType(Button)
70 .find((instance) => instance.props["aria-label"] === label);
71 if (!button) throw new Error(`Missing code button: ${label}`);
72 return button.props as ComponentProps<typeof Button>;
74​
75describe("ChatMarkdown favicon privacy", () => {
76 it("suppresses private link images while preserving public links across updates", async () => {
77 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
78 let renderer: ReactTestRenderer | undefined;
79 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
80 try {
81 await act(async () => {
82 renderer = create(markdown("https://github.com"));
83 });
84 expect(renderer!.root.findAllByType("img").map((image) => image.props.src)).toEqual([
85 "https://www.google.com/s2/favicons?domain=github.com&sz=32",
86 ]);
87 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
88 await act(async () => {
89 renderer!.update(markdown(url));
90 });
91 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
92 }
93 await act(async () => {
94 renderer!.update(markdown("https://github.com"));
95 });
96 expect(renderer!.root.findAllByType("img")).toHaveLength(1);
97 } finally {
98 await act(async () => {
99 renderer?.unmount();
100 });
101 vi.unstubAllGlobals();
102 }
103 });
104});
105​
106describe("ChatMarkdown streaming", () => {
107 it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
108 const highlighter = await getSyntaxHighlighterPromise("text");
109 const codeToHtml = highlighter.codeToHtml.bind(highlighter);
110 let fail = true;
111 vi.spyOn(highlighter, "codeToHtml").mockImplementation((...args) => {
112 if (fail) throw new Error("Temporary highlighter failure");
113 return codeToHtml(...args);
114 });
115 vi.spyOn(console, "error").mockImplementation(() => {});
116 vi.spyOn(console, "warn").mockImplementation(() => {});
117 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
118 let renderer: ReactTestRenderer | undefined;
119​
120 try {
121 await act(async () => {
122 renderer = create(
123 <ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
124 );
125 });
126 const mounted = renderer!;
127 const codeBlock = mounted.root.findByProps({ "data-language": "text" });
128 const initialWrap = codeBlock.props["data-wrap"] === "true";
129 const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
130 await act(async () => {
131 wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
132 });
133 expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(0);
134​
135 fail = false;
136 await act(async () => {
137 mounted.update(
138 <ChatMarkdown cwd="/tmp/project" text={"```text\nrecovered\n```"} isStreaming />,
139 );
140 });
141 expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(1);
142 expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
143 expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
144 } finally {
145 await act(async () => renderer?.unmount());
146 vi.unstubAllGlobals();
147 vi.restoreAllMocks();
148 }
149 });
150​
151 it("preserves code controls and details without highlighting an unchanged fence again", async () => {
152 const highlighter = await getSyntaxHighlighterPromise("text");
153 const highlight = vi.spyOn(highlighter, "codeToHtml");
154 const writeText = vi.fn(async (_text: string) => {});
155 vi.stubGlobal("navigator", { clipboard: { writeText } });
156 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
157 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
158 let renderer: ReactTestRenderer | undefined;
159 const text = [
160 "```text",
161 "First code block",
162 "```",
163 "",
164 "<details><summary>More</summary>",
165 "",
166 "Details content",
167 "",
168 "</details>",
169 "",
170 "Streaming reply",
171 ].join("\n");
172​
173 try {
174 await act(async () => {
175 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
176 });
177 const mounted = renderer!;
178 const codeBlock = mounted.root.findByProps({ "data-language": "text" });
179 const initialWrap = codeBlock.props["data-wrap"] === "true";
180 const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
181 const copy = codeButton(mounted, "Copy code");
182 await act(async () => {
183 wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
184 copy.onClick?.({} as Parameters<NonNullable<typeof copy.onClick>>[0]);
185 });
186​
187 const detailsButton = mounted.root.find(
188 (instance) =>
189 instance.type === "button" && instance.props["data-markdown-details-summary"] === "",
190 );
191 await act(async () => {
192 detailsButton.props.onClick({ nativeEvent: new Event("click") });
193 });
194 const details = mounted.root.findByProps({ "data-markdown-details": "" });
195 expect(details.props["data-markdown-details-open"]).toBe("true");
196 expect(writeText).toHaveBeenCalledWith("First code block\n");
197 expect(highlight).toHaveBeenCalledTimes(1);
198​
199 for (let index = 0; index < 10; index += 1) {
200 await act(async () => {
201 mounted.update(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
202 });
203 }
204​
205 expect(highlight).toHaveBeenCalledTimes(1);
206 expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
207 expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
208 expect(mounted.root.findByProps({ "data-markdown-details": "" })).toBe(details);
209 expect(details.props["data-markdown-details-open"]).toBe("true");
210 await act(async () => {
211 mounted.update(
212 <ChatMarkdown
213 cwd="/tmp/project"
214 text={text.replace("First code block", "Updated code block")}
215 isStreaming
216 />,
217 );
218 });
219 const copyUpdated = codeButton(mounted, "Copied");
220 await act(async () => {
221 copyUpdated.onClick?.({} as Parameters<NonNullable<typeof copyUpdated.onClick>>[0]);
222 });
223 expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
224 expect(highlight).toHaveBeenCalledTimes(2);
225 } finally {
226 await act(async () => renderer?.unmount());
227 vi.useRealTimers();
228 vi.unstubAllGlobals();
229 vi.restoreAllMocks();
230 }
231 });
232​
233 it("edits the current task text and marker after reusing a renderer", async () => {
234 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
235 let renderer: ReactTestRenderer | undefined;
236 let editedText: string | undefined;
237 const message = (text: string) => (
238 <ChatMarkdown
239 cwd="/tmp/project"
240 text={text}
241 onTaskListChange={({ markerOffset, checked }) => {
242 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
243 renderer!.update(message(editedText));
244 }}
245 />
246 );
247​
248 try {
249 await act(async () => {
250 renderer = create(message("- [ ] First\n- [ ] Second"));
251 });
252 const mounted = renderer!;
253 const originalInput = mounted.root.findAllByType("input")[1]!;
254 await act(async () => {
255 mounted.update(message("- [ ] A longer first task\n- [ ] Second"));
256 });
257​
258 const input = mounted.root.findAllByType("input")[1]!;
259 const listItem = mounted.root.findAllByType("li")[1]!;
260 const { onChange } = input.props as ComponentProps<"input">;
261 if (!onChange) throw new Error("Task checkbox has no edit handler");
262 await act(async () => {
263 onChange({
264 currentTarget: {
265 checked: true,
266 closest: () => ({
267 dataset: { taskMarkerOffset: String(listItem.props["data-task-marker-offset"]) },
268 }),
269 },
270 } as unknown as Parameters<typeof onChange>[0]);
271 });
272​
273 expect(input).toBe(originalInput);
274 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
275 expect(mounted.root.findAllByType("input")[1]!.props.checked).toBe(true);
276 } finally {
277 await act(async () => renderer?.unmount());
278 vi.unstubAllGlobals();
279 }
280 });
281});
282​
283describe("canUseMarkdownFileShellActions", () => {
284 const environmentId = EnvironmentId.make("environment-1");
285​
286 it("allows editor and file manager actions for local environments", () => {
287 expect(canUseMarkdownFileShellActions(environmentId, "local-exec", true)).toBe(true);
288 });
289​
290 it("hides shell actions until the environment mode is resolved", () => {
291 expect(canUseMarkdownFileShellActions(environmentId, "local-exec", false)).toBe(false);
292 });
293​
294 it("hides editor and file manager actions for remote environments", () => {
295 expect(canUseMarkdownFileShellActions(environmentId, "remote-links", true)).toBe(false);
296 expect(canUseMarkdownFileShellActions(environmentId, "remote-unavailable", true)).toBe(false);
297 });
298​
299 it("hides shell actions when no environment owns the markdown", () => {
300 expect(canUseMarkdownFileShellActions(null, "local-exec", true)).toBe(false);
301 });
302});
303​
304describe("hasMarkdownFilePrimaryAction", () => {
305 it("keeps the chip interactive when an editor, browser, or panel can open it", () => {
306 expect(
307 hasMarkdownFilePrimaryAction({
308 canOpenInEditor: true,
309 canOpenInBrowser: false,
310 canOpenInPanel: false,
311 }),
312 ).toBe(true);
313 expect(
314 hasMarkdownFilePrimaryAction({
315 canOpenInEditor: false,
316 canOpenInBrowser: true,
317 canOpenInPanel: false,
318 }),
319 ).toBe(true);
320 expect(
321 hasMarkdownFilePrimaryAction({
322 canOpenInEditor: false,
323 canOpenInBrowser: false,
324 canOpenInPanel: true,
325 }),
326 ).toBe(true);
327 });
328​
329 it("removes the link affordance when no primary action can open the file", () => {
330 expect(
331 hasMarkdownFilePrimaryAction({
332 canOpenInEditor: false,
333 canOpenInBrowser: false,
334 canOpenInPanel: false,
335 }),
336 ).toBe(false);
337 });
338});
339​
340describe("ChatMarkdown skill chips", () => {
341 it("updates digit-leading skill labels when discovered skills change", async () => {
342 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
343 let renderer: ReactTestRenderer | undefined;
344 const text = "Use $2spec with a $20k budget.";
345 try {
346 await act(async () => {
347 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} />);
348 });
349 const mounted = renderer!;
350 const labels = (label: string) =>
351 mounted.root.findAllByType("span").filter((node) => node.children.includes(label));
352 expect(labels("2Spec")).toHaveLength(0);
353​
354 await act(async () => {
355 mounted.update(
356 <ChatMarkdown
357 cwd="/tmp/project"
358 text={text}
359 skills={[
360 { name: "2spec", displayName: "2Spec" },
361 { name: "20k", displayName: "MoneySkill" },
362 ]}
363 />,
364 );
365 });
366 expect(labels("2Spec")).toHaveLength(1);
367 expect(labels("MoneySkill")).toHaveLength(0);
368​
369 await act(async () => {
370 mounted.update(<ChatMarkdown cwd="/tmp/project" text={text} skills={[]} />);
371 });
372 expect(labels("2Spec")).toHaveLength(0);
373 } finally {
374 await act(async () => renderer?.unmount());
375 vi.unstubAllGlobals();
376 }
377 });
378});
379​
380describe("ChatMarkdown file option chips", () => {
381 it("keeps the fallback button text selectable", () => {
382 const html = renderToStaticMarkup(
383 <ChatMarkdown cwd="/tmp/project" text="[Source](/tmp/project/src/main.ts)" />,
384 );
385​
386 expect(html).toContain("<button");
387 expect(html).toContain('aria-haspopup="menu"');
388 expect(html).toContain("select-text");
389 });
390​
391 it.each([true, false])(
392 "renders Codex file citations as file chips with parseRawHtml=%s",
393 (parseRawHtml) => {
394 const html = renderToStaticMarkup(
395 <ChatMarkdown
396 cwd="/tmp/project"
397 text={
398 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.'
399 }
400 lineBreaks={!parseRawHtml}
401 parseRawHtml={parseRawHtml}
402 />,
403 );
404​
405 expect(html).not.toContain("codex-file-citation");
406 expect(html).toContain("chat-markdown-file-link");
407 expect(html).toContain(
408 'data-markdown-copy="[report.xlsx](/tmp/project/outputs/report.xlsx)"',
409 );
410 expect(html).toContain("report.xlsx");
411 },
412 );
413​
414 it("leaves an unfinished streaming citation visible until it is complete", () => {
415 const html = renderToStaticMarkup(
416 <ChatMarkdown
417 cwd="/tmp/project"
418 text={'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"'}
419 isStreaming
420 />,
421 );
422​
423 expect(html).toContain(":codex-file-citation");
424 expect(html).not.toContain("chat-markdown-file-link");
425 });
426​
427 it("leaves malformed and similarly named file directives literal", () => {
428 for (const text of [
429 ':codex-file-citation{purpose="output"}',
430 ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
431 ]) {
432 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
433​
434 expect(html).toContain(text.replaceAll('"', "&quot;"));
435 expect(html).not.toContain("chat-markdown-file-link");
436 }
437 });
438​
439 it("preserves Codex file citation examples inside code", () => {
440 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
441 const html = renderToStaticMarkup(
442 <ChatMarkdown
443 cwd="/tmp/project"
444 text={`Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``}
445 />,
446 );
447​
448 expect(html.match(/:codex-file-citation/g)).toHaveLength(2);
449 expect(html).not.toContain("chat-markdown-file-link");
450 });
451​
452 it("preserves escaped Codex file citations as literal text", () => {
453 const html = renderToStaticMarkup(
454 <ChatMarkdown
455 cwd="/tmp/project"
456 text={'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
457 />,
458 );
459​
460 expect(html).toContain(":codex-file-citation");
461 expect(html).not.toContain("chat-markdown-file-link");
462 });
463​
464 it("does not create a nested link for citations inside link text", () => {
465 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
466 const html = renderToStaticMarkup(
467 <ChatMarkdown cwd="/tmp/project" text={`[See ${directive}](https://example.com)`} />,
468 );
469 const renderedText = html.replace(/<[^>]+>/g, "");
470​
471 expect(renderedText).toContain("codex-file-citation");
472 expect(html).not.toContain("chat-markdown-file-link");
473 });
474​
475 it("renders file citations created by over-indented list recovery", () => {
476 const html = renderToStaticMarkup(
477 <ChatMarkdown
478 cwd="/tmp/project"
479 text={'- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
480 />,
481 );
482​
483 expect(html).not.toContain("<pre>");
484 expect(html).toContain("Created ");
485 expect(html).toContain("chat-markdown-file-link");
486 expect(html).toContain("report.xlsx");
487 });
488​
489 it("disambiguates Codex citations with the same basename", () => {
490 const html = renderToStaticMarkup(
491 <ChatMarkdown
492 cwd="/tmp/project"
493 text={
494 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.'
495 }
496 />,
497 );
498​
499 expect(html).toContain("index.ts · project/src");
500 expect(html).toContain("index.ts · project/test");
501 });
502​
503 it("preserves rejected citations created by over-indented list recovery", () => {
504 const malformedHtml = renderToStaticMarkup(
505 <ChatMarkdown
506 cwd="/tmp/project"
507 text={'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}'}
508 />,
509 );
510 const nestedLinkHtml = renderToStaticMarkup(
511 <ChatMarkdown
512 cwd="/tmp/project"
513 text={
514 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)'
515 }
516 />,
517 );
518 const nestedLinkText = nestedLinkHtml.replace(/<[^>]+>/g, "");
519​
520 expect(malformedHtml).toContain(
521 "<li>Bad :codex-file-citation{purpose=&quot;output&quot;}</li>",
522 );
523 expect(nestedLinkText).toContain(
524 "Bad :codex-file-citation{path=&quot;/tmp/project/report.xlsx&quot;}",
525 );
526 });
527});
528​
529const ARTIFACT_TEMPLATE_DIRECTIVE =
530 '::artifact-template{skill_name="artifact-template-hello-world" skill_directory="/Users/test/.codex/skills/artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
531​
532describe("ChatMarkdown artifact-template cards", () => {
533 it.each([true, false])("renders the Codex result card with parseRawHtml=%s", (parseRawHtml) => {
534 const html = renderToStaticMarkup(
535 <ChatMarkdown
536 cwd="/tmp/project"
537 text={ARTIFACT_TEMPLATE_DIRECTIVE}
538 parseRawHtml={parseRawHtml}
539 onUseArtifactTemplate={() => undefined}
540 />,
541 );
542​
543 expect(html).not.toContain("::artifact-template");
544 expect(html).toContain("chat-markdown-artifact-template");
545 expect(html).toContain('data-artifact-kind="document"');
546 expect(html).toContain('data-markdown-copy="Hello World (Document template)\n\n"');
547 expect(html).toContain('data-skill-name="artifact-template-hello-world"');
548 expect(html).toContain("Hello World");
549 expect(html).toContain("Document template");
550 expect(html).toContain("Use template");
551 expect(html).not.toContain("<p><div");
552 });
553​
554 it("renders a passive card outside a composer-backed timeline", () => {
555 const html = renderToStaticMarkup(
556 <ChatMarkdown cwd="/tmp/project" text={ARTIFACT_TEMPLATE_DIRECTIVE} />,
557 );
558​
559 expect(html).toContain("chat-markdown-artifact-template");
560 expect(html).not.toContain("Use template");
561 });
562​
563 it("leaves malformed and unfinished artifact-template directives literal", () => {
564 const malformed =
565 '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
566 const unfinished = ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1);
567​
568 for (const text of [malformed, unfinished]) {
569 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
570 expect(html).toContain("::artifact-template");
571 expect(html).not.toContain("chat-markdown-artifact-template");
572 }
573 });
574​
575 it("leaves escaped and similarly named artifact-template directives literal", () => {
576 for (const text of [
577 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
578 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
579 ]) {
580 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
581​
582 expect(html).toContain("::artifact-template");
583 expect(html).not.toContain("chat-markdown-artifact-template");
584 }
585 });
586​
587 it("preserves artifact-template examples inside code", () => {
588 const html = renderToStaticMarkup(
589 <ChatMarkdown
590 cwd="/tmp/project"
591 text={`\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``}
592 />,
593 );
594​
595 expect(html.match(/::artifact-template/g)).toHaveLength(2);
596 expect(html).not.toContain("chat-markdown-artifact-template");
597 });
598});
599​
600describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
601 it("uses the browser when it is the only available primary action", () => {
602 expect(
603 shouldUseMarkdownFileBrowserPrimaryAction({
604 iconPath: "/tmp/report.html",
605 canOpenInEditor: false,
606 canOpenInBrowser: true,
607 canOpenInPanel: false,
608 }),
609 ).toBe(true);
610 });
611​
612 it("preserves the normal editor and panel defaults for HTML files", () => {
613 expect(
614 shouldUseMarkdownFileBrowserPrimaryAction({
615 iconPath: "/tmp/report.html",
616 canOpenInEditor: true,
617 canOpenInBrowser: true,
618 canOpenInPanel: false,
619 }),
620 ).toBe(false);
621 expect(
622 shouldUseMarkdownFileBrowserPrimaryAction({
623 iconPath: "/tmp/report.html",
624 canOpenInEditor: false,
625 canOpenInBrowser: true,
626 canOpenInPanel: true,
627 }),
628 ).toBe(false);
629 });
630​
631 it("continues to open PDF files in the browser by default", () => {
632 expect(
633 shouldUseMarkdownFileBrowserPrimaryAction({
634 iconPath: "/tmp/report.pdf",
635 canOpenInEditor: true,
636 canOpenInBrowser: true,
637 canOpenInPanel: true,
638 }),
639 ).toBe(true);
640 });
641});
642​
643describe("orderedListGutterStyle", () => {
644 it("leaves the default gutter alone for single-digit lists", () => {
645 expect(orderedListGutterStyle(9, undefined)).toBeUndefined();
646 });
647​
648 it("widens the gutter for two-digit lists", () => {
649 expect(orderedListGutterStyle(99, undefined)).toEqual({ "--list-gutter": "3ch" });
650 });
651​
652 it("widens the gutter for a two-digit list that starts above 1", () => {
653 // start=50 + 49 items => last marker is "98", still two digits.
654 expect(orderedListGutterStyle(49, 50)).toEqual({ "--list-gutter": "3ch" });
655 });
656​
657 it("widens the gutter once the last marker reaches three digits", () => {
658 // item 100 is the bug from #6512: a 100-item list starting at 1.
659 expect(orderedListGutterStyle(100, undefined)).toEqual({ "--list-gutter": "4ch" });
660 });
661​
662 it("accounts for a non-default start attribute", () => {
663 // start=95 + 9 items => last marker is "103", three digits.
664 expect(orderedListGutterStyle(9, 95)).toEqual({ "--list-gutter": "4ch" });
665 expect(orderedListGutterStyle(5, "999995")).toEqual({ "--list-gutter": "7ch" });
666 });
667​
668 it("scales further for four-digit markers", () => {
669 expect(orderedListGutterStyle(1000, undefined)).toEqual({ "--list-gutter": "5ch" });
670 });
671​
672 it("uses the widest marker and includes a negative start's minus sign", () => {
673 expect(orderedListGutterStyle(1001, -1000)).toEqual({ "--list-gutter": "6ch" });
674 expect(orderedListGutterStyle(3, -15)).toEqual({ "--list-gutter": "4ch" });
675 expect(orderedListGutterStyle(3, -5)).toEqual({ "--list-gutter": "3ch" });
676 });
677​
678 it("treats a missing/zero item count as a single item", () => {
679 expect(orderedListGutterStyle(0, undefined)).toBeUndefined();
680 expect(orderedListGutterStyle(0, 100)).toEqual({ "--list-gutter": "4ch" });
681 });
682});
683​
684describe("ChatMarkdown Windows file links", () => {
685 const environmentId = EnvironmentId.make("env-windows");
686​
687 it.each([true, false])("preserves drive paths with parseRawHtml=%s", (parseRawHtml) => {
688 const html = renderToStaticMarkup(
689 <ChatMarkdown
690 cwd="C:/Users/shawn/project"
691 environmentId={environmentId}
692 text="[Open](C:/Users/shawn/project/src/main.ts)"
693 lineBreaks={!parseRawHtml}
694 parseRawHtml={parseRawHtml}
695 />,
696 );
697​
698 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
699 expect(html).toContain("chat-markdown-file-link");
700 });
701​
702 it.each([true, false])("normalizes backslashes with parseRawHtml=%s", (parseRawHtml) => {
703 const html = renderToStaticMarkup(
704 <ChatMarkdown
705 cwd="C:/Users/shawn/project"
706 environmentId={environmentId}
707 text={String.raw`[Open](C:\Users\shawn\project\src\main.ts)`}
708 lineBreaks={!parseRawHtml}
709 parseRawHtml={parseRawHtml}
710 />,
711 );
712​
713 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
714 expect(html).toContain("chat-markdown-file-link");
715 });
716​
717 it.each([true, false])(
718 "distinguishes same-named backslash paths with parseRawHtml=%s",
719 (parseRawHtml) => {
720 const html = renderToStaticMarkup(
721 <ChatMarkdown
722 cwd="C:/Users/shawn/project"
723 environmentId={environmentId}
724 text={String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`}
725 lineBreaks={!parseRawHtml}
726 parseRawHtml={parseRawHtml}
727 />,
728 );
729​
730 expect(html).toContain("index.ts · project/src");
731 expect(html).toContain("index.ts · project/test");
732 },
733 );
734​
735 it.each([true, false])(
736 "does not disambiguate the same file in links and inline code with parseRawHtml=%s",
737 (parseRawHtml) => {
738 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
739 const html = renderToStaticMarkup(
740 <ChatMarkdown
741 cwd="C:/Users/shawn/project"
742 environmentId={environmentId}
743 text={`[Source](${path}) and \`${path}\``}
744 lineBreaks={!parseRawHtml}
745 parseRawHtml={parseRawHtml}
746 />,
747 );
748​
749 expect(html.match(/chat-markdown-file-link/g)).toHaveLength(2);
750 expect(html).not.toContain("main.ts ·");
751 },
752 );
753​
754 it.each([true, false])("preserves reference links with parseRawHtml=%s", (parseRawHtml) => {
755 const html = renderToStaticMarkup(
756 <ChatMarkdown
757 cwd="C:/Users/shawn/project"
758 environmentId={environmentId}
759 text={"[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"}
760 lineBreaks={!parseRawHtml}
761 parseRawHtml={parseRawHtml}
762 />,
763 );
764​
765 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
766 expect(html).toContain("chat-markdown-file-link");
767 });
768​
769 it.each([true, false])("still rejects unsafe schemes with parseRawHtml=%s", (parseRawHtml) => {
770 const html = renderToStaticMarkup(
771 <ChatMarkdown
772 cwd="C:/Users/shawn/project"
773 environmentId={environmentId}
774 text="[unsafe](javascript:alert(1)) and [unknown](d:alert(1))"
775 lineBreaks={!parseRawHtml}
776 parseRawHtml={parseRawHtml}
777 />,
778 );
779​
780 expect(html).not.toContain("javascript:");
781 expect(html).not.toContain("d:alert");
782 expect(html).not.toContain("chat-markdown-file-link");
783 });
784});