runtime-read-pdf.test.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import { tmpdir } from "node:os";
  2. import { join } from "node:path";
  3. import { describe, expect, it, vi } from "vitest";
  4. import {
  5. createSessionId,
  6. type FileSystemPort,
  7. type ImageProcessorPort,
  8. type ModelRequest,
  9. type PdfDocumentPort,
  10. } from "@zcode/contracts";
  11. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  12. import { createTestSessionEventStore } from "./test-event-store.js";
  13. import { createTestModelFactory } from "./test-runtime-model.js";
  14. const WORKSPACE_PATH = join(tmpdir(), "zcode-runtime-read-pdf");
  15. const PDF_PATH = join(WORKSPACE_PATH, "report.pdf");
  16. const PDF_CONTENT = new Uint8Array(Buffer.from("%PDF-1.7\nfixture"));
  17. const TOOL_CALL_ID = "read-pdf";
  18. describe.each(["interactive", "subagent_child"] as const)(
  19. "AgentRuntime PDF dependency wiring (%s)",
  20. (taskType) => {
  21. it("returns rendered page images to the model through the injected PDF port", async () => {
  22. const renderPages = vi.fn<PdfDocumentPort["renderPages"]>(async () =>
  23. [2, 3].map((pageNumber) => ({
  24. pageNumber,
  25. data: new Uint8Array(Buffer.from(`page-${pageNumber}`)),
  26. mediaType: "image/jpeg",
  27. })),
  28. );
  29. const getPageCount = vi.fn<PdfDocumentPort["getPageCount"]>();
  30. const { requests, readBinaryFile } = await executePdfRead(taskType, {
  31. pages: "2-3",
  32. pdfDocumentPort: { getPageCount, renderPages },
  33. });
  34. expect(renderPages).toHaveBeenCalledExactlyOnceWith(
  35. expect.objectContaining({ filePath: PDF_PATH, firstPage: 2, lastPage: 3 }),
  36. expect.objectContaining({ signal: expect.any(AbortSignal) }),
  37. );
  38. expect(getPageCount).not.toHaveBeenCalled();
  39. expect(readBinaryFile).not.toHaveBeenCalled();
  40. const toolResult = requests[1]?.messages.find(
  41. (message) => message.role === "tool" && message.toolCallId === TOOL_CALL_ID,
  42. );
  43. expect(toolResult).toMatchObject({ role: "tool", toolName: "Read", isError: false });
  44. expect(toolResult?.content).toEqual([
  45. expect.objectContaining({
  46. type: "text",
  47. text: expect.stringContaining("PDF pages extracted: 2 page(s)"),
  48. }),
  49. ...[2, 3].map((pageNumber) =>
  50. expect.objectContaining({
  51. type: "image",
  52. mediaType: "image/jpeg",
  53. dataUrl: `data:image/jpeg;base64,${Buffer.from(`page-${pageNumber}`).toString("base64")}`,
  54. }),
  55. ),
  56. ]);
  57. });
  58. it("checks the page count before sending a whole PDF to the model", async () => {
  59. const getPageCount = vi.fn<PdfDocumentPort["getPageCount"]>(async () => 11);
  60. const renderPages = vi.fn<PdfDocumentPort["renderPages"]>();
  61. const { requests, readBinaryFile } = await executePdfRead(taskType, {
  62. pdfDocumentPort: { getPageCount, renderPages },
  63. });
  64. expect(getPageCount).toHaveBeenCalledExactlyOnceWith(
  65. expect.objectContaining({ filePath: PDF_PATH }),
  66. expect.objectContaining({ signal: expect.any(AbortSignal) }),
  67. );
  68. expect(renderPages).not.toHaveBeenCalled();
  69. expect(readBinaryFile).not.toHaveBeenCalled();
  70. expect(
  71. requests[1]?.messages.find(
  72. (message) => message.role === "tool" && message.toolCallId === TOOL_CALL_ID,
  73. ),
  74. ).toMatchObject({
  75. isError: true,
  76. content: expect.stringContaining(
  77. "This PDF has 11 pages, which is too many to read at once",
  78. ),
  79. });
  80. });
  81. },
  82. );
  83. async function executePdfRead(
  84. taskType: "interactive" | "subagent_child",
  85. options: { pages?: string; pdfDocumentPort: PdfDocumentPort },
  86. ) {
  87. const requests: ModelRequest[] = [];
  88. const readBinaryFile = vi.fn<FileSystemPort["readBinaryFile"]>(async (request) => ({
  89. path: request.path,
  90. content: PDF_CONTENT,
  91. bytesRead: PDF_CONTENT.byteLength,
  92. sizeBytes: PDF_CONTENT.byteLength,
  93. }));
  94. const fileSystemPort = {
  95. stat: vi.fn<FileSystemPort["stat"]>(async (request) => ({
  96. path: request.path,
  97. kind: "file",
  98. sizeBytes: PDF_CONTENT.byteLength,
  99. })),
  100. readBinaryFile,
  101. } as unknown as FileSystemPort;
  102. const imageProcessorPort: ImageProcessorPort = {
  103. resizeToFit: vi.fn<ImageProcessorPort["resizeToFit"]>(),
  104. async prepareForModel(request) {
  105. return {
  106. data: request.data,
  107. mediaType: request.mediaType,
  108. originalSizeBytes: request.data.byteLength,
  109. transformedSizeBytes: request.data.byteLength,
  110. resized: false,
  111. compressed: false,
  112. strategy: "original",
  113. };
  114. },
  115. };
  116. const runtime = createTestAgentRuntime(
  117. createSessionId(`runtime-read-pdf-${taskType}`),
  118. {
  119. taskType,
  120. mode: "build",
  121. modelStreaming: "off",
  122. workingDirectory: WORKSPACE_PATH,
  123. memory: { enabled: false },
  124. compact: { enabled: false },
  125. },
  126. {
  127. eventStore: createTestSessionEventStore(),
  128. fileSystemPort,
  129. imageProcessorPort,
  130. pdfDocumentPort: options.pdfDocumentPort,
  131. modelFactory: createTestModelFactory({
  132. async generateText(request) {
  133. requests.push(request);
  134. return requests.length === 1
  135. ? {
  136. finishReason: "tool-calls",
  137. text: "",
  138. toolCalls: [
  139. {
  140. id: TOOL_CALL_ID,
  141. name: "Read",
  142. input: {
  143. file_path: PDF_PATH,
  144. ...(options.pages === undefined ? {} : { pages: options.pages }),
  145. },
  146. },
  147. ],
  148. usage: {},
  149. }
  150. : { finishReason: "stop", text: "done", usage: {} };
  151. },
  152. }),
  153. },
  154. );
  155. await runtime.executeTurn("Read the PDF");
  156. expect(requests).toHaveLength(2);
  157. return { requests, readBinaryFile };
  158. }