conversationShareService.test.ts 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422
  1. import { createHash } from "node:crypto";
  2. import { materializeConversationShareInlineImages } from "../src/conversation-share/conversationShareInlineImages.js";
  3. import type {
  4. ConversationRow,
  5. ConversationShareCapabilities,
  6. ConversationShareConfirmRequest,
  7. ConversationSharePreparationRequest,
  8. } from "@zcode/shared";
  9. import { ProxyChannel } from "@zcode/rpc";
  10. import {
  11. ZCODE_ATTACHMENT_FAULT_CODES,
  12. ZCodeAttachmentFaultError,
  13. } from "@zcode/shared/zcode-protocol-v4";
  14. import { describe, expect, it, vi } from "vitest";
  15. import type { IZCodeAgentService } from "../src/zcode-agent/zcodeAgent.js";
  16. import {
  17. ConversationShareClientError,
  18. type ConversationShareHttpClient,
  19. } from "../src/conversation-share/conversationShareHttpClient.js";
  20. import { sha256ConversationShareJson } from "../src/conversation-share/conversationShareIntegrity.js";
  21. import {
  22. ConversationShareService,
  23. conversationShareConnectionScopeFactory,
  24. type ConversationShareServiceOptions,
  25. } from "../src/conversation-share/conversationShareService.js";
  26. import {
  27. ConversationShareServiceError,
  28. type ConversationSharePublishProgress,
  29. type ConversationShareFailureIssue,
  30. } from "../src/conversation-share/conversationShare.js";
  31. const capabilities: ConversationShareCapabilities = {
  32. schema_version: 1,
  33. ttl_ms: 60_000,
  34. access_modes: ["private", "public_readonly", "public_importable"],
  35. max_rows: 100,
  36. max_payload_bytes: 100_000,
  37. max_artifact_count: 0,
  38. max_artifact_bytes: 1,
  39. max_total_artifact_bytes: 1,
  40. allowed_artifacts: [],
  41. };
  42. const shareRecord = {
  43. share_code: "share-1",
  44. share_url: "https://zcode.z.ai/cn/share/share-1",
  45. access_mode: "public_importable" as const,
  46. expires_at: 20_000,
  47. };
  48. function pendingSafetyCheck(retryAfterMs?: number, requestId?: string) {
  49. return new ConversationShareClientError({
  50. kind: "safety_check_pending",
  51. message: "share safety check pending",
  52. status: 409,
  53. code: 3215,
  54. ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
  55. ...(requestId === undefined ? {} : { requestId }),
  56. });
  57. }
  58. type PollOptions = Pick<
  59. ConversationShareServiceOptions,
  60. "confirmPollIntervalMs" | "confirmPollTimeoutMs" | "logger" | "now" | "sleep"
  61. >;
  62. function completedRows(): ConversationRow[] {
  63. return [
  64. {
  65. rowId: 1,
  66. turnId: "turn-1",
  67. productTurnId: "product-turn-1",
  68. createdAt: 1_000,
  69. createdAtSeq: 1,
  70. kind: "turnHeader",
  71. origin: "userInput",
  72. state: "completedSuccess",
  73. startedAt: 1_000,
  74. endedAt: 1_100,
  75. },
  76. {
  77. rowId: 2,
  78. turnId: "turn-1",
  79. productTurnId: "product-turn-1",
  80. createdAt: 1_010,
  81. createdAtSeq: 2,
  82. kind: "assistantText",
  83. text: "第一轮完成",
  84. state: "complete",
  85. },
  86. {
  87. rowId: 3,
  88. turnId: "turn-2",
  89. productTurnId: "product-turn-2",
  90. createdAt: 2_000,
  91. createdAtSeq: 3,
  92. kind: "turnHeader",
  93. origin: "userInput",
  94. state: "failed",
  95. startedAt: 2_000,
  96. endedAt: 2_100,
  97. },
  98. {
  99. rowId: 4,
  100. turnId: "turn-2",
  101. productTurnId: "product-turn-2",
  102. createdAt: 2_010,
  103. createdAtSeq: 4,
  104. kind: "assistantText",
  105. text: "第二轮失败",
  106. state: "failed",
  107. },
  108. ];
  109. }
  110. /** 只含一条带 txt 附件的用户输入轮,用于附件预检分类用例。 */
  111. function attachmentPreflightRows(): ConversationRow[] {
  112. const rows = completedRows().slice(0, 2);
  113. rows[0] = { ...rows[0]!, entityId: "header-entity" };
  114. rows.push({
  115. rowId: 5,
  116. turnId: "turn-1",
  117. productTurnId: "product-turn-1",
  118. entityId: "input-entity",
  119. createdAt: 1_050,
  120. createdAtSeq: 5,
  121. kind: "userInput",
  122. text: "粘贴文本",
  123. origin: "realUser",
  124. attachments: [
  125. { ref: "/workspace/pasted.txt", fileName: "pasted.txt", mime: "text/plain", bytes: 10 },
  126. ],
  127. });
  128. return rows;
  129. }
  130. function completedRowsWithSubagent(): ConversationRow[] {
  131. const rows = completedRows();
  132. return [
  133. {
  134. ...rows[0]!,
  135. entityId: "local-header-entity",
  136. actions: { canFork: true },
  137. },
  138. {
  139. ...rows[1]!,
  140. entityId: "local-assistant-entity",
  141. },
  142. {
  143. rowId: 3,
  144. turnId: "turn-1",
  145. entityId: "local-agent-tool-entity",
  146. productTurnId: "product-turn-1",
  147. createdAt: 1_020,
  148. createdAtSeq: 3,
  149. actions: { canRetry: true },
  150. kind: "toolCall",
  151. toolCallId: "local-agent-tool-call",
  152. toolName: "Agent",
  153. status: "success",
  154. inputText: '{"description":"研究"}',
  155. output: { text: "研究完成" },
  156. approvalInteractionId: "local-approval",
  157. },
  158. {
  159. rowId: 4,
  160. turnId: "turn-1",
  161. entityId: "local-subagent-entity",
  162. productTurnId: "product-turn-1",
  163. createdAt: 1_030,
  164. createdAtSeq: 4,
  165. kind: "subagent",
  166. parentToolCallId: "local-agent-tool-call",
  167. subagentType: "research",
  168. status: "success",
  169. summaryText: "研究完成",
  170. childSessionId: "local-child-session",
  171. },
  172. { ...rows[2]!, rowId: 5, createdAtSeq: 5 },
  173. { ...rows[3]!, rowId: 6, createdAtSeq: 6 },
  174. ];
  175. }
  176. function completedRowsWithFileChanges(): ConversationRow[] {
  177. const rows = completedRows();
  178. rows[0] = {
  179. ...rows[0]!,
  180. entityId: "turn-header-1",
  181. fileChanges: { files: 3, additions: 0, deletions: 0, state: "active" },
  182. };
  183. rows[1] = { ...rows[1]!, text: "已生成 reports/调研报告.pdf 和 reports/汇报.pptx" };
  184. return rows;
  185. }
  186. function createDependencies(rows = completedRows(), pollOptions: PollOptions = {}) {
  187. const conversationRowsRangeV4 = vi.fn(async ({ beforeRowId }: { beforeRowId?: number }) =>
  188. beforeRowId === undefined
  189. ? {
  190. rows: rows.slice(rows.length > 2 ? 2 : 0),
  191. atSeq: 4,
  192. atRevision: 7,
  193. atLogEpoch: "epoch-1",
  194. hasMore: rows.length > 2,
  195. }
  196. : {
  197. rows: rows.slice(0, 2),
  198. atSeq: 4,
  199. atRevision: 7,
  200. atLogEpoch: "epoch-1",
  201. hasMore: false,
  202. },
  203. );
  204. const conversationFileChangesV4 = vi.fn(async () => ({
  205. files: 0,
  206. additions: 0,
  207. deletions: 0,
  208. items: [],
  209. }));
  210. const conversationAttachmentReadV4 = vi.fn(async () => {
  211. throw new Error("attachment unavailable in test fixture");
  212. });
  213. const conversationAttachmentStatV4 = vi.fn(async () => ({
  214. mediaType: "text/plain",
  215. totalBytes: 0,
  216. }));
  217. const confirmRequests: ConversationShareConfirmRequest[] = [];
  218. const preparationRequests: ConversationSharePreparationRequest[] = [];
  219. const client = {
  220. getCapabilities: vi.fn(async () => capabilities),
  221. createPreparation: vi.fn(async (request: ConversationSharePreparationRequest) => {
  222. preparationRequests.push(request);
  223. return {
  224. preparation_id: "preparation-1",
  225. status: "preparing" as const,
  226. access_mode: request.access_mode,
  227. expires_at: 20_000,
  228. };
  229. }),
  230. confirm: vi.fn(async (_preparationId: string, request: ConversationShareConfirmRequest) => {
  231. confirmRequests.push(request);
  232. return {
  233. share_code: "share-1",
  234. share_url: "https://zcode.z.ai/cn/share/share-1",
  235. access_mode: preparationRequests.at(-1)?.access_mode ?? "private",
  236. expires_at: 20_000,
  237. };
  238. }),
  239. uploadArtifact: vi.fn(async (_preparationId, descriptor) => ({
  240. artifact_id: descriptor.artifact_id,
  241. size_bytes: descriptor.size_bytes,
  242. sha256: descriptor.sha256,
  243. status: "uploaded" as const,
  244. })),
  245. getPreview: vi.fn(),
  246. getContinuation: vi.fn(),
  247. };
  248. const artifactSource = {
  249. stat: vi.fn(async ({ ref }: { ref: string }) => ({
  250. canonicalPath: ref,
  251. size: 0,
  252. mtimeMs: 1,
  253. })),
  254. read: vi.fn(async ({ ref }: { ref: string }) => ({
  255. bytes: new Uint8Array(),
  256. canonicalPath: ref,
  257. })),
  258. };
  259. const service = new ConversationShareService({
  260. zcodeAgentService: {
  261. conversationRowsRangeV4,
  262. conversationFileChangesV4,
  263. conversationAttachmentReadV4,
  264. conversationAttachmentStatV4,
  265. } as unknown as Pick<
  266. IZCodeAgentService,
  267. | "conversationRowsRangeV4"
  268. | "conversationFileChangesV4"
  269. | "conversationAttachmentReadV4"
  270. | "conversationAttachmentStatV4"
  271. >,
  272. client: client as unknown as ConversationShareHttpClient,
  273. artifactSource,
  274. ...pollOptions,
  275. });
  276. return {
  277. service,
  278. client,
  279. conversationRowsRangeV4,
  280. conversationFileChangesV4,
  281. conversationAttachmentReadV4,
  282. conversationAttachmentStatV4,
  283. confirmRequests,
  284. preparationRequests,
  285. artifactSource,
  286. };
  287. }
  288. function publishInput() {
  289. return {
  290. workspacePath: "/workspace",
  291. workspaceIdentity: "ssh://host/workspace",
  292. sessionId: "session-1",
  293. title: "会话分享",
  294. accessMode: "public_importable" as const,
  295. selection: { kind: "all" as const },
  296. clientRequestId: "publish-request-1",
  297. disclosureAcceptedAt: 10_000,
  298. };
  299. }
  300. function collectPublishProgress(
  301. service: ConversationShareService,
  302. operationId: string,
  303. ): ConversationSharePublishProgress[] {
  304. const events: ConversationSharePublishProgress[] = [];
  305. service.onDynamicPublishProgress(operationId)((event) => events.push(event));
  306. return events;
  307. }
  308. function firstWarnings(
  309. events: readonly ConversationSharePublishProgress[],
  310. ): readonly ConversationShareFailureIssue[] | undefined {
  311. return events.find((event) => event.warnings?.length)?.warnings;
  312. }
  313. describe("ConversationShareService", () => {
  314. it("选择阶段 preflight 区分运行中阻断、文件跳过和静默内部结构", async () => {
  315. const rows = completedRows();
  316. rows[0] = { ...rows[0]!, entityId: "header-entity" };
  317. rows.push(
  318. {
  319. rowId: 5,
  320. turnId: "turn-1",
  321. productTurnId: "product-turn-1",
  322. entityId: "input-entity",
  323. createdAt: 1_050,
  324. createdAtSeq: 5,
  325. kind: "userInput",
  326. text: "附带文件",
  327. origin: "userInput",
  328. attachments: [
  329. { ref: "/workspace/video.mp4", fileName: "video.mp4", mime: "video/mp4", bytes: 0 },
  330. ],
  331. },
  332. {
  333. rowId: 6,
  334. turnId: "turn-1",
  335. productTurnId: "product-turn-1",
  336. createdAt: 1_060,
  337. createdAtSeq: 6,
  338. kind: "timelineMarker",
  339. marker: { type: "forkNotice", parentSessionId: "private-parent", parentRowId: 1 },
  340. },
  341. {
  342. rowId: 7,
  343. turnId: "turn-1",
  344. productTurnId: "product-turn-1",
  345. createdAt: 1_070,
  346. createdAtSeq: 7,
  347. kind: "toolCall",
  348. toolCallId: "node-repl",
  349. toolName: "NodeRepl",
  350. status: "success",
  351. inputText: "{}",
  352. display: {
  353. kind: "node_repl_images",
  354. images: [{ base64: "secret", mimeType: "image/png" }],
  355. },
  356. },
  357. {
  358. rowId: 8,
  359. turnId: "turn-3",
  360. productTurnId: "product-turn-3",
  361. createdAt: 1_080,
  362. createdAtSeq: 8,
  363. kind: "turnHeader",
  364. origin: "userInput",
  365. state: "running",
  366. startedAt: 1_080,
  367. },
  368. );
  369. const { service } = createDependencies(rows);
  370. const result = await service.preflight({
  371. workspacePath: "/workspace",
  372. sessionId: "session-1",
  373. selection: { kind: "all" },
  374. });
  375. expect(result.blockingIssues).toEqual([expect.objectContaining({ code: "running_turn" })]);
  376. expect(result.skippableWarnings).toEqual([
  377. expect.objectContaining({
  378. code: "artifact_type_not_allowed",
  379. artifactType: "image",
  380. }),
  381. expect.objectContaining({
  382. code: "artifact_type_not_allowed",
  383. artifactDisplayName: "video.mp4",
  384. }),
  385. ]);
  386. expect(result.skippableWarnings).not.toEqual(
  387. expect.arrayContaining([
  388. expect.objectContaining({ code: "inline_tool_image" }),
  389. expect.objectContaining({ code: "unsupported_timeline" }),
  390. ]),
  391. );
  392. expect(result.turnResults).toEqual(
  393. expect.arrayContaining([
  394. expect.objectContaining({
  395. productTurnId: "product-turn-1",
  396. skippableWarnings: expect.arrayContaining([
  397. expect.objectContaining({ artifactDisplayName: "video.mp4" }),
  398. expect.objectContaining({ artifactType: "image" }),
  399. ]),
  400. }),
  401. ]),
  402. );
  403. });
  404. it("全局预检问题会进入每个 turn 的缓存结果,避免客户端聚合时丢失", async () => {
  405. const rows = completedRows().map((row) =>
  406. row.kind === "assistantText" ? { ...row, text: "" } : row,
  407. );
  408. const { service } = createDependencies(rows);
  409. const result = await service.preflight({
  410. workspacePath: "/workspace",
  411. sessionId: "session-1",
  412. selection: { kind: "all" },
  413. });
  414. expect(result.blockingIssues).toEqual([
  415. expect.objectContaining({ code: "no_shareable_content", scope: "conversation" }),
  416. ]);
  417. expect(result.turnResults).toEqual(
  418. expect.arrayContaining([
  419. expect.objectContaining({
  420. productTurnId: "product-turn-1",
  421. blockingIssues: [expect.objectContaining({ code: "no_shareable_content" })],
  422. }),
  423. expect.objectContaining({
  424. productTurnId: "product-turn-2",
  425. blockingIssues: [expect.objectContaining({ code: "no_shareable_content" })],
  426. }),
  427. ]),
  428. );
  429. });
  430. it("选择阶段 preflight 能提前识别已清理的用户输入附件", async () => {
  431. const rows = completedRows().slice(0, 2);
  432. rows[0] = { ...rows[0]!, entityId: "header-entity" };
  433. rows.push({
  434. rowId: 5,
  435. turnId: "turn-1",
  436. productTurnId: "product-turn-1",
  437. entityId: "input-entity",
  438. createdAt: 1_050,
  439. createdAtSeq: 5,
  440. kind: "userInput",
  441. text: "粘贴文本",
  442. origin: "realUser",
  443. attachments: [
  444. { ref: "/workspace/pasted.txt", fileName: "pasted.txt", mime: "text/plain", bytes: 10 },
  445. ],
  446. });
  447. const { service, client, conversationAttachmentStatV4 } = createDependencies(rows);
  448. client.getCapabilities.mockResolvedValueOnce({
  449. ...capabilities,
  450. max_artifact_bytes: 100,
  451. allowed_artifacts: [{ type: "text", extensions: ["txt"], mime_types: ["text/plain"] }],
  452. });
  453. conversationAttachmentStatV4.mockRejectedValueOnce(new Error("ENOENT: attachment removed"));
  454. const result = await service.preflight({
  455. workspacePath: "/workspace",
  456. sessionId: "session-1",
  457. selection: { kind: "all" },
  458. });
  459. expect(result.blockingIssues).toEqual([]);
  460. expect(result.skippableWarnings).toEqual([
  461. expect.objectContaining({
  462. code: "input_attachment_unavailable",
  463. artifactDisplayName: "pasted.txt",
  464. availability: "not_found",
  465. }),
  466. ]);
  467. expect(conversationAttachmentStatV4).toHaveBeenCalledWith(
  468. expect.objectContaining({ attachmentIndex: 0, ref: "/workspace/pasted.txt" }),
  469. );
  470. });
  471. it("选择阶段把超大附件判为阻断的 artifact_size_limit,而不是降级成 deferred", async () => {
  472. const rows = attachmentPreflightRows();
  473. const { service, client, conversationAttachmentStatV4 } = createDependencies(rows);
  474. client.getCapabilities.mockResolvedValueOnce({
  475. ...capabilities,
  476. max_artifact_bytes: 100,
  477. allowed_artifacts: [{ type: "text", extensions: ["txt"], mime_types: ["text/plain"] }],
  478. });
  479. // 真实文件大小远超协议旧上限(30MiB);stat 必须能表达它,预检才能确定阻断。
  480. conversationAttachmentStatV4.mockResolvedValueOnce({
  481. mediaType: "text/plain",
  482. totalBytes: 64 * 1024 * 1024,
  483. });
  484. const result = await service.preflight({
  485. workspacePath: "/workspace",
  486. sessionId: "session-1",
  487. selection: { kind: "all" },
  488. });
  489. expect(result.deferredIssues).toEqual([]);
  490. expect(result.blockingIssues).toEqual([
  491. expect.objectContaining({
  492. code: "artifact_size_limit",
  493. artifactDisplayName: "pasted.txt",
  494. productTurnId: "product-turn-1",
  495. actual: 64 * 1024 * 1024,
  496. limit: 100,
  497. }),
  498. ]);
  499. });
  500. it("stat 报 shareStatTooLarge 时也阻断,而不是当成未知错误", async () => {
  501. const rows = attachmentPreflightRows();
  502. const { service, client, conversationAttachmentStatV4 } = createDependencies(rows);
  503. client.getCapabilities.mockResolvedValueOnce({
  504. ...capabilities,
  505. max_artifact_bytes: 100,
  506. allowed_artifacts: [{ type: "text", extensions: ["txt"], mime_types: ["text/plain"] }],
  507. });
  508. conversationAttachmentStatV4.mockRejectedValueOnce(
  509. new ZCodeAttachmentFaultError(ZCODE_ATTACHMENT_FAULT_CODES.shareStatTooLarge),
  510. );
  511. const result = await service.preflight({
  512. workspacePath: "/workspace",
  513. sessionId: "session-1",
  514. selection: { kind: "all" },
  515. });
  516. expect(result.deferredIssues).toEqual([]);
  517. expect(result.blockingIssues).toEqual([
  518. expect.objectContaining({ code: "artifact_size_limit", limit: 100 }),
  519. ]);
  520. });
  521. it("不支持的附件类型即使超大也只是可跳过的 artifact_type_not_allowed", async () => {
  522. const rows = attachmentPreflightRows();
  523. const { service, client, conversationAttachmentStatV4 } = createDependencies(rows);
  524. client.getCapabilities.mockResolvedValueOnce({
  525. ...capabilities,
  526. max_artifact_bytes: 100,
  527. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  528. });
  529. conversationAttachmentStatV4.mockResolvedValueOnce({
  530. mediaType: "text/plain",
  531. totalBytes: 64 * 1024 * 1024,
  532. });
  533. const result = await service.preflight({
  534. workspacePath: "/workspace",
  535. sessionId: "session-1",
  536. selection: { kind: "all" },
  537. });
  538. // 不支持的类型根本不会上传,体积与分享无关:不能升级成阻断。
  539. expect(result.blockingIssues).toEqual([]);
  540. expect(result.skippableWarnings).toEqual([
  541. expect.objectContaining({
  542. code: "artifact_type_not_allowed",
  543. artifactDisplayName: "pasted.txt",
  544. }),
  545. ]);
  546. });
  547. it("选择阶段只检查最终预览卡片:忽略 ~/ 路径和缺失 Markdown,提示已存在视频不可分享", async () => {
  548. const rows = completedRows();
  549. rows[0] = { ...rows[0]!, entityId: "turn-header-1" };
  550. rows[1] = {
  551. ...rows[1]!,
  552. text: [
  553. "~/Code/vibe/shows/deliver/晨报.pdf",
  554. '::zcode-file-citation{path="/workspace/晨报.pdf" purpose="output"}',
  555. "build_mn/qa/layout-review.md",
  556. "out/one.mp4 out/two.mp4 out/three.mp4",
  557. ].join("\n"),
  558. };
  559. const { service, client, artifactSource } = createDependencies(rows);
  560. client.getCapabilities.mockResolvedValueOnce({
  561. ...capabilities,
  562. max_artifact_count: 4,
  563. max_artifact_bytes: 1024,
  564. max_total_artifact_bytes: 4096,
  565. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  566. });
  567. const result = await service.preflight({
  568. workspacePath: "/workspace",
  569. sessionId: "session-1",
  570. selection: { kind: "productTurns", productTurnIds: ["product-turn-1"] },
  571. });
  572. expect(artifactSource.stat).toHaveBeenCalledTimes(4);
  573. expect(artifactSource.stat.mock.calls.map(([input]) => input.ref)).toEqual([
  574. "/workspace/out/three.mp4",
  575. "/workspace/out/two.mp4",
  576. "/workspace/out/one.mp4",
  577. "/workspace/晨报.pdf",
  578. ]);
  579. expect(result.skippableWarnings).toEqual([
  580. expect.objectContaining({
  581. code: "artifact_type_not_allowed",
  582. artifactDisplayName: "three.mp4",
  583. }),
  584. expect.objectContaining({
  585. code: "artifact_type_not_allowed",
  586. artifactDisplayName: "two.mp4",
  587. }),
  588. expect.objectContaining({
  589. code: "artifact_type_not_allowed",
  590. artifactDisplayName: "one.mp4",
  591. }),
  592. ]);
  593. expect(result.skippableWarnings).not.toEqual(
  594. expect.arrayContaining([
  595. expect.objectContaining({ artifactDisplayName: "晨报.pdf" }),
  596. expect.objectContaining({ artifactDisplayName: "layout-review.md" }),
  597. ]),
  598. );
  599. });
  600. it("选择阶段缺失的预览卡片不会在发布阶段重新变成 warning", async () => {
  601. const rows = completedRowsWithFileChanges().slice(0, 2);
  602. rows[1] = { ...rows[1]!, text: "已生成 layout-review.md report.pdf" };
  603. const { service, client, artifactSource, conversationFileChangesV4, preparationRequests } =
  604. createDependencies(rows);
  605. conversationFileChangesV4.mockResolvedValue({
  606. files: 1,
  607. additions: 1,
  608. deletions: 0,
  609. state: "active",
  610. items: [
  611. {
  612. path: "/workspace/layout-review.md",
  613. additions: 1,
  614. deletions: 0,
  615. writeCount: 1,
  616. toolNames: ["Write"],
  617. patches: [],
  618. },
  619. ],
  620. });
  621. client.getCapabilities.mockResolvedValue({
  622. ...capabilities,
  623. max_artifact_count: 2,
  624. max_artifact_bytes: 1024,
  625. max_total_artifact_bytes: 2048,
  626. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  627. });
  628. artifactSource.stat.mockImplementation(async ({ ref }) => {
  629. if (ref.endsWith("layout-review.md")) {
  630. throw new ConversationShareServiceError(
  631. "invalid_conversation",
  632. "Conversation artifact cannot be read",
  633. { reasonCode: "artifact_read_failed", diagnostics: { errno: "ENOENT" } },
  634. );
  635. }
  636. return { canonicalPath: ref, size: 4, mtimeMs: 1 };
  637. });
  638. artifactSource.read.mockResolvedValue({
  639. bytes: new TextEncoder().encode("pdf!"),
  640. canonicalPath: "/workspace/report.pdf",
  641. });
  642. const selection = {
  643. kind: "productTurns" as const,
  644. productTurnIds: ["product-turn-1"],
  645. };
  646. const preflight = await service.preflight({
  647. workspacePath: "/workspace",
  648. workspaceIdentity: "ssh://host/workspace",
  649. remoteSessionId: "remote-session-1",
  650. sessionId: "session-1",
  651. selection,
  652. });
  653. expect(preflight.skippableWarnings).not.toEqual(
  654. expect.arrayContaining([
  655. expect.objectContaining({ artifactDisplayName: "layout-review.md" }),
  656. ]),
  657. );
  658. const progress = collectPublishProgress(service, "publish-op-preview-snapshot");
  659. await expect(
  660. service.publish(
  661. {
  662. ...publishInput(),
  663. remoteSessionId: "remote-session-1",
  664. selection,
  665. },
  666. "publish-op-preview-snapshot",
  667. ),
  668. ).resolves.toEqual(shareRecord);
  669. expect(artifactSource.stat.mock.calls.map(([input]) => input.ref)).toEqual([
  670. "/workspace/report.pdf",
  671. "/workspace/layout-review.md",
  672. "/workspace/report.pdf",
  673. ]);
  674. expect(artifactSource.read).toHaveBeenCalledTimes(1);
  675. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 1 });
  676. expect(firstWarnings(progress)).toBeUndefined();
  677. });
  678. it("选择阶段会检查候选上限内全部文件,再按存在性取最终可见卡片", async () => {
  679. const rows = completedRows().slice(0, 2);
  680. rows[1] = {
  681. ...rows[1]!,
  682. text: Array.from({ length: 12 }, (_, index) => `clip-${index + 1}.mp4`).join(" "),
  683. };
  684. const { service, client, artifactSource } = createDependencies(rows);
  685. client.getCapabilities.mockResolvedValueOnce({
  686. ...capabilities,
  687. max_artifact_count: 10,
  688. max_artifact_bytes: 1024,
  689. max_total_artifact_bytes: 4096,
  690. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  691. });
  692. const result = await service.preflight({
  693. workspacePath: "/workspace",
  694. sessionId: "session-1",
  695. selection: { kind: "productTurns", productTurnIds: ["product-turn-1"] },
  696. });
  697. expect(artifactSource.stat).toHaveBeenCalledTimes(12);
  698. expect(result.skippableWarnings.map((issue) => issue.artifactDisplayName)).toEqual([
  699. "clip-12.mp4",
  700. "clip-11.mp4",
  701. "clip-10.mp4",
  702. "clip-9.mp4",
  703. "clip-8.mp4",
  704. ]);
  705. });
  706. it("即使能力列表误包含媒体,视频预览也只 warning 不上传", async () => {
  707. const rows = completedRows().slice(0, 2);
  708. rows[1] = {
  709. ...rows[1]!,
  710. text: "report.pdf clip.mp4",
  711. };
  712. const { service, client, artifactSource, preparationRequests } = createDependencies(rows);
  713. client.getCapabilities.mockResolvedValue({
  714. ...capabilities,
  715. max_artifact_count: 2,
  716. max_artifact_bytes: 1024,
  717. max_total_artifact_bytes: 2048,
  718. allowed_artifacts: [
  719. { type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] },
  720. { type: "video", extensions: ["mp4"], mime_types: ["video/mp4"] },
  721. ],
  722. });
  723. artifactSource.read.mockResolvedValue({
  724. bytes: new TextEncoder().encode("pdf!"),
  725. canonicalPath: "/workspace/report.pdf",
  726. });
  727. const preflight = await service.preflight({
  728. workspacePath: "/workspace",
  729. sessionId: "session-1",
  730. selection: { kind: "productTurns", productTurnIds: ["product-turn-1"] },
  731. });
  732. expect(preflight.skippableWarnings).toEqual([
  733. expect.objectContaining({
  734. code: "artifact_type_not_allowed",
  735. artifactDisplayName: "clip.mp4",
  736. }),
  737. ]);
  738. await expect(service.publish(publishInput(), "publish-op-media-capability")).resolves.toEqual(
  739. shareRecord,
  740. );
  741. expect(artifactSource.read).toHaveBeenCalledTimes(1);
  742. expect(artifactSource.read).toHaveBeenCalledWith({
  743. workspacePath: "/workspace",
  744. ref: "/workspace/report.pdf",
  745. maxBytes: 1024,
  746. });
  747. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 1 });
  748. });
  749. it("exposes a stable safe reason code for invalid conversation failures", () => {
  750. const error = new ConversationShareServiceError(
  751. "invalid_conversation",
  752. "Conversation attachments require the artifact row protocol",
  753. { diagnostics: { rowKind: "userInput", rowId: 9 } },
  754. );
  755. expect(error.reasonCode).toBe("input_attachment");
  756. expect(error.diagnostics).toEqual({ rowKind: "userInput", rowId: 9 });
  757. });
  758. it("把 artifact 读失败消息归类到 artifact_read_failed 而不是兜底", () => {
  759. // 旧正则只覆盖 ended|source|chunk|readable,本地/远端兜底消息因此落到 invalid_conversation,
  760. // UI 于是显示了无关的「结构不支持」文案。
  761. expect(
  762. new ConversationShareServiceError(
  763. "invalid_conversation",
  764. "Conversation artifact cannot be read",
  765. ).reasonCode,
  766. ).toBe("artifact_read_failed");
  767. expect(
  768. new ConversationShareServiceError(
  769. "invalid_conversation",
  770. "Conversation artifact cannot be read from the remote workspace",
  771. ).reasonCode,
  772. ).toBe("artifact_read_failed");
  773. expect(
  774. new ConversationShareServiceError(
  775. "invalid_conversation",
  776. "Conversation artifact source is not a file",
  777. ).reasonCode,
  778. ).toBe("artifact_read_failed");
  779. });
  780. it("errno 进 diagnostics,cause 不进跨 RPC 载荷", () => {
  781. const cause = Object.assign(new Error("ENOENT: no such file"), {
  782. code: "ENOENT",
  783. path: "/workspace/DELIVER/报告.pdf",
  784. });
  785. const error = new ConversationShareServiceError(
  786. "invalid_conversation",
  787. "Conversation artifact cannot be read",
  788. { reasonCode: "artifact_read_failed", cause, diagnostics: { errno: "ENOENT" } },
  789. );
  790. expect(error.cause).toBe(cause);
  791. expect(error.diagnostics).toEqual({ errno: "ENOENT" });
  792. expect(error.details).not.toHaveProperty("cause");
  793. expect(JSON.stringify(error.details)).not.toContain("报告.pdf");
  794. });
  795. it("keeps a safe request id in the service error details envelope", () => {
  796. const error = new ConversationShareServiceError(
  797. "artifact_not_allowed",
  798. "Conversation artifacts cannot be shared",
  799. {
  800. requestId: "server-request-123",
  801. issues: [{ code: "artifact_type_not_allowed", scope: "artifact" }],
  802. },
  803. );
  804. expect(error.requestId).toBe("server-request-123");
  805. expect(error.details).toMatchObject({
  806. requestId: "server-request-123",
  807. issues: [{ code: "artifact_type_not_allowed", scope: "artifact" }],
  808. issueCount: 1,
  809. omittedIssueCount: 0,
  810. });
  811. });
  812. it("SHARE08:已选历史轮次的 PDF/PPTX 通过预览候选上传后再 confirm", async () => {
  813. const pdfBytes = new TextEncoder().encode("pdf!");
  814. const pptxBytes = new TextEncoder().encode("pptx!");
  815. const { service, client, artifactSource, conversationFileChangesV4, preparationRequests } =
  816. createDependencies(completedRowsWithFileChanges());
  817. client.getCapabilities.mockResolvedValueOnce({
  818. ...capabilities,
  819. max_artifact_count: 4,
  820. max_artifact_bytes: 1024,
  821. max_total_artifact_bytes: 4096,
  822. allowed_artifacts: [
  823. { type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] },
  824. {
  825. type: "pptx",
  826. extensions: ["pptx"],
  827. mime_types: ["application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  828. },
  829. ],
  830. });
  831. conversationFileChangesV4.mockResolvedValueOnce({
  832. files: 3,
  833. additions: 0,
  834. deletions: 0,
  835. state: "active",
  836. items: [
  837. {
  838. path: "reports/调研报告.pdf",
  839. additions: 0,
  840. deletions: 0,
  841. writeCount: 1,
  842. toolNames: ["Bash"],
  843. patches: [],
  844. },
  845. {
  846. path: "reports/汇报.pptx",
  847. additions: 0,
  848. deletions: 0,
  849. writeCount: 1,
  850. toolNames: ["Bash"],
  851. patches: [],
  852. },
  853. {
  854. path: "scripts/generate.py",
  855. additions: 10,
  856. deletions: 0,
  857. writeCount: 1,
  858. toolNames: ["Write"],
  859. patches: [],
  860. },
  861. ],
  862. });
  863. artifactSource.read.mockImplementation(async ({ ref }) => {
  864. if (ref.endsWith(".pdf")) {
  865. return { bytes: pdfBytes, canonicalPath: "/workspace/reports/调研报告.pdf" };
  866. }
  867. if (ref.endsWith(".pptx")) {
  868. return { bytes: pptxBytes, canonicalPath: "/workspace/reports/汇报.pptx" };
  869. }
  870. throw new Error(`unexpected artifact read: ${ref}`);
  871. });
  872. const order: string[] = [];
  873. client.createPreparation.mockImplementationOnce(async (request) => {
  874. order.push("prepare");
  875. preparationRequests.push(request);
  876. return {
  877. preparation_id: "preparation-1",
  878. status: "preparing",
  879. access_mode: request.access_mode,
  880. expires_at: 20_000,
  881. };
  882. });
  883. client.uploadArtifact.mockImplementation(async (_id, descriptor) => {
  884. order.push(`upload:${descriptor.extension}`);
  885. return {
  886. artifact_id: descriptor.artifact_id,
  887. size_bytes: descriptor.size_bytes,
  888. sha256: descriptor.sha256,
  889. status: "uploaded",
  890. };
  891. });
  892. client.confirm.mockImplementationOnce(async () => {
  893. order.push("confirm");
  894. return shareRecord;
  895. });
  896. await expect(service.publish(publishInput(), "publish-op-1")).resolves.toEqual(shareRecord);
  897. expect(conversationFileChangesV4).not.toHaveBeenCalled();
  898. expect(artifactSource.read).toHaveBeenCalledTimes(2);
  899. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 2 });
  900. expect(order).toEqual(["prepare", "upload:pptx", "upload:pdf", "confirm"]);
  901. });
  902. it("正文引用的文件读不到时跳过该结果物并回传非阻断提示,发布照常成功", async () => {
  903. const pptxBytes = new TextEncoder().encode("pptx!");
  904. const { service, client, artifactSource, preparationRequests } = createDependencies(
  905. completedRowsWithFileChanges(),
  906. );
  907. client.getCapabilities.mockResolvedValueOnce({
  908. ...capabilities,
  909. max_artifact_count: 4,
  910. max_artifact_bytes: 1024,
  911. max_total_artifact_bytes: 4096,
  912. allowed_artifacts: [
  913. { type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] },
  914. {
  915. type: "pptx",
  916. extensions: ["pptx"],
  917. mime_types: ["application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  918. },
  919. ],
  920. });
  921. // PDF 是正文里已不存在的路径(例如 SKILL.md 的模板占位符),PPTX 真实存在。
  922. artifactSource.read.mockImplementation(async ({ ref }) => {
  923. if (ref.endsWith(".pdf")) {
  924. throw new ConversationShareServiceError(
  925. "invalid_conversation",
  926. "Conversation artifact cannot be read",
  927. { reasonCode: "artifact_read_failed", diagnostics: { errno: "ENOENT" } },
  928. );
  929. }
  930. return { bytes: pptxBytes, canonicalPath: "/workspace/reports/汇报.pptx" };
  931. });
  932. const progress: ConversationSharePublishProgress[] = [];
  933. service.onDynamicPublishProgress("publish-op-skip")((event) => progress.push(event));
  934. await expect(service.publish(publishInput(), "publish-op-skip")).resolves.toEqual(shareRecord);
  935. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 1 });
  936. expect(firstWarnings(progress)).toEqual([
  937. expect.objectContaining({
  938. code: "artifact_read_failed",
  939. scope: "artifact",
  940. artifactDisplayName: "调研报告.pdf",
  941. artifactType: "pdf",
  942. extension: "pdf",
  943. }),
  944. ]);
  945. });
  946. it("没有预览卡片的正式 artifact row 不再作为独立分享来源", async () => {
  947. const bytes = new TextEncoder().encode("pdf!");
  948. const rows = completedRows().slice(0, 2);
  949. rows.push({
  950. rowId: 3,
  951. turnId: "turn-1",
  952. productTurnId: "product-turn-1",
  953. createdAt: 1_020,
  954. createdAtSeq: 3,
  955. kind: "artifact",
  956. artifactVersionId: "registered-report",
  957. logicalArtifactKey: "registered-report",
  958. displayName: "正式报告.pdf",
  959. artifactType: "pdf",
  960. mimeType: "application/pdf",
  961. sizeBytes: bytes.byteLength,
  962. sha256: createHash("sha256").update(bytes).digest("hex"),
  963. ref: "/workspace/output/report.pdf",
  964. state: "current",
  965. });
  966. const { service, client, artifactSource, preparationRequests, confirmRequests } =
  967. createDependencies(rows);
  968. client.getCapabilities.mockResolvedValueOnce({
  969. ...capabilities,
  970. max_artifact_count: 2,
  971. max_artifact_bytes: 1024,
  972. max_total_artifact_bytes: 2048,
  973. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  974. });
  975. artifactSource.read.mockRejectedValue(
  976. new ConversationShareServiceError(
  977. "invalid_conversation",
  978. "Conversation artifact cannot be read",
  979. { reasonCode: "artifact_read_failed" },
  980. ),
  981. );
  982. await expect(service.publish(publishInput(), "publish-op-skip-2")).resolves.toEqual(
  983. shareRecord,
  984. );
  985. expect(artifactSource.read).not.toHaveBeenCalled();
  986. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 0 });
  987. expect(confirmRequests.at(-1)?.projection.rows).not.toEqual(
  988. expect.arrayContaining([expect.objectContaining({ kind: "artifact" })]),
  989. );
  990. });
  991. it("用户输入附件降级为跳过:删掉 attachments 后正文照常分享", async () => {
  992. const base = completedRows();
  993. const rows: ConversationRow[] = [
  994. base[0]!,
  995. {
  996. rowId: 2,
  997. turnId: "turn-1",
  998. productTurnId: "product-turn-1",
  999. createdAt: 1_005,
  1000. createdAtSeq: 2,
  1001. kind: "userInput",
  1002. text: "帮我看看这个截图",
  1003. origin: "realUser",
  1004. attachments: [
  1005. {
  1006. ref: "/Users/me/Desktop/截图.png",
  1007. fileName: "截图.png",
  1008. mime: "image/png",
  1009. bytes: 2048,
  1010. },
  1011. ],
  1012. },
  1013. { ...base[1]!, rowId: 3, createdAtSeq: 3 },
  1014. ];
  1015. const { service, confirmRequests } = createDependencies(rows);
  1016. const progress = collectPublishProgress(service, "publish-op-attach");
  1017. await expect(service.publish(publishInput(), "publish-op-attach")).resolves.toEqual(
  1018. shareRecord,
  1019. );
  1020. const userInput = confirmRequests
  1021. .at(-1)
  1022. ?.projection.rows.find((row) => row.kind === "userInput");
  1023. expect(userInput).toMatchObject({ text: "帮我看看这个截图" });
  1024. expect(userInput).not.toHaveProperty("attachments");
  1025. expect(firstWarnings(progress)).toEqual([
  1026. expect.objectContaining({
  1027. code: "artifact_type_not_allowed",
  1028. scope: "artifact",
  1029. turnOrdinal: 1,
  1030. }),
  1031. ]);
  1032. });
  1033. it("用户输入文本附件生成 text manifest 并改写为公开引用", async () => {
  1034. const rows: ConversationRow[] = [
  1035. {
  1036. rowId: 1,
  1037. turnId: "turn-1",
  1038. entityId: "user-entity",
  1039. productTurnId: "product-turn-1",
  1040. createdAt: 1_000,
  1041. createdAtSeq: 1,
  1042. kind: "turnHeader",
  1043. origin: "userInput",
  1044. state: "completedSuccess",
  1045. startedAt: 1_000,
  1046. endedAt: 1_100,
  1047. },
  1048. {
  1049. rowId: 2,
  1050. turnId: "turn-1",
  1051. entityId: "user-entity",
  1052. productTurnId: "product-turn-1",
  1053. createdAt: 1_010,
  1054. createdAtSeq: 2,
  1055. kind: "userInput",
  1056. text: "分析这个大文本",
  1057. origin: "realUser",
  1058. attachments: [
  1059. {
  1060. ref: "/data/.zcode/tmp/paste-attachments/pasted.txt",
  1061. fileName: "pasted.txt",
  1062. mime: "text/plain",
  1063. bytes: 11,
  1064. },
  1065. ],
  1066. },
  1067. {
  1068. rowId: 3,
  1069. turnId: "turn-1",
  1070. productTurnId: "product-turn-1",
  1071. createdAt: 1_020,
  1072. createdAtSeq: 3,
  1073. kind: "assistantText",
  1074. text: "已读取",
  1075. state: "complete",
  1076. },
  1077. ];
  1078. const { service, client, conversationAttachmentReadV4, confirmRequests } =
  1079. createDependencies(rows);
  1080. client.getCapabilities.mockResolvedValueOnce({
  1081. ...capabilities,
  1082. max_artifact_count: 2,
  1083. max_artifact_bytes: 1024,
  1084. max_total_artifact_bytes: 2048,
  1085. allowed_artifacts: [{ type: "text", extensions: ["txt"], mime_types: ["text/plain"] }],
  1086. });
  1087. conversationAttachmentReadV4.mockImplementation(async ({ offset }: { offset: number }) => ({
  1088. dataBase64: Buffer.from("hello world")
  1089. .subarray(offset, offset + 6)
  1090. .toString("base64"),
  1091. mediaType: "text/plain",
  1092. totalBytes: 11,
  1093. nextOffset: offset + 6 < 11 ? offset + 6 : null,
  1094. }));
  1095. await expect(service.publish(publishInput(), "publish-op-text-attach")).resolves.toEqual(
  1096. shareRecord,
  1097. );
  1098. const request = confirmRequests.at(-1)!;
  1099. const userInput = request.projection.rows.find((row) => row.kind === "userInput");
  1100. expect(userInput).toMatchObject({
  1101. attachments: [
  1102. expect.objectContaining({
  1103. ref: "zcode-artifact://share/share-input-artifact-1",
  1104. previewRef: "zcode-artifact://share/share-input-artifact-1",
  1105. }),
  1106. ],
  1107. });
  1108. expect(request.integrity.projection_sha256).toMatch(/^[0-9a-f]{64}$/u);
  1109. expect(conversationAttachmentReadV4).toHaveBeenCalled();
  1110. expect(client.uploadArtifact).toHaveBeenCalledWith(
  1111. "preparation-1",
  1112. expect.objectContaining({
  1113. artifact_type: "text",
  1114. producer_product_turn_id: "share-product-turn-1",
  1115. }),
  1116. expect.any(Blob),
  1117. );
  1118. });
  1119. it("内嵌工具图片复用 artifact 上传且预检与发布一致", async () => {
  1120. const rows = completedRows().slice(0, 2);
  1121. rows.push({
  1122. rowId: 5,
  1123. turnId: "turn-1",
  1124. productTurnId: "product-turn-1",
  1125. createdAt: 1_050,
  1126. createdAtSeq: 5,
  1127. kind: "toolCall",
  1128. toolCallId: "node-repl-call",
  1129. toolName: "NodeRepl",
  1130. status: "success",
  1131. inputText: "{}",
  1132. output: { text: "已绘图" },
  1133. display: {
  1134. kind: "node_repl_images",
  1135. images: [{ base64: "aGVsbG8=", mimeType: "image/png" }],
  1136. },
  1137. });
  1138. const { service, client, confirmRequests, artifactSource } = createDependencies(rows);
  1139. vi.mocked(client.getCapabilities).mockResolvedValue({
  1140. ...capabilities,
  1141. max_artifact_count: 10,
  1142. max_artifact_bytes: 1000,
  1143. max_total_artifact_bytes: 10000,
  1144. allowed_artifacts: [{ type: "image", extensions: ["png"], mime_types: ["image/png"] }],
  1145. });
  1146. const preflight = await service.preflight(publishInput());
  1147. expect(preflight.blockingIssues).toEqual([]);
  1148. expect(preflight.skippableWarnings).toEqual([]);
  1149. const progress = collectPublishProgress(service, "publish-op-image");
  1150. await expect(service.publish(publishInput(), "publish-op-image")).resolves.toEqual(shareRecord);
  1151. const toolCall = confirmRequests.at(-1)?.projection.rows.find((row) => row.kind === "toolCall");
  1152. expect(toolCall).toMatchObject({ toolName: "NodeRepl", status: "success" });
  1153. expect(toolCall).not.toHaveProperty("display");
  1154. expect(JSON.stringify(confirmRequests.at(-1))).not.toContain("aGVsbG8=");
  1155. expect(firstWarnings(progress)).toBeUndefined();
  1156. expect(client.uploadArtifact).toHaveBeenCalledWith(
  1157. "preparation-1",
  1158. expect.objectContaining({ artifact_type: "image", size_bytes: 5 }),
  1159. expect.any(Blob),
  1160. );
  1161. const uploaded = vi.mocked(client.uploadArtifact).mock.calls[0]![2];
  1162. expect(await uploaded.text()).toBe("hello");
  1163. expect(
  1164. confirmRequests
  1165. .at(-1)
  1166. ?.projection.rows.some((row) => row.kind === "artifact" && row.artifactType === "image"),
  1167. ).toBe(true);
  1168. expect(artifactSource.read).not.toHaveBeenCalled();
  1169. client.getCapabilities.mockResolvedValue({
  1170. ...capabilities,
  1171. max_artifact_count: 10,
  1172. max_artifact_bytes: 4,
  1173. max_total_artifact_bytes: 100,
  1174. allowed_artifacts: [{ type: "image", extensions: ["png"], mime_types: ["image/png"] }],
  1175. });
  1176. const oversized = await service.preflight(publishInput());
  1177. expect(oversized.blockingIssues).toContainEqual(
  1178. expect.objectContaining({ code: "artifact_size_limit", actual: 5, limit: 4 }),
  1179. );
  1180. expect(oversized.turnResults[0]?.blockingIssues).toContainEqual(
  1181. expect.objectContaining({ code: "artifact_size_limit", productTurnId: "product-turn-1" }),
  1182. );
  1183. await expect(service.publish(publishInput(), "oversized-image")).rejects.toMatchObject({
  1184. kind: "limit_exceeded",
  1185. });
  1186. });
  1187. it("分支/回滚时间线标记降级为跳过:整行丢弃且不泄漏本地会话标识", async () => {
  1188. const rows = completedRows().slice(0, 2);
  1189. rows.push(
  1190. {
  1191. rowId: 5,
  1192. turnId: "turn-1",
  1193. productTurnId: "product-turn-1",
  1194. createdAt: 1_060,
  1195. createdAtSeq: 5,
  1196. kind: "timelineMarker",
  1197. marker: { type: "checkpointRestored", checkpointId: "local-checkpoint-1" },
  1198. },
  1199. {
  1200. rowId: 6,
  1201. turnId: "turn-1",
  1202. productTurnId: "product-turn-1",
  1203. createdAt: 1_070,
  1204. createdAtSeq: 6,
  1205. kind: "timelineMarker",
  1206. marker: { type: "forkNotice", parentSessionId: "local-parent-session", parentRowId: 9 },
  1207. },
  1208. );
  1209. const { service, confirmRequests } = createDependencies(rows);
  1210. const progress = collectPublishProgress(service, "publish-op-timeline");
  1211. await expect(service.publish(publishInput(), "publish-op-timeline")).resolves.toEqual(
  1212. shareRecord,
  1213. );
  1214. expect(confirmRequests.at(-1)?.projection.rows.map((row) => row.rowId)).toEqual([1, 2]);
  1215. const payload = JSON.stringify(confirmRequests.at(-1));
  1216. expect(payload).not.toContain("local-checkpoint-1");
  1217. expect(payload).not.toContain("local-parent-session");
  1218. expect(firstWarnings(progress)).toBeUndefined();
  1219. });
  1220. it("整类 timelineMarker 在发布时静默剥掉,不产生提示", async () => {
  1221. const rows = completedRows().slice(0, 2);
  1222. rows.push(
  1223. {
  1224. rowId: 5,
  1225. turnId: "turn-1",
  1226. productTurnId: "product-turn-1",
  1227. createdAt: 1_080,
  1228. createdAtSeq: 5,
  1229. kind: "timelineMarker",
  1230. marker: { type: "compact", origin: "auto", status: "success" },
  1231. },
  1232. {
  1233. rowId: 6,
  1234. turnId: "turn-1",
  1235. productTurnId: "product-turn-1",
  1236. createdAt: 1_090,
  1237. createdAtSeq: 6,
  1238. kind: "timelineMarker",
  1239. marker: {
  1240. type: "modelChange",
  1241. fromProvider: "p1",
  1242. fromModel: "m1",
  1243. toProvider: "p2",
  1244. toModel: "m2",
  1245. toThought: "high",
  1246. },
  1247. },
  1248. {
  1249. rowId: 7,
  1250. turnId: "turn-1",
  1251. productTurnId: "product-turn-1",
  1252. createdAt: 1_100,
  1253. createdAtSeq: 7,
  1254. kind: "timelineMarker",
  1255. marker: { type: "goalVerify", iteration: 1, outcome: "pass" },
  1256. },
  1257. );
  1258. const { service, confirmRequests } = createDependencies(rows);
  1259. const progress = collectPublishProgress(service, "publish-op-markers");
  1260. await expect(service.publish(publishInput(), "publish-op-markers")).resolves.toEqual(
  1261. shareRecord,
  1262. );
  1263. // compact 的 lane 是 assistantWork,留在 flow 尾部会顶掉折叠锚点,让整轮过程在分享页默认展开。
  1264. // goalVerify 等在分享页本就不渲染。三者都属纯运行时记账,静默剥掉、不打扰分享者。
  1265. expect(confirmRequests.at(-1)?.projection.rows.map((row) => row.rowId)).toEqual([1, 2]);
  1266. expect(firstWarnings(progress)).toBeUndefined();
  1267. });
  1268. it("EnterPlanMode 工具行在发布时剥掉,不占 payload 配额", async () => {
  1269. const rows = completedRows().slice(0, 2);
  1270. rows.push({
  1271. rowId: 5,
  1272. turnId: "turn-1",
  1273. productTurnId: "product-turn-1",
  1274. createdAt: 1_110,
  1275. createdAtSeq: 5,
  1276. kind: "toolCall",
  1277. toolCallId: "enter-plan-mode-call",
  1278. toolName: "EnterPlanMode",
  1279. status: "success",
  1280. inputText: "{}",
  1281. output: { text: "ok" },
  1282. });
  1283. const { service, confirmRequests } = createDependencies(rows);
  1284. await expect(service.publish(publishInput(), "publish-op-plan-mode")).resolves.toEqual(
  1285. shareRecord,
  1286. );
  1287. // 渲染层 isVisibleAssistantWorkRow 本来就过滤它,进 payload 只是白吃 max_rows 配额。
  1288. expect(confirmRequests.at(-1)?.projection.rows.map((row) => row.rowId)).toEqual([1, 2]);
  1289. });
  1290. it("运行中的结构仍然阻断发布,不被降级", async () => {
  1291. const rows = completedRows().slice(0, 2);
  1292. rows.push({
  1293. rowId: 5,
  1294. turnId: "turn-1",
  1295. productTurnId: "product-turn-1",
  1296. createdAt: 1_090,
  1297. createdAtSeq: 5,
  1298. kind: "timelineMarker",
  1299. marker: { type: "goalVerify", iteration: 1, outcome: "running" },
  1300. });
  1301. const { service } = createDependencies(rows);
  1302. // 内容尚未定稿,跳过等于分享半成品;这类必须让用户等完成或取消该轮。
  1303. await expect(service.publish(publishInput(), "publish-op-running")).rejects.toMatchObject({
  1304. issues: [expect.objectContaining({ code: "unsupported_timeline" })],
  1305. });
  1306. });
  1307. it("服务端允许 md 时,正文引用的 .md 能正常上传分享", async () => {
  1308. const mdBytes = new TextEncoder().encode("# 报告");
  1309. const rows = completedRowsWithFileChanges();
  1310. rows[1] = { ...rows[1]!, text: "已生成 reports/MCP使用统计报告.md" };
  1311. const { service, client, artifactSource, conversationFileChangesV4, preparationRequests } =
  1312. createDependencies(rows);
  1313. client.getCapabilities.mockResolvedValueOnce({
  1314. ...capabilities,
  1315. max_artifact_count: 2,
  1316. max_artifact_bytes: 1024,
  1317. max_total_artifact_bytes: 2048,
  1318. allowed_artifacts: [{ type: "md", extensions: ["md"], mime_types: ["text/markdown"] }],
  1319. });
  1320. conversationFileChangesV4.mockResolvedValueOnce({
  1321. files: 1,
  1322. additions: 0,
  1323. deletions: 0,
  1324. state: "active",
  1325. items: [
  1326. {
  1327. path: "reports/MCP使用统计报告.md",
  1328. additions: 0,
  1329. deletions: 0,
  1330. writeCount: 1,
  1331. toolNames: ["Write"],
  1332. patches: [],
  1333. },
  1334. ],
  1335. });
  1336. artifactSource.read.mockResolvedValue({
  1337. bytes: mdBytes,
  1338. canonicalPath: "/workspace/reports/MCP使用统计报告.md",
  1339. });
  1340. await expect(service.publish(publishInput(), "publish-op-md")).resolves.toEqual(shareRecord);
  1341. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 1 });
  1342. expect(client.uploadArtifact).toHaveBeenCalledWith(
  1343. "preparation-1",
  1344. expect.objectContaining({ artifact_type: "md", extension: "md" }),
  1345. expect.anything(),
  1346. );
  1347. });
  1348. it("发布链接跟随界面语言:英文界面改写到裸 /share,中文界面保持 /cn/share", async () => {
  1349. const { service } = createDependencies();
  1350. // 服务端固定下发 /cn/share/...(见 shareRecord),客户端按界面语言改写站点前缀。
  1351. await expect(
  1352. service.publish({ ...publishInput(), locale: "en-US" }, "publish-op-locale-en"),
  1353. ).resolves.toMatchObject({ share_url: "https://zcode.z.ai/share/share-1" });
  1354. await expect(
  1355. service.publish({ ...publishInput(), locale: "zh-CN" }, "publish-op-locale-zh"),
  1356. ).resolves.toEqual(shareRecord);
  1357. });
  1358. it("未传 locale 时原样返回服务端下发的链接", async () => {
  1359. const { service } = createDependencies();
  1360. await expect(service.publish(publishInput(), "publish-op-locale-none")).resolves.toEqual(
  1361. shareRecord,
  1362. );
  1363. });
  1364. it("reports the exact historical preview file when capabilities reject it", async () => {
  1365. const rows = completedRowsWithFileChanges();
  1366. const { service, client, artifactSource } = createDependencies(rows);
  1367. client.getCapabilities.mockResolvedValueOnce({
  1368. ...capabilities,
  1369. max_artifact_count: 2,
  1370. max_artifact_bytes: 1024,
  1371. max_total_artifact_bytes: 2048,
  1372. allowed_artifacts: [
  1373. {
  1374. type: "pptx",
  1375. extensions: ["pptx"],
  1376. mime_types: ["application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  1377. },
  1378. ],
  1379. });
  1380. const progress = collectPublishProgress(service, "publish-op-2");
  1381. await expect(service.publish(publishInput(), "publish-op-2")).resolves.toEqual(shareRecord);
  1382. expect(firstWarnings(progress)).toEqual([
  1383. expect.objectContaining({
  1384. code: "artifact_type_not_allowed",
  1385. artifactDisplayName: "调研报告.pdf",
  1386. artifactType: "pdf",
  1387. extension: "pdf",
  1388. mimeType: "application/pdf",
  1389. }),
  1390. ]);
  1391. expect(artifactSource.read).toHaveBeenCalledTimes(1);
  1392. expect(client.createPreparation).toHaveBeenCalledTimes(1);
  1393. });
  1394. it("SHARE08:fileChanges 中未被预览引用的中间文件不会读取或上传", async () => {
  1395. const rows = completedRowsWithFileChanges();
  1396. rows[1] = { ...rows[1]!, text: "已生成 index.html" };
  1397. const { service, client, artifactSource, conversationFileChangesV4, preparationRequests } =
  1398. createDependencies(rows);
  1399. client.getCapabilities.mockResolvedValueOnce({
  1400. ...capabilities,
  1401. max_artifact_count: 2,
  1402. max_artifact_bytes: 1024,
  1403. max_total_artifact_bytes: 2048,
  1404. allowed_artifacts: [{ type: "html", extensions: ["html"], mime_types: ["text/html"] }],
  1405. });
  1406. conversationFileChangesV4.mockResolvedValueOnce({
  1407. files: 2,
  1408. additions: 0,
  1409. deletions: 0,
  1410. state: "active",
  1411. items: [
  1412. {
  1413. path: "index.html",
  1414. additions: 0,
  1415. deletions: 0,
  1416. writeCount: 1,
  1417. toolNames: ["Bash"],
  1418. patches: [],
  1419. },
  1420. {
  1421. path: "tmp/debug.pdf",
  1422. additions: 0,
  1423. deletions: 0,
  1424. writeCount: 1,
  1425. toolNames: ["Bash"],
  1426. patches: [],
  1427. },
  1428. ],
  1429. });
  1430. artifactSource.read.mockResolvedValueOnce({
  1431. bytes: new TextEncoder().encode("<html />"),
  1432. canonicalPath: "/workspace/index.html",
  1433. });
  1434. await service.publish(publishInput(), "publish-op-3");
  1435. expect(artifactSource.read).toHaveBeenCalledTimes(1);
  1436. expect(artifactSource.read).toHaveBeenCalledWith({
  1437. workspacePath: "/workspace",
  1438. ref: "/workspace/index.html",
  1439. maxBytes: 1024,
  1440. });
  1441. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 1 });
  1442. });
  1443. it("SHARE10:正式 artifact 与预览卡片指向同一 realpath 时只上传可见卡片一次", async () => {
  1444. const bytes = new TextEncoder().encode("pdf!");
  1445. const rows = completedRowsWithFileChanges().slice(0, 2);
  1446. rows[1] = { ...rows[1]!, text: "已生成 report.pdf" };
  1447. rows.push({
  1448. rowId: 3,
  1449. turnId: "turn-1",
  1450. productTurnId: "product-turn-1",
  1451. createdAt: 1_020,
  1452. createdAtSeq: 3,
  1453. kind: "artifact",
  1454. artifactVersionId: "registered-report",
  1455. logicalArtifactKey: "registered-report",
  1456. displayName: "正式报告.pdf",
  1457. artifactType: "pdf",
  1458. mimeType: "application/pdf",
  1459. sizeBytes: bytes.byteLength,
  1460. sha256: createHash("sha256").update(bytes).digest("hex"),
  1461. ref: "/workspace/output/report.pdf",
  1462. state: "current",
  1463. });
  1464. const { service, client, artifactSource, conversationFileChangesV4, preparationRequests } =
  1465. createDependencies(rows);
  1466. client.getCapabilities.mockResolvedValueOnce({
  1467. ...capabilities,
  1468. max_artifact_count: 2,
  1469. max_artifact_bytes: 1024,
  1470. max_total_artifact_bytes: 2048,
  1471. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  1472. });
  1473. conversationFileChangesV4.mockResolvedValueOnce({
  1474. files: 1,
  1475. additions: 0,
  1476. deletions: 0,
  1477. state: "active",
  1478. items: [
  1479. {
  1480. path: "alias/report.pdf",
  1481. additions: 0,
  1482. deletions: 0,
  1483. writeCount: 1,
  1484. toolNames: ["Bash"],
  1485. patches: [],
  1486. },
  1487. ],
  1488. });
  1489. artifactSource.read.mockResolvedValue({
  1490. bytes,
  1491. canonicalPath: "/workspace/real/report.pdf",
  1492. });
  1493. await service.publish(publishInput(), "publish-op-4");
  1494. expect(conversationFileChangesV4).not.toHaveBeenCalled();
  1495. expect(artifactSource.read).toHaveBeenCalledTimes(1);
  1496. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 1 });
  1497. expect(client.uploadArtifact).toHaveBeenCalledTimes(1);
  1498. expect(client.uploadArtifact.mock.calls[0]?.[1]).toMatchObject({
  1499. display_name: "report.pdf",
  1500. });
  1501. });
  1502. it("SHARE11:rows 分页 revision 不一致时在查询 fileChanges 和 prepare 前拒绝", async () => {
  1503. const { service, client, conversationRowsRangeV4, conversationFileChangesV4 } =
  1504. createDependencies(completedRowsWithFileChanges());
  1505. conversationRowsRangeV4
  1506. .mockResolvedValueOnce({
  1507. rows: completedRowsWithFileChanges().slice(1),
  1508. atSeq: 4,
  1509. atRevision: 8,
  1510. atLogEpoch: "epoch-1",
  1511. hasMore: true,
  1512. })
  1513. .mockResolvedValueOnce({
  1514. rows: completedRowsWithFileChanges().slice(0, 1),
  1515. atSeq: 4,
  1516. atRevision: 7,
  1517. atLogEpoch: "epoch-1",
  1518. hasMore: false,
  1519. });
  1520. await expect(service.publish(publishInput(), "publish-op-5")).rejects.toMatchObject({
  1521. kind: "invalid_conversation",
  1522. });
  1523. expect(conversationFileChangesV4).not.toHaveBeenCalled();
  1524. expect(client.createPreparation).not.toHaveBeenCalled();
  1525. });
  1526. it("SHARE11:reverted fileChanges 不生成临时 artifact", async () => {
  1527. const rows = completedRowsWithFileChanges();
  1528. rows[1] = { ...rows[1]!, text: "已生成 index.html" };
  1529. const { service, client, artifactSource, conversationFileChangesV4, preparationRequests } =
  1530. createDependencies(rows);
  1531. conversationFileChangesV4.mockResolvedValueOnce({
  1532. files: 1,
  1533. additions: 0,
  1534. deletions: 0,
  1535. state: "reverted",
  1536. items: [
  1537. {
  1538. path: "index.html",
  1539. additions: 0,
  1540. deletions: 0,
  1541. writeCount: 1,
  1542. toolNames: ["Bash"],
  1543. patches: [],
  1544. },
  1545. ],
  1546. });
  1547. await service.publish(publishInput(), "publish-op-6");
  1548. expect(conversationFileChangesV4).toHaveBeenCalledTimes(1);
  1549. expect(artifactSource.read).not.toHaveBeenCalled();
  1550. expect(client.uploadArtifact).not.toHaveBeenCalled();
  1551. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 0 });
  1552. });
  1553. it("SHARE03:未选轮次的 fileChanges 不查询也不读取", async () => {
  1554. const rows = completedRows();
  1555. rows[2] = {
  1556. ...rows[2]!,
  1557. entityId: "turn-header-2",
  1558. fileChanges: { files: 1, additions: 0, deletions: 0, state: "active" },
  1559. };
  1560. const { service, artifactSource, conversationFileChangesV4 } = createDependencies(rows);
  1561. await service.publish(
  1562. {
  1563. ...publishInput(),
  1564. selection: { kind: "rowAnchors", rowIds: [2] },
  1565. },
  1566. "publish-op-7",
  1567. );
  1568. expect(conversationFileChangesV4).not.toHaveBeenCalled();
  1569. expect(artifactSource.read).not.toHaveBeenCalled();
  1570. });
  1571. it("SHARE11:fileChanges 查询发现 stale revision 时在 prepare 前拒绝", async () => {
  1572. const rows = completedRowsWithFileChanges();
  1573. rows[1] = { ...rows[1]!, text: "已生成 index.html" };
  1574. const { service, client, conversationFileChangesV4 } = createDependencies(rows);
  1575. conversationFileChangesV4.mockRejectedValueOnce(new Error("proto.staleRevision"));
  1576. await expect(service.publish(publishInput(), "publish-op-8")).rejects.toMatchObject({
  1577. kind: "invalid_conversation",
  1578. });
  1579. expect(client.createPreparation).not.toHaveBeenCalled();
  1580. });
  1581. it("SHARE02:已选结果物在 prepare 后上传,全部成功后再 confirm", async () => {
  1582. const bytes = new TextEncoder().encode("pdf!");
  1583. const sha256 = createHash("sha256").update(bytes).digest("hex");
  1584. const rows = completedRows().slice(0, 2);
  1585. rows[1] = { ...rows[1]!, text: "已生成 report.pdf" };
  1586. const { service, client, artifactSource, preparationRequests, confirmRequests } =
  1587. createDependencies(rows);
  1588. client.getCapabilities.mockResolvedValueOnce({
  1589. ...capabilities,
  1590. max_artifact_count: 2,
  1591. max_artifact_bytes: 1024,
  1592. max_total_artifact_bytes: 2048,
  1593. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  1594. });
  1595. artifactSource.read.mockResolvedValueOnce({
  1596. bytes,
  1597. canonicalPath: "/workspace/report.pdf",
  1598. });
  1599. const order: string[] = [];
  1600. client.createPreparation.mockImplementationOnce(async (request) => {
  1601. order.push("prepare");
  1602. preparationRequests.push(request);
  1603. return {
  1604. preparation_id: "preparation-1",
  1605. status: "preparing",
  1606. access_mode: request.access_mode,
  1607. expires_at: 20_000,
  1608. };
  1609. });
  1610. client.uploadArtifact.mockImplementationOnce(async (_id, descriptor, file) => {
  1611. order.push("upload");
  1612. expect(await file.text()).toBe("pdf!");
  1613. return {
  1614. artifact_id: descriptor.artifact_id,
  1615. size_bytes: descriptor.size_bytes,
  1616. sha256: descriptor.sha256,
  1617. status: "uploaded",
  1618. };
  1619. });
  1620. client.confirm.mockImplementationOnce(async (_id, request) => {
  1621. order.push("confirm");
  1622. confirmRequests.push(request);
  1623. return shareRecord;
  1624. });
  1625. await expect(service.publish(publishInput(), "publish-op-9")).resolves.toEqual(shareRecord);
  1626. expect(order).toEqual(["prepare", "upload", "confirm"]);
  1627. expect(artifactSource.read).toHaveBeenCalledWith({
  1628. workspacePath: "/workspace",
  1629. ref: "/workspace/report.pdf",
  1630. maxBytes: 1024,
  1631. });
  1632. expect(preparationRequests.at(-1)).toMatchObject({ artifact_count: 1 });
  1633. expect(client.uploadArtifact).toHaveBeenCalledWith(
  1634. "preparation-1",
  1635. expect.objectContaining({
  1636. artifact_id: "share-artifact-1",
  1637. artifact_type: "pdf",
  1638. size_bytes: bytes.byteLength,
  1639. sha256,
  1640. }),
  1641. expect.any(Blob),
  1642. );
  1643. expect(confirmRequests.at(-1)?.projection.rows.at(-1)).toMatchObject({
  1644. kind: "artifact",
  1645. ref: "zcode-artifact://share/share-artifact-1",
  1646. });
  1647. });
  1648. it("SHARE07:上传回执不一致时不调用 confirm", async () => {
  1649. const bytes = new Uint8Array([1]);
  1650. const sha256 = createHash("sha256").update(bytes).digest("hex");
  1651. const rows = completedRows().slice(0, 2);
  1652. rows[1] = { ...rows[1]!, text: "已生成 report.pdf" };
  1653. const { service, client, artifactSource } = createDependencies(rows);
  1654. client.getCapabilities.mockResolvedValueOnce({
  1655. ...capabilities,
  1656. max_artifact_count: 1,
  1657. max_artifact_bytes: 10,
  1658. max_total_artifact_bytes: 10,
  1659. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  1660. });
  1661. artifactSource.read.mockResolvedValueOnce({
  1662. bytes,
  1663. canonicalPath: "/workspace/report.pdf",
  1664. });
  1665. client.uploadArtifact.mockResolvedValueOnce({
  1666. artifact_id: "wrong-artifact",
  1667. size_bytes: 1,
  1668. sha256,
  1669. status: "uploaded",
  1670. });
  1671. await expect(service.publish(publishInput(), "publish-op-10")).rejects.toMatchObject({
  1672. kind: "upload_incomplete",
  1673. });
  1674. expect(client.confirm).not.toHaveBeenCalled();
  1675. });
  1676. it("SHARE04:后端未允许结果物类型时不创建 preparation", async () => {
  1677. const rows = completedRows().slice(0, 2);
  1678. rows[1] = { ...rows[1]!, text: "已生成 report.pdf" };
  1679. const { service, client, artifactSource } = createDependencies(rows);
  1680. client.getCapabilities.mockResolvedValueOnce({
  1681. ...capabilities,
  1682. max_artifact_count: 1,
  1683. max_artifact_bytes: 10,
  1684. max_total_artifact_bytes: 10,
  1685. allowed_artifacts: [],
  1686. });
  1687. const progress = collectPublishProgress(service, "publish-op-11");
  1688. await expect(service.publish(publishInput(), "publish-op-11")).resolves.toEqual(shareRecord);
  1689. expect(firstWarnings(progress)).toEqual([
  1690. expect.objectContaining({
  1691. code: "artifact_type_not_allowed",
  1692. artifactDisplayName: "report.pdf",
  1693. }),
  1694. ]);
  1695. expect(client.createPreparation).toHaveBeenCalledTimes(1);
  1696. expect(artifactSource.read).not.toHaveBeenCalled();
  1697. });
  1698. it("aggregates multiple preview-card whitelist issues without creating preparation", async () => {
  1699. const rows = completedRows().slice(0, 2);
  1700. rows[1] = { ...rows[1]!, text: "已生成 report.pdf 和 clip.mp4" };
  1701. const { service, client } = createDependencies(rows);
  1702. client.getCapabilities.mockResolvedValueOnce({
  1703. ...capabilities,
  1704. max_artifact_count: 4,
  1705. max_artifact_bytes: 10,
  1706. max_total_artifact_bytes: 20,
  1707. allowed_artifacts: [],
  1708. });
  1709. const progress = collectPublishProgress(service, "publish-op-12");
  1710. await expect(service.publish(publishInput(), "publish-op-12")).resolves.toEqual(shareRecord);
  1711. expect(firstWarnings(progress)).toEqual([
  1712. expect.objectContaining({ artifactDisplayName: "clip.mp4" }),
  1713. expect.objectContaining({ artifactDisplayName: "report.pdf" }),
  1714. ]);
  1715. expect(client.createPreparation).toHaveBeenCalledTimes(1);
  1716. });
  1717. it("SHARE07:选择后预览文件被删除时发布成功但回传最终 warning", async () => {
  1718. const rows = completedRows().slice(0, 2);
  1719. rows[1] = { ...rows[1]!, text: "已生成 report.pdf" };
  1720. const { service, client, artifactSource } = createDependencies(rows);
  1721. client.getCapabilities.mockResolvedValueOnce({
  1722. ...capabilities,
  1723. max_artifact_count: 1,
  1724. max_artifact_bytes: 10,
  1725. max_total_artifact_bytes: 10,
  1726. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  1727. });
  1728. artifactSource.stat.mockRejectedValueOnce(
  1729. new ConversationShareServiceError(
  1730. "invalid_conversation",
  1731. "Conversation artifact cannot be read",
  1732. { reasonCode: "artifact_read_failed", diagnostics: { errno: "ENOENT" } },
  1733. ),
  1734. );
  1735. const progress = collectPublishProgress(service, "publish-op-13");
  1736. await expect(service.publish(publishInput(), "publish-op-13")).resolves.toEqual(shareRecord);
  1737. expect(firstWarnings(progress)).toEqual([
  1738. expect.objectContaining({
  1739. code: "artifact_read_failed",
  1740. artifactDisplayName: "report.pdf",
  1741. availability: "not_found",
  1742. }),
  1743. ]);
  1744. expect(artifactSource.read).not.toHaveBeenCalled();
  1745. expect(client.uploadArtifact).not.toHaveBeenCalled();
  1746. expect(client.confirm).toHaveBeenCalledTimes(1);
  1747. });
  1748. it("loads all row pages and publishes selected product turns in conversation order", async () => {
  1749. const { service, conversationRowsRangeV4, preparationRequests, confirmRequests } =
  1750. createDependencies();
  1751. const result = await service.publish(
  1752. {
  1753. ...publishInput(),
  1754. selection: { kind: "rowAnchors", rowIds: [4, 2] },
  1755. },
  1756. "publish-op-14",
  1757. );
  1758. expect(result.share_code).toBe("share-1");
  1759. expect(conversationRowsRangeV4).toHaveBeenNthCalledWith(1, {
  1760. workspacePath: "/workspace",
  1761. workspaceIdentity: "ssh://host/workspace",
  1762. sessionId: "session-1",
  1763. limit: 200,
  1764. });
  1765. expect(conversationRowsRangeV4).toHaveBeenNthCalledWith(2, {
  1766. workspacePath: "/workspace",
  1767. workspaceIdentity: "ssh://host/workspace",
  1768. sessionId: "session-1",
  1769. beforeRowId: 3,
  1770. limit: 200,
  1771. });
  1772. expect(confirmRequests[0].selected_product_turn_ids).toEqual([
  1773. "share-product-turn-1",
  1774. "share-product-turn-2",
  1775. ]);
  1776. expect(confirmRequests[0].projection.rows.map((row) => row.rowId)).toEqual([1, 2, 3, 4]);
  1777. expect(Object.keys(confirmRequests[0])).toEqual([
  1778. "selected_product_turn_ids",
  1779. "projection",
  1780. "integrity",
  1781. "disclosure_confirmation",
  1782. ]);
  1783. expect(confirmRequests[0].integrity).not.toHaveProperty("payload_sha256");
  1784. expect(preparationRequests[0]).toMatchObject({
  1785. client_request_id: "publish-request-1",
  1786. title: "会话分享",
  1787. access_mode: "public_importable",
  1788. artifact_count: 0,
  1789. payload_sha256: sha256ConversationShareJson(confirmRequests[0]),
  1790. });
  1791. });
  1792. it("publishes a public projection without subagent details or local write identities", async () => {
  1793. const { service, confirmRequests } = createDependencies(completedRowsWithSubagent());
  1794. await service.publish(publishInput(), "publish-op-15");
  1795. expect(confirmRequests[0].projection.rows.map((row) => row.kind)).toEqual([
  1796. "turnHeader",
  1797. "assistantText",
  1798. "toolCall",
  1799. "turnHeader",
  1800. "assistantText",
  1801. ]);
  1802. expect(confirmRequests[0].projection.rows).toEqual(
  1803. expect.arrayContaining([
  1804. expect.objectContaining({
  1805. kind: "toolCall",
  1806. toolName: "Agent",
  1807. toolCallId: "share-tool-call-1",
  1808. status: "success",
  1809. }),
  1810. ]),
  1811. );
  1812. expect(JSON.stringify(confirmRequests[0].projection.rows)).not.toMatch(
  1813. /local-agent-tool-call|local-subagent|local-child-session|local-approval/u,
  1814. );
  1815. });
  1816. it("rejects active rows before creating a preparation", async () => {
  1817. const rows = completedRows();
  1818. rows[1] = {
  1819. ...rows[1],
  1820. kind: "assistantText",
  1821. text: "生成中",
  1822. state: "streaming",
  1823. };
  1824. const { service, client } = createDependencies(rows);
  1825. await expect(service.publish(publishInput(), "publish-op-16")).rejects.toMatchObject({
  1826. kind: "invalid_conversation",
  1827. });
  1828. expect(client.createPreparation).not.toHaveBeenCalled();
  1829. });
  1830. it.each([
  1831. ["data:text/plain;base64,YQ==", "unsafe_structure"],
  1832. ["file:///tmp/report.html", "unsafe_structure"],
  1833. ["zcode-artifact://share/report", "artifact_protocol_not_ready"],
  1834. ] as const)("rejects unsupported local reference %s", async (text, kind) => {
  1835. const rows = completedRows();
  1836. rows[1] = { ...rows[1], kind: "assistantText", text, state: "complete" };
  1837. const { service, client } = createDependencies(rows);
  1838. await expect(service.publish(publishInput(), "publish-op-17")).rejects.toMatchObject({ kind });
  1839. expect(client.createPreparation).not.toHaveBeenCalled();
  1840. });
  1841. it("rejects missing product turn identity, empty selections and disclosure omissions", async () => {
  1842. const rows = completedRows();
  1843. delete rows[1].productTurnId;
  1844. const { service, client } = createDependencies(rows);
  1845. await expect(service.publish(publishInput(), "publish-op-18")).rejects.toMatchObject({
  1846. kind: "invalid_conversation",
  1847. });
  1848. await expect(
  1849. service.publish(
  1850. {
  1851. ...publishInput(),
  1852. selection: { kind: "rowAnchors", rowIds: [] },
  1853. },
  1854. "publish-op-19",
  1855. ),
  1856. ).rejects.toMatchObject({ kind: "invalid_selection" });
  1857. await expect(
  1858. service.publish(
  1859. {
  1860. ...publishInput(),
  1861. disclosureAcceptedAt: 0,
  1862. },
  1863. "publish-op-20",
  1864. ),
  1865. ).rejects.toMatchObject({ kind: "disclosure_required" });
  1866. expect(client.createPreparation).not.toHaveBeenCalled();
  1867. });
  1868. it("选择阶段已知行数超限必须阻断", async () => {
  1869. const { service, client } = createDependencies();
  1870. client.getCapabilities.mockResolvedValueOnce({
  1871. ...capabilities,
  1872. max_rows: 1,
  1873. });
  1874. const result = await service.preflight(publishInput());
  1875. expect(result.blockingIssues).toContainEqual(
  1876. expect.objectContaining({ code: "rows_limit", actual: 4, limit: 1 }),
  1877. );
  1878. });
  1879. it("enforces capability row and payload limits", async () => {
  1880. const { service, client } = createDependencies();
  1881. client.getCapabilities.mockResolvedValueOnce({
  1882. ...capabilities,
  1883. max_rows: 1,
  1884. });
  1885. await expect(service.publish(publishInput(), "publish-op-21")).rejects.toMatchObject({
  1886. kind: "limit_exceeded",
  1887. issues: [
  1888. expect.objectContaining({
  1889. code: "rows_limit",
  1890. actual: 4,
  1891. limit: 1,
  1892. }),
  1893. ],
  1894. });
  1895. expect(client.createPreparation).not.toHaveBeenCalled();
  1896. });
  1897. it("short-circuits when preparation idempotency returns a confirmed share", async () => {
  1898. const { service, client } = createDependencies();
  1899. client.createPreparation.mockResolvedValueOnce({
  1900. preparation_id: "preparation-1",
  1901. status: "confirmed",
  1902. access_mode: "public_importable",
  1903. expires_at: 20_000,
  1904. share: {
  1905. share_code: "existing-share",
  1906. share_url: "https://zcode.z.ai/cn/share/existing-share",
  1907. access_mode: "public_importable",
  1908. expires_at: 20_000,
  1909. },
  1910. });
  1911. await expect(service.publish(publishInput(), "publish-op-22")).resolves.toMatchObject({
  1912. share_code: "existing-share",
  1913. });
  1914. expect(client.confirm).not.toHaveBeenCalled();
  1915. });
  1916. it("幂等 confirmed 结果也按界面语言改写分享链接", async () => {
  1917. const { service, client } = createDependencies();
  1918. client.createPreparation.mockResolvedValueOnce({
  1919. preparation_id: "preparation-1",
  1920. status: "confirmed",
  1921. access_mode: "public_importable",
  1922. expires_at: 20_000,
  1923. share: {
  1924. share_code: "existing-share-locale",
  1925. share_url: "https://zcode.z.ai/cn/share/existing-share-locale",
  1926. access_mode: "public_importable",
  1927. expires_at: 20_000,
  1928. },
  1929. });
  1930. await expect(
  1931. service.publish({ ...publishInput(), locale: "en-US" }, "publish-op-confirmed-locale"),
  1932. ).resolves.toMatchObject({
  1933. share_url: "https://zcode.z.ai/share/existing-share-locale",
  1934. });
  1935. });
  1936. it("SHARE29:含结果物的幂等 preparation 已 confirmed 时仍先复验但不重复上传", async () => {
  1937. const bytes = new Uint8Array([1]);
  1938. const rows = completedRows().slice(0, 2);
  1939. rows[1] = { ...rows[1]!, text: "已生成 report.pdf" };
  1940. const { service, client, artifactSource } = createDependencies(rows);
  1941. artifactSource.read.mockResolvedValueOnce({
  1942. bytes,
  1943. canonicalPath: "/workspace/report.pdf",
  1944. });
  1945. client.getCapabilities.mockResolvedValueOnce({
  1946. ...capabilities,
  1947. max_artifact_count: 1,
  1948. max_artifact_bytes: 10,
  1949. max_total_artifact_bytes: 10,
  1950. allowed_artifacts: [{ type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] }],
  1951. });
  1952. client.createPreparation.mockResolvedValueOnce({
  1953. preparation_id: "preparation-1",
  1954. status: "confirmed",
  1955. access_mode: "public_importable",
  1956. expires_at: 20_000,
  1957. share: {
  1958. share_code: "existing-share",
  1959. share_url: "https://zcode.z.ai/cn/share/existing-share",
  1960. access_mode: "public_importable",
  1961. expires_at: 20_000,
  1962. },
  1963. });
  1964. await expect(service.publish(publishInput(), "publish-op-23")).resolves.toMatchObject({
  1965. share_code: "existing-share",
  1966. });
  1967. expect(artifactSource.read).toHaveBeenCalledTimes(1);
  1968. expect(client.uploadArtifact).not.toHaveBeenCalled();
  1969. expect(client.confirm).not.toHaveBeenCalled();
  1970. });
  1971. it("retries the same confirm request after safety-check pending", async () => {
  1972. let now = 0;
  1973. const sleep = vi.fn(async (delayMs: number) => {
  1974. now += delayMs;
  1975. });
  1976. const { service, client } = createDependencies(completedRows(), {
  1977. now: () => now,
  1978. sleep,
  1979. });
  1980. const attempts: Array<{
  1981. preparationId: string;
  1982. request: ConversationShareConfirmRequest;
  1983. }> = [];
  1984. client.confirm.mockImplementation(async (preparationId, request) => {
  1985. attempts.push({ preparationId, request });
  1986. if (attempts.length <= 2) {
  1987. throw pendingSafetyCheck();
  1988. }
  1989. return shareRecord;
  1990. });
  1991. await expect(service.publish(publishInput(), "publish-op-24")).resolves.toEqual(shareRecord);
  1992. expect(sleep).toHaveBeenCalledTimes(2);
  1993. expect(sleep).toHaveBeenNthCalledWith(1, 5_000);
  1994. expect(sleep).toHaveBeenNthCalledWith(2, 5_000);
  1995. expect(attempts.map((attempt) => attempt.preparationId)).toEqual([
  1996. "preparation-1",
  1997. "preparation-1",
  1998. "preparation-1",
  1999. ]);
  2000. expect(attempts[1]?.request).toBe(attempts[0]?.request);
  2001. expect(attempts[2]?.request).toBe(attempts[0]?.request);
  2002. expect(client.createPreparation).toHaveBeenCalledTimes(1);
  2003. });
  2004. it("prefers Retry-After over the five-second fallback", async () => {
  2005. let now = 0;
  2006. const sleep = vi.fn(async (delayMs: number) => {
  2007. now += delayMs;
  2008. });
  2009. const { service, client } = createDependencies(completedRows(), {
  2010. now: () => now,
  2011. sleep,
  2012. });
  2013. client.confirm
  2014. .mockRejectedValueOnce(pendingSafetyCheck(12_000))
  2015. .mockResolvedValueOnce(shareRecord);
  2016. await expect(service.publish(publishInput(), "publish-op-25")).resolves.toEqual(shareRecord);
  2017. expect(sleep).toHaveBeenCalledTimes(1);
  2018. expect(sleep).toHaveBeenCalledWith(12_000);
  2019. });
  2020. it("stops at the two-minute safety-check deadline without another confirm", async () => {
  2021. let now = 0;
  2022. const sleep = vi.fn(async (delayMs: number) => {
  2023. now += delayMs;
  2024. });
  2025. const { service, client } = createDependencies(completedRows(), {
  2026. confirmPollIntervalMs: 5_000,
  2027. confirmPollTimeoutMs: 120_000,
  2028. now: () => now,
  2029. sleep,
  2030. });
  2031. client.confirm.mockRejectedValue(pendingSafetyCheck(undefined, "server-request-timeout"));
  2032. await expect(service.publish(publishInput(), "publish-op-26")).rejects.toMatchObject({
  2033. kind: "safety_check_timeout",
  2034. requestId: "server-request-timeout",
  2035. });
  2036. expect(client.confirm).toHaveBeenCalledTimes(24);
  2037. expect(now).toBe(120_000);
  2038. });
  2039. it("caps Retry-After at the remaining deadline without another confirm", async () => {
  2040. let now = 0;
  2041. const sleep = vi.fn(async (delayMs: number) => {
  2042. now += delayMs;
  2043. });
  2044. const { service, client } = createDependencies(completedRows(), {
  2045. confirmPollIntervalMs: 5_000,
  2046. confirmPollTimeoutMs: 120_000,
  2047. now: () => now,
  2048. sleep,
  2049. });
  2050. client.confirm
  2051. .mockRejectedValueOnce(pendingSafetyCheck(115_000))
  2052. .mockRejectedValueOnce(pendingSafetyCheck(60_000));
  2053. await expect(service.publish(publishInput(), "publish-op-27")).rejects.toMatchObject({
  2054. kind: "safety_check_timeout",
  2055. });
  2056. expect(sleep).toHaveBeenNthCalledWith(1, 115_000);
  2057. expect(sleep).toHaveBeenNthCalledWith(2, 5_000);
  2058. expect(sleep).toHaveBeenCalledTimes(2);
  2059. expect(now).toBe(120_000);
  2060. expect(client.confirm).toHaveBeenCalledTimes(2);
  2061. });
  2062. it("does not retry other confirm errors", async () => {
  2063. const sleep = vi.fn(async () => {});
  2064. const { service, client } = createDependencies(completedRows(), { sleep });
  2065. const error = new ConversationShareClientError({
  2066. kind: "upload_incomplete",
  2067. message: "share upload incomplete",
  2068. status: 409,
  2069. code: 3210,
  2070. });
  2071. client.confirm.mockRejectedValueOnce(error);
  2072. await expect(service.publish(publishInput(), "publish-op-28")).rejects.toBe(error);
  2073. expect(client.confirm).toHaveBeenCalledTimes(1);
  2074. expect(sleep).not.toHaveBeenCalled();
  2075. });
  2076. it("logs the publish phase and stable error fields without raw content", async () => {
  2077. const logger = {
  2078. debug: vi.fn(),
  2079. info: vi.fn(),
  2080. warn: vi.fn(),
  2081. error: vi.fn(),
  2082. };
  2083. const { service, client } = createDependencies(completedRows(), { logger });
  2084. client.getCapabilities.mockRejectedValueOnce(
  2085. new ConversationShareClientError({
  2086. kind: "artifact_not_allowed",
  2087. message: "contains /private/path and https://signed.example/token",
  2088. status: 422,
  2089. code: 3208,
  2090. requestId: "server-request-123",
  2091. }),
  2092. );
  2093. await expect(service.publish(publishInput(), "share-operation-1")).rejects.toMatchObject({
  2094. kind: "artifact_not_allowed",
  2095. });
  2096. expect(logger.warn).toHaveBeenCalledWith(undefined, "conversation share publish failed", {
  2097. operationId: "share-operation-1",
  2098. phase: "collecting",
  2099. kind: "artifact_not_allowed",
  2100. status: 422,
  2101. code: 3208,
  2102. requestId: "server-request-123",
  2103. errorName: "ConversationShareClientError",
  2104. });
  2105. expect(JSON.stringify(logger.warn.mock.calls)).not.toContain("/private/path");
  2106. expect(JSON.stringify(logger.warn.mock.calls)).not.toContain("signed.example");
  2107. });
  2108. it("connection-scoped facade uses the attachment Agent and shares publish progress", async () => {
  2109. const { service, client, conversationRowsRangeV4 } = createDependencies(completedRows());
  2110. expect("createConnectionScopedService" in service).toBe(false);
  2111. expect(() =>
  2112. ProxyChannel.fromService(service as unknown as Record<string, unknown>).call(
  2113. "host",
  2114. "createConnectionScopedService",
  2115. ),
  2116. ).toThrow("Method not found");
  2117. const scopedRowsRange = vi.fn(async () => ({
  2118. rows: completedRows(),
  2119. atSeq: 4,
  2120. atRevision: 7,
  2121. atLogEpoch: "epoch-1",
  2122. hasMore: false,
  2123. }));
  2124. const scopedFileChanges = vi.fn(async () => ({
  2125. files: 0,
  2126. additions: 0,
  2127. deletions: 0,
  2128. items: [],
  2129. }));
  2130. const scoped = service[conversationShareConnectionScopeFactory]({
  2131. conversationRowsRangeV4: scopedRowsRange,
  2132. conversationFileChangesV4: scopedFileChanges,
  2133. } as never);
  2134. const phases: string[] = [];
  2135. const subscription = service.onDynamicPublishProgress("share-operation-scoped")((progress) =>
  2136. phases.push(progress.phase),
  2137. );
  2138. try {
  2139. await expect(scoped.publish(publishInput(), "share-operation-scoped")).resolves.toEqual(
  2140. shareRecord,
  2141. );
  2142. } finally {
  2143. subscription.dispose();
  2144. }
  2145. expect(scopedRowsRange).toHaveBeenCalledTimes(1);
  2146. expect(scopedFileChanges).not.toHaveBeenCalled();
  2147. expect(conversationRowsRangeV4).not.toHaveBeenCalled();
  2148. expect(client.createPreparation).toHaveBeenCalledTimes(1);
  2149. expect(phases).toEqual(["collecting", "uploading", "checking", "complete"]);
  2150. });
  2151. it.each([
  2152. "fault.conversation.rowsRangeConnectionUntrusted",
  2153. "fault.connection.handshakeRequired",
  2154. "fault.connection.closed",
  2155. ])("normalizes %s from the scoped Agent", async (message) => {
  2156. const { service } = createDependencies(completedRows());
  2157. const scoped = service[conversationShareConnectionScopeFactory]({
  2158. conversationRowsRangeV4: vi.fn(async () => {
  2159. throw new Error(message);
  2160. }),
  2161. conversationFileChangesV4: vi.fn(),
  2162. } as never);
  2163. await expect(scoped.publish(publishInput(), `operation-${message}`)).rejects.toMatchObject({
  2164. kind: "connection_unavailable",
  2165. });
  2166. });
  2167. it("keeps concurrent attachment facades on their own Agent scope", async () => {
  2168. const { service, conversationRowsRangeV4 } = createDependencies(completedRows());
  2169. const rowsFor = (expectedIdentity: string) =>
  2170. vi.fn(async (params: { workspaceIdentity?: string }) => {
  2171. expect(params.workspaceIdentity).toBe(expectedIdentity);
  2172. return {
  2173. rows: completedRows(),
  2174. atSeq: 4,
  2175. atRevision: 7,
  2176. atLogEpoch: "epoch-1",
  2177. hasMore: false,
  2178. };
  2179. });
  2180. const rowsA = rowsFor("ssh://host-a/workspace");
  2181. const rowsB = rowsFor("ssh://host-b/workspace");
  2182. const noFileChanges = vi.fn();
  2183. const scopedA = service[conversationShareConnectionScopeFactory]({
  2184. conversationRowsRangeV4: rowsA,
  2185. conversationFileChangesV4: noFileChanges,
  2186. } as never);
  2187. const scopedB = service[conversationShareConnectionScopeFactory]({
  2188. conversationRowsRangeV4: rowsB,
  2189. conversationFileChangesV4: noFileChanges,
  2190. } as never);
  2191. await Promise.all([
  2192. scopedA.publish(
  2193. { ...publishInput(), workspaceIdentity: "ssh://host-a/workspace" },
  2194. "operation-a",
  2195. ),
  2196. scopedB.publish(
  2197. { ...publishInput(), workspaceIdentity: "ssh://host-b/workspace" },
  2198. "operation-b",
  2199. ),
  2200. ]);
  2201. expect(rowsA).toHaveBeenCalledTimes(1);
  2202. expect(rowsB).toHaveBeenCalledTimes(1);
  2203. expect(conversationRowsRangeV4).not.toHaveBeenCalled();
  2204. });
  2205. it("delegates preview and continuation without persisting signed URLs", async () => {
  2206. const { service, client } = createDependencies();
  2207. client.getPreview.mockResolvedValueOnce({ marker: "preview" });
  2208. client.getContinuation.mockResolvedValueOnce({ marker: "continuation" });
  2209. await expect(service.getPreview("share-code")).resolves.toEqual({
  2210. marker: "preview",
  2211. });
  2212. await expect(
  2213. service.getContinuation({
  2214. shareCode: "share-code",
  2215. clientRequestId: "import-1",
  2216. }),
  2217. ).resolves.toEqual({ marker: "continuation" });
  2218. expect(client.getContinuation).toHaveBeenCalledWith("share-code", {
  2219. schema_version: 1,
  2220. client_request_id: "import-1",
  2221. });
  2222. });
  2223. });
  2224. it("损坏的内嵌图片只警告,不丢工具文字或修改原 rows", () => {
  2225. const rows: ConversationRow[] = [
  2226. {
  2227. kind: "toolCall",
  2228. rowId: 1,
  2229. turnId: "t",
  2230. productTurnId: "p",
  2231. createdAt: 1,
  2232. createdAtSeq: 1,
  2233. toolCallId: "tool",
  2234. toolName: "NodeRepl",
  2235. status: "success",
  2236. output: { text: "结果" },
  2237. display: { kind: "node_repl_images", images: [{ base64: "%%%", mimeType: "image/png" }] },
  2238. },
  2239. ];
  2240. const result = materializeConversationShareInlineImages(
  2241. rows,
  2242. {
  2243. ...capabilities,
  2244. allowed_artifacts: [{ type: "image", extensions: ["png"], mime_types: ["image/png"] }],
  2245. },
  2246. new Map([["p", 1]]),
  2247. );
  2248. expect(result.rows).toEqual([expect.objectContaining({ output: { text: "结果" } })]);
  2249. expect(result.rows[0]).not.toHaveProperty("display");
  2250. expect(rows[0]).toHaveProperty("display");
  2251. expect(result.warnings).toEqual([
  2252. expect.objectContaining({
  2253. code: "artifact_read_failed",
  2254. productTurnId: "p",
  2255. rowId: 1,
  2256. turnOrdinal: 1,
  2257. }),
  2258. ]);
  2259. expect(result.bytesBySourceRef.size).toBe(0);
  2260. });