read-pdf.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. CoreErrorType,
  4. READ_PDF_EXTRACT_MAX_INPUT_BYTES,
  5. READ_PDF_NATIVE_MAX_INPUT_BYTES,
  6. createSessionId,
  7. createToolCallId,
  8. createTurnId,
  9. PdfDocumentPortError,
  10. ReadErrorCode,
  11. type FileSystemPort,
  12. type ImageProcessorPort,
  13. type PdfDocumentPort,
  14. } from "@zcode/contracts";
  15. import { readHandler, readToolEntry } from "../src/tool/handlers/read.js";
  16. import type { ToolExecutionContext } from "../src/tool/types.js";
  17. import { createTestRuntimeModel } from "./test-runtime-model.js";
  18. const PDF_PATH = "/tmp/report.pdf";
  19. describe("Read PDF handling", () => {
  20. it("returns the page summary followed by ordered prepared page images", async () => {
  21. const renderPages = vi.fn(async () => [
  22. {
  23. pageNumber: 2,
  24. data: new Uint8Array(Buffer.from("page-two")),
  25. mediaType: "image/jpeg" as const,
  26. },
  27. {
  28. pageNumber: 3,
  29. data: new Uint8Array(Buffer.from("page-three")),
  30. mediaType: "image/jpeg" as const,
  31. },
  32. ]);
  33. const result = await executeReadPdf(
  34. { file_path: PDF_PATH, pages: "2-3" },
  35. { supportsPdf: true, supportsImages: true },
  36. { renderPages },
  37. );
  38. expect(result.output).toMatchObject({
  39. type: "parts",
  40. filePath: PDF_PATH,
  41. numParts: 2,
  42. originalSize: 1_536,
  43. pages: [{ pageNumber: 2 }, { pageNumber: 3 }],
  44. });
  45. expect(result.modelContent).toEqual([
  46. { type: "text", text: `PDF pages extracted: 2 page(s) from ${PDF_PATH} (1.5KB)` },
  47. expect.objectContaining({
  48. type: "image",
  49. mediaType: "image/jpeg",
  50. dataUrl: `data:image/jpeg;base64,${Buffer.from("page-two").toString("base64")}`,
  51. }),
  52. expect.objectContaining({
  53. type: "image",
  54. mediaType: "image/jpeg",
  55. dataUrl: `data:image/jpeg;base64,${Buffer.from("page-three").toString("base64")}`,
  56. }),
  57. ]);
  58. expect(JSON.stringify(result.modelContent)).not.toMatch(
  59. /Page_\d+_(?:image|parse_result)|text layer/u,
  60. );
  61. });
  62. it("returns a unified tool error before Poppler when page images are unsupported", async () => {
  63. const renderPages = vi.fn();
  64. const result = await executeReadPdf(
  65. { file_path: PDF_PATH, pages: "1-2" },
  66. { supportsPdf: true, supportsImages: false },
  67. { renderPages },
  68. );
  69. expect(result.success).toBe(false);
  70. expect(result.output).toEqual({
  71. result: false,
  72. errorCode: ReadErrorCode.PDF_PAGES_IMAGES_UNSUPPORTED,
  73. message:
  74. "The current model supports PDF input but does not support image input; remove the pages parameter.",
  75. });
  76. expect(result.modelContent).toBe(
  77. "<tool_use_error>The current model supports PDF input but does not support image input; remove the pages parameter.</tool_use_error>",
  78. );
  79. expect(renderPages).not.toHaveBeenCalled();
  80. });
  81. it.each([
  82. ["unavailable", ReadErrorCode.PDF_CONFIGURATION_ERROR],
  83. ["corrupted", ReadErrorCode.PDF_INVALID],
  84. ["timeout", ReadErrorCode.PDF_TIMEOUT],
  85. ["password_protected", ReadErrorCode.PDF_PASSWORD_PROTECTED],
  86. ["page_out_of_range", ReadErrorCode.PDF_PAGE_OUT_OF_RANGE],
  87. ["permission_denied", ReadErrorCode.PDF_PERMISSION_DENIED],
  88. ["io_error", ReadErrorCode.PDF_IO_ERROR],
  89. ["process_failed", ReadErrorCode.PDF_PROCESS_FAILED],
  90. ] as const)("preserves the %s Poppler failure category", async (portCode, readCode) => {
  91. const result = await executeReadPdf(
  92. { file_path: PDF_PATH, pages: "1" },
  93. { supportsPdf: true, supportsImages: true },
  94. {
  95. renderPages: async () => {
  96. throw new PdfDocumentPortError(portCode, `PDF failure: ${portCode}`);
  97. },
  98. },
  99. );
  100. expect(result.output).toEqual({
  101. result: false,
  102. errorCode: readCode,
  103. message: `PDF failure: ${portCode}`,
  104. });
  105. });
  106. it("normalizes paged Poppler cancellation for the executor", async () => {
  107. await expect(
  108. executeReadPdf(
  109. { file_path: PDF_PATH, pages: "1" },
  110. { supportsPdf: true, supportsImages: true },
  111. {
  112. renderPages: async () => {
  113. throw new PdfDocumentPortError("cancelled", "PDF extraction cancelled");
  114. },
  115. },
  116. ),
  117. ).rejects.toMatchObject({
  118. message: "PDF extraction cancelled",
  119. type: CoreErrorType.ToolCancelled,
  120. });
  121. });
  122. it("reads a small PDF natively without invoking Poppler rendering", async () => {
  123. const getPageCount = vi.fn(async () => 2);
  124. const renderPages = vi.fn();
  125. const result = await executeReadPdf(
  126. { file_path: PDF_PATH },
  127. { supportsPdf: true, supportsImages: false },
  128. { getPageCount, renderPages },
  129. );
  130. expect(result.success).toBe(true);
  131. expect(result.modelContent).toEqual([
  132. { type: "text", text: `PDF file read: ${PDF_PATH} (1.5KB)` },
  133. expect.objectContaining({
  134. type: "file",
  135. mediaType: "application/pdf",
  136. dataUrl: expect.stringMatching(/^data:application\/pdf;base64,/u),
  137. }),
  138. ]);
  139. expect(getPageCount).toHaveBeenCalledTimes(1);
  140. expect(renderPages).not.toHaveBeenCalled();
  141. });
  142. it("uses the exact error for a non-regular PDF path", async () => {
  143. const result = await executeReadPdf(
  144. { file_path: PDF_PATH, pages: "1" },
  145. { supportsPdf: true, supportsImages: true },
  146. {},
  147. fileSystemPortWith({
  148. async stat(request) {
  149. return { path: request.path, kind: "directory", sizeBytes: 0 };
  150. },
  151. }),
  152. );
  153. expect(result.modelContent).toBe(
  154. `<tool_use_error>Path is not a regular file: ${PDF_PATH}</tool_use_error>`,
  155. );
  156. });
  157. it("uses the exact native PDF size-limit error", async () => {
  158. const result = await executeReadPdf(
  159. { file_path: PDF_PATH },
  160. { supportsPdf: true, supportsImages: false },
  161. {},
  162. fileSystemPortWith({
  163. async stat(request) {
  164. return {
  165. path: request.path,
  166. kind: "file",
  167. sizeBytes: READ_PDF_NATIVE_MAX_INPUT_BYTES + 1,
  168. };
  169. },
  170. }),
  171. );
  172. expect(result.modelContent).toBe(
  173. "<tool_use_error>PDF file exceeds maximum allowed size of 20MB.</tool_use_error>",
  174. );
  175. });
  176. it("uses the exact page-extraction size-limit error", async () => {
  177. const result = await executeReadPdf(
  178. { file_path: PDF_PATH, pages: "1" },
  179. { supportsPdf: true, supportsImages: true },
  180. {},
  181. fileSystemPortWith({
  182. async stat(request) {
  183. return {
  184. path: request.path,
  185. kind: "file",
  186. sizeBytes: READ_PDF_EXTRACT_MAX_INPUT_BYTES + 1,
  187. };
  188. },
  189. }),
  190. );
  191. expect(result.modelContent).toBe(
  192. "<tool_use_error>PDF file exceeds maximum allowed size for text extraction (100MB).</tool_use_error>",
  193. );
  194. });
  195. it("uses the exact missing-PDF-header error", async () => {
  196. const invalidPdf = new Uint8Array(Buffer.from("not-a-pdf"));
  197. const result = await executeReadPdf(
  198. { file_path: PDF_PATH },
  199. { supportsPdf: true, supportsImages: false },
  200. { getPageCount: async () => undefined },
  201. fileSystemPortWith({
  202. async readBinaryFile(request) {
  203. return {
  204. path: request.path,
  205. content: invalidPdf,
  206. bytesRead: invalidPdf.byteLength,
  207. sizeBytes: invalidPdf.byteLength,
  208. truncated: false,
  209. };
  210. },
  211. async stat(request) {
  212. return { path: request.path, kind: "file", sizeBytes: invalidPdf.byteLength };
  213. },
  214. }),
  215. );
  216. expect(result.modelContent).toBe(
  217. `<tool_use_error>File is not a valid PDF (missing %PDF- header): ${PDF_PATH}</tool_use_error>`,
  218. );
  219. });
  220. it("uses the fixed punctuation when requiring pages for a long PDF", async () => {
  221. const result = await executeReadPdf(
  222. { file_path: PDF_PATH },
  223. { supportsPdf: true, supportsImages: false },
  224. { getPageCount: async () => 88 },
  225. );
  226. expect(result.modelContent).toBe(
  227. '<tool_use_error>This PDF has 88 pages, which is too many to read at once. Use the pages parameter to read specific page ranges (e.g., pages: "1-5"). Maximum 20 pages per request.</tool_use_error>',
  228. );
  229. });
  230. it("continues native PDF reading when page-count inspection is unavailable", async () => {
  231. const result = await executeReadPdf(
  232. { file_path: PDF_PATH },
  233. { supportsPdf: true, supportsImages: false },
  234. { getPageCount: async () => undefined },
  235. );
  236. expect(result.success).toBe(true);
  237. expect(result.output).toMatchObject({ type: "pdf", filePath: PDF_PATH });
  238. });
  239. it("propagates native page-count cancellation while the outer signal is still live", async () => {
  240. await expect(
  241. executeReadPdf(
  242. { file_path: PDF_PATH },
  243. { supportsPdf: true, supportsImages: false },
  244. {
  245. getPageCount: async () => {
  246. throw new PdfDocumentPortError("cancelled", "PDF inspection cancelled");
  247. },
  248. },
  249. ),
  250. ).rejects.toMatchObject({
  251. message: "PDF inspection cancelled",
  252. type: CoreErrorType.ToolCancelled,
  253. });
  254. });
  255. it("propagates unexpected native page-count inspection failures", async () => {
  256. const inspectionError = new Error("unexpected pdfinfo adapter failure");
  257. await expect(
  258. executeReadPdf(
  259. { file_path: PDF_PATH },
  260. { supportsPdf: true, supportsImages: false },
  261. {
  262. getPageCount: async () => {
  263. throw inspectionError;
  264. },
  265. },
  266. ),
  267. ).rejects.toBe(inspectionError);
  268. });
  269. it("reads PDF-disabled current turn input as text", async () => {
  270. const context = contextWith({});
  271. context.model = createTestRuntimeModel({
  272. generateText: async () => ({ finishReason: "stop", text: "", usage: {} }),
  273. inputFormat: { supportsPdf: false },
  274. modelId: "turn-unknown-pdf",
  275. });
  276. const output = await readHandler({ file_path: PDF_PATH, pages: "1" }, context);
  277. expect(output).toMatchObject({ type: "text", filePath: PDF_PATH });
  278. });
  279. });
  280. async function executeReadPdf(
  281. input: unknown,
  282. capabilities: { supportsPdf?: boolean; supportsImages?: boolean },
  283. pdfPort: Partial<PdfDocumentPort>,
  284. fileSystem?: FileSystemPort,
  285. ) {
  286. const context = contextWith(pdfPort, fileSystem);
  287. context.model = createTestRuntimeModel({
  288. generateText: async () => ({ finishReason: "stop", text: "", usage: {} }),
  289. inputFormat: {
  290. supportsPdf: capabilities.supportsPdf ?? false,
  291. supportsImage: capabilities.supportsImages ?? false,
  292. },
  293. modelId: "pdf-model",
  294. });
  295. const output = await readHandler(input, context);
  296. if (isHandlerFailure(output)) {
  297. return {
  298. success: false,
  299. output,
  300. modelContent: `<tool_use_error>${output.message}</tool_use_error>`,
  301. };
  302. }
  303. return {
  304. success: true,
  305. output,
  306. modelContent: readToolEntry.formatModelContent?.(output),
  307. };
  308. }
  309. function isHandlerFailure(
  310. value: unknown,
  311. ): value is { result: false; errorCode: number; message: string } {
  312. return typeof value === "object" && value !== null && "result" in value && value.result === false;
  313. }
  314. function contextWith(
  315. pdfPort: Partial<PdfDocumentPort>,
  316. fileSystem: FileSystemPort = fileSystemPort(),
  317. ): ToolExecutionContext {
  318. return {
  319. abortSignal: new AbortController().signal,
  320. fileSystemPort: fileSystem,
  321. imageProcessorPort: imageProcessorPort(),
  322. pdfDocumentPort: pdfPort as PdfDocumentPort,
  323. sessionId: createSessionId("read-pdf-context"),
  324. toolCallId: createToolCallId("read-pdf-context"),
  325. traceId: "trace-read-pdf" as never,
  326. turnId: createTurnId("read-pdf-context"),
  327. workingDirectory: "/tmp",
  328. workspaceRoot: "/tmp",
  329. };
  330. }
  331. function fileSystemPortWith(overrides: Partial<FileSystemPort>): FileSystemPort {
  332. return { ...fileSystemPort(), ...overrides } as FileSystemPort;
  333. }
  334. function fileSystemPort(): FileSystemPort {
  335. const data = Buffer.concat([Buffer.from("%PDF-1.7\n"), Buffer.alloc(1_527)]);
  336. return {
  337. async stat(request) {
  338. return { path: request.path, kind: "file", sizeBytes: data.byteLength };
  339. },
  340. async readBinaryFile(request) {
  341. return {
  342. path: request.path,
  343. content: new Uint8Array(data),
  344. bytesRead: data.byteLength,
  345. sizeBytes: data.byteLength,
  346. truncated: false,
  347. };
  348. },
  349. async readTextFileRange(request) {
  350. return {
  351. path: request.path,
  352. content: data.toString("utf8"),
  353. encoding: "utf8" as const,
  354. bytesRead: data.byteLength,
  355. sizeBytes: data.byteLength,
  356. truncated: false,
  357. startLine: 1,
  358. lineCount: 1,
  359. totalLines: 1,
  360. };
  361. },
  362. } as FileSystemPort;
  363. }
  364. function imageProcessorPort(): ImageProcessorPort {
  365. return {
  366. async prepareForModel(request) {
  367. return {
  368. data: request.data,
  369. mediaType: request.mediaType,
  370. originalSizeBytes: request.data.byteLength,
  371. transformedSizeBytes: request.data.byteLength,
  372. resized: false,
  373. compressed: false,
  374. strategy: "original" as const,
  375. };
  376. },
  377. };
  378. }