tool-artifact-store.test.ts 19 KB

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