read-pdf.test.ts 13 KB

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