attachment-resume-wire.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. import { png, fixture } from "./attachment-resume-wire-fixture.js";
  2. import { createAnthropic } from "@ai-sdk/anthropic";
  3. import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
  4. import { generateText } from "ai";
  5. import { describe, expect, it } from "vitest";
  6. import {
  7. createMessageId,
  8. type AttachmentStorageMetadata,
  9. type ModelInputMessage,
  10. type TurnAttachment,
  11. } from "@zcode/contracts";
  12. import { resolveTurnAttachments } from "../../core/src/runtime/helpers/attachments.js";
  13. import { buildRuntimeUserEntriesFromTurn } from "../../core/src/runtime/helpers/conversation.js";
  14. import { projectMessagesWithMediaAttachmentPaths } from "../../core/src/runtime/helpers/media-attachment-path.js";
  15. import { buildProviderRequestMessages } from "../../core/src/runtime/helpers/provider-request-messages.js";
  16. import { toAiSdkMessages } from "../src/model/transform.js";
  17. const pdf = `data:application/pdf;base64,${Buffer.from("%PDF-1.7\nfixture").toString("base64")}`;
  18. const scenarios: Array<{ name: string; attachments: TurnAttachment[] }> = [
  19. { name: "binary path", attachments: [{ type: "file", path: "bundle.zip" }] },
  20. {
  21. name: "clipboard path",
  22. attachments: [{ type: "file", path: "pasted.txt", sourceKind: "clipboard-text" }],
  23. },
  24. { name: "PDF", attachments: [{ type: "pdf", filename: "report.pdf", content: pdf }] },
  25. {
  26. name: "mixed media",
  27. attachments: [
  28. { type: "image", content: png },
  29. { type: "pdf", filename: "report.pdf", content: pdf },
  30. { type: "video", content: "data:video/mp4;base64,dmlkZW8=" },
  31. { type: "image", content: png },
  32. ],
  33. },
  34. { name: "text file", attachments: [{ type: "file", path: "notes.md" }] },
  35. { name: "inline text", attachments: [{ type: "file", content: "inline notes" }] },
  36. { name: "no attachment", attachments: [] },
  37. ];
  38. async function captureWire(messages: ModelInputMessage[], kind: "anthropic" | "openai") {
  39. let captured: unknown;
  40. const fetch = async (_input: unknown, init?: RequestInit) => {
  41. captured = JSON.parse(String(init?.body));
  42. return Response.json(
  43. kind === "anthropic"
  44. ? {
  45. id: "fixture",
  46. type: "message",
  47. role: "assistant",
  48. model: "fixture",
  49. content: [{ type: "text", text: "done" }],
  50. stop_reason: "end_turn",
  51. stop_sequence: null,
  52. usage: { input_tokens: 1, output_tokens: 1 },
  53. }
  54. : {
  55. id: "fixture",
  56. object: "chat.completion",
  57. created: 1,
  58. model: "fixture",
  59. choices: [
  60. { index: 0, message: { role: "assistant", content: "done" }, finish_reason: "stop" },
  61. ],
  62. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  63. },
  64. );
  65. };
  66. const options = { apiKey: "fixture-key", baseURL: "https://provider.example/v1", fetch };
  67. const model =
  68. kind === "anthropic"
  69. ? createAnthropic(options)("fixture")
  70. : createOpenAICompatible({ ...options, name: "fixture" })("fixture");
  71. await generateText({
  72. model,
  73. maxRetries: 0,
  74. messages: toAiSdkMessages(messages, {
  75. inputFormat: { supportsImage: true, supportsPdf: true, supportsVideo: true },
  76. }),
  77. });
  78. expect(captured).toBeDefined();
  79. return captured;
  80. }
  81. describe("attachment history across durable cold resume", () => {
  82. for (const scenario of scenarios) {
  83. it.each(scenario.attachments.length ? ["Summarize the attachment.", ""] : ["Text only."])(
  84. `${scenario.name}, prompt=%j: preserves final SDK request`,
  85. async (prompt) => {
  86. const f = await fixture();
  87. try {
  88. const resolved = await resolveTurnAttachments(scenario.attachments, {
  89. ...f.runtime,
  90. traceContext: { traceId: "fixture" },
  91. });
  92. f.history.addEntries(buildRuntimeUserEntriesFromTurn(prompt, resolved));
  93. await f.runtime.persistUserPrompt(createMessageId("first"), prompt, resolved, {
  94. traceId: "fixture",
  95. });
  96. const cold = await f.cold();
  97. for (const attachment of resolved.filter((a) => a.metadata.storageKind === "local_ref")) {
  98. const part = cold.messages[0]!.parts.find(
  99. (p) => p.type === "file" && p.url === attachment.url,
  100. );
  101. expect(part).toMatchObject({
  102. metadata: {
  103. pathReferenceText:
  104. attachment.contentBlock.type === "text"
  105. ? attachment.contentBlock.text
  106. : undefined,
  107. },
  108. });
  109. }
  110. for (const useMidConversationSystem of [false, true]) {
  111. const requests = await Promise.all(
  112. [f.history, cold.history].map(async (history) => {
  113. const entries = [
  114. ...history.toRuntimeEntries(),
  115. { message: { role: "assistant" as const, content: "done" } },
  116. {
  117. message: { role: "user" as const, content: "Continue." },
  118. metadata: { source: "real_user" as const },
  119. },
  120. ];
  121. const { messages } = buildProviderRequestMessages({
  122. entries,
  123. useMidConversationSystem,
  124. applyCacheControl: true,
  125. });
  126. return projectMessagesWithMediaAttachmentPaths(messages, f.artifactStore);
  127. }),
  128. );
  129. for (const provider of ["anthropic", "openai"] as const) {
  130. expect(await captureWire(requests[1]!, provider)).toEqual(
  131. await captureWire(requests[0]!, provider),
  132. );
  133. }
  134. }
  135. expect((await f.cold()).history.toRuntimeEntries()).toEqual(
  136. cold.history.toRuntimeEntries(),
  137. );
  138. } finally {
  139. await f.close();
  140. }
  141. },
  142. );
  143. }
  144. it("keeps local images in submission order even when hydration rebuilds their media source as inline", async () => {
  145. const f = await fixture();
  146. try {
  147. const resolved = await resolveTurnAttachments(
  148. [
  149. { type: "image", content: png },
  150. { type: "image", path: "local.png" },
  151. { type: "pdf", content: pdf, filename: "report.pdf" },
  152. ],
  153. { ...f.runtime, traceContext: { traceId: "fixture" } },
  154. );
  155. f.history.addEntries(buildRuntimeUserEntriesFromTurn("Compare.", resolved));
  156. await f.runtime.persistUserPrompt(createMessageId("mixed-local"), "Compare.", resolved, {
  157. traceId: "fixture",
  158. });
  159. const cold = await f.cold();
  160. // 这里只比较媒体与正文合同;local path 到 artifact 派生 path 的既有投影单独测试。
  161. const requests = [f.history, cold.history].map(
  162. (h) => buildProviderRequestMessages({ entries: h.toRuntimeEntries() }).messages,
  163. );
  164. const transformOptions = {
  165. inputFormat: { supportsImage: true, supportsPdf: true, supportsVideo: true },
  166. };
  167. const first = toAiSdkMessages(requests[0]!, transformOptions);
  168. expect(toAiSdkMessages(requests[1]!, transformOptions)).toEqual(first);
  169. const user = requests[0]!.find((m) => m.role === "user")!;
  170. expect(Array.isArray(user.content) && user.content.map((b) => b.type)).toEqual([
  171. "text",
  172. "image",
  173. "file",
  174. "image",
  175. ]);
  176. } finally {
  177. await f.close();
  178. }
  179. });
  180. it.each([undefined, 42, { text: "invalid" }])(
  181. "keeps the legacy placeholder when saved path text is %j",
  182. async (pathReferenceText) => {
  183. const f = await fixture();
  184. try {
  185. const resolved = await resolveTurnAttachments([{ type: "file", path: "bundle.zip" }], {
  186. ...f.runtime,
  187. traceContext: { traceId: "fixture" },
  188. });
  189. resolved[0]!.metadata = {
  190. ...resolved[0]!.metadata,
  191. pathReferenceText,
  192. } as AttachmentStorageMetadata;
  193. await f.runtime.persistUserPrompt(createMessageId("legacy"), "Prompt", resolved, {
  194. traceId: "fixture",
  195. });
  196. const cold = await f.cold();
  197. expect(
  198. buildProviderRequestMessages({ entries: cold.history.toRuntimeEntries() }).messages.at(-1)
  199. ?.content,
  200. ).toEqual([
  201. { type: "text", text: "Prompt" },
  202. { type: "text", text: "[Attached application/octet-stream: bundle.zip]" },
  203. ]);
  204. } finally {
  205. await f.close();
  206. }
  207. },
  208. );
  209. });