attachment-resume-wire.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { createAnthropic } from "@ai-sdk/anthropic";
  5. import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
  6. import { generateText } from "ai";
  7. import { describe, expect, it } from "vitest";
  8. import {
  9. createMessageId,
  10. createProjectId,
  11. createSessionId,
  12. type AttachmentStorageMetadata,
  13. type ModelInputMessage,
  14. type TurnAttachment,
  15. } from "@zcode/contracts";
  16. import { MessageHistoryImpl } from "../../core/src/agent/message-history.js";
  17. import { hydrateMessageHistoryFromSession } from "../../core/src/agent/session-history-hydrator.js";
  18. import { resolveTurnAttachments } from "../../core/src/runtime/helpers/attachments.js";
  19. import { resolvedPathReferenceAttachment } from "../../core/src/runtime/helpers/attachment-path-reference.js";
  20. import { buildRuntimeUserEntriesFromTurn } from "../../core/src/runtime/helpers/conversation.js";
  21. import { projectMessagesWithMediaAttachmentPaths } from "../../core/src/runtime/helpers/media-attachment-path.js";
  22. import { buildProviderRequestMessages } from "../../core/src/runtime/helpers/provider-request-messages.js";
  23. import { persistUserPrompt } from "../../core/src/runtime/methods/message-persistence.js";
  24. import type { AgentRuntimeInternal } from "../../core/src/runtime/internal.js";
  25. import { createNodeFileSystemAdapter } from "../src/fs/index.js";
  26. import { toAiSdkMessages } from "../src/model/transform.js";
  27. import { createNodeToolArtifactStore, createSqliteSessionStore } from "../src/storage/index.js";
  28. const png =
  29. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aDo0AAAAASUVORK5CYII=";
  30. const pdf = `data:application/pdf;base64,${Buffer.from("%PDF-1.7\nfixture").toString("base64")}`;
  31. const scenarios: Array<{ name: string; attachments: TurnAttachment[] }> = [
  32. { name: "binary path", attachments: [{ type: "file", path: "bundle.zip" }] },
  33. {
  34. name: "clipboard path",
  35. attachments: [{ type: "file", path: "pasted.txt", sourceKind: "clipboard-text" }],
  36. },
  37. { name: "PDF", attachments: [{ type: "pdf", filename: "report.pdf", content: pdf }] },
  38. {
  39. name: "mixed media",
  40. attachments: [
  41. { type: "image", content: png },
  42. { type: "pdf", filename: "report.pdf", content: pdf },
  43. { type: "video", content: "data:video/mp4;base64,dmlkZW8=" },
  44. { type: "image", content: png },
  45. ],
  46. },
  47. { name: "text file", attachments: [{ type: "file", path: "notes.md" }] },
  48. { name: "inline text", attachments: [{ type: "file", content: "inline notes" }] },
  49. { name: "no attachment", attachments: [] },
  50. ];
  51. async function captureWire(messages: ModelInputMessage[], kind: "anthropic" | "openai") {
  52. let captured: unknown;
  53. const fetch = async (_input: unknown, init?: RequestInit) => {
  54. captured = JSON.parse(String(init?.body));
  55. return Response.json(
  56. kind === "anthropic"
  57. ? {
  58. id: "fixture",
  59. type: "message",
  60. role: "assistant",
  61. model: "fixture",
  62. content: [{ type: "text", text: "done" }],
  63. stop_reason: "end_turn",
  64. stop_sequence: null,
  65. usage: { input_tokens: 1, output_tokens: 1 },
  66. }
  67. : {
  68. id: "fixture",
  69. object: "chat.completion",
  70. created: 1,
  71. model: "fixture",
  72. choices: [
  73. { index: 0, message: { role: "assistant", content: "done" }, finish_reason: "stop" },
  74. ],
  75. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  76. },
  77. );
  78. };
  79. const options = { apiKey: "fixture-key", baseURL: "https://provider.example/v1", fetch };
  80. const model =
  81. kind === "anthropic"
  82. ? createAnthropic(options)("fixture")
  83. : createOpenAICompatible({ ...options, name: "fixture" })("fixture");
  84. await generateText({
  85. model,
  86. maxRetries: 0,
  87. messages: toAiSdkMessages(messages, {
  88. inputFormat: { supportsImage: true, supportsPdf: true, supportsVideo: true },
  89. }),
  90. });
  91. expect(captured).toBeDefined();
  92. return captured;
  93. }
  94. async function fixture() {
  95. const root = await mkdtemp(join(tmpdir(), "attachment-resume-"));
  96. const dbPath = join(root, "session.sqlite");
  97. const sessionId = createSessionId("attachment-resume");
  98. let store = await createSqliteSessionStore({ dbPath });
  99. await store.createSession({
  100. id: sessionId,
  101. projectID: createProjectId("fixture"),
  102. slug: "fixture",
  103. directory: root,
  104. title: "fixture",
  105. version: "1",
  106. });
  107. await Promise.all([
  108. writeFile(join(root, "bundle.zip"), "binary fixture"),
  109. writeFile(join(root, "pasted.txt"), "clipboard text"),
  110. writeFile(join(root, "notes.md"), "# Notes\nKeep exact text."),
  111. writeFile(join(root, "local.png"), Buffer.from(png.split(",")[1]!, "base64")),
  112. ]);
  113. const artifactStore = createNodeToolArtifactStore({
  114. rootDir: join(root, "artifacts"),
  115. imageCacheRootDir: join(root, "images"),
  116. videoCacheRootDir: join(root, "videos"),
  117. });
  118. const history = new MessageHistoryImpl();
  119. history.init("system fixture");
  120. const runtime = {
  121. sessionId,
  122. sessionStore: store,
  123. messageHistory: history,
  124. artifactStore,
  125. fileSystemPort: createNodeFileSystemAdapter(),
  126. workingDirectory: root,
  127. config: { agentName: "fixture", systemPrompt: "system fixture" },
  128. getTools: () => [],
  129. getSessionModelSelection: () => undefined,
  130. persistMessage: (message: Parameters<typeof store.saveMessage>[0]) =>
  131. store.saveMessage(message),
  132. persistPart: (part: Parameters<typeof store.savePart>[0]) => store.savePart(part),
  133. } as unknown as AgentRuntimeInternal;
  134. runtime.persistUserPrompt = persistUserPrompt.bind(runtime);
  135. return {
  136. root,
  137. runtime,
  138. history,
  139. artifactStore,
  140. async cold() {
  141. store.close();
  142. store = await createSqliteSessionStore({ dbPath });
  143. const messages = await store.messages({ sessionID: sessionId });
  144. const cold = new MessageHistoryImpl();
  145. cold.init("system fixture");
  146. await hydrateMessageHistoryFromSession({ history: cold, messages, artifactStore });
  147. return { history: cold, messages };
  148. },
  149. async close() {
  150. store.close();
  151. await rm(root, { recursive: true, force: true });
  152. },
  153. };
  154. }
  155. describe("attachment history across durable cold resume", () => {
  156. for (const scenario of scenarios) {
  157. it.each(scenario.attachments.length ? ["Summarize the attachment.", ""] : ["Text only."])(
  158. `${scenario.name}, prompt=%j: preserves final SDK request`,
  159. async (prompt) => {
  160. const f = await fixture();
  161. try {
  162. const resolved = await resolveTurnAttachments(scenario.attachments, {
  163. ...f.runtime,
  164. traceContext: { traceId: "fixture" },
  165. });
  166. f.history.addEntries(buildRuntimeUserEntriesFromTurn(prompt, resolved));
  167. await f.runtime.persistUserPrompt(createMessageId("first"), prompt, resolved, {
  168. traceId: "fixture",
  169. });
  170. const cold = await f.cold();
  171. for (const attachment of resolved.filter((a) => a.metadata.storageKind === "local_ref")) {
  172. const part = cold.messages[0]!.parts.find(
  173. (p) => p.type === "file" && p.url === attachment.url,
  174. );
  175. expect(part).toMatchObject({
  176. metadata: {
  177. pathReferenceText:
  178. attachment.contentBlock.type === "text"
  179. ? attachment.contentBlock.text
  180. : undefined,
  181. },
  182. });
  183. }
  184. for (const useMidConversationSystem of [false, true]) {
  185. const requests = await Promise.all(
  186. [f.history, cold.history].map(async (history) => {
  187. const entries = [
  188. ...history.toRuntimeEntries(),
  189. { message: { role: "assistant" as const, content: "done" } },
  190. {
  191. message: { role: "user" as const, content: "Continue." },
  192. metadata: { source: "real_user" as const },
  193. },
  194. ];
  195. const { messages } = buildProviderRequestMessages({
  196. entries,
  197. useMidConversationSystem,
  198. applyCacheControl: true,
  199. });
  200. return projectMessagesWithMediaAttachmentPaths(messages, f.artifactStore);
  201. }),
  202. );
  203. for (const provider of ["anthropic", "openai"] as const) {
  204. expect(await captureWire(requests[1]!, provider)).toEqual(
  205. await captureWire(requests[0]!, provider),
  206. );
  207. }
  208. }
  209. expect((await f.cold()).history.toRuntimeEntries()).toEqual(
  210. cold.history.toRuntimeEntries(),
  211. );
  212. } finally {
  213. await f.close();
  214. }
  215. },
  216. );
  217. }
  218. it.each([
  219. ["image/png", "image_too_large"],
  220. ["application/pdf", "pdf_too_large"],
  221. ["video/mp4", "video_too_large"],
  222. ["text/plain", "text_too_large"],
  223. ["text/plain", "deferred_topic_history"],
  224. ] as const)("restores %s path text for %s without preview or source IO", async (mime, reason) => {
  225. const f = await fixture();
  226. try {
  227. const path = join(f.root, "missing-attachment");
  228. const attachment = resolvedPathReferenceAttachment({ type: "file", path }, path, {
  229. mime,
  230. reason,
  231. source: { type: "file", path, text: { value: path, start: 0, end: path.length } },
  232. });
  233. expect(attachment.metadata.preview).toBeUndefined();
  234. f.history.addEntries(buildRuntimeUserEntriesFromTurn("Inspect.", [attachment]));
  235. await f.runtime.persistUserPrompt(createMessageId("path-text"), "Inspect.", [attachment], {
  236. traceId: "fixture",
  237. });
  238. expect((await f.cold()).history.toRuntimeEntries()).toEqual(f.history.toRuntimeEntries());
  239. } finally {
  240. await f.close();
  241. }
  242. });
  243. it("keeps local images in submission order even when hydration rebuilds their media source as inline", async () => {
  244. const f = await fixture();
  245. try {
  246. const resolved = await resolveTurnAttachments(
  247. [
  248. { type: "image", content: png },
  249. { type: "image", path: "local.png" },
  250. { type: "pdf", content: pdf, filename: "report.pdf" },
  251. ],
  252. { ...f.runtime, traceContext: { traceId: "fixture" } },
  253. );
  254. f.history.addEntries(buildRuntimeUserEntriesFromTurn("Compare.", resolved));
  255. await f.runtime.persistUserPrompt(createMessageId("mixed-local"), "Compare.", resolved, {
  256. traceId: "fixture",
  257. });
  258. const cold = await f.cold();
  259. // 这里只比较媒体与正文合同;local path 到 artifact 派生 path 的既有投影单独测试。
  260. const requests = [f.history, cold.history].map(
  261. (h) => buildProviderRequestMessages({ entries: h.toRuntimeEntries() }).messages,
  262. );
  263. const transformOptions = {
  264. inputFormat: { supportsImage: true, supportsPdf: true, supportsVideo: true },
  265. };
  266. const first = toAiSdkMessages(requests[0]!, transformOptions);
  267. expect(toAiSdkMessages(requests[1]!, transformOptions)).toEqual(first);
  268. const user = requests[0]!.find((m) => m.role === "user")!;
  269. expect(Array.isArray(user.content) && user.content.map((b) => b.type)).toEqual([
  270. "text",
  271. "image",
  272. "file",
  273. "image",
  274. ]);
  275. } finally {
  276. await f.close();
  277. }
  278. });
  279. it.each([undefined, 42, { text: "invalid" }])(
  280. "keeps the legacy placeholder when saved path text is %j",
  281. async (pathReferenceText) => {
  282. const f = await fixture();
  283. try {
  284. const resolved = await resolveTurnAttachments([{ type: "file", path: "bundle.zip" }], {
  285. ...f.runtime,
  286. traceContext: { traceId: "fixture" },
  287. });
  288. resolved[0]!.metadata = {
  289. ...resolved[0]!.metadata,
  290. pathReferenceText,
  291. } as AttachmentStorageMetadata;
  292. await f.runtime.persistUserPrompt(createMessageId("legacy"), "Prompt", resolved, {
  293. traceId: "fixture",
  294. });
  295. const cold = await f.cold();
  296. expect(
  297. buildProviderRequestMessages({ entries: cold.history.toRuntimeEntries() }).messages.at(-1)
  298. ?.content,
  299. ).toEqual([
  300. { type: "text", text: "Prompt" },
  301. { type: "text", text: "[Attached application/octet-stream: bundle.zip]" },
  302. ]);
  303. } finally {
  304. await f.close();
  305. }
  306. },
  307. );
  308. });