conversationShareService.test.ts 86 KB

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