v4-native-attachments.test.ts 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  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. const read = vi.fn().mockResolvedValue({
  803. bytes,
  804. mediaType: "video/quicktime",
  805. });
  806. const gateway = makeGateway({ readSessionAttachment: read });
  807. ingestAttachmentRow(gateway, [pathRef, video]);
  808. const first = await gateway.attachmentRead({
  809. sessionId: "s1",
  810. ref: video.ref,
  811. target: { rowId: 2, entityId: "message-preview" },
  812. attachmentIndex: 1,
  813. offset: 0,
  814. limit: 100,
  815. });
  816. expect(first).toMatchObject({
  817. dataBase64: Buffer.from(bytes.subarray(0, 100)).toString("base64"),
  818. mediaType: "video/quicktime",
  819. totalBytes: bytes.byteLength,
  820. nextOffset: 100,
  821. });
  822. await gateway.attachmentRead({
  823. sessionId: "s1",
  824. ref: video.ref,
  825. target: { rowId: 2, entityId: "message-preview" },
  826. attachmentIndex: 1,
  827. offset: first.nextOffset!,
  828. limit: 100,
  829. });
  830. expect(read).toHaveBeenCalledWith("s1", {
  831. ref: video.ref,
  832. mime: video.mime,
  833. maxBytes: PROTOCOL_V4_LIMITS.attachmentPreviewMaxBytes,
  834. messageId: "message-preview",
  835. attachmentIndex: 1,
  836. });
  837. expect(read).toHaveBeenCalledTimes(1);
  838. await expect(
  839. gateway.attachmentRead({
  840. sessionId: "s1",
  841. ref: video.ref,
  842. target: { rowId: 2, entityId: "another-message" },
  843. attachmentIndex: 1,
  844. offset: 0,
  845. limit: 100,
  846. }),
  847. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  848. gateway.dispose();
  849. });
  850. it("已发送 PDF 按 row 身份授权并通过 chunk 读取", async () => {
  851. const pdf = {
  852. ref: "zcode-artifact://preview-pdf",
  853. fileName: "report.pdf",
  854. mime: "application/pdf; charset=binary",
  855. bytes: 13,
  856. };
  857. const bytes = Buffer.from("%PDF-1.7\nbody");
  858. const read = vi.fn().mockResolvedValue({ bytes, mediaType: "application/pdf" });
  859. const gateway = makeGateway({ readSessionAttachment: read });
  860. ingestAttachmentRow(gateway, [pathRef, pdf]);
  861. await expect(
  862. gateway.attachmentRead({
  863. sessionId: "s1",
  864. ref: pdf.ref,
  865. target: { rowId: 2, entityId: "message-preview" },
  866. attachmentIndex: 1,
  867. offset: 0,
  868. limit: 100,
  869. }),
  870. ).resolves.toMatchObject({
  871. dataBase64: bytes.toString("base64"),
  872. mediaType: "application/pdf",
  873. totalBytes: bytes.byteLength,
  874. nextOffset: null,
  875. });
  876. expect(read).toHaveBeenCalledWith("s1", {
  877. ref: pdf.ref,
  878. mime: pdf.mime,
  879. maxBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  880. messageId: "message-preview",
  881. attachmentIndex: 1,
  882. });
  883. await expect(
  884. gateway.attachmentRead({
  885. sessionId: "s1",
  886. ref: pdf.ref,
  887. target: { rowId: 2, entityId: "wrong-message" },
  888. attachmentIndex: 1,
  889. offset: 0,
  890. limit: 100,
  891. }),
  892. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  893. gateway.dispose();
  894. });
  895. it("Desktop local sent video reuses exact authorization before returning a local source", async () => {
  896. const video = {
  897. ref: "/tmp/demo.mov",
  898. previewRef: "zcode-artifact://preview-video",
  899. fileName: "demo.mov",
  900. mime: "video/quicktime",
  901. bytes: 8,
  902. };
  903. const resolveSource = vi.fn().mockResolvedValue({
  904. kind: "local_path",
  905. path: "/tmp/.zcode/video-cache/demo.mov",
  906. mediaType: "video/quicktime",
  907. });
  908. const gateway = makeGateway({ resolveSessionAttachmentPreviewSource: resolveSource });
  909. ingestAttachmentRow(gateway, [pathRef, video]);
  910. await expect(
  911. gateway.attachmentPreviewSource({
  912. sessionId: "s1",
  913. ref: video.ref,
  914. target: { rowId: 2, entityId: "message-preview" },
  915. attachmentIndex: 1,
  916. clientMode: "desktop-continuous",
  917. }),
  918. ).resolves.toEqual({
  919. kind: "local_path",
  920. path: "/tmp/.zcode/video-cache/demo.mov",
  921. mediaType: "video/quicktime",
  922. });
  923. expect(resolveSource).toHaveBeenCalledWith("s1", {
  924. ref: video.ref,
  925. mime: video.mime,
  926. messageId: "message-preview",
  927. attachmentIndex: 1,
  928. });
  929. await expect(
  930. gateway.attachmentPreviewSource({
  931. sessionId: "s1",
  932. ref: video.ref,
  933. target: { rowId: 2, entityId: "wrong-message" },
  934. attachmentIndex: 1,
  935. clientMode: "desktop-continuous",
  936. }),
  937. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  938. gateway.dispose();
  939. });
  940. it("local source query leaves images and web-remote video on the chunked path", async () => {
  941. const resolveSource = vi.fn();
  942. const gateway = makeGateway({ resolveSessionAttachmentPreviewSource: resolveSource });
  943. const video = {
  944. ref: "/tmp/demo.mp4",
  945. fileName: "demo.mp4",
  946. mime: "video/mp4",
  947. bytes: 8,
  948. };
  949. ingestAttachmentRow(gateway, [pathRef, video]);
  950. await expect(
  951. gateway.attachmentPreviewSource({
  952. sessionId: "s1",
  953. ref: pathRef.ref,
  954. target: { rowId: 2, entityId: "message-preview" },
  955. attachmentIndex: 0,
  956. clientMode: "desktop-continuous",
  957. }),
  958. ).resolves.toEqual({ kind: "chunked" });
  959. await expect(
  960. gateway.attachmentPreviewSource({
  961. sessionId: "s1",
  962. ref: video.ref,
  963. target: { rowId: 2, entityId: "message-preview" },
  964. attachmentIndex: 1,
  965. clientMode: "web-remote-replayable",
  966. }),
  967. ).resolves.toEqual({ kind: "chunked" });
  968. expect(resolveSource).not.toHaveBeenCalled();
  969. gateway.dispose();
  970. });
  971. it("拒绝助手 Markdown 引用其他 session 的 artifact", async () => {
  972. const foreignRef = "zcode-artifact://s2/cua-shot";
  973. const read = vi.fn().mockResolvedValue({
  974. bytes: Buffer.from("foreign-cua-image"),
  975. mediaType: "image/png",
  976. });
  977. const gateway = makeGateway({ readSessionAttachment: read });
  978. ingestAssistantArtifactImage(gateway, foreignRef);
  979. await expect(
  980. gateway.attachmentRead({
  981. sessionId: "s1",
  982. ref: foreignRef,
  983. offset: 0,
  984. limit: 100,
  985. }),
  986. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  987. expect(read).not.toHaveBeenCalled();
  988. gateway.dispose();
  989. });
  990. it("同一原始路径跨轮预览按各自持久消息隔离缓存", async () => {
  991. type GatewayEvent = Parameters<ConversationV4Gateway["ingest"]>[1];
  992. const video = {
  993. ref: "/tmp/reused.mp4",
  994. fileName: "reused.mp4",
  995. mime: "video/mp4",
  996. bytes: 1,
  997. };
  998. const read = vi.fn(async (_sessionId: string, input: { messageId?: string }) => ({
  999. bytes: Buffer.from(input.messageId ?? "missing"),
  1000. mediaType: "video/mp4",
  1001. }));
  1002. const gateway = makeGateway({ readSessionAttachment: read });
  1003. ingestAttachmentRow(gateway, [{ ...video, previewRef: "zcode-artifact://first" }]);
  1004. gateway.ingest("s1", {
  1005. id: "preview-turn-complete",
  1006. sessionId: "s1",
  1007. turnId: "turn-preview",
  1008. type: SessionEventType.TurnComplete,
  1009. timestamp: new Date(3),
  1010. traceId: "trace-preview",
  1011. sequenceNumber: 3,
  1012. payload: {
  1013. response: "done",
  1014. tokenCount: 0,
  1015. toolCallCount: 0,
  1016. duration: 1,
  1017. resultType: "success",
  1018. },
  1019. } as GatewayEvent);
  1020. gateway.ingest("s1", {
  1021. id: "preview-turn-started-2",
  1022. sessionId: "s1",
  1023. turnId: "turn-preview-2",
  1024. type: SessionEventType.TurnStarted,
  1025. timestamp: new Date(4),
  1026. traceId: "trace-preview-2",
  1027. sequenceNumber: 4,
  1028. payload: {
  1029. turnNumber: 2,
  1030. input: "preview again",
  1031. messageId: "message-preview-2",
  1032. intent: {
  1033. attachmentRefs: [{ ...video, previewRef: "zcode-artifact://second" }],
  1034. },
  1035. },
  1036. } as GatewayEvent);
  1037. const first = await gateway.attachmentRead({
  1038. sessionId: "s1",
  1039. ref: video.ref,
  1040. target: { rowId: 2, entityId: "message-preview" },
  1041. attachmentIndex: 0,
  1042. offset: 0,
  1043. limit: 100,
  1044. });
  1045. const second = await gateway.attachmentRead({
  1046. sessionId: "s1",
  1047. ref: video.ref,
  1048. target: { rowId: 4, entityId: "message-preview-2" },
  1049. attachmentIndex: 0,
  1050. offset: 0,
  1051. limit: 100,
  1052. });
  1053. expect(Buffer.from(first.dataBase64, "base64").toString()).toBe("message-preview");
  1054. expect(Buffer.from(second.dataBase64, "base64").toString()).toBe("message-preview-2");
  1055. expect(read).toHaveBeenCalledTimes(2);
  1056. expect(read).toHaveBeenNthCalledWith(
  1057. 1,
  1058. "s1",
  1059. expect.objectContaining({ messageId: "message-preview", attachmentIndex: 0 }),
  1060. );
  1061. expect(read).toHaveBeenNthCalledWith(
  1062. 2,
  1063. "s1",
  1064. expect.objectContaining({ messageId: "message-preview-2", attachmentIndex: 0 }),
  1065. );
  1066. gateway.dispose();
  1067. });
  1068. it("app restart 冷恢复先恢复 session/persisted row,再授权 previewRef", async () => {
  1069. type GatewayEvent = Parameters<ConversationV4Gateway["ingest"]>[1];
  1070. const attachment = { ...pathRef, previewRef: "zcode-artifact://preview-cold" };
  1071. const persistedEvents = [
  1072. {
  1073. id: "cold-session-created",
  1074. sessionId: "s1",
  1075. type: SessionEventType.SessionCreated,
  1076. timestamp: new Date(1),
  1077. traceId: "trace-cold",
  1078. sequenceNumber: 1,
  1079. payload: { mode: "default", contextWindow: 200_000 },
  1080. } as GatewayEvent,
  1081. {
  1082. id: "cold-turn-started",
  1083. sessionId: "s1",
  1084. turnId: "turn-cold",
  1085. type: SessionEventType.TurnStarted,
  1086. timestamp: new Date(2),
  1087. traceId: "trace-cold",
  1088. sequenceNumber: 2,
  1089. payload: {
  1090. turnNumber: 1,
  1091. input: "cold preview",
  1092. intent: { attachmentRefs: [attachment] },
  1093. },
  1094. } as GatewayEvent,
  1095. ];
  1096. let sessionExists = false;
  1097. const resumePersistedSession = vi.fn(async () => {
  1098. sessionExists = true;
  1099. return { status: "resumed" as const };
  1100. });
  1101. const read = vi.fn().mockResolvedValue({
  1102. bytes: Buffer.from("cold-image"),
  1103. mediaType: "image/png",
  1104. });
  1105. const gateway = new ConversationV4Gateway({
  1106. sessionExists: () => sessionExists,
  1107. resumePersistedSession,
  1108. loadPersistedEvents: async () => ({ events: persistedEvents, synthesized: true }),
  1109. emitWireFrame: () => {},
  1110. executeCommand: async () => undefined,
  1111. readSessionAttachment: read,
  1112. });
  1113. await expect(
  1114. gateway.attachmentRead({
  1115. sessionId: "s1",
  1116. ref: attachment.previewRef,
  1117. offset: 0,
  1118. limit: 100,
  1119. }),
  1120. ).resolves.toMatchObject({
  1121. dataBase64: Buffer.from("cold-image").toString("base64"),
  1122. mediaType: "image/png",
  1123. nextOffset: null,
  1124. });
  1125. // 冷恢复统一以 (sessionId, thoughtLevel, workspace, additionalDirectories, persistedMessages) 五参调用宿主钩子。
  1126. expect(resumePersistedSession).toHaveBeenCalledWith(
  1127. "s1",
  1128. undefined,
  1129. undefined,
  1130. undefined,
  1131. undefined,
  1132. );
  1133. expect(read).toHaveBeenCalledWith("s1", {
  1134. ref: attachment.previewRef,
  1135. mime: "image/png",
  1136. maxBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  1137. });
  1138. gateway.dispose();
  1139. });
  1140. it("detached projection hydration 不替代 attachment 所需的 host activation", async () => {
  1141. let sessionExists = false;
  1142. let releaseHydration!: () => void;
  1143. let markHydrationStarted!: () => void;
  1144. const hydrationStarted = new Promise<void>((resolve) => {
  1145. markHydrationStarted = resolve;
  1146. });
  1147. const hydrationGate = new Promise<void>((resolve) => {
  1148. releaseHydration = resolve;
  1149. });
  1150. const resumePersistedSession = vi.fn(async () => {
  1151. sessionExists = true;
  1152. return { status: "resumed" as const };
  1153. });
  1154. const read = vi.fn().mockResolvedValue({
  1155. bytes: Buffer.from("detached-image"),
  1156. mediaType: "image/png",
  1157. });
  1158. const gateway = new ConversationV4Gateway({
  1159. sessionExists: () => sessionExists,
  1160. resumePersistedSession,
  1161. loadPersistedEvents: async () => {
  1162. markHydrationStarted();
  1163. await hydrationGate;
  1164. return { events: [], synthesized: false };
  1165. },
  1166. emitWireFrame: () => {},
  1167. executeCommand: async () => undefined,
  1168. readSessionAttachment: read,
  1169. });
  1170. ingestAttachmentRow(gateway, [pathRef], { detached: true });
  1171. const subscribing = gateway.subscribe({
  1172. topic: "conversation/s1",
  1173. connectionId: "connection-detached",
  1174. clientMode: "desktop-continuous",
  1175. });
  1176. await hydrationStarted;
  1177. const reading = gateway.attachmentRead({
  1178. sessionId: "s1",
  1179. ref: pathRef.ref,
  1180. offset: 0,
  1181. limit: 100,
  1182. });
  1183. try {
  1184. await Promise.resolve();
  1185. // 冷恢复统一以 (sessionId, thoughtLevel, workspace, additionalDirectories, persistedMessages) 五参调用宿主钩子。
  1186. expect(resumePersistedSession).toHaveBeenCalledWith(
  1187. "s1",
  1188. undefined,
  1189. undefined,
  1190. undefined,
  1191. undefined,
  1192. );
  1193. releaseHydration();
  1194. await expect(reading).resolves.toMatchObject({
  1195. dataBase64: Buffer.from("detached-image").toString("base64"),
  1196. });
  1197. await subscribing;
  1198. } finally {
  1199. releaseHydration();
  1200. await Promise.allSettled([subscribing, reading]);
  1201. gateway.dispose();
  1202. }
  1203. });
  1204. it("非 image/video、跨行 ref 与越界读取在宿主文件系统前拒绝", async () => {
  1205. const read = vi.fn().mockResolvedValue({ bytes: Buffer.from("png"), mediaType: "image/png" });
  1206. const gateway = makeGateway({ readSessionAttachment: read });
  1207. ingestAttachmentRow(gateway, [
  1208. pathRef,
  1209. { ref: "/tmp/note.txt", fileName: "note.txt", mime: "text/plain", bytes: 4 },
  1210. ]);
  1211. await expect(
  1212. gateway.attachmentRead({
  1213. sessionId: "s1",
  1214. ref: "/tmp/note.txt",
  1215. offset: 0,
  1216. limit: 100,
  1217. }),
  1218. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  1219. await expect(
  1220. gateway.attachmentRead({
  1221. sessionId: "s1",
  1222. ref: "/tmp/foreign.png",
  1223. offset: 0,
  1224. limit: 100,
  1225. }),
  1226. ).rejects.toThrow("fault.attachment.previewRefNotAuthorized");
  1227. expect(read).not.toHaveBeenCalled();
  1228. await gateway.attachmentRead({ sessionId: "s1", ref: pathRef.ref, offset: 0, limit: 100 });
  1229. await expect(
  1230. gateway.attachmentRead({ sessionId: "s1", ref: pathRef.ref, offset: 4, limit: 100 }),
  1231. ).rejects.toThrow("fault.attachment.previewRangeInvalid");
  1232. gateway.dispose();
  1233. });
  1234. });