v4-native-attachments.test.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. // L2:M5 附件命令面——AttachmentRef → TurnAttachment 映射(attachment-refs.ts)、
  2. // sendText/createSession 携带附件的 core 调用、active turn queue fallback、
  3. // gateway chunked attachment transaction 的尺寸、顺序、幂等与宿主钩子收口。
  4. // 模式对齐 v4-native-commands.test.ts(fake app/record/host → executor → 断言 core 调用)。
  5. import { createHash } from "node:crypto";
  6. import { describe, expect, it, vi } from "vitest";
  7. import { SessionEventType } from "@zcode/contracts";
  8. import type { CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  9. import { PROTOCOL_V4_LIMITS } from "@zcode/shared/zcode-protocol-v4";
  10. import {
  11. isUriAttachmentRef,
  12. mapAttachmentRefsToTurnAttachments,
  13. } from "../src/zcode-protocol-v4/commands/attachment-refs.js";
  14. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  15. import type {
  16. V4CommandCoreHost,
  17. V4SessionRecordView,
  18. } from "../src/zcode-protocol-v4/commands/types.js";
  19. import { ConversationV4Gateway } from "../src/zcode-protocol-v4/index.js";
  20. function makeApp(overrides: Record<string, unknown> = {}) {
  21. return {
  22. sessionId: "s1",
  23. runtime: {
  24. getSessionModelSelection: () => ({ providerId: "test-provider", modelId: "test-model" }),
  25. },
  26. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  27. options?.onTurnStartedObserved?.({
  28. id: "event-started",
  29. type: SessionEventType.TurnStarted,
  30. payload: { messageId: "msg-event-started" },
  31. });
  32. return {
  33. completion: Promise.resolve({}),
  34. kind: "started_turn",
  35. turnId: "turn-1",
  36. };
  37. }),
  38. steerTurn: vi.fn().mockResolvedValue({}),
  39. enqueueDeferredInput: vi.fn().mockResolvedValue({
  40. kind: "queued",
  41. pendingInputId: "pending-1",
  42. queueLength: 1,
  43. turnId: "turn-1",
  44. }),
  45. readTarget: vi.fn().mockResolvedValue(null),
  46. updateTargetStatus: vi.fn().mockResolvedValue(null),
  47. readToolResultArtifact: vi.fn().mockResolvedValue({
  48. uri: "zcode-artifact://a1",
  49. content: "data:text/plain;base64,aGVsbG8gd29ybGQ=", // "hello world"
  50. contentType: "text/plain",
  51. bytes: 11,
  52. }),
  53. ...overrides,
  54. };
  55. }
  56. function makeRecord(
  57. overrides: Partial<V4SessionRecordView> & { app?: ReturnType<typeof makeApp> } = {},
  58. ): V4SessionRecordView {
  59. return {
  60. app: (overrides.app ?? makeApp()) as unknown as V4SessionRecordView["app"],
  61. workspace: { workspacePath: "/w" },
  62. persistence: "immediate",
  63. ...overrides,
  64. } as V4SessionRecordView;
  65. }
  66. function makeHost(
  67. record: V4SessionRecordView,
  68. overrides: Partial<V4CommandCoreHost> = {},
  69. ): V4CommandCoreHost {
  70. return {
  71. getRecord: (id) => (id === "s1" ? record : undefined),
  72. afterLegacyStateMutation: async () => {},
  73. waitForProjectionEventCommit: async () => {},
  74. ...overrides,
  75. };
  76. }
  77. function envelope(type: string, payload: unknown): CommandEnvelope {
  78. return {
  79. type,
  80. payload,
  81. sessionId: "s1",
  82. commandId: "cmd-1",
  83. baseRevision: 0,
  84. } as unknown as CommandEnvelope;
  85. }
  86. async function settle() {
  87. await new Promise((r) => setTimeout(r, 0));
  88. await new Promise((r) => setTimeout(r, 0));
  89. }
  90. const pathRef = {
  91. ref: "/tmp/pic.png",
  92. fileName: "pic.png",
  93. mime: "image/png",
  94. bytes: 123,
  95. };
  96. describe("attachment-refs 映射(AttachmentRef → TurnAttachment)", () => {
  97. it("话题历史 artifact 保留引用,禁止自动解码正文", async () => {
  98. const app = makeApp();
  99. const mapped = await mapAttachmentRefsToTurnAttachments(app as never, [
  100. {
  101. ref: "zcode-artifact://history",
  102. fileName: "topic-history.txt",
  103. mime: "text/plain",
  104. bytes: 12,
  105. sourceKind: "topic-history",
  106. },
  107. ]);
  108. expect(mapped).toEqual([
  109. expect.objectContaining({
  110. type: "file",
  111. content: "zcode-artifact://history",
  112. sourceKind: "topic-history",
  113. }),
  114. ]);
  115. expect(app.readToolResultArtifact).not.toHaveBeenCalled();
  116. });
  117. it("本地路径 ref:图片/视频/文件按 mime 分型为 path 引用,展示元信息保真", async () => {
  118. const app = makeApp() as unknown as V4SessionRecordView["app"];
  119. const mapped = await mapAttachmentRefsToTurnAttachments(app, [
  120. pathRef,
  121. { ref: "/tmp/demo.mp4", fileName: "demo.mp4", mime: "video/mp4", bytes: 456 },
  122. { ref: "/tmp/report.pdf", fileName: "report.pdf", mime: "application/pdf", bytes: 789 },
  123. { ref: "/tmp/notes.txt", fileName: "notes.txt", mime: "text/plain", bytes: 9 },
  124. ]);
  125. expect(mapped).toEqual([
  126. {
  127. path: "/tmp/pic.png",
  128. type: "image",
  129. filename: "pic.png",
  130. mimeType: "image/png",
  131. sizeBytes: 123,
  132. },
  133. {
  134. path: "/tmp/demo.mp4",
  135. type: "video",
  136. filename: "demo.mp4",
  137. mimeType: "video/mp4",
  138. sizeBytes: 456,
  139. },
  140. {
  141. path: "/tmp/report.pdf",
  142. type: "pdf",
  143. filename: "report.pdf",
  144. mimeType: "application/pdf",
  145. sizeBytes: 789,
  146. },
  147. {
  148. path: "/tmp/notes.txt",
  149. type: "file",
  150. filename: "notes.txt",
  151. mimeType: "text/plain",
  152. sizeBytes: 9,
  153. },
  154. ]);
  155. });
  156. it("PDF artifact URI ref 保留 durable URI,禁止按文本解码", async () => {
  157. const app = makeApp({
  158. readToolResultArtifact: vi.fn().mockResolvedValue({
  159. uri: "zcode-artifact://pdf-1",
  160. content: "data:application/pdf;base64,JVBERi0xLjQK",
  161. contentType: "text/plain",
  162. bytes: 9,
  163. }),
  164. }) as unknown as V4SessionRecordView["app"];
  165. const mapped = await mapAttachmentRefsToTurnAttachments(app, [
  166. { ref: "zcode-artifact://pdf-1", fileName: "report.pdf", mime: "application/pdf", bytes: 9 },
  167. ]);
  168. expect(mapped).toEqual([
  169. {
  170. content: "zcode-artifact://pdf-1",
  171. path: "report.pdf",
  172. type: "pdf",
  173. filename: "report.pdf",
  174. mimeType: "application/pdf",
  175. sizeBytes: 9,
  176. },
  177. ]);
  178. expect(app.readToolResultArtifact).not.toHaveBeenCalled();
  179. });
  180. it("图片/视频 artifact URI ref:content 携带 URI(core 解析链读回,不在命令层内联)", async () => {
  181. const app = makeApp() as unknown as V4SessionRecordView["app"];
  182. const mapped = await mapAttachmentRefsToTurnAttachments(app, [
  183. { ref: "zcode-artifact://img-1", fileName: "shot.png", mime: "image/png", bytes: 42 },
  184. { ref: "zcode-artifact://video-1", fileName: "demo.mp4", mime: "video/mp4", bytes: 84 },
  185. ]);
  186. expect(mapped).toEqual([
  187. {
  188. content: "zcode-artifact://img-1",
  189. path: "shot.png",
  190. type: "image",
  191. filename: "shot.png",
  192. mimeType: "image/png",
  193. sizeBytes: 42,
  194. },
  195. {
  196. content: "zcode-artifact://video-1",
  197. path: "demo.mp4",
  198. type: "video",
  199. filename: "demo.mp4",
  200. mimeType: "video/mp4",
  201. sizeBytes: 84,
  202. },
  203. ]);
  204. });
  205. it("文本 artifact URI ref:读回并解码为 ≤64KiB 文本内容(旧 decodeTextProtocolAttachment 语义)", async () => {
  206. const rawApp = makeApp();
  207. const mapped = await mapAttachmentRefsToTurnAttachments(
  208. rawApp as unknown as V4SessionRecordView["app"],
  209. [{ ref: "zcode-artifact://a1", fileName: "paste.txt", mime: "text/plain", bytes: 11 }],
  210. );
  211. expect(rawApp.readToolResultArtifact).toHaveBeenCalledWith("zcode-artifact://a1");
  212. expect(mapped?.[0]).toMatchObject({
  213. content: "hello world",
  214. path: "paste.txt",
  215. type: "file",
  216. });
  217. });
  218. it("超限/读取失败的非图片 artifact ref:降级为仅展示元信息(不让发送整体失败)", async () => {
  219. const rawApp = makeApp({
  220. readToolResultArtifact: vi.fn().mockRejectedValue(new Error("gone")),
  221. });
  222. const app = rawApp as unknown as V4SessionRecordView["app"];
  223. const oversized = await mapAttachmentRefsToTurnAttachments(app, [
  224. {
  225. ref: "zcode-artifact://big",
  226. fileName: "big.txt",
  227. mime: "text/plain",
  228. bytes: 65 * 1024,
  229. },
  230. ]);
  231. expect(oversized?.[0]).toEqual({
  232. type: "file",
  233. filename: "big.txt",
  234. mimeType: "text/plain",
  235. sizeBytes: 65 * 1024,
  236. });
  237. const unreadable = await mapAttachmentRefsToTurnAttachments(app, [
  238. { ref: "zcode-artifact://a1", fileName: "gone.txt", mime: "text/plain", bytes: 4 },
  239. ]);
  240. expect(unreadable?.[0]).toEqual({
  241. type: "file",
  242. filename: "gone.txt",
  243. mimeType: "text/plain",
  244. sizeBytes: 4,
  245. });
  246. });
  247. it("空/缺省 → undefined;isUriAttachmentRef 区分 scheme:// 与本地路径(含 Windows 盘符)", async () => {
  248. const app = makeApp() as unknown as V4SessionRecordView["app"];
  249. expect(await mapAttachmentRefsToTurnAttachments(app, undefined)).toBeUndefined();
  250. expect(await mapAttachmentRefsToTurnAttachments(app, [])).toBeUndefined();
  251. expect(isUriAttachmentRef("zcode-artifact://x")).toBe(true);
  252. expect(isUriAttachmentRef("/tmp/a.png")).toBe(false);
  253. // Windows 盘符路径(C:\...)没有 //,不得误判为 URI。
  254. expect(isUriAttachmentRef("C:\\Users\\a.png")).toBe(false);
  255. });
  256. });
  257. describe("v4 原生 sendText(附件)", () => {
  258. it("空闲会话:仅 attachments 也会映射后随 sendInput 提交", async () => {
  259. const app = makeApp();
  260. const record = makeRecord({ app });
  261. await new V4CommandExecutor(makeHost(record)).execute(
  262. envelope("sendText", { text: "", attachments: [pathRef] }),
  263. );
  264. await settle();
  265. expect(app.sendInput).toHaveBeenCalledWith(
  266. {
  267. text: "",
  268. attachments: [
  269. {
  270. path: "/tmp/pic.png",
  271. type: "image",
  272. filename: "pic.png",
  273. mimeType: "image/png",
  274. sizeBytes: 123,
  275. },
  276. ],
  277. },
  278. expect.objectContaining({
  279. inputId: "cmd-1",
  280. intent: expect.objectContaining({
  281. sourceCommandId: "cmd-1",
  282. attachmentRefs: [pathRef],
  283. requestedDelivery: "startNow",
  284. }),
  285. }),
  286. );
  287. });
  288. it("运行中仅附件:同 sourceCommandId/附件回退 CLI queue,不丢 payload", async () => {
  289. const app = makeApp({
  290. sendInput: vi.fn().mockResolvedValue({
  291. kind: "queued",
  292. pendingInputId: "pending-1",
  293. queueLength: 1,
  294. turnId: "turn-1",
  295. }),
  296. });
  297. const record = makeRecord({ app, activeAbortController: new AbortController() });
  298. await new V4CommandExecutor(makeHost(record, { getInputRoutingMode: () => "guide" })).execute(
  299. envelope("sendText", { text: "", attachments: [pathRef] }),
  300. );
  301. expect(app.sendInput).toHaveBeenCalledWith(
  302. expect.objectContaining({
  303. text: "",
  304. attachments: [expect.objectContaining({ path: "/tmp/pic.png", type: "image" })],
  305. }),
  306. expect.objectContaining({
  307. inputId: "cmd-1",
  308. intent: expect.objectContaining({
  309. sourceCommandId: "cmd-1",
  310. clientId: "cli",
  311. attachmentRefs: [pathRef],
  312. requestedDelivery: "guide",
  313. fallbackReasonCode: "guide.attachmentsUnsupported",
  314. }),
  315. }),
  316. );
  317. expect(app.steerTurn).not.toHaveBeenCalled();
  318. expect(app.enqueueDeferredInput).not.toHaveBeenCalled();
  319. });
  320. it("正文和附件都为空时统一拒绝", async () => {
  321. const app = makeApp();
  322. const record = makeRecord({ app });
  323. await expect(
  324. new V4CommandExecutor(makeHost(record)).execute(
  325. envelope("sendText", { text: " ", attachments: [] }),
  326. ),
  327. ).rejects.toMatchObject({ reasonCode: "proto.invalidPayload" });
  328. expect(app.sendInput).not.toHaveBeenCalled();
  329. expect(app.enqueueDeferredInput).not.toHaveBeenCalled();
  330. });
  331. });
  332. describe("v4 原生 createSession(firstInput 附件)", () => {
  333. it("仅 firstInput.attachments 也会映射后随首条 turn 提交", async () => {
  334. const app = makeApp();
  335. const record = makeRecord({ app, persistence: "deferred" });
  336. const host = makeHost(record, {
  337. createSessionRecord: async () => ({ sessionId: "s1" }),
  338. });
  339. const result = await new V4CommandExecutor(host).execute(
  340. envelope("createSession", {
  341. workspaceId: "/w",
  342. firstInput: { text: "", attachments: [pathRef] },
  343. }),
  344. );
  345. await settle();
  346. expect(result).toEqual({
  347. type: "createSession",
  348. sessionId: "s1",
  349. input: {
  350. delivery: "startNow",
  351. inputId: "cmd-1",
  352. },
  353. });
  354. expect(app.sendInput).toHaveBeenCalledWith(
  355. expect.objectContaining({
  356. text: "",
  357. attachments: [expect.objectContaining({ path: "/tmp/pic.png", type: "image" })],
  358. }),
  359. expect.anything(),
  360. );
  361. });
  362. });
  363. describe("gateway v4 chunked attachment transaction", () => {
  364. function makeGateway(overrides: {
  365. putSessionAttachment?: (
  366. sessionId: string,
  367. input: { fileName: string; mime: string; bytes: Uint8Array },
  368. ) => Promise<{ ref: string }>;
  369. readSessionAttachment?: (
  370. sessionId: string,
  371. input: {
  372. ref: string;
  373. mime: string;
  374. maxBytes: number;
  375. messageId?: string;
  376. attachmentIndex?: number;
  377. },
  378. ) => Promise<{ bytes: Uint8Array; mediaType: string }>;
  379. resolveSessionAttachmentPreviewSource?: (
  380. sessionId: string,
  381. input: {
  382. ref: string;
  383. mime: string;
  384. messageId?: string;
  385. attachmentIndex?: number;
  386. },
  387. ) => Promise<{ kind: "local_path"; path: string; mediaType: string } | { kind: "chunked" }>;
  388. }) {
  389. return new ConversationV4Gateway({
  390. sessionExists: (sessionId) => sessionId === "s1",
  391. emitWireFrame: () => {},
  392. executeCommand: async () => undefined,
  393. ...overrides,
  394. });
  395. }
  396. const sha256 = (bytes: Uint8Array) =>
  397. `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
  398. const begin = (bytes: Uint8Array, overrides: Record<string, unknown> = {}) => ({
  399. connectionId: "connection-1",
  400. uploadId: "upload-1",
  401. sessionId: "s1",
  402. fileName: "shot.png",
  403. mime: "image/png",
  404. totalBytes: bytes.byteLength,
  405. totalChunks: bytes.byteLength === 0 ? 0 : 1,
  406. checksum: sha256(bytes),
  407. ...overrides,
  408. });
  409. function ingestAttachmentRow(
  410. gateway: ConversationV4Gateway,
  411. attachments: readonly (typeof pathRef)[],
  412. options: { detached?: boolean } = {},
  413. ): void {
  414. type GatewayEvent = Parameters<ConversationV4Gateway["ingest"]>[1];
  415. const ingest = (event: GatewayEvent) => {
  416. if (options.detached) gateway.ingestDetachedLiveSession("s1", event);
  417. else gateway.ingest("s1", event);
  418. };
  419. ingest({
  420. id: "preview-session-created",
  421. sessionId: "s1",
  422. type: SessionEventType.SessionCreated,
  423. timestamp: new Date(1),
  424. traceId: "trace-preview",
  425. sequenceNumber: 1,
  426. payload: { mode: "default", contextWindow: 200_000 },
  427. } as GatewayEvent);
  428. ingest({
  429. id: "preview-turn-started",
  430. sessionId: "s1",
  431. turnId: "turn-preview",
  432. type: SessionEventType.TurnStarted,
  433. timestamp: new Date(2),
  434. traceId: "trace-preview",
  435. sequenceNumber: 2,
  436. payload: {
  437. turnNumber: 1,
  438. input: "preview",
  439. messageId: "message-preview",
  440. intent: { attachmentRefs: attachments },
  441. },
  442. } as GatewayEvent);
  443. }
  444. function ingestAssistantArtifactImage(gateway: ConversationV4Gateway, ref: string): void {
  445. ingestAttachmentRow(gateway, []);
  446. type GatewayEvent = Parameters<ConversationV4Gateway["ingest"]>[1];
  447. gateway.ingest("s1", {
  448. id: "preview-assistant-text",
  449. sessionId: "s1",
  450. turnId: "turn-preview",
  451. type: SessionEventType.ModelStreaming,
  452. timestamp: new Date(3),
  453. traceId: "trace-preview",
  454. sequenceNumber: 3,
  455. payload: {
  456. kind: "text_delta",
  457. delta: `Screenshot: ![CUA result](${ref})`,
  458. done: false,
  459. },
  460. } as GatewayEvent);
  461. }
  462. it("begin/chunk/commit 原子寄存,begin/commit retry 返回同一进度/ref", async () => {
  463. const bytes = Buffer.from("hello attachment");
  464. const put = vi.fn().mockResolvedValue({ ref: "zcode-artifact://p1" });
  465. const gateway = makeGateway({ putSessionAttachment: put });
  466. await expect(gateway.attachmentBegin(begin(bytes))).resolves.toEqual({
  467. uploadId: "upload-1",
  468. state: "staging",
  469. nextChunkIndex: 0,
  470. });
  471. await expect(gateway.attachmentBegin(begin(bytes))).resolves.toEqual({
  472. uploadId: "upload-1",
  473. state: "staging",
  474. nextChunkIndex: 0,
  475. });
  476. await expect(
  477. gateway.attachmentChunk({
  478. connectionId: "connection-1",
  479. uploadId: "upload-1",
  480. sessionId: "s1",
  481. chunkIndex: 0,
  482. dataBase64: bytes.toString("base64"),
  483. }),
  484. ).resolves.toEqual({ uploadId: "upload-1", nextChunkIndex: 1 });
  485. const result = await gateway.attachmentCommit({
  486. connectionId: "connection-1",
  487. uploadId: "upload-1",
  488. sessionId: "s1",
  489. });
  490. expect(result).toEqual({ ref: "zcode-artifact://p1" });
  491. await expect(
  492. gateway.attachmentCommit({
  493. connectionId: "connection-1",
  494. uploadId: "upload-1",
  495. sessionId: "s1",
  496. }),
  497. ).resolves.toEqual(result);
  498. await expect(gateway.attachmentBegin(begin(bytes))).resolves.toEqual({
  499. uploadId: "upload-1",
  500. state: "committed",
  501. nextChunkIndex: 1,
  502. ref: "zcode-artifact://p1",
  503. });
  504. expect(put).toHaveBeenCalledTimes(1);
  505. expect(put).toHaveBeenCalledWith("s1", {
  506. fileName: "shot.png",
  507. mime: "image/png",
  508. bytes: new Uint8Array(bytes),
  509. });
  510. });
  511. it("20MiB+1 在 begin/staging 前拒绝,不触碰宿主钩子", async () => {
  512. const put = vi.fn();
  513. const gateway = makeGateway({ putSessionAttachment: put });
  514. await expect(
  515. gateway.attachmentBegin(
  516. begin(new Uint8Array(), {
  517. totalBytes: 20 * 1024 * 1024 + 1,
  518. totalChunks: 41,
  519. }),
  520. ),
  521. ).rejects.toThrow();
  522. expect(put).not.toHaveBeenCalled();
  523. });
  524. it("duplicate identical no-op;future/conflicting duplicate 与错误 checksum 明确失败", async () => {
  525. const bytes = Buffer.from("abcdef");
  526. const gateway = makeGateway({
  527. putSessionAttachment: vi.fn().mockResolvedValue({ ref: "zcode-artifact://p1" }),
  528. });
  529. await gateway.attachmentBegin(begin(bytes, { totalChunks: 2 }));
  530. const first = Buffer.from("abc");
  531. const chunk = {
  532. connectionId: "connection-1",
  533. uploadId: "upload-1",
  534. sessionId: "s1",
  535. chunkIndex: 0,
  536. dataBase64: first.toString("base64"),
  537. };
  538. await gateway.attachmentChunk(chunk);
  539. await expect(gateway.attachmentChunk(chunk)).resolves.toEqual({
  540. uploadId: "upload-1",
  541. nextChunkIndex: 1,
  542. });
  543. await expect(gateway.attachmentChunk({ ...chunk, chunkIndex: 2 })).rejects.toThrow(
  544. "fault.attachment.chunkGap",
  545. );
  546. await expect(
  547. gateway.attachmentChunk({ ...chunk, dataBase64: Buffer.from("xxx").toString("base64") }),
  548. ).rejects.toThrow("fault.attachment.chunkConflict");
  549. await gateway.attachmentChunk({
  550. ...chunk,
  551. chunkIndex: 1,
  552. dataBase64: Buffer.from("def").toString("base64"),
  553. });
  554. await expect(
  555. gateway.attachmentCommit({
  556. connectionId: "connection-1",
  557. uploadId: "upload-1",
  558. sessionId: "s1",
  559. }),
  560. ).resolves.toEqual({ ref: "zcode-artifact://p1" });
  561. const wrong = makeGateway({ putSessionAttachment: vi.fn() });
  562. await wrong.attachmentBegin(
  563. begin(bytes, { totalChunks: 2, checksum: `sha256:${"0".repeat(64)}` }),
  564. );
  565. await wrong.attachmentChunk(chunk);
  566. await wrong.attachmentChunk({
  567. ...chunk,
  568. chunkIndex: 1,
  569. dataBase64: Buffer.from("def").toString("base64"),
  570. });
  571. await expect(
  572. wrong.attachmentCommit({
  573. connectionId: "connection-1",
  574. uploadId: "upload-1",
  575. sessionId: "s1",
  576. }),
  577. ).rejects.toThrow("fault.attachment.checksumMismatch");
  578. });
  579. it("empty upload 可直接 commit;missing/abort/connection close/session close 清 staging", async () => {
  580. const put = vi.fn().mockResolvedValue({ ref: "zcode-artifact://empty" });
  581. const gateway = makeGateway({ putSessionAttachment: put });
  582. await gateway.attachmentBegin(begin(new Uint8Array()));
  583. await expect(
  584. gateway.attachmentCommit({
  585. connectionId: "connection-1",
  586. uploadId: "upload-1",
  587. sessionId: "s1",
  588. }),
  589. ).resolves.toEqual({ ref: "zcode-artifact://empty" });
  590. const bytes = Buffer.from("pending");
  591. await gateway.attachmentBegin(begin(bytes, { uploadId: "abort-me" }));
  592. await gateway.attachmentAbort({
  593. connectionId: "connection-1",
  594. uploadId: "abort-me",
  595. sessionId: "s1",
  596. });
  597. await gateway.attachmentAbort({
  598. connectionId: "connection-1",
  599. uploadId: "abort-me",
  600. sessionId: "s1",
  601. });
  602. await expect(
  603. gateway.attachmentCommit({
  604. connectionId: "connection-1",
  605. uploadId: "abort-me",
  606. sessionId: "s1",
  607. }),
  608. ).rejects.toThrow("fault.attachment.uploadNotFound");
  609. await gateway.attachmentBegin(begin(bytes, { uploadId: "connection-close" }));
  610. gateway.setConnectionFlowState({ connectionId: "connection-1", state: "closed" });
  611. await expect(
  612. gateway.attachmentCommit({
  613. connectionId: "connection-1",
  614. uploadId: "connection-close",
  615. sessionId: "s1",
  616. }),
  617. ).rejects.toThrow("fault.attachment.uploadNotFound");
  618. await gateway.attachmentBegin(begin(bytes, { uploadId: "session-close" }));
  619. gateway.disposeSession("s1");
  620. await expect(
  621. gateway.attachmentCommit({
  622. connectionId: "connection-1",
  623. uploadId: "session-close",
  624. sessionId: "s1",
  625. }),
  626. ).rejects.toThrow("fault.attachment.uploadNotFound");
  627. });
  628. it("已发送图片按 row/ref 授权分块读取,并复用有界短时缓存", async () => {
  629. const bytes = Buffer.alloc(PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes + 3, 7);
  630. const read = vi.fn().mockResolvedValue({ bytes, mediaType: "image/png" });
  631. const gateway = makeGateway({ readSessionAttachment: read });
  632. ingestAttachmentRow(gateway, [pathRef]);
  633. const first = await gateway.attachmentRead({
  634. sessionId: "s1",
  635. ref: pathRef.ref,
  636. offset: 0,
  637. limit: PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  638. });
  639. expect(Buffer.from(first.dataBase64, "base64")).toHaveLength(
  640. PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  641. );
  642. expect(first).toMatchObject({
  643. mediaType: "image/png",
  644. totalBytes: bytes.byteLength,
  645. nextOffset: PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  646. });
  647. await expect(
  648. gateway.attachmentRead({
  649. sessionId: "s1",
  650. ref: pathRef.ref,
  651. offset: first.nextOffset,
  652. limit: PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  653. }),
  654. ).resolves.toMatchObject({
  655. dataBase64: Buffer.from(bytes.subarray(-3)).toString("base64"),
  656. nextOffset: null,
  657. });
  658. expect(read).toHaveBeenCalledTimes(1);
  659. expect(read).toHaveBeenCalledWith("s1", {
  660. ref: pathRef.ref,
  661. mime: pathRef.mime,
  662. maxBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  663. });
  664. gateway.dispose();
  665. });
  666. it("Share metadata stat 也必须经过 row/index 授权,不能触发任意路径读取", async () => {
  667. const stat = vi.fn().mockResolvedValue({
  668. totalBytes: 10,
  669. mediaType: "text/plain",
  670. });
  671. const gateway = makeGateway({ statSessionAttachment: stat });
  672. ingestAttachmentRow(gateway, [pathRef]);
  673. await expect(
  674. gateway.conversationAttachmentStat({
  675. sessionId: "s1",
  676. ref: "/tmp/not-authorized.txt",
  677. target: { rowId: 42, entityId: "not-authorized" },
  678. attachmentIndex: 0,
  679. }),
  680. ).rejects.toThrow("fault.attachment.shareStatNotAuthorized");
  681. expect(stat).not.toHaveBeenCalled();
  682. gateway.dispose();
  683. });
  684. it.each(["topic-history", "clipboard-text"] as const)(
  685. "%s 文本按权威行授权预览,拒绝其他行及引用",
  686. async (sourceKind) => {
  687. const bytes = Buffer.from("Sender: 群成员 | open_id: ou_member\n原文第二行");
  688. const attachment = {
  689. ref: "zcode-artifact://history",
  690. fileName: "history.txt",
  691. mime: "text/plain",
  692. bytes: bytes.length,
  693. sourceKind,
  694. };
  695. const read = vi.fn().mockResolvedValue({ bytes, mediaType: "text/plain" });
  696. const gateway = makeGateway({ readSessionAttachment: read });
  697. ingestAttachmentRow(gateway, [attachment]);
  698. const request = {
  699. sessionId: "s1",
  700. ref: attachment.ref,
  701. target: { rowId: 2, entityId: "message-preview" },
  702. attachmentIndex: 0,
  703. offset: 0,
  704. limit: 1000,
  705. };
  706. await expect(gateway.attachmentRead(request)).resolves.toMatchObject({
  707. dataBase64: bytes.toString("base64"),
  708. nextOffset: null,
  709. });
  710. await expect(
  711. gateway.attachmentRead({
  712. ...request,
  713. target: { ...request.target, entityId: "other-message" },
  714. }),
  715. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  716. await expect(
  717. gateway.attachmentRead({ ...request, ref: "/tmp/arbitrary.txt" }),
  718. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  719. expect(read).toHaveBeenCalledTimes(1);
  720. gateway.dispose();
  721. },
  722. );
  723. it("legacy ref-only 读取在 durable previewRef 存在时不回退原始路径", async () => {
  724. const attachment = {
  725. ...pathRef,
  726. previewRef: "zcode-artifact://preview-image",
  727. };
  728. const bytes = Buffer.from("persisted-image");
  729. const read = vi.fn().mockResolvedValue({ bytes, mediaType: "image/png" });
  730. const gateway = makeGateway({ readSessionAttachment: read });
  731. ingestAttachmentRow(gateway, [attachment]);
  732. await expect(
  733. gateway.attachmentRead({
  734. sessionId: "s1",
  735. ref: attachment.ref,
  736. offset: 0,
  737. limit: 100,
  738. }),
  739. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  740. expect(read).not.toHaveBeenCalled();
  741. await expect(
  742. gateway.attachmentRead({
  743. sessionId: "s1",
  744. ref: attachment.previewRef,
  745. offset: 0,
  746. limit: 100,
  747. }),
  748. ).resolves.toMatchObject({
  749. dataBase64: bytes.toString("base64"),
  750. mediaType: "image/png",
  751. nextOffset: null,
  752. });
  753. expect(read).toHaveBeenCalledWith("s1", {
  754. ref: attachment.previewRef,
  755. mime: attachment.mime,
  756. maxBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  757. });
  758. gateway.dispose();
  759. });
  760. it("只授权当前 session 助手 Markdown 中真实出现的图片 artifact", async () => {
  761. const ref = "zcode-artifact://s1/cua-shot";
  762. const read = vi.fn().mockResolvedValue({
  763. bytes: Buffer.from("cua-image"),
  764. mediaType: "image/png",
  765. });
  766. const gateway = makeGateway({ readSessionAttachment: read });
  767. ingestAssistantArtifactImage(gateway, ref);
  768. await expect(
  769. gateway.attachmentRead({ sessionId: "s1", ref, offset: 0, limit: 100 }),
  770. ).resolves.toMatchObject({
  771. dataBase64: Buffer.from("cua-image").toString("base64"),
  772. mediaType: "image/png",
  773. nextOffset: null,
  774. });
  775. await expect(
  776. gateway.attachmentRead({
  777. sessionId: "s1",
  778. ref: "zcode-artifact://s1/not-in-markdown",
  779. offset: 0,
  780. limit: 100,
  781. }),
  782. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  783. expect(read).toHaveBeenCalledTimes(1);
  784. expect(read).toHaveBeenCalledWith("s1", {
  785. ref,
  786. mime: "image/*",
  787. maxBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  788. });
  789. gateway.dispose();
  790. });
  791. it("已发送视频按 row 身份和附件序号授权,并把持久消息锚点交给宿主", async () => {
  792. const video = {
  793. ref: "/tmp/demo.mov",
  794. previewRef: "zcode-artifact://preview-video",
  795. fileName: "demo.mov",
  796. mime: "video/quicktime",
  797. bytes: 8,
  798. };
  799. // 修复原因:video 全局 preview 上限已从 100MiB 收敛到 30MiB;样本只需越过
  800. // V4 upload 20MiB 边界来证明已发送预览读取不复用上传上限。
  801. const bytes = Buffer.alloc(PROTOCOL_V4_LIMITS.attachmentMaxBytes + 1, 9);
  802. expect(bytes.byteLength).toBeLessThanOrEqual(PROTOCOL_V4_LIMITS.attachmentPreviewMaxBytes);
  803. const read = vi.fn().mockResolvedValue({
  804. bytes,
  805. mediaType: "video/quicktime",
  806. });
  807. const gateway = makeGateway({ readSessionAttachment: read });
  808. ingestAttachmentRow(gateway, [pathRef, video]);
  809. const first = await gateway.attachmentRead({
  810. sessionId: "s1",
  811. ref: video.ref,
  812. target: { rowId: 2, entityId: "message-preview" },
  813. attachmentIndex: 1,
  814. offset: 0,
  815. limit: 100,
  816. });
  817. expect(first).toMatchObject({
  818. dataBase64: Buffer.from(bytes.subarray(0, 100)).toString("base64"),
  819. mediaType: "video/quicktime",
  820. totalBytes: bytes.byteLength,
  821. nextOffset: 100,
  822. });
  823. await gateway.attachmentRead({
  824. sessionId: "s1",
  825. ref: video.ref,
  826. target: { rowId: 2, entityId: "message-preview" },
  827. attachmentIndex: 1,
  828. offset: first.nextOffset!,
  829. limit: 100,
  830. });
  831. expect(read).toHaveBeenCalledWith("s1", {
  832. ref: video.ref,
  833. mime: video.mime,
  834. maxBytes: PROTOCOL_V4_LIMITS.attachmentPreviewMaxBytes,
  835. messageId: "message-preview",
  836. attachmentIndex: 1,
  837. });
  838. expect(read).toHaveBeenCalledTimes(1);
  839. await expect(
  840. gateway.attachmentRead({
  841. sessionId: "s1",
  842. ref: video.ref,
  843. target: { rowId: 2, entityId: "another-message" },
  844. attachmentIndex: 1,
  845. offset: 0,
  846. limit: 100,
  847. }),
  848. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  849. gateway.dispose();
  850. });
  851. it("已发送 PDF 按 row 身份授权并通过 chunk 读取", async () => {
  852. const pdf = {
  853. ref: "zcode-artifact://preview-pdf",
  854. fileName: "report.pdf",
  855. mime: "application/pdf; charset=binary",
  856. bytes: 13,
  857. };
  858. const bytes = Buffer.from("%PDF-1.7\nbody");
  859. const read = vi.fn().mockResolvedValue({ bytes, mediaType: "application/pdf" });
  860. const gateway = makeGateway({ readSessionAttachment: read });
  861. ingestAttachmentRow(gateway, [pathRef, pdf]);
  862. await expect(
  863. gateway.attachmentRead({
  864. sessionId: "s1",
  865. ref: pdf.ref,
  866. target: { rowId: 2, entityId: "message-preview" },
  867. attachmentIndex: 1,
  868. offset: 0,
  869. limit: 100,
  870. }),
  871. ).resolves.toMatchObject({
  872. dataBase64: bytes.toString("base64"),
  873. mediaType: "application/pdf",
  874. totalBytes: bytes.byteLength,
  875. nextOffset: null,
  876. });
  877. expect(read).toHaveBeenCalledWith("s1", {
  878. ref: pdf.ref,
  879. mime: pdf.mime,
  880. maxBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  881. messageId: "message-preview",
  882. attachmentIndex: 1,
  883. });
  884. await expect(
  885. gateway.attachmentRead({
  886. sessionId: "s1",
  887. ref: pdf.ref,
  888. target: { rowId: 2, entityId: "wrong-message" },
  889. attachmentIndex: 1,
  890. offset: 0,
  891. limit: 100,
  892. }),
  893. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  894. gateway.dispose();
  895. });
  896. it("Desktop local sent video reuses exact authorization before returning a local source", async () => {
  897. const video = {
  898. ref: "/tmp/demo.mov",
  899. previewRef: "zcode-artifact://preview-video",
  900. fileName: "demo.mov",
  901. mime: "video/quicktime",
  902. bytes: 8,
  903. };
  904. const resolveSource = vi.fn().mockResolvedValue({
  905. kind: "local_path",
  906. path: "/tmp/.zcode/video-cache/demo.mov",
  907. mediaType: "video/quicktime",
  908. });
  909. const gateway = makeGateway({ resolveSessionAttachmentPreviewSource: resolveSource });
  910. ingestAttachmentRow(gateway, [pathRef, video]);
  911. await expect(
  912. gateway.attachmentPreviewSource({
  913. sessionId: "s1",
  914. ref: video.ref,
  915. target: { rowId: 2, entityId: "message-preview" },
  916. attachmentIndex: 1,
  917. clientMode: "desktop-continuous",
  918. }),
  919. ).resolves.toEqual({
  920. kind: "local_path",
  921. path: "/tmp/.zcode/video-cache/demo.mov",
  922. mediaType: "video/quicktime",
  923. });
  924. expect(resolveSource).toHaveBeenCalledWith("s1", {
  925. ref: video.ref,
  926. mime: video.mime,
  927. messageId: "message-preview",
  928. attachmentIndex: 1,
  929. });
  930. await expect(
  931. gateway.attachmentPreviewSource({
  932. sessionId: "s1",
  933. ref: video.ref,
  934. target: { rowId: 2, entityId: "wrong-message" },
  935. attachmentIndex: 1,
  936. clientMode: "desktop-continuous",
  937. }),
  938. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  939. gateway.dispose();
  940. });
  941. it("local source query leaves images and web-remote video on the chunked path", async () => {
  942. const resolveSource = vi.fn();
  943. const gateway = makeGateway({ resolveSessionAttachmentPreviewSource: resolveSource });
  944. const video = {
  945. ref: "/tmp/demo.mp4",
  946. fileName: "demo.mp4",
  947. mime: "video/mp4",
  948. bytes: 8,
  949. };
  950. ingestAttachmentRow(gateway, [pathRef, video]);
  951. await expect(
  952. gateway.attachmentPreviewSource({
  953. sessionId: "s1",
  954. ref: pathRef.ref,
  955. target: { rowId: 2, entityId: "message-preview" },
  956. attachmentIndex: 0,
  957. clientMode: "desktop-continuous",
  958. }),
  959. ).resolves.toEqual({ kind: "chunked" });
  960. await expect(
  961. gateway.attachmentPreviewSource({
  962. sessionId: "s1",
  963. ref: video.ref,
  964. target: { rowId: 2, entityId: "message-preview" },
  965. attachmentIndex: 1,
  966. clientMode: "web-remote-replayable",
  967. }),
  968. ).resolves.toEqual({ kind: "chunked" });
  969. expect(resolveSource).not.toHaveBeenCalled();
  970. gateway.dispose();
  971. });
  972. it("拒绝助手 Markdown 引用其他 session 的 artifact", async () => {
  973. const foreignRef = "zcode-artifact://s2/cua-shot";
  974. const read = vi.fn().mockResolvedValue({
  975. bytes: Buffer.from("foreign-cua-image"),
  976. mediaType: "image/png",
  977. });
  978. const gateway = makeGateway({ readSessionAttachment: read });
  979. ingestAssistantArtifactImage(gateway, foreignRef);
  980. await expect(
  981. gateway.attachmentRead({
  982. sessionId: "s1",
  983. ref: foreignRef,
  984. offset: 0,
  985. limit: 100,
  986. }),
  987. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  988. expect(read).not.toHaveBeenCalled();
  989. gateway.dispose();
  990. });
  991. it("同一原始路径跨轮预览按各自持久消息隔离缓存", async () => {
  992. type GatewayEvent = Parameters<ConversationV4Gateway["ingest"]>[1];
  993. const video = {
  994. ref: "/tmp/reused.mp4",
  995. fileName: "reused.mp4",
  996. mime: "video/mp4",
  997. bytes: 1,
  998. };
  999. const read = vi.fn(async (_sessionId: string, input: { messageId?: string }) => ({
  1000. bytes: Buffer.from(input.messageId ?? "missing"),
  1001. mediaType: "video/mp4",
  1002. }));
  1003. const gateway = makeGateway({ readSessionAttachment: read });
  1004. ingestAttachmentRow(gateway, [{ ...video, previewRef: "zcode-artifact://first" }]);
  1005. gateway.ingest("s1", {
  1006. id: "preview-turn-complete",
  1007. sessionId: "s1",
  1008. turnId: "turn-preview",
  1009. type: SessionEventType.TurnComplete,
  1010. timestamp: new Date(3),
  1011. traceId: "trace-preview",
  1012. sequenceNumber: 3,
  1013. payload: {
  1014. response: "done",
  1015. tokenCount: 0,
  1016. toolCallCount: 0,
  1017. duration: 1,
  1018. resultType: "success",
  1019. },
  1020. } as GatewayEvent);
  1021. gateway.ingest("s1", {
  1022. id: "preview-turn-started-2",
  1023. sessionId: "s1",
  1024. turnId: "turn-preview-2",
  1025. type: SessionEventType.TurnStarted,
  1026. timestamp: new Date(4),
  1027. traceId: "trace-preview-2",
  1028. sequenceNumber: 4,
  1029. payload: {
  1030. turnNumber: 2,
  1031. input: "preview again",
  1032. messageId: "message-preview-2",
  1033. intent: {
  1034. attachmentRefs: [{ ...video, previewRef: "zcode-artifact://second" }],
  1035. },
  1036. },
  1037. } as GatewayEvent);
  1038. const first = await gateway.attachmentRead({
  1039. sessionId: "s1",
  1040. ref: video.ref,
  1041. target: { rowId: 2, entityId: "message-preview" },
  1042. attachmentIndex: 0,
  1043. offset: 0,
  1044. limit: 100,
  1045. });
  1046. const second = await gateway.attachmentRead({
  1047. sessionId: "s1",
  1048. ref: video.ref,
  1049. target: { rowId: 4, entityId: "message-preview-2" },
  1050. attachmentIndex: 0,
  1051. offset: 0,
  1052. limit: 100,
  1053. });
  1054. expect(Buffer.from(first.dataBase64, "base64").toString()).toBe("message-preview");
  1055. expect(Buffer.from(second.dataBase64, "base64").toString()).toBe("message-preview-2");
  1056. expect(read).toHaveBeenCalledTimes(2);
  1057. expect(read).toHaveBeenNthCalledWith(
  1058. 1,
  1059. "s1",
  1060. expect.objectContaining({ messageId: "message-preview", attachmentIndex: 0 }),
  1061. );
  1062. expect(read).toHaveBeenNthCalledWith(
  1063. 2,
  1064. "s1",
  1065. expect.objectContaining({ messageId: "message-preview-2", attachmentIndex: 0 }),
  1066. );
  1067. gateway.dispose();
  1068. });
  1069. it("app restart 冷恢复先恢复 session/persisted row,再授权 previewRef", async () => {
  1070. type GatewayEvent = Parameters<ConversationV4Gateway["ingest"]>[1];
  1071. const attachment = { ...pathRef, previewRef: "zcode-artifact://preview-cold" };
  1072. const persistedEvents = [
  1073. {
  1074. id: "cold-session-created",
  1075. sessionId: "s1",
  1076. type: SessionEventType.SessionCreated,
  1077. timestamp: new Date(1),
  1078. traceId: "trace-cold",
  1079. sequenceNumber: 1,
  1080. payload: { mode: "default", contextWindow: 200_000 },
  1081. } as GatewayEvent,
  1082. {
  1083. id: "cold-turn-started",
  1084. sessionId: "s1",
  1085. turnId: "turn-cold",
  1086. type: SessionEventType.TurnStarted,
  1087. timestamp: new Date(2),
  1088. traceId: "trace-cold",
  1089. sequenceNumber: 2,
  1090. payload: {
  1091. turnNumber: 1,
  1092. input: "cold preview",
  1093. intent: { attachmentRefs: [attachment] },
  1094. },
  1095. } as GatewayEvent,
  1096. ];
  1097. let sessionExists = false;
  1098. const resumePersistedSession = vi.fn(async () => {
  1099. sessionExists = true;
  1100. return { status: "resumed" as const };
  1101. });
  1102. const read = vi.fn().mockResolvedValue({
  1103. bytes: Buffer.from("cold-image"),
  1104. mediaType: "image/png",
  1105. });
  1106. const gateway = new ConversationV4Gateway({
  1107. sessionExists: () => sessionExists,
  1108. resumePersistedSession,
  1109. loadPersistedEvents: async () => ({ events: persistedEvents, synthesized: true }),
  1110. emitWireFrame: () => {},
  1111. executeCommand: async () => undefined,
  1112. readSessionAttachment: read,
  1113. });
  1114. await expect(
  1115. gateway.attachmentRead({
  1116. sessionId: "s1",
  1117. ref: attachment.previewRef,
  1118. offset: 0,
  1119. limit: 100,
  1120. }),
  1121. ).resolves.toMatchObject({
  1122. dataBase64: Buffer.from("cold-image").toString("base64"),
  1123. mediaType: "image/png",
  1124. nextOffset: null,
  1125. });
  1126. expect(resumePersistedSession).toHaveBeenCalledWith("s1", undefined);
  1127. expect(read).toHaveBeenCalledWith("s1", {
  1128. ref: attachment.previewRef,
  1129. mime: "image/png",
  1130. maxBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  1131. });
  1132. gateway.dispose();
  1133. });
  1134. it("detached projection hydration 不替代 attachment 所需的 host activation", async () => {
  1135. let sessionExists = false;
  1136. let releaseHydration!: () => void;
  1137. let markHydrationStarted!: () => void;
  1138. const hydrationStarted = new Promise<void>((resolve) => {
  1139. markHydrationStarted = resolve;
  1140. });
  1141. const hydrationGate = new Promise<void>((resolve) => {
  1142. releaseHydration = resolve;
  1143. });
  1144. const resumePersistedSession = vi.fn(async () => {
  1145. sessionExists = true;
  1146. return { status: "resumed" as const };
  1147. });
  1148. const read = vi.fn().mockResolvedValue({
  1149. bytes: Buffer.from("detached-image"),
  1150. mediaType: "image/png",
  1151. });
  1152. const gateway = new ConversationV4Gateway({
  1153. sessionExists: () => sessionExists,
  1154. resumePersistedSession,
  1155. loadPersistedEvents: async () => {
  1156. markHydrationStarted();
  1157. await hydrationGate;
  1158. return { events: [], synthesized: false };
  1159. },
  1160. emitWireFrame: () => {},
  1161. executeCommand: async () => undefined,
  1162. readSessionAttachment: read,
  1163. });
  1164. ingestAttachmentRow(gateway, [pathRef], { detached: true });
  1165. const subscribing = gateway.subscribe({
  1166. topic: "conversation/s1",
  1167. connectionId: "connection-detached",
  1168. clientMode: "desktop-continuous",
  1169. });
  1170. await hydrationStarted;
  1171. const reading = gateway.attachmentRead({
  1172. sessionId: "s1",
  1173. ref: pathRef.ref,
  1174. offset: 0,
  1175. limit: 100,
  1176. });
  1177. try {
  1178. await Promise.resolve();
  1179. expect(resumePersistedSession).toHaveBeenCalledWith("s1", undefined);
  1180. releaseHydration();
  1181. await expect(reading).resolves.toMatchObject({
  1182. dataBase64: Buffer.from("detached-image").toString("base64"),
  1183. });
  1184. await subscribing;
  1185. } finally {
  1186. releaseHydration();
  1187. await Promise.allSettled([subscribing, reading]);
  1188. gateway.dispose();
  1189. }
  1190. });
  1191. it("非 image/video、跨行 ref 与越界读取在宿主文件系统前拒绝", async () => {
  1192. const read = vi.fn().mockResolvedValue({ bytes: Buffer.from("png"), mediaType: "image/png" });
  1193. const gateway = makeGateway({ readSessionAttachment: read });
  1194. ingestAttachmentRow(gateway, [
  1195. pathRef,
  1196. { ref: "/tmp/note.txt", fileName: "note.txt", mime: "text/plain", bytes: 4 },
  1197. ]);
  1198. await expect(
  1199. gateway.attachmentRead({
  1200. sessionId: "s1",
  1201. ref: "/tmp/note.txt",
  1202. offset: 0,
  1203. limit: 100,
  1204. }),
  1205. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  1206. await expect(
  1207. gateway.attachmentRead({
  1208. sessionId: "s1",
  1209. ref: "/tmp/foreign.png",
  1210. offset: 0,
  1211. limit: 100,
  1212. }),
  1213. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  1214. expect(read).not.toHaveBeenCalled();
  1215. await gateway.attachmentRead({ sessionId: "s1", ref: pathRef.ref, offset: 0, limit: 100 });
  1216. await expect(
  1217. gateway.attachmentRead({ sessionId: "s1", ref: pathRef.ref, offset: 4, limit: 100 }),
  1218. ).rejects.toThrow("fault.attachment.previewRangeInvalid");
  1219. gateway.dispose();
  1220. });
  1221. });