messageResponseStreamdownMode.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. import { readFileSync } from "node:fs";
  2. import { resolve } from "node:path";
  3. import { createElement } from "react";
  4. import { renderToStaticMarkup } from "react-dom/server";
  5. import { describe, expect, it, vi } from "vitest";
  6. import {
  7. buildMessageFileLinkTarget,
  8. buildMessageStreamdownRenderKey,
  9. messageResponsePropsAreEqual,
  10. MessageResponse,
  11. openMessageFileLinkInEditor,
  12. resolveMessageStreamdownMode,
  13. } from "@/components/ai-elements/message.js";
  14. import { TooltipProvider } from "@/components/ui/tooltip.js";
  15. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  16. vi.mock("@/store/StoreProvider.js", () => ({
  17. useZCodeStore: (selector: (state: unknown) => unknown) =>
  18. selector({
  19. codePreviewSettings: {
  20. darkTheme: "github-dark",
  21. fontSizePx: 13,
  22. lightTheme: "github-light",
  23. wrapLongLines: true,
  24. },
  25. theme: "zai-light",
  26. }),
  27. }));
  28. vi.mock("@/hooks/usePlatform.js", () => ({
  29. usePlatform: () => ({
  30. getInstalledEditors: vi.fn().mockResolvedValue([]),
  31. openInEditor: vi.fn().mockResolvedValue({ success: true }),
  32. openInFileManager: vi.fn().mockResolvedValue({ success: true }),
  33. }),
  34. useOptionalPlatform: () => ({
  35. getInstalledEditors: vi.fn().mockResolvedValue([]),
  36. openInEditor: vi.fn().mockResolvedValue({ success: true }),
  37. openInFileManager: vi.fn().mockResolvedValue({ success: true }),
  38. }),
  39. }));
  40. describe("resolveMessageStreamdownMode", () => {
  41. it("invalidates memoized artifact images when their session or reader changes", () => {
  42. const readAttachment = vi.fn();
  43. const base = {
  44. children: "![CUA](zcode-artifact://session-1/shot)",
  45. sessionId: "session-1",
  46. readAttachment,
  47. };
  48. expect(messageResponsePropsAreEqual(base, base)).toBe(true);
  49. expect(messageResponsePropsAreEqual(base, { ...base, sessionId: "session-2" })).toBe(false);
  50. expect(messageResponsePropsAreEqual(base, { ...base, readAttachment: vi.fn() })).toBe(false);
  51. });
  52. it("保留 Markdown 目录链接的 pathKind 和远程 workspace scope", () => {
  53. expect(
  54. buildMessageFileLinkTarget({
  55. href: "./src/",
  56. label: "src",
  57. path: "/workspace/repo/src/",
  58. workspacePath: "/workspace/repo",
  59. workspaceIdentity: "remote:wsl:Ubuntu:/workspace/repo",
  60. workspaceRemoteSessionId: "wsl-session",
  61. }),
  62. ).toEqual({
  63. path: "/workspace/repo/src/",
  64. label: "src",
  65. pathKind: "directory",
  66. relativePath: "src",
  67. workspacePath: "/workspace/repo",
  68. workspaceIdentity: "remote:wsl:Ubuntu:/workspace/repo",
  69. workspaceRemoteSessionId: "wsl-session",
  70. });
  71. });
  72. it.each([
  73. ["./src/App.tsx", "/workspace/repo/src/App.tsx"],
  74. ["./config", "/workspace/repo/config"],
  75. ["/etc/hosts", "/etc/hosts"],
  76. ])("Markdown 文件链接 %s 不在渲染阶段猜测文件系统类型", (href, path) => {
  77. expect(
  78. buildMessageFileLinkTarget({
  79. href,
  80. label: "file",
  81. path,
  82. workspacePath: "/workspace/repo",
  83. }).pathKind,
  84. ).toBeUndefined();
  85. });
  86. it.each(["file", "directory"] as const)(
  87. "Markdown 打开方式通过 workspace stat 传递真实 %s 类型",
  88. async (type) => {
  89. const statFile = vi.fn().mockResolvedValue({ type });
  90. const openInEditor = vi.fn().mockResolvedValue({ success: true });
  91. const fileLink = buildMessageFileLinkTarget({
  92. href: "./config",
  93. label: "config",
  94. path: "/workspace/repo/config",
  95. workspacePath: "/workspace/repo",
  96. workspaceIdentity: "remote:wsl:Ubuntu:/workspace/repo",
  97. });
  98. const remoteTarget = { kind: "wsl" as const, distro: "Ubuntu" };
  99. await expect(
  100. openMessageFileLinkInEditor({
  101. editorId: "vscode",
  102. fileLink,
  103. openInEditor,
  104. remoteTarget,
  105. statFile,
  106. }),
  107. ).resolves.toEqual({ success: true });
  108. expect(statFile).toHaveBeenCalledWith({ path: "/workspace/repo/config" });
  109. expect(openInEditor).toHaveBeenCalledWith("vscode", "/workspace/repo/config", {
  110. pathKind: type,
  111. remoteTarget,
  112. workspaceIdentity: "remote:wsl:Ubuntu:/workspace/repo",
  113. });
  114. },
  115. );
  116. it("Markdown 打开方式 stat 失败时不调用本机编辑器", async () => {
  117. const statFile = vi.fn().mockRejectedValue(new Error("path not found"));
  118. const openInEditor = vi.fn();
  119. const fileLink = buildMessageFileLinkTarget({
  120. href: "./config",
  121. label: "config",
  122. path: "/workspace/repo/config",
  123. workspacePath: "/workspace/repo",
  124. });
  125. await expect(
  126. openMessageFileLinkInEditor({
  127. editorId: "vscode",
  128. fileLink,
  129. openInEditor,
  130. statFile,
  131. }),
  132. ).rejects.toThrow("path not found");
  133. expect(openInEditor).not.toHaveBeenCalled();
  134. });
  135. it("越界相对 Markdown 链接不生成可点击文件操作目标", () => {
  136. const html = renderToStaticMarkup(
  137. createElement(
  138. MessageResponse,
  139. {
  140. workspacePath: "/workspace",
  141. onOpenFileLink: vi.fn(),
  142. },
  143. "[private](foo/../../private.pdf)",
  144. ),
  145. );
  146. expect(html).toContain("private");
  147. expect(html).not.toContain("/workspace/foo/../../private.pdf");
  148. expect(html).not.toContain("cursor-pointer");
  149. });
  150. it("Assistant citation 使用现有文件链接渲染,普通文件名仍保持原文", () => {
  151. const html = renderToStaticMarkup(
  152. createElement(
  153. ZCodeIntlProvider,
  154. { initialLocale: "zh-CN" },
  155. createElement(
  156. MessageResponse,
  157. {
  158. renderZCodeFileCitations: true,
  159. workspacePath: "/workspace",
  160. onOpenFileLink: vi.fn(),
  161. },
  162. [
  163. "普通文件 report.pdf。",
  164. ':zcode-file-citation{path="docs/年度 报告.pdf" purpose="output" page_number=2}',
  165. ':::zcode-file-citation{path="docs/论文.pdf" purpose="source"}',
  166. ].join("\n\n"),
  167. ),
  168. ),
  169. );
  170. expect(html).toContain("普通文件 report.pdf");
  171. expect(html).not.toContain(":zcode-file-citation");
  172. expect(html).toContain("<button");
  173. expect(html).toContain('title="/workspace/docs/年度 报告.pdf"');
  174. expect(html).toContain('title="/workspace/docs/论文.pdf"');
  175. expect(html).toContain("年度 报告.pdf");
  176. });
  177. it("citation 和 Markdown 文件链接支持智能引号且不污染路径", () => {
  178. const html = renderToStaticMarkup(
  179. createElement(
  180. ZCodeIntlProvider,
  181. { initialLocale: "zh-CN" },
  182. createElement(
  183. MessageResponse,
  184. {
  185. renderZCodeFileCitations: true,
  186. workspacePath: "/workspace",
  187. onOpenFileLink: vi.fn(),
  188. },
  189. [
  190. '规划完成。已生成 ::zcode-file-citation{path=“/workspace/冰岛 行程.pdf” purpose="output"}',
  191. "[说明](‘docs/说明.md’)",
  192. ].join("\n\n"),
  193. ),
  194. ),
  195. );
  196. expect(html).toContain('title="/workspace/冰岛 行程.pdf"');
  197. expect(html).toContain('title="/workspace/docs/说明.md"');
  198. expect(html).not.toContain("/workspace/“");
  199. expect(html).not.toContain("说明.md’");
  200. expect(html).not.toContain("[blocked]");
  201. });
  202. it("正文文件链接由文字提供真实基线,图标独立居中,并仅在 hover 显示虚线下划线", () => {
  203. const html = renderToStaticMarkup(
  204. createElement(
  205. ZCodeIntlProvider,
  206. { initialLocale: "zh-CN" },
  207. createElement(
  208. MessageResponse,
  209. {
  210. workspacePath: "/workspace",
  211. onOpenFileLink: vi.fn(),
  212. },
  213. "[项目交付稿](docs/项目交付稿.pptx)",
  214. ),
  215. ),
  216. );
  217. expect(html).toContain("text-icon-blue");
  218. expect(html).toContain("gap-1");
  219. expect(html).not.toContain("gap-1.5");
  220. expect(html).toContain("ml-0.5");
  221. expect(html).toContain("items-baseline");
  222. expect(html).toContain("self-center");
  223. expect(html).toContain("self-baseline");
  224. expect(html).not.toContain("items-center");
  225. expect(html).not.toContain("top-px");
  226. expect(html).toContain("align-baseline");
  227. expect(html).not.toContain("align-middle");
  228. expect(html).toContain("no-underline");
  229. expect(html).toContain("decoration-dotted");
  230. expect(html).not.toContain("decoration-dashed");
  231. expect(html).toContain("hover:underline");
  232. expect(html).not.toContain("hover:no-underline");
  233. });
  234. it("正文公网链接与文件链接使用相同的浏览器式链接交互", () => {
  235. const html = renderToStaticMarkup(
  236. createElement(
  237. ZCodeIntlProvider,
  238. { initialLocale: "zh-CN" },
  239. createElement(
  240. MessageResponse,
  241. { onOpenExternalUrl: vi.fn() },
  242. "[ZCode](https://zcode-ai.com)",
  243. ),
  244. ),
  245. );
  246. expect(html).toContain("text-icon-blue");
  247. expect(html).toContain("no-underline");
  248. expect(html).toContain("decoration-dotted");
  249. expect(html).not.toContain("decoration-dashed");
  250. expect(html).toContain("hover:underline");
  251. });
  252. it("streaming 时隐藏未闭合 citation,异常换行后的正文仍可见", () => {
  253. const html = renderToStaticMarkup(
  254. createElement(
  255. ZCodeIntlProvider,
  256. { initialLocale: "zh-CN" },
  257. createElement(
  258. MessageResponse,
  259. {
  260. renderZCodeFileCitations: true,
  261. streaming: true,
  262. workspacePath: "/workspace",
  263. onOpenFileLink: vi.fn(),
  264. },
  265. '正文\n::zcode-file-citation{path="docs/report.pdf"',
  266. ),
  267. ),
  268. );
  269. expect(html).toContain("正文");
  270. expect(html).not.toContain("::zcode-file-citation");
  271. const malformedHtml = renderToStaticMarkup(
  272. createElement(
  273. ZCodeIntlProvider,
  274. { initialLocale: "zh-CN" },
  275. createElement(
  276. MessageResponse,
  277. {
  278. renderZCodeFileCitations: true,
  279. streaming: true,
  280. workspacePath: "/workspace",
  281. onOpenFileLink: vi.fn(),
  282. },
  283. '正文\n::zcode-file-citation{path="docs/report.pdf"\n后续说明仍然可见',
  284. ),
  285. ),
  286. );
  287. expect(malformedHtml).toContain("后续说明仍然可见");
  288. });
  289. it.each([
  290. ["盘符路径", String.raw`C:\Users\demo\年度 报告.pdf`, "C:/Users/demo/年度 报告.pdf"],
  291. ["Windows file URL", "file:///C:/Users/demo/report.pdf", "C:/Users/demo/report.pdf"],
  292. ])("Assistant citation 的 Windows %s 通过 harden 后仍可点击", (_case, path, resolvedPath) => {
  293. const html = renderToStaticMarkup(
  294. createElement(
  295. ZCodeIntlProvider,
  296. { initialLocale: "zh-CN" },
  297. createElement(
  298. MessageResponse,
  299. {
  300. renderZCodeFileCitations: true,
  301. workspacePath: "C:\\workspace",
  302. onOpenFileLink: vi.fn(),
  303. },
  304. `::zcode-file-citation{path="${path}" purpose="output"}`,
  305. ),
  306. ),
  307. );
  308. expect(html).not.toContain("[blocked]");
  309. expect(html).toContain("<button");
  310. expect(html).toContain(`title="${resolvedPath}"`);
  311. });
  312. it("越界 citation 保持原文且不生成文件链接", () => {
  313. const directive = '::zcode-file-citation{path="foo/../../private.pdf"}';
  314. const html = renderToStaticMarkup(
  315. createElement(
  316. MessageResponse,
  317. {
  318. renderZCodeFileCitations: true,
  319. workspacePath: "/workspace",
  320. onOpenFileLink: vi.fn(),
  321. },
  322. directive,
  323. ),
  324. );
  325. expect(html).toContain("::zcode-file-citation");
  326. expect(html).not.toContain('title="/workspace/foo/../../private.pdf"');
  327. });
  328. it("citation 不解析代码节点,并保留 Streamdown 默认 GFM 表格", () => {
  329. const directive = '::zcode-file-citation{path="docs/report.pdf"}';
  330. const compatibilityDirective = ':zcode-file-citation{path="docs/legacy.pdf"}';
  331. const html = renderToStaticMarkup(
  332. createElement(
  333. ZCodeIntlProvider,
  334. { initialLocale: "zh-CN" },
  335. createElement(
  336. TooltipProvider,
  337. null,
  338. createElement(
  339. MessageResponse,
  340. {
  341. renderZCodeFileCitations: true,
  342. workspacePath: "/workspace",
  343. onOpenFileLink: vi.fn(),
  344. },
  345. [
  346. `\`${directive}\``,
  347. `\`${compatibilityDirective}\``,
  348. "",
  349. "| 文件 | 状态 |",
  350. "| --- | --- |",
  351. "| report.pdf | 完成 |",
  352. ].join("\n"),
  353. ),
  354. ),
  355. ),
  356. );
  357. expect(html).toContain("::zcode-file-citation");
  358. expect(html).toContain(":zcode-file-citation");
  359. expect(html).toContain("<table");
  360. expect(html).not.toContain('title="/workspace/docs/report.pdf"');
  361. expect(html).not.toContain('title="/workspace/docs/legacy.pdf"');
  362. });
  363. it.each([
  364. ["盘符正斜杠", "[报告](C:/Users/demo/report.md)", "C:/Users/demo/report.md"],
  365. ["盘符反斜杠", String.raw`[报告](C:\Users\demo\report.md)`, "C:/Users/demo/report.md"],
  366. ["Windows file URL", "[报告](file:///C:/Users/demo/report.md)", "C:/Users/demo/report.md"],
  367. [
  368. "中文空格路径",
  369. "[报告](<C:/Users/demo/中文 目录/report.md>)",
  370. "C:/Users/demo/中文 目录/report.md",
  371. ],
  372. ])("Windows 绝对 Markdown 链接(%s)通过 harden 后仍可点击", (_case, markdown, path) => {
  373. const html = renderToStaticMarkup(
  374. createElement(
  375. ZCodeIntlProvider,
  376. { initialLocale: "zh-CN" },
  377. createElement(
  378. MessageResponse,
  379. {
  380. workspacePath: "C:\\workspace",
  381. onOpenFileLink: vi.fn(),
  382. },
  383. markdown,
  384. ),
  385. ),
  386. );
  387. expect(html).not.toContain("[blocked]");
  388. expect(html).toContain("<button");
  389. expect(html).toContain(`title="${path}"`);
  390. });
  391. it("UNC workspace 中 Windows 绝对 Markdown 链接通过 harden 后仍可点击", () => {
  392. const html = renderToStaticMarkup(
  393. createElement(
  394. ZCodeIntlProvider,
  395. { initialLocale: "zh-CN" },
  396. createElement(
  397. MessageResponse,
  398. {
  399. workspacePath: "\\\\server\\share\\repo",
  400. onOpenFileLink: vi.fn(),
  401. },
  402. "[报告](C:/Users/demo/report.md)",
  403. ),
  404. ),
  405. );
  406. expect(html).not.toContain("[blocked]");
  407. expect(html).toContain("<button");
  408. expect(html).toContain('title="C:/Users/demo/report.md"');
  409. });
  410. it.each([
  411. ["盘符正斜杠", "![截图](C:/Users/demo/screenshot.png)"],
  412. ["盘符反斜杠", String.raw`![截图](C:\Users\demo\screenshot.png)`],
  413. ["Windows file URL", "![截图](file:///C:/Users/demo/screenshot.png)"],
  414. ])("Windows 绝对 Markdown 图片(%s)通过 harden 后保留本地路径", (_case, markdown) => {
  415. const html = renderToStaticMarkup(
  416. createElement(
  417. ZCodeIntlProvider,
  418. { initialLocale: "zh-CN" },
  419. createElement(MessageResponse, { workspacePath: "C:\\workspace" }, markdown),
  420. ),
  421. );
  422. expect(html).not.toContain("[blocked]");
  423. expect(html).toContain('data-markdown-local-image="loading"');
  424. expect(html).toContain('title="C:/Users/demo/screenshot.png"');
  425. });
  426. it("UNC workspace 中 Windows 绝对 Markdown 图片通过 harden 后保留本地路径", () => {
  427. const html = renderToStaticMarkup(
  428. createElement(
  429. ZCodeIntlProvider,
  430. { initialLocale: "zh-CN" },
  431. createElement(
  432. MessageResponse,
  433. { workspacePath: "\\\\server\\share\\repo" },
  434. "![截图](C:/Users/demo/screenshot.png)",
  435. ),
  436. ),
  437. );
  438. expect(html).not.toContain("[blocked]");
  439. expect(html).toContain('data-markdown-local-image="loading"');
  440. expect(html).toContain('title="C:/Users/demo/screenshot.png"');
  441. });
  442. it("正文裸文件名保持普通文本且 GFM 表格正常渲染", () => {
  443. const html = renderToStaticMarkup(
  444. createElement(
  445. ZCodeIntlProvider,
  446. { initialLocale: "zh-CN" },
  447. createElement(
  448. TooltipProvider,
  449. null,
  450. createElement(
  451. MessageResponse,
  452. {
  453. workspacePath: "/workspace",
  454. },
  455. [
  456. "| 项 | 状态 |",
  457. "| --- | --- |",
  458. "| Word 文档 | ✅ |",
  459. "",
  460. "已生成 report.docx。",
  461. ].join("\n"),
  462. ),
  463. ),
  464. ),
  465. );
  466. expect(html).toContain("<table");
  467. expect(html).toContain("已生成 report.docx。");
  468. expect(html).not.toMatch(/title="[^"]*report\.docx"/);
  469. });
  470. it.each([false, true])("仅双波浪线渲染删除线(streaming=%s)", (streaming) => {
  471. const html = renderToStaticMarkup(
  472. createElement(
  473. MessageResponse,
  474. { streaming, workspacePath: "/workspace" },
  475. "~单波浪线~ 与 ~~双波浪线。~~后续文字",
  476. ),
  477. );
  478. expect(html).toContain("~单波浪线~");
  479. expect(html).not.toContain("<del>单波浪线</del>");
  480. expect(html).toContain("<del>双波浪线。</del>后续文字");
  481. });
  482. it("keeps completed messages on Streamdown static mode", () => {
  483. expect(resolveMessageStreamdownMode(false)).toBe("static");
  484. });
  485. it("uses Streamdown streaming mode only while the message is actively streaming", () => {
  486. expect(resolveMessageStreamdownMode(true)).toBe("streaming");
  487. });
  488. it("changes the Streamdown render key when code block rendering settings change", () => {
  489. const base = buildMessageStreamdownRenderKey({
  490. codeBlockTheme: "github-light",
  491. fontSizePx: 12,
  492. workspacePath: "/workspace",
  493. wrapLongLines: false,
  494. });
  495. expect(
  496. buildMessageStreamdownRenderKey({
  497. codeBlockTheme: "github-dark",
  498. fontSizePx: 12,
  499. workspacePath: "/workspace",
  500. wrapLongLines: false,
  501. }),
  502. ).not.toBe(base);
  503. expect(
  504. buildMessageStreamdownRenderKey({
  505. codeBlockTheme: "github-light",
  506. fontSizePx: 13,
  507. workspacePath: "/workspace",
  508. wrapLongLines: false,
  509. }),
  510. ).not.toBe(base);
  511. expect(
  512. buildMessageStreamdownRenderKey({
  513. codeBlockTheme: "github-light",
  514. fontSizePx: 12,
  515. workspacePath: "/workspace",
  516. wrapLongLines: true,
  517. }),
  518. ).not.toBe(base);
  519. });
  520. it("keeps the Streamdown render key stable across streaming mode changes", () => {
  521. const staticModeKey = buildMessageStreamdownRenderKey({
  522. codeBlockTheme: "github-light",
  523. fontSizePx: 12,
  524. workspacePath: "/workspace",
  525. wrapLongLines: false,
  526. });
  527. const streamingModeKey = buildMessageStreamdownRenderKey({
  528. codeBlockTheme: "github-light",
  529. fontSizePx: 12,
  530. workspacePath: "/workspace",
  531. wrapLongLines: false,
  532. });
  533. expect(streamingModeKey).toBe(staticModeKey);
  534. });
  535. it("changes the Streamdown render key with artifact permission context", () => {
  536. const base = buildMessageStreamdownRenderKey({
  537. attachmentReaderEpoch: 1,
  538. codeBlockTheme: "github-light",
  539. fontSizePx: 12,
  540. sessionId: "session-a",
  541. workspacePath: "/workspace",
  542. wrapLongLines: false,
  543. });
  544. expect(
  545. buildMessageStreamdownRenderKey({
  546. attachmentReaderEpoch: 1,
  547. codeBlockTheme: "github-light",
  548. fontSizePx: 12,
  549. sessionId: "session-b",
  550. workspacePath: "/workspace",
  551. wrapLongLines: false,
  552. }),
  553. ).not.toBe(base);
  554. expect(
  555. buildMessageStreamdownRenderKey({
  556. attachmentReaderEpoch: 2,
  557. codeBlockTheme: "github-light",
  558. fontSizePx: 12,
  559. sessionId: "session-a",
  560. workspacePath: "/workspace",
  561. wrapLongLines: false,
  562. }),
  563. ).not.toBe(base);
  564. });
  565. it("renders single-dollar inline math as KaTeX", () => {
  566. const html = renderToStaticMarkup(
  567. createElement(
  568. MessageResponse,
  569. { workspacePath: "/workspace" },
  570. "其中 $c(\\mathbf{r})$ 是声速,$\\omega=2\\pi f$ 是角频率。",
  571. ),
  572. );
  573. expect(html).toContain("katex");
  574. expect(html).not.toContain("$c(\\mathbf{r})$");
  575. expect(html).not.toContain("$\\omega=2\\pi f$");
  576. });
  577. it("rewrites assistant artifact images before Streamdown hardening", () => {
  578. const html = renderToStaticMarkup(
  579. createElement(
  580. ZCodeIntlProvider,
  581. { initialLocale: "zh-CN" },
  582. createElement(
  583. MessageResponse,
  584. {
  585. workspacePath: "/workspace",
  586. sessionId: "session-1",
  587. readAttachment: async () => ({
  588. bytes: new Uint8Array([1]),
  589. mediaType: "image/png",
  590. }),
  591. },
  592. "![CUA](zcode-artifact://session-1/shot)",
  593. ),
  594. ),
  595. );
  596. expect(html).toContain('data-markdown-local-image="loading"');
  597. expect(html).not.toContain("Image blocked");
  598. expect(html).not.toContain("zcode-artifact://");
  599. });
  600. it("keeps paired currency dollars as text", () => {
  601. const html = renderToStaticMarkup(
  602. createElement(
  603. MessageResponse,
  604. { workspacePath: "/workspace" },
  605. "Pricing is $5 today and $10 tomorrow.",
  606. ),
  607. );
  608. expect(html).not.toContain("katex");
  609. expect(html).toContain("Pricing is $5 today and $10 tomorrow.");
  610. });
  611. it("keeps compact currency ranges as text", () => {
  612. const html = renderToStaticMarkup(
  613. createElement(
  614. MessageResponse,
  615. { workspacePath: "/workspace" },
  616. "Pricing is $5-$10 depending on usage.",
  617. ),
  618. );
  619. expect(html).not.toContain("katex");
  620. expect(html).toContain("Pricing is $5-$10 depending on usage.");
  621. });
  622. it("keeps paired shell environment dollars as text", () => {
  623. const html = renderToStaticMarkup(
  624. createElement(
  625. MessageResponse,
  626. { workspacePath: "/workspace" },
  627. "Use $HOME and $PATH to inspect environment variables.",
  628. ),
  629. );
  630. expect(html).not.toContain("katex");
  631. expect(html).toContain("Use $HOME and $PATH to inspect environment variables.");
  632. });
  633. it("loads KaTeX CSS so MathML fallback does not duplicate visual output", () => {
  634. const styles = readFileSync(resolve(process.cwd(), "packages/ui/src/styles.css"), "utf8");
  635. const packageJson = JSON.parse(
  636. readFileSync(resolve(process.cwd(), "packages/ui/package.json"), "utf8"),
  637. ) as { dependencies?: Record<string, string> };
  638. expect(styles).toContain('@import "katex/dist/katex.min.css";');
  639. // Bugfix: styles.css 作为 @zcode/ui 的公开入口会被 web/desktop 直接构建,
  640. // 不能依赖 pnpm hoist 偶然把间接依赖 katex 放到根 node_modules。
  641. expect(packageJson.dependencies?.katex).toBeTruthy();
  642. });
  643. });
  644. it("通用模式回答保留代码容器和复制入口,锁定换行入口且模式变化会重新渲染", () => {
  645. const codePreviewSettings = {
  646. darkTheme: "github-dark",
  647. lightTheme: "github-light",
  648. fontSizePx: 13,
  649. wrapLongLines: false,
  650. };
  651. const props = { children: "```python\nprint('MODE_CODE_RETAINED')\n```", codePreviewSettings };
  652. const render = (forceCodeWrap: boolean) =>
  653. renderToStaticMarkup(
  654. createElement(
  655. ZCodeIntlProvider,
  656. { initialLocale: "zh-CN" },
  657. createElement(
  658. TooltipProvider,
  659. null,
  660. createElement(MessageResponse, { ...props, forceCodeWrap }),
  661. ),
  662. ),
  663. );
  664. const general = render(true);
  665. expect(general).toContain('data-language="python"');
  666. expect(general).toContain("复制代码");
  667. expect(general).not.toContain("自动换行");
  668. expect(render(false)).toContain("自动换行");
  669. expect(codePreviewSettings.wrapLongLines).toBe(false);
  670. expect(
  671. messageResponsePropsAreEqual(
  672. { ...props, forceCodeWrap: true },
  673. { ...props, forceCodeWrap: false },
  674. ),
  675. ).toBe(false);
  676. });