chatAttachments.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. import { describe, expect, it, vi } from "vitest";
  2. import { VIDEO_INPUT_MAX_BYTES } from "@zcode/shared";
  3. import { PROTOCOL_V4_LIMITS } from "@zcode/shared/zcode-protocol-v4";
  4. import {
  5. MissingInlineImageContentError,
  6. OversizedInlineImageAttachmentError,
  7. OversizedInlinePdfAttachmentError,
  8. OversizedInlineVideoAttachmentError,
  9. countClipboardTextLines,
  10. createClipboardTextComposerAttachment,
  11. createClipboardTextPathComposerAttachment,
  12. createChatComposerAttachment,
  13. createChatComposerPathAttachment,
  14. restoreChatComposerAttachment,
  15. serializeChatComposerAttachment,
  16. shouldCreateClipboardTextAttachment,
  17. shouldPreferSpreadsheetClipboardText,
  18. } from "../src/lib/chatAttachments.js";
  19. class TestFileReader {
  20. result: string | ArrayBuffer | null = null;
  21. error: Error | null = null;
  22. onload: (() => void) | null = null;
  23. onerror: (() => void) | null = null;
  24. readAsDataURL(file: File) {
  25. void file.arrayBuffer().then(
  26. (buffer) => {
  27. const bytes = Buffer.from(buffer);
  28. this.result = `data:${file.type};base64,${bytes.toString("base64")}`;
  29. this.onload?.();
  30. },
  31. (error: unknown) => {
  32. this.error = error instanceof Error ? error : new Error(String(error));
  33. this.onerror?.();
  34. },
  35. );
  36. }
  37. }
  38. vi.stubGlobal("FileReader", TestFileReader);
  39. const OVERSIZED_INLINE_IMAGE_BASE64 = "A".repeat(Math.ceil(((20 * 1024 * 1024 + 1) * 4) / 3));
  40. const OVERSIZED_INLINE_VIDEO_BASE64 = "A".repeat(Math.ceil(((VIDEO_INPUT_MAX_BYTES + 1) * 4) / 3));
  41. const OVERSIZED_INLINE_PDF_BASE64 = "A".repeat(
  42. Math.ceil(((PROTOCOL_V4_LIMITS.attachmentMaxBytes + 1) * 4) / 3),
  43. );
  44. describe("serializeChatComposerAttachment", () => {
  45. it("keeps deferred text source metadata in Web file serialization", async () => {
  46. const file = createClipboardTextComposerAttachment("original text");
  47. expect(
  48. await serializeChatComposerAttachment({
  49. ...file,
  50. sourceKind: "topic-history",
  51. messageCount: 2,
  52. }),
  53. ).toMatchObject({ sourceKind: "topic-history", messageCount: 2, textContent: "original text" });
  54. });
  55. it("文本文件会作为普通 file 附件序列化,并保留可读内容", async () => {
  56. const file = new File(["hello zcode"], "notes.txt", {
  57. type: "text/plain",
  58. });
  59. const attachment = await serializeChatComposerAttachment(createChatComposerAttachment(file));
  60. expect(attachment).toMatchObject({
  61. kind: "file",
  62. filename: "notes.txt",
  63. mimeType: "text/plain",
  64. sizeBytes: file.size,
  65. textContent: "hello zcode",
  66. });
  67. expect(attachment.dataBase64).toBeUndefined();
  68. });
  69. it("本地 PDF 路径只序列化路径,并保留 PDF attachment kind", async () => {
  70. const attachment = await serializeChatComposerAttachment(
  71. createChatComposerPathAttachment("/tmp/report.pdf"),
  72. );
  73. expect(attachment).toEqual({
  74. kind: "pdf",
  75. filename: "report.pdf",
  76. localPath: "/tmp/report.pdf",
  77. mimeType: "application/pdf",
  78. sizeBytes: 0,
  79. });
  80. });
  81. it("无路径 PDF 使用 dataBase64 序列化,并可从草稿恢复", async () => {
  82. const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31]);
  83. const file = new File([bytes], "report.pdf", { type: "application/pdf; charset=binary" });
  84. const serialized = await serializeChatComposerAttachment(createChatComposerAttachment(file));
  85. expect(serialized).toEqual({
  86. kind: "pdf",
  87. filename: "report.pdf",
  88. mimeType: "application/pdf",
  89. dataBase64: Buffer.from(bytes).toString("base64"),
  90. sizeBytes: bytes.byteLength,
  91. });
  92. expect(restoreChatComposerAttachment(serialized)).toMatchObject({
  93. filename: "report.pdf",
  94. mimeType: "application/pdf",
  95. sizeBytes: bytes.byteLength,
  96. });
  97. });
  98. it("Web PDF 超过 V4 上限时在 base64 编码前抛结构化错误", async () => {
  99. const file = new File([new Uint8Array([0x25, 0x50, 0x44, 0x46])], "large.pdf", {
  100. type: "application/pdf",
  101. });
  102. const attachment = createChatComposerAttachment(file);
  103. Object.defineProperty(attachment, "sizeBytes", {
  104. value: PROTOCOL_V4_LIMITS.attachmentMaxBytes + 1,
  105. });
  106. const readAsDataUrl = vi.spyOn(TestFileReader.prototype, "readAsDataURL");
  107. try {
  108. await expect(serializeChatComposerAttachment(attachment)).rejects.toMatchObject({
  109. filename: "large.pdf",
  110. maxSizeBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  111. name: "OversizedInlinePdfAttachmentError",
  112. });
  113. expect(readAsDataUrl).not.toHaveBeenCalled();
  114. } finally {
  115. readAsDataUrl.mockRestore();
  116. }
  117. });
  118. it("带本地路径的拖拽普通文件只序列化路径引用", async () => {
  119. const file = new File(["hello zcode"], "notes.txt", {
  120. type: "text/plain",
  121. });
  122. const attachment = await serializeChatComposerAttachment(
  123. createChatComposerAttachment(file, "/tmp/notes.txt"),
  124. );
  125. expect(attachment).toEqual({
  126. kind: "file",
  127. filename: "notes.txt",
  128. localPath: "/tmp/notes.txt",
  129. mimeType: "text/plain",
  130. sizeBytes: file.size,
  131. });
  132. });
  133. it("图片仍保持 ZCode Agent image 附件格式", async () => {
  134. const file = new File(["png-bytes"], "image.png", {
  135. type: "image/png",
  136. });
  137. await expect(
  138. serializeChatComposerAttachment({
  139. ...createChatComposerAttachment(file),
  140. id: "attachment-2",
  141. }),
  142. ).resolves.toEqual({
  143. kind: "image",
  144. filename: "image.png",
  145. mimeType: "image/png",
  146. dataBase64: "cG5nLWJ5dGVz",
  147. sizeBytes: file.size,
  148. });
  149. });
  150. it("无本地路径的大图片会在发送前拦截,避免 base64 payload 过大", async () => {
  151. const file = new File(["png-bytes"], "large.png", {
  152. type: "image/png",
  153. });
  154. await expect(
  155. serializeChatComposerAttachment({
  156. ...createChatComposerAttachment(file),
  157. sizeBytes: 21 * 1024 * 1024,
  158. }),
  159. ).rejects.toMatchObject({
  160. filename: "large.png",
  161. maxSizeBytes: 20 * 1024 * 1024,
  162. name: "OversizedInlineImageAttachmentError",
  163. sizeBytes: 21 * 1024 * 1024,
  164. });
  165. await expect(
  166. serializeChatComposerAttachment({
  167. ...createChatComposerAttachment(file),
  168. sizeBytes: 21 * 1024 * 1024,
  169. }),
  170. ).rejects.toBeInstanceOf(OversizedInlineImageAttachmentError);
  171. });
  172. it("带本地路径的大图片只序列化路径引用", async () => {
  173. const file = new File(["png-bytes"], "large.png", {
  174. type: "image/png",
  175. });
  176. await expect(
  177. serializeChatComposerAttachment({
  178. ...createChatComposerAttachment(file, "/tmp/large.png"),
  179. sizeBytes: 21 * 1024 * 1024,
  180. }),
  181. ).resolves.toEqual({
  182. kind: "image",
  183. filename: "large.png",
  184. localPath: "/tmp/large.png",
  185. mimeType: "image/png",
  186. sizeBytes: 21 * 1024 * 1024,
  187. });
  188. });
  189. it("恢复无本地路径的大图片时会在 base64 解码前拦截", () => {
  190. expect(() =>
  191. restoreChatComposerAttachment({
  192. dataBase64: "A",
  193. filename: "large.png",
  194. kind: "image",
  195. mimeType: "image/png",
  196. sizeBytes: 21 * 1024 * 1024,
  197. }),
  198. ).toThrow(OversizedInlineImageAttachmentError);
  199. });
  200. it("恢复无本地路径的超大 PDF 时会在 base64 解码前拦截", () => {
  201. expect(() =>
  202. restoreChatComposerAttachment({
  203. dataBase64: OVERSIZED_INLINE_PDF_BASE64,
  204. filename: "large.pdf",
  205. kind: "pdf",
  206. mimeType: "application/pdf",
  207. }),
  208. ).toThrow(OversizedInlinePdfAttachmentError);
  209. });
  210. it("恢复缺少 sizeBytes 的超大 base64 图片时会在解码前拦截", () => {
  211. expect(() =>
  212. restoreChatComposerAttachment({
  213. dataBase64: OVERSIZED_INLINE_IMAGE_BASE64,
  214. filename: "legacy-large.png",
  215. kind: "image",
  216. mimeType: "image/png",
  217. }),
  218. ).toThrow(OversizedInlineImageAttachmentError);
  219. });
  220. it("恢复 sizeBytes 偏小但 base64 超限的图片时会按实际长度拦截", () => {
  221. expect(() =>
  222. restoreChatComposerAttachment({
  223. dataBase64: OVERSIZED_INLINE_IMAGE_BASE64,
  224. filename: "mismatched-large.png",
  225. kind: "image",
  226. mimeType: "image/png",
  227. sizeBytes: 1,
  228. }),
  229. ).toThrow(OversizedInlineImageAttachmentError);
  230. });
  231. it("恢复带本地路径且 base64 超限的图片时跳过解码并保留路径引用", () => {
  232. const atobSpy = vi.spyOn(globalThis, "atob");
  233. try {
  234. expect(
  235. restoreChatComposerAttachment({
  236. dataBase64: OVERSIZED_INLINE_IMAGE_BASE64,
  237. filename: "path-large.png",
  238. kind: "image",
  239. localPath: "/tmp/path-large.png",
  240. mimeType: "image/png",
  241. sizeBytes: 1,
  242. }),
  243. ).toMatchObject({
  244. filename: "path-large.png",
  245. localPath: "/tmp/path-large.png",
  246. mimeType: "image/png",
  247. sizeBytes: 20 * 1024 * 1024 + 1,
  248. });
  249. expect(atobSpy).not.toHaveBeenCalled();
  250. } finally {
  251. atobSpy.mockRestore();
  252. }
  253. });
  254. it("恢复无本地路径且无 base64 的小图片时会结构化拒绝", () => {
  255. expect(() =>
  256. restoreChatComposerAttachment({
  257. filename: "metadata-only.png",
  258. kind: "image",
  259. mimeType: "image/png",
  260. sizeBytes: 1,
  261. }),
  262. ).toThrow(MissingInlineImageContentError);
  263. });
  264. it("恢复无本地路径且无 base64 的超大图片时保留发送前拦截状态", () => {
  265. expect(
  266. restoreChatComposerAttachment({
  267. filename: "metadata-only-large.png",
  268. kind: "image",
  269. mimeType: "image/png",
  270. sizeBytes: 21 * 1024 * 1024,
  271. }),
  272. ).toMatchObject({
  273. filename: "metadata-only-large.png",
  274. mimeType: "image/png",
  275. sizeBytes: 21 * 1024 * 1024,
  276. });
  277. });
  278. });
  279. describe("clipboard text attachments", () => {
  280. it("Excel HTML 或制表符文本优先于同 payload 的合成图片", () => {
  281. expect(shouldPreferSpreadsheetClipboardText("A\tB\n1\t2", "")).toBe(true);
  282. expect(
  283. shouldPreferSpreadsheetClipboardText(
  284. "单个单元格",
  285. '<html xmlns:x="urn:schemas-microsoft-com:office:excel"><meta name=ProgId content=Excel.Sheet>',
  286. ),
  287. ).toBe(true);
  288. expect(
  289. shouldPreferSpreadsheetClipboardText("Numbers 单元格", "<table><tr><td>x</td></tr></table>"),
  290. ).toBe(true);
  291. expect(shouldPreferSpreadsheetClipboardText("https://example.com/image.png", "<img>")).toBe(
  292. false,
  293. );
  294. expect(shouldPreferSpreadsheetClipboardText("", "Excel.Sheet")).toBe(false);
  295. });
  296. it("剪贴板文本大于等于 15360 字符时转为附件", () => {
  297. expect(shouldCreateClipboardTextAttachment("a".repeat(15_359))).toBe(false);
  298. expect(shouldCreateClipboardTextAttachment("a".repeat(15_360))).toBe(true);
  299. });
  300. it("转附件不再依赖行数", () => {
  301. const manyShortLines = Array.from({ length: 100 }, () => "x").join("\n");
  302. const singleLongLine = "x".repeat(15_360);
  303. expect(countClipboardTextLines(manyShortLines)).toBe(100);
  304. expect(shouldCreateClipboardTextAttachment(manyShortLines)).toBe(false);
  305. expect(countClipboardTextLines(singleLongLine)).toBe(1);
  306. expect(shouldCreateClipboardTextAttachment(singleLongLine)).toBe(true);
  307. });
  308. it("兼容 CRLF 和 CR 换行计数", () => {
  309. expect(countClipboardTextLines("a\r\nb\rc\nd")).toBe(4);
  310. });
  311. it("创建带 clipboard-text 元数据的文本附件", async () => {
  312. const text = Array.from({ length: 15 }, (_, index) => `line ${index + 1}`).join("\n");
  313. const attachment = createClipboardTextComposerAttachment(text, {
  314. now: new Date("2026-06-27T15:30:12"),
  315. });
  316. expect(attachment).toMatchObject({
  317. filename: "pasted-text-20260627-153012.txt",
  318. mimeType: "text/plain",
  319. sourceKind: "clipboard-text",
  320. lineCount: 15,
  321. charCount: text.length,
  322. });
  323. await expect(attachment.file?.text()).resolves.toBe(text);
  324. });
  325. it("落盘后的粘贴文本附件只序列化 localPath,不内联 textContent", async () => {
  326. const text = "x".repeat(15_360);
  327. const attachment = await serializeChatComposerAttachment(
  328. createClipboardTextPathComposerAttachment(text, {
  329. filename: "pasted-text-20260630-104512-a1b2c3.txt",
  330. localPath: "/Users/test/.zcode/tmp/paste-attachments/2026-06-30/pasted-text.txt",
  331. mimeType: "text/plain",
  332. sizeBytes: Buffer.byteLength(text, "utf8"),
  333. }),
  334. );
  335. expect(attachment).toEqual({
  336. kind: "file",
  337. filename: "pasted-text-20260630-104512-a1b2c3.txt",
  338. localPath: "/Users/test/.zcode/tmp/paste-attachments/2026-06-30/pasted-text.txt",
  339. mimeType: "text/plain",
  340. sourceKind: "clipboard-text",
  341. sizeBytes: 15_360,
  342. });
  343. });
  344. });
  345. describe("video attachments", () => {
  346. it("使用 30MiB 全局 video 输入上限", () => {
  347. expect(VIDEO_INPUT_MAX_BYTES).toBe(30 * 1024 * 1024);
  348. });
  349. it("无 localPath 的视频走 dataBase64 序列化为 kind video", async () => {
  350. const file = new File([new Uint8Array([1, 2, 3, 4])], "demo.mp4", {
  351. type: "video/mp4",
  352. });
  353. const attachment = await serializeChatComposerAttachment(createChatComposerAttachment(file));
  354. expect(attachment).toMatchObject({
  355. kind: "video",
  356. filename: "demo.mp4",
  357. mimeType: "video/mp4",
  358. sizeBytes: file.size,
  359. });
  360. expect(attachment.dataBase64).toEqual(Buffer.from([1, 2, 3, 4]).toString("base64"));
  361. });
  362. it("有 localPath 的视频只序列化路径引用(零拷贝)", async () => {
  363. const file = new File([new Uint8Array([9, 9])], "clip.mov", {
  364. type: "video/quicktime",
  365. });
  366. const attachment = await serializeChatComposerAttachment(
  367. createChatComposerAttachment(file, "/tmp/clip.mov"),
  368. );
  369. expect(attachment).toEqual({
  370. kind: "video",
  371. filename: "clip.mov",
  372. localPath: "/tmp/clip.mov",
  373. mimeType: "video/quicktime",
  374. sizeBytes: file.size,
  375. });
  376. });
  377. it("Web 无路径视频超过 V4 上限时在 base64 编码前抛结构化错误", async () => {
  378. const file = new File([new Uint8Array(4)], "big.mp4", { type: "video/mp4" });
  379. const attachment = createChatComposerAttachment(file);
  380. Object.defineProperty(attachment, "sizeBytes", {
  381. value: PROTOCOL_V4_LIMITS.attachmentMaxBytes + 1,
  382. });
  383. const readAsDataUrl = vi.spyOn(TestFileReader.prototype, "readAsDataURL");
  384. try {
  385. await expect(serializeChatComposerAttachment(attachment)).rejects.toMatchObject({
  386. filename: "big.mp4",
  387. maxSizeBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  388. name: "OversizedInlineVideoAttachmentError",
  389. sizeBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes + 1,
  390. });
  391. expect(readAsDataUrl).not.toHaveBeenCalled();
  392. } finally {
  393. readAsDataUrl.mockRestore();
  394. }
  395. });
  396. it("restore 恢复 video dataBase64 附件并生成可预览 objectUrl", () => {
  397. const attachment = restoreChatComposerAttachment({
  398. kind: "video",
  399. filename: "demo.mp4",
  400. mimeType: "video/mp4",
  401. dataBase64: Buffer.from([5, 6, 7]).toString("base64"),
  402. sizeBytes: 3,
  403. });
  404. expect(attachment.mimeType).toBe("video/mp4");
  405. expect(attachment.sizeBytes).toBeGreaterThanOrEqual(3);
  406. expect(attachment.objectUrl).toBeDefined();
  407. });
  408. it.each([
  409. ["缺少", undefined],
  410. ["低报", 1],
  411. ])("restore 会在解码前拦截 sizeBytes %s的超限视频", (_label, sizeBytes) => {
  412. const atobSpy = vi.spyOn(globalThis, "atob");
  413. try {
  414. expect(() =>
  415. restoreChatComposerAttachment({
  416. kind: "video",
  417. filename: "oversized.mp4",
  418. mimeType: "video/mp4",
  419. dataBase64: OVERSIZED_INLINE_VIDEO_BASE64,
  420. ...(sizeBytes === undefined ? {} : { sizeBytes }),
  421. }),
  422. ).toThrow(OversizedInlineVideoAttachmentError);
  423. expect(atobSpy).not.toHaveBeenCalled();
  424. } finally {
  425. atobSpy.mockRestore();
  426. }
  427. });
  428. it("video 扩展名在无浏览器 mime 时按文件名推断", () => {
  429. const attachment = createChatComposerAttachment(
  430. new File([new Uint8Array(1)], "a.MOV", { type: "" }),
  431. );
  432. expect(attachment.mimeType).toBe("video/quicktime");
  433. });
  434. });