tool-artifact-store.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import { mkdtemp, readdir, readFile, rm, unlink } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { dirname, join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import { createSessionId, createToolCallId } from "@zcode/contracts";
  6. import {
  7. createStorageFsFaultInjector,
  8. resetStorageFsFaultInjectorForTests,
  9. setStorageFsFaultInjectorForTests,
  10. } from "../src/storage/fs-fault-injection.js";
  11. import { createNodeToolArtifactStore } from "../src/storage/index.js";
  12. describe("Node tool artifact store", () => {
  13. afterEach(() => {
  14. resetStorageFsFaultInjectorForTests();
  15. });
  16. it("persists tool result artifacts under a session directory", async () => {
  17. const rootDir = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  18. const store = createNodeToolArtifactStore({
  19. imageCacheRootDir: join(rootDir, "image-cache"),
  20. rootDir,
  21. videoCacheRootDir: join(rootDir, "video-cache"),
  22. });
  23. try {
  24. const result = await store.writeToolResultArtifact({
  25. sessionId: createSessionId("artifact-session"),
  26. toolCallId: createToolCallId("artifact-call"),
  27. toolName: "BigTool",
  28. content: "large output",
  29. contentType: "text/plain",
  30. retention: "session",
  31. });
  32. expect(result.uri).toContain("zcode-artifact://");
  33. expect(result.path).toBeDefined();
  34. expect(result.bytes).toBe(Buffer.byteLength("large output", "utf8"));
  35. await expect(readFile(result.path!, "utf8")).resolves.toBe("large output");
  36. const read = await store.readToolResultArtifact({ uri: result.uri });
  37. expect(read).toMatchObject({
  38. bytes: Buffer.byteLength("large output", "utf8"),
  39. content: "large output",
  40. contentType: "text/plain",
  41. uri: result.uri,
  42. });
  43. await expect(store.statToolResultArtifact!({ uri: result.uri })).resolves.toMatchObject({
  44. uri: result.uri,
  45. bytes: Buffer.byteLength("large output", "utf8"),
  46. contentType: "text/plain",
  47. path: result.path,
  48. });
  49. } finally {
  50. await rm(rootDir, { force: true, recursive: true });
  51. }
  52. });
  53. it("injects fs faults before text artifact writes", async () => {
  54. const rootDir = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  55. const store = createNodeToolArtifactStore({
  56. imageCacheRootDir: join(rootDir, "image-cache"),
  57. rootDir,
  58. videoCacheRootDir: join(rootDir, "video-cache"),
  59. });
  60. const sessionId = createSessionId("artifact-session");
  61. setStorageFsFaultInjectorForTests(
  62. createStorageFsFaultInjector([
  63. {
  64. id: "D05-artifact-write-enospc",
  65. code: "ENOSPC",
  66. operations: ["writeFile"],
  67. pathRegex: "tool-result-.*\\.txt$",
  68. },
  69. ]),
  70. );
  71. try {
  72. await expect(
  73. store.writeToolResultArtifact({
  74. sessionId,
  75. toolCallId: createToolCallId("artifact-call"),
  76. toolName: "BigTool",
  77. content: "large output",
  78. contentType: "text/plain",
  79. retention: "session",
  80. }),
  81. ).rejects.toMatchObject({
  82. code: "ENOSPC",
  83. syscall: "writeFile",
  84. zcodeFsFaultId: "D05-artifact-write-enospc",
  85. });
  86. await expect(readdir(join(rootDir, sessionId))).resolves.toEqual([]);
  87. } finally {
  88. await rm(rootDir, { force: true, recursive: true });
  89. }
  90. });
  91. it("persists binary tool result artifacts without text encoding", async () => {
  92. const rootDir = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  93. const store = createNodeToolArtifactStore({
  94. imageCacheRootDir: join(rootDir, "image-cache"),
  95. rootDir,
  96. videoCacheRootDir: join(rootDir, "video-cache"),
  97. });
  98. const pngBytes = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0xff]);
  99. try {
  100. const result = await store.writeToolResultBinaryArtifact!({
  101. sessionId: createSessionId("artifact-session"),
  102. toolCallId: createToolCallId("artifact-call"),
  103. toolName: "McpScreenshot",
  104. content: pngBytes,
  105. contentType: "image/png",
  106. extension: ".png",
  107. retention: "session",
  108. });
  109. expect(result.path).toBeDefined();
  110. expect(result.path).toMatch(/\.png$/);
  111. expect(result.bytes).toBe(pngBytes.byteLength);
  112. expect(result.contentType).toBe("image/png");
  113. await expect(readFile(result.path!)).resolves.toEqual(Buffer.from(pngBytes));
  114. const read = await store.readToolResultArtifact({ uri: result.uri });
  115. expect(read).toMatchObject({
  116. bytes: pngBytes.byteLength,
  117. content: Buffer.from(pngBytes).toString("base64"),
  118. contentType: "image/png",
  119. uri: result.uri,
  120. });
  121. const rawBytes = Uint8Array.from([0x00, 0x01, 0x02, 0x03]);
  122. const rawResult = await store.writeToolResultBinaryArtifact!({
  123. sessionId: createSessionId("artifact-session"),
  124. toolCallId: createToolCallId("raw-call"),
  125. toolName: "RawBytes",
  126. content: rawBytes,
  127. contentType: "application/octet-stream",
  128. retention: "session",
  129. });
  130. expect(rawResult.path).toMatch(/\.bin$/);
  131. const rawRead = await store.readToolResultArtifact({ uri: rawResult.uri });
  132. expect(rawRead).toMatchObject({
  133. bytes: rawBytes.byteLength,
  134. content: Buffer.from(rawBytes).toString("base64"),
  135. contentType: "application/octet-stream",
  136. uri: rawResult.uri,
  137. });
  138. } finally {
  139. await rm(rootDir, { force: true, recursive: true });
  140. }
  141. });
  142. // Bug 根因(2026-09-04):文本读回按文件名推 contentType,办公文件扩展名不在表里 → 当作
  143. // application/json 走 utf8 解码 → 字节损坏。二进制读回返回原始字节,不经任何编码。
  144. it("reads binary artifacts back as raw bytes regardless of extension", async () => {
  145. const rootDir = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  146. const store = createNodeToolArtifactStore({
  147. imageCacheRootDir: join(rootDir, "image-cache"),
  148. rootDir,
  149. videoCacheRootDir: join(rootDir, "video-cache"),
  150. });
  151. // 含无效 utf8 序列(0xff 0xfe)与 NUL:任何文本解码都会改写它。
  152. const xlsxLikeBytes = Uint8Array.from([0x50, 0x4b, 0x03, 0x04, 0xff, 0xfe, 0x00, 0xc3, 0x28]);
  153. try {
  154. const written = await store.writeToolResultBinaryArtifact!({
  155. sessionId: createSessionId("artifact-session"),
  156. toolCallId: createToolCallId("dwfrun-1:artifact#1@1"),
  157. toolName: "CreateWorkflow",
  158. content: xlsxLikeBytes,
  159. contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  160. extension: ".xlsx",
  161. retention: "project",
  162. });
  163. expect(written.path).toMatch(/\.xlsx$/);
  164. const read = await store.readToolResultBinaryArtifact!({ uri: written.uri });
  165. expect(Array.from(read.bytes)).toEqual(Array.from(xlsxLikeBytes));
  166. expect(read.uri).toBe(written.uri);
  167. expect(read.path).toBe(written.path);
  168. // 文件名推断只是兜底:办公扩展名给 octet-stream,绝不再给 application/json。
  169. expect(read.contentType).toBe("application/octet-stream");
  170. // 对照:文本读回在同一文件上的确会损坏(这是二进制读回存在的理由)。
  171. const text = await store.readToolResultArtifact({ uri: written.uri });
  172. expect(text.contentType).toBe("application/octet-stream");
  173. expect(text.content).toBe(Buffer.from(xlsxLikeBytes).toString("base64"));
  174. // 同一会话目录下不存在的 artifactId:定位失败要报「not found」,不是裸 ENOENT。
  175. await expect(
  176. store.readToolResultBinaryArtifact!({
  177. uri: written.uri.replace(/tool-result-[^/]+$/, "tool-result-missing"),
  178. }),
  179. ).rejects.toThrow(/not found/);
  180. } finally {
  181. await rm(rootDir, { force: true, recursive: true });
  182. }
  183. });
  184. it("primes one derived image path and rebuilds it from the durable data URL artifact", async () => {
  185. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  186. const rootDir = join(tempRoot, "artifacts");
  187. const imageCacheRootDir = join(tempRoot, "image-cache");
  188. const store = createNodeToolArtifactStore({
  189. imageCacheRootDir,
  190. rootDir,
  191. videoCacheRootDir: join(tempRoot, "video-cache"),
  192. });
  193. const sessionId = createSessionId("artifact-image-cache");
  194. const imageBytes = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x01]);
  195. try {
  196. const artifact = await store.writeToolResultArtifact({
  197. sessionId,
  198. toolCallId: createToolCallId("prompt-image"),
  199. toolName: "prompt-attachment:upload",
  200. content: `data:image/png;base64,${Buffer.from(imageBytes).toString("base64")}`,
  201. contentType: "text/plain",
  202. retention: "session",
  203. });
  204. const primePromise = store.primeImageAttachmentPath!({
  205. bytes: imageBytes,
  206. mediaType: "image/png",
  207. uri: artifact.uri,
  208. });
  209. const ensurePromise = store.ensureMediaAttachmentPath!({
  210. mediaType: "image/png",
  211. uri: artifact.uri,
  212. });
  213. expect(ensurePromise).toBe(primePromise);
  214. const [primed, ensured] = await Promise.all([primePromise, ensurePromise]);
  215. if (primed.status !== "ready" || ensured.status !== "ready") {
  216. throw new Error("expected supported PNG image paths");
  217. }
  218. expect(dirname(artifact.path!)).toBe(join(rootDir, sessionId));
  219. expect(dirname(primed.path)).toBe(join(imageCacheRootDir, sessionId));
  220. expect(primed.path).toBe(ensured.path);
  221. expect(primed.path).toMatch(/\.png$/);
  222. await expect(readFile(primed.path)).resolves.toEqual(Buffer.from(imageBytes));
  223. expect(
  224. (await readdir(join(imageCacheRootDir, sessionId))).filter((name) => name.endsWith(".png")),
  225. ).toHaveLength(1);
  226. await unlink(primed.path);
  227. const rebuilt = await store.ensureMediaAttachmentPath!({
  228. mediaType: "image/png",
  229. uri: artifact.uri,
  230. });
  231. expect(rebuilt).toEqual({ status: "ready", path: primed.path });
  232. if (rebuilt.status !== "ready") throw new Error("expected rebuilt PNG image path");
  233. await expect(readFile(rebuilt.path)).resolves.toEqual(Buffer.from(imageBytes));
  234. } finally {
  235. await rm(tempRoot, { force: true, recursive: true });
  236. }
  237. });
  238. it("materializes one video path and rebuilds it from the durable data URL artifact", async () => {
  239. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  240. const rootDir = join(tempRoot, "artifacts");
  241. const videoCacheRootDir = join(tempRoot, "video-cache");
  242. const store = createNodeToolArtifactStore({
  243. imageCacheRootDir: join(tempRoot, "image-cache"),
  244. rootDir,
  245. videoCacheRootDir,
  246. });
  247. const sessionId = createSessionId("artifact-video-cache");
  248. const videoBytes = Uint8Array.from([0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70]);
  249. try {
  250. const artifact = await store.writeToolResultArtifact({
  251. sessionId,
  252. toolCallId: createToolCallId("prompt-video"),
  253. toolName: "prompt-attachment:upload",
  254. content: `data:video/mp4;base64,${Buffer.from(videoBytes).toString("base64")}`,
  255. contentType: "text/plain",
  256. retention: "session",
  257. });
  258. const first = store.ensureMediaAttachmentPath!({
  259. mediaType: "video/mp4",
  260. uri: artifact.uri,
  261. });
  262. const second = store.ensureMediaAttachmentPath!({
  263. mediaType: "video/mp4",
  264. uri: artifact.uri,
  265. });
  266. expect(second).toBe(first);
  267. const materialized = await first;
  268. if (materialized.status !== "ready") throw new Error("expected supported MP4 video path");
  269. expect(dirname(materialized.path)).toBe(join(videoCacheRootDir, sessionId));
  270. expect(materialized.path).toMatch(/\.mp4$/);
  271. await expect(readFile(materialized.path)).resolves.toEqual(Buffer.from(videoBytes));
  272. await unlink(materialized.path);
  273. const rebuilt = await store.ensureMediaAttachmentPath!({
  274. mediaType: "video/mp4",
  275. uri: artifact.uri,
  276. });
  277. expect(rebuilt).toEqual({ status: "ready", path: materialized.path });
  278. if (rebuilt.status !== "ready") throw new Error("expected rebuilt MP4 video path");
  279. await expect(readFile(rebuilt.path)).resolves.toEqual(Buffer.from(videoBytes));
  280. } finally {
  281. await rm(tempRoot, { force: true, recursive: true });
  282. }
  283. });
  284. it("materializes one PDF path and rebuilds it from the durable data URL artifact", async () => {
  285. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  286. const rootDir = join(tempRoot, "artifacts");
  287. const pdfCacheRootDir = join(tempRoot, "pdf-cache");
  288. const store = createNodeToolArtifactStore({
  289. imageCacheRootDir: join(tempRoot, "image-cache"),
  290. pdfCacheRootDir,
  291. rootDir,
  292. videoCacheRootDir: join(tempRoot, "video-cache"),
  293. });
  294. const sessionId = createSessionId("artifact-pdf-cache");
  295. const pdfBytes = Buffer.from("%PDF-1.7\\nbody");
  296. try {
  297. const artifact = await store.writeToolResultArtifact({
  298. sessionId,
  299. toolCallId: createToolCallId("prompt-pdf"),
  300. toolName: "prompt-attachment:pdf",
  301. content: `data:application/pdf;base64,${pdfBytes.toString("base64")}`,
  302. contentType: "text/plain",
  303. retention: "session",
  304. });
  305. const first = store.ensureMediaAttachmentPath!({
  306. mediaType: "application/pdf",
  307. uri: artifact.uri,
  308. });
  309. const second = store.ensureMediaAttachmentPath!({
  310. mediaType: "application/pdf",
  311. uri: artifact.uri,
  312. });
  313. expect(second).toBe(first);
  314. const materialized = await first;
  315. if (materialized.status !== "ready") throw new Error("expected supported PDF path");
  316. expect(dirname(materialized.path)).toBe(join(pdfCacheRootDir, sessionId));
  317. expect(materialized.path).toMatch(/\.pdf$/);
  318. await expect(readFile(materialized.path)).resolves.toEqual(pdfBytes);
  319. await unlink(materialized.path);
  320. const rebuilt = await store.ensureMediaAttachmentPath!({
  321. mediaType: "application/pdf",
  322. uri: artifact.uri,
  323. });
  324. expect(rebuilt).toEqual({ status: "ready", path: materialized.path });
  325. if (rebuilt.status !== "ready") throw new Error("expected rebuilt PDF path");
  326. await expect(readFile(rebuilt.path)).resolves.toEqual(pdfBytes);
  327. } finally {
  328. await rm(tempRoot, { force: true, recursive: true });
  329. }
  330. });
  331. it("skips unsupported image cache media types without interrupting the attachment flow", async () => {
  332. const rootDir = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  333. const imageCacheRootDir = join(rootDir, "image-cache");
  334. const store = createNodeToolArtifactStore({
  335. imageCacheRootDir,
  336. rootDir,
  337. videoCacheRootDir: join(rootDir, "video-cache"),
  338. });
  339. const sessionId = createSessionId("artifact-unsupported-image-cache");
  340. const imageBytes = Uint8Array.from([0x42, 0x4d, 0x01, 0x02]);
  341. try {
  342. const artifact = await store.writeToolResultArtifact({
  343. sessionId,
  344. toolCallId: createToolCallId("prompt-image"),
  345. toolName: "prompt-attachment:upload",
  346. content: `data:image/bmp;base64,${Buffer.from(imageBytes).toString("base64")}`,
  347. contentType: "text/plain",
  348. retention: "session",
  349. });
  350. const primePromise = store.primeImageAttachmentPath!({
  351. bytes: imageBytes,
  352. mediaType: "image/bmp",
  353. uri: artifact.uri,
  354. });
  355. const ensurePromise = store.ensureMediaAttachmentPath!({
  356. mediaType: "image/bmp",
  357. uri: artifact.uri,
  358. });
  359. expect(ensurePromise).toBe(primePromise);
  360. await expect(primePromise).resolves.toEqual({ status: "unsupported" });
  361. await expect(
  362. store.ensureMediaAttachmentPath!({
  363. mediaType: "image/bmp",
  364. uri: artifact.uri,
  365. }),
  366. ).resolves.toEqual({ status: "unsupported" });
  367. await expect(readdir(join(imageCacheRootDir, sessionId))).rejects.toMatchObject({
  368. code: "ENOENT",
  369. });
  370. } finally {
  371. await rm(rootDir, { force: true, recursive: true });
  372. }
  373. });
  374. it("injects fs faults before binary artifact directory creation", async () => {
  375. const rootDir = await mkdtemp(join(tmpdir(), "zcode-tool-artifacts-"));
  376. const store = createNodeToolArtifactStore({
  377. imageCacheRootDir: join(rootDir, "image-cache"),
  378. rootDir,
  379. videoCacheRootDir: join(rootDir, "video-cache"),
  380. });
  381. const pngBytes = Uint8Array.from([0x89, 0x50, 0x4e, 0x47]);
  382. setStorageFsFaultInjectorForTests(
  383. createStorageFsFaultInjector([
  384. {
  385. id: "D05-artifact-mkdir-eacces",
  386. code: "EACCES",
  387. operations: ["mkdir"],
  388. pathIncludes: rootDir,
  389. },
  390. ]),
  391. );
  392. try {
  393. await expect(
  394. store.writeToolResultBinaryArtifact!({
  395. sessionId: createSessionId("artifact-session"),
  396. toolCallId: createToolCallId("artifact-call"),
  397. toolName: "McpScreenshot",
  398. content: pngBytes,
  399. contentType: "image/png",
  400. extension: ".png",
  401. retention: "session",
  402. }),
  403. ).rejects.toMatchObject({
  404. code: "EACCES",
  405. syscall: "mkdir",
  406. zcodeFsFaultId: "D05-artifact-mkdir-eacces",
  407. });
  408. await expect(readdir(rootDir)).resolves.toEqual([]);
  409. } finally {
  410. await rm(rootDir, { force: true, recursive: true });
  411. }
  412. });
  413. });