conversationShareImportService.test.ts 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { resolveRuntimeZCodeEndpointOrigin } from "@zcode/shared";
  6. import { ConversationShareHttpClient } from "../src/conversation-share/conversationShareHttpClient.js";
  7. import { sha256ConversationShareJson } from "../src/conversation-share/conversationShareIntegrity.js";
  8. import { ConversationShareMockApiClient } from "./helpers/conversationShareMockApiClient.js";
  9. import { ConversationShareService } from "../src/conversation-share/conversationShareService.js";
  10. const roots: string[] = [];
  11. afterEach(async () => {
  12. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  13. });
  14. describe("ConversationShareService import", () => {
  15. it("installs imported artifacts under the captured local workspace without deleting siblings on failure", async () => {
  16. const conversationRoot = await mkdtemp(join(tmpdir(), "zcode-share-import-default-"));
  17. const targetRoot = await mkdtemp(join(tmpdir(), "zcode-share-import-target-"));
  18. roots.push(conversationRoot, targetRoot);
  19. await writeFile(join(targetRoot, "keep.txt"), "keep", "utf8");
  20. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  21. const client = new ConversationShareHttpClient({
  22. apiClient,
  23. baseUrl: "https://api.example.com/api/v1",
  24. tokenProvider: async () => "owner",
  25. });
  26. const service = new ConversationShareService({
  27. client,
  28. conversationWorkspaceRoot: conversationRoot,
  29. zcodeSessionService: {
  30. createSession: vi.fn(async () => {
  31. throw new Error("injected commit failure");
  32. }) as never,
  33. listSessions: vi.fn(async () => []),
  34. },
  35. artifactSource: {
  36. read: async () => {
  37. throw new Error("unexpected artifact read");
  38. },
  39. },
  40. zcodeAgentService: {
  41. conversationRowsRangeV4: vi.fn(async () => ({
  42. rows: [
  43. {
  44. rowId: 1,
  45. turnId: "turn-1",
  46. entityId: "entity-1",
  47. productTurnId: "product-1",
  48. createdAt: 1,
  49. createdAtSeq: 1,
  50. kind: "turnHeader" as const,
  51. origin: "userInput" as const,
  52. state: "completedSuccess" as const,
  53. startedAt: 1,
  54. endedAt: 2,
  55. },
  56. ],
  57. atSeq: 1,
  58. atRevision: 1,
  59. atLogEpoch: "epoch",
  60. hasMore: false,
  61. })),
  62. conversationFileChangesV4: vi.fn(),
  63. },
  64. });
  65. const share = await service.publish(
  66. {
  67. workspacePath: targetRoot,
  68. sessionId: "session-1",
  69. title: "Shared Research",
  70. accessMode: "public_importable",
  71. selection: { kind: "all" },
  72. clientRequestId: "publish-target-1",
  73. disclosureAcceptedAt: 9_000,
  74. },
  75. "publish-op-1",
  76. );
  77. await expect(
  78. service.importShare(
  79. {
  80. shareCode: share.share_code,
  81. clientRequestId: "import-target-1",
  82. targetWorkspacePath: targetRoot,
  83. targetWorkspaceKind: "local",
  84. },
  85. "operation-target-1",
  86. ),
  87. ).rejects.toThrow("injected commit failure");
  88. await expect(readFile(join(targetRoot, "keep.txt"), "utf8")).resolves.toBe("keep");
  89. });
  90. it("发布后导入到新 workspace,并把 shared_context 交给原子 session create", async () => {
  91. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-"));
  92. roots.push(root);
  93. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  94. const client = new ConversationShareHttpClient({
  95. apiClient,
  96. baseUrl: "https://api.example.com/api/v1",
  97. tokenProvider: async () => "owner",
  98. });
  99. const createSession = vi.fn(async () => ({
  100. session: { sessionId: "imported-session" },
  101. }));
  102. const rows = [
  103. {
  104. rowId: 1,
  105. turnId: "turn-1",
  106. entityId: "entity-1",
  107. productTurnId: "product-1",
  108. createdAt: 1,
  109. createdAtSeq: 1,
  110. kind: "turnHeader" as const,
  111. origin: "userInput" as const,
  112. state: "completedSuccess" as const,
  113. startedAt: 1,
  114. endedAt: 2,
  115. },
  116. {
  117. rowId: 2,
  118. turnId: "turn-1",
  119. entityId: "entity-2",
  120. productTurnId: "product-1",
  121. createdAt: 2,
  122. createdAtSeq: 2,
  123. kind: "userInput" as const,
  124. origin: "realUser" as const,
  125. text: "Continue this work",
  126. },
  127. ];
  128. const service = new ConversationShareService({
  129. client,
  130. conversationWorkspaceRoot: root,
  131. zcodeSessionService: {
  132. createSession: createSession as never,
  133. listSessions: vi.fn(async () => []),
  134. },
  135. artifactSource: {
  136. read: async () => {
  137. throw new Error("unexpected artifact read");
  138. },
  139. },
  140. zcodeAgentService: {
  141. conversationRowsRangeV4: vi.fn(async () => ({
  142. rows,
  143. atSeq: 2,
  144. atRevision: 3,
  145. atLogEpoch: "epoch-1",
  146. hasMore: false,
  147. })),
  148. conversationFileChangesV4: vi.fn(),
  149. },
  150. });
  151. const share = await service.publish(
  152. {
  153. workspacePath: root,
  154. sessionId: "session-1",
  155. title: "Shared Research",
  156. accessMode: "public_importable",
  157. selection: { kind: "all" },
  158. clientRequestId: "publish-1",
  159. disclosureAcceptedAt: 9_000,
  160. },
  161. "publish-op-2",
  162. );
  163. const imported = await service.importShare(
  164. { shareCode: share.share_code, clientRequestId: "import-1" },
  165. "operation-1",
  166. );
  167. expect(imported.sessionId).toBe("imported-session");
  168. const shareRootEntries = await readdir(join(imported.workspacePath, ".zcode-share"));
  169. expect(shareRootEntries).toHaveLength(1);
  170. expect(
  171. (
  172. await stat(
  173. join(imported.workspacePath, ".zcode-share", shareRootEntries[0]!, "shared-artifacts"),
  174. )
  175. ).isDirectory(),
  176. ).toBe(true);
  177. await expect(
  178. readFile(
  179. join(
  180. imported.workspacePath,
  181. ".zcode-share",
  182. shareRootEntries[0]!,
  183. ".zcode-share-import.json",
  184. ),
  185. ),
  186. ).rejects.toThrow();
  187. expect(createSession).toHaveBeenCalledWith(
  188. expect.objectContaining({
  189. workspacePath: imported.workspacePath,
  190. importedHistory: expect.objectContaining({
  191. source: "sharedContext",
  192. markdown: expect.stringContaining("Continue this work"),
  193. }),
  194. }),
  195. );
  196. });
  197. it("英文界面:标题带 From Share 前缀,但持久化的回链仍是规范 /cn/share/", async () => {
  198. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-locale-"));
  199. roots.push(root);
  200. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  201. const client = new ConversationShareHttpClient({
  202. apiClient,
  203. baseUrl: "https://api.example.com/api/v1",
  204. tokenProvider: async () => "owner",
  205. });
  206. const createSession = vi.fn(async () => ({ session: { sessionId: "imported-session" } }));
  207. const service = new ConversationShareService({
  208. client,
  209. conversationWorkspaceRoot: root,
  210. zcodeSessionService: {
  211. createSession: createSession as never,
  212. listSessions: vi.fn(async () => []),
  213. },
  214. artifactSource: {
  215. read: async () => {
  216. throw new Error("unexpected artifact read");
  217. },
  218. },
  219. zcodeAgentService: {
  220. conversationRowsRangeV4: vi.fn(async () => ({
  221. rows: [
  222. {
  223. rowId: 1,
  224. turnId: "turn-1",
  225. entityId: "entity-1",
  226. productTurnId: "product-1",
  227. createdAt: 1,
  228. createdAtSeq: 1,
  229. kind: "turnHeader" as const,
  230. origin: "userInput" as const,
  231. state: "completedSuccess" as const,
  232. startedAt: 1,
  233. endedAt: 2,
  234. },
  235. ],
  236. atSeq: 1,
  237. atRevision: 1,
  238. atLogEpoch: "epoch",
  239. hasMore: false,
  240. })),
  241. conversationFileChangesV4: vi.fn(),
  242. },
  243. });
  244. const share = await service.publish(
  245. {
  246. workspacePath: root,
  247. sessionId: "session-1",
  248. title: "Shared Research",
  249. accessMode: "public_importable",
  250. selection: { kind: "all" },
  251. clientRequestId: "publish-locale",
  252. disclosureAcceptedAt: 9_000,
  253. },
  254. "publish-op-locale",
  255. );
  256. const imported = await service.importShare(
  257. { shareCode: share.share_code, clientRequestId: "import-locale", locale: "en-US" },
  258. "operation-locale",
  259. );
  260. expect(createSession).toHaveBeenCalledWith(
  261. expect.objectContaining({
  262. importedHistory: expect.objectContaining({ title: "From Share: Shared Research" }),
  263. }),
  264. );
  265. // sharedContextImportV2StateSchema 硬编码 /^\/cn\/share\/[^/]+$/,持久化的回链
  266. // 绝不能跟随界面语言变成 /share/<code>,否则英文界面导入直接挂在 schema 上。
  267. expect(new URL(imported.shareUrl).pathname).toMatch(/^\/cn\/share\/[^/]+$/u);
  268. const provenanceUrl = (
  269. createSession.mock.calls[0]![0] as {
  270. importedHistory: { provenance: { shareUrl: string } };
  271. }
  272. ).importedHistory.provenance.shareUrl;
  273. expect(new URL(provenanceUrl).pathname).toMatch(/^\/cn\/share\/[^/]+$/u);
  274. });
  275. it("落盘公开 rows,并能按 contextId 取回用于只读块", async () => {
  276. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-rows-"));
  277. roots.push(root);
  278. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  279. const client = new ConversationShareHttpClient({
  280. apiClient,
  281. baseUrl: "https://api.example.com/api/v1",
  282. tokenProvider: async () => "owner",
  283. });
  284. const service = new ConversationShareService({
  285. client,
  286. conversationWorkspaceRoot: root,
  287. zcodeSessionService: {
  288. createSession: vi.fn(async () => ({ session: { sessionId: "imported-session" } })) as never,
  289. listSessions: vi.fn(async () => []),
  290. },
  291. artifactSource: {
  292. read: async () => {
  293. throw new Error("unexpected artifact read");
  294. },
  295. },
  296. zcodeAgentService: {
  297. conversationRowsRangeV4: vi.fn(async () => ({
  298. rows: [
  299. {
  300. rowId: 1,
  301. turnId: "turn-1",
  302. entityId: "entity-1",
  303. productTurnId: "product-1",
  304. createdAt: 1,
  305. createdAtSeq: 1,
  306. kind: "turnHeader" as const,
  307. origin: "userInput" as const,
  308. state: "completedSuccess" as const,
  309. startedAt: 1,
  310. endedAt: 2,
  311. },
  312. {
  313. rowId: 2,
  314. turnId: "turn-1",
  315. entityId: "entity-2",
  316. productTurnId: "product-1",
  317. createdAt: 2,
  318. createdAtSeq: 2,
  319. kind: "userInput" as const,
  320. origin: "realUser" as const,
  321. text: "Continue this work",
  322. },
  323. ],
  324. atSeq: 2,
  325. atRevision: 1,
  326. atLogEpoch: "epoch",
  327. hasMore: false,
  328. })),
  329. conversationFileChangesV4: vi.fn(),
  330. },
  331. });
  332. const share = await service.publish(
  333. {
  334. workspacePath: root,
  335. sessionId: "session-1",
  336. title: "Shared Research",
  337. accessMode: "public_importable",
  338. selection: { kind: "all" },
  339. clientRequestId: "publish-rows",
  340. disclosureAcceptedAt: 9_000,
  341. },
  342. "publish-op-rows",
  343. );
  344. const imported = await service.importShare(
  345. { shareCode: share.share_code, clientRequestId: "import-rows" },
  346. "operation-rows",
  347. );
  348. const loaded = await service.getImportedConversation({
  349. workspacePath: imported.workspacePath,
  350. contextId: imported.contextId,
  351. });
  352. expect(loaded?.rows.map((row) => row.kind)).toEqual(["turnHeader", "userInput"]);
  353. expect(loaded?.title).toBe("Shared Research");
  354. // 目录名是 share_id,不等于 contextId:拿错 contextId 必须落空而不是返回别人的副本。
  355. await expect(
  356. service.getImportedConversation({
  357. workspacePath: imported.workspacePath,
  358. contextId: "shared-context-does-not-exist",
  359. }),
  360. ).resolves.toBeNull();
  361. await expect(
  362. service.getImportedConversation({ workspacePath: root, contextId: imported.contextId }),
  363. ).resolves.toBeTruthy();
  364. });
  365. it("reuses the completed import for the same client request", async () => {
  366. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-dedupe-"));
  367. roots.push(root);
  368. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  369. const client = new ConversationShareHttpClient({
  370. apiClient,
  371. baseUrl: "https://api.example.com/api/v1",
  372. tokenProvider: async () => "owner",
  373. });
  374. const createSession = vi.fn(async () => ({ session: { sessionId: "imported-session" } }));
  375. const service = new ConversationShareService({
  376. client,
  377. conversationWorkspaceRoot: root,
  378. zcodeSessionService: {
  379. createSession: createSession as never,
  380. listSessions: vi.fn(async () => []),
  381. },
  382. artifactSource: {
  383. read: async () => {
  384. throw new Error("unexpected artifact read");
  385. },
  386. },
  387. zcodeAgentService: {
  388. conversationRowsRangeV4: vi.fn(async () => ({
  389. rows: [
  390. {
  391. rowId: 1,
  392. turnId: "turn-1",
  393. entityId: "entity-1",
  394. productTurnId: "product-1",
  395. createdAt: 1,
  396. createdAtSeq: 1,
  397. kind: "turnHeader" as const,
  398. origin: "userInput" as const,
  399. state: "completedSuccess" as const,
  400. startedAt: 1,
  401. endedAt: 2,
  402. },
  403. ],
  404. atSeq: 1,
  405. atRevision: 1,
  406. atLogEpoch: "epoch",
  407. hasMore: false,
  408. })),
  409. conversationFileChangesV4: vi.fn(),
  410. },
  411. });
  412. const publish = await service.publish(
  413. {
  414. workspacePath: root,
  415. sessionId: "session-1",
  416. title: "Shared Research",
  417. accessMode: "public_importable",
  418. selection: { kind: "all" },
  419. clientRequestId: "publish-1",
  420. disclosureAcceptedAt: 9_000,
  421. },
  422. "publish-op-3",
  423. );
  424. const first = await service.importShare(
  425. { shareCode: publish.share_code, clientRequestId: "same-request" },
  426. "operation-1",
  427. );
  428. const second = await service.importShare(
  429. { shareCode: publish.share_code, clientRequestId: "new-request" },
  430. "operation-2",
  431. );
  432. expect(second).toMatchObject({
  433. ...first,
  434. reused: true,
  435. });
  436. expect(createSession).toHaveBeenCalledOnce();
  437. });
  438. it("对象存储把 .md 标成别的 content-type 时仍能导入;SHA-256 不符仍然拒绝", async () => {
  439. const mdBytes = new TextEncoder().encode("# feature map\n");
  440. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-mime-"));
  441. roots.push(root);
  442. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  443. const client = new ConversationShareHttpClient({
  444. apiClient,
  445. baseUrl: "https://api.example.com/api/v1",
  446. tokenProvider: async () => "owner",
  447. });
  448. const rows = [
  449. {
  450. rowId: 1,
  451. turnId: "turn-1",
  452. entityId: "entity-1",
  453. productTurnId: "product-1",
  454. createdAt: 1,
  455. createdAtSeq: 1,
  456. kind: "turnHeader" as const,
  457. origin: "userInput" as const,
  458. state: "completedSuccess" as const,
  459. startedAt: 1,
  460. endedAt: 2,
  461. fileChanges: { files: 1, additions: 1, deletions: 0, state: "active" as const },
  462. },
  463. {
  464. rowId: 2,
  465. turnId: "turn-1",
  466. entityId: "entity-2",
  467. productTurnId: "product-1",
  468. createdAt: 2,
  469. createdAtSeq: 2,
  470. kind: "assistantText" as const,
  471. text: "已生成 feature_map.md",
  472. state: "complete" as const,
  473. },
  474. ];
  475. const createService = (download: (url: string) => Promise<Response>) =>
  476. new ConversationShareService({
  477. client,
  478. conversationWorkspaceRoot: root,
  479. download,
  480. zcodeSessionService: {
  481. createSession: vi.fn(async () => ({
  482. session: { sessionId: "imported-session" },
  483. })) as never,
  484. listSessions: vi.fn(async () => []),
  485. },
  486. artifactSource: {
  487. read: async () => ({ bytes: mdBytes, canonicalPath: `${root}/feature_map.md` }),
  488. },
  489. zcodeAgentService: {
  490. conversationRowsRangeV4: vi.fn(async () => ({
  491. rows,
  492. atSeq: 2,
  493. atRevision: 1,
  494. atLogEpoch: "epoch",
  495. hasMore: false,
  496. })),
  497. conversationFileChangesV4: vi.fn(async () => ({
  498. files: 1,
  499. additions: 1,
  500. deletions: 0,
  501. state: "active" as const,
  502. items: [
  503. {
  504. path: "feature_map.md",
  505. additions: 1,
  506. deletions: 0,
  507. writeCount: 1,
  508. toolNames: ["Write"],
  509. patches: [],
  510. },
  511. ],
  512. })),
  513. },
  514. });
  515. // 对象存储/CDN 常把 .md 标成 text/plain,与发布时的 text/markdown 无关。
  516. const mislabeled = createService(
  517. async () => new Response(mdBytes, { status: 200, headers: { "content-type": "text/plain" } }),
  518. );
  519. const share = await mislabeled.publish(
  520. {
  521. workspacePath: root,
  522. sessionId: "session-1",
  523. title: "Feature map",
  524. accessMode: "public_importable",
  525. selection: { kind: "all" },
  526. clientRequestId: "publish-mime",
  527. disclosureAcceptedAt: 9_000,
  528. },
  529. "publish-op-mime",
  530. );
  531. const imported = await mislabeled.importShare(
  532. { shareCode: share.share_code, clientRequestId: "import-mime" },
  533. "operation-mime",
  534. );
  535. const artifactDir = join(
  536. imported.workspacePath,
  537. ".zcode-share",
  538. (await readdir(join(imported.workspacePath, ".zcode-share")))[0]!,
  539. "shared-artifacts",
  540. );
  541. expect(await readdir(artifactDir)).toHaveLength(1);
  542. // 完整性门禁仍在 SHA-256 上:字节被改过就必须拒绝。
  543. // 必须换一个 share —— 同 share + 同 workspace 会命中完成索引直接复用,根本不会下载。
  544. const tampered = createService(
  545. async () =>
  546. new Response(new TextEncoder().encode("tampered"), {
  547. status: 200,
  548. headers: { "content-type": "text/markdown" },
  549. }),
  550. );
  551. const secondShare = await tampered.publish(
  552. {
  553. workspacePath: root,
  554. sessionId: "session-2",
  555. title: "Feature map again",
  556. accessMode: "public_importable",
  557. selection: { kind: "all" },
  558. clientRequestId: "publish-mime-2",
  559. disclosureAcceptedAt: 9_000,
  560. },
  561. "publish-op-mime-2",
  562. );
  563. expect(secondShare.share_code).not.toBe(share.share_code);
  564. await expect(
  565. tampered.importShare(
  566. { shareCode: secondShare.share_code, clientRequestId: "import-mime-tampered" },
  567. "operation-mime-tampered",
  568. ),
  569. ).rejects.toMatchObject({ kind: "invalid_contract" });
  570. });
  571. it("Content-Length 超过 manifest 声明时在读 body 前中断,不把超大响应读进内存", async () => {
  572. const mdBytes = new TextEncoder().encode("# feature map\n");
  573. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-oversize-"));
  574. roots.push(root);
  575. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  576. const client = new ConversationShareHttpClient({
  577. apiClient,
  578. baseUrl: "https://api.example.com/api/v1",
  579. tokenProvider: async () => "owner",
  580. });
  581. // Bug 根因:完整性校验(size + SHA-256)此前在 response.arrayBuffer() 之后才执行,
  582. // 被篡改/损坏的存储可以让客户端先把超大 payload 全量读进内存再发现不符。
  583. // 预检必须在读 body 前:Content-Length 声明超过 size_bytes 即中断下载。
  584. const arrayBuffer = vi.fn(async () => {
  585. throw new Error("body must not be read when Content-Length exceeds the manifest size");
  586. });
  587. // markdown 预览候选必须有 active fileChanges 作为存在性证据,否则不会生成 artifact、
  588. // download 根本不会被调用。
  589. const fileChanges = async () => ({
  590. files: 1,
  591. additions: 1,
  592. deletions: 0,
  593. state: "active" as const,
  594. items: [
  595. {
  596. path: "feature_map.md",
  597. additions: 1,
  598. deletions: 0,
  599. writeCount: 1,
  600. toolNames: ["Write"],
  601. patches: [],
  602. },
  603. ],
  604. });
  605. const oversized = {
  606. ok: true,
  607. headers: new Headers({ "content-length": "999999" }),
  608. arrayBuffer,
  609. } as unknown as Response;
  610. const download = vi.fn(async () => oversized);
  611. const service = new ConversationShareService({
  612. client,
  613. conversationWorkspaceRoot: root,
  614. download,
  615. zcodeSessionService: {
  616. createSession: vi.fn(async () => ({ session: { sessionId: "s" } })) as never,
  617. listSessions: vi.fn(async () => []),
  618. },
  619. artifactSource: {
  620. read: async () => ({ bytes: mdBytes, canonicalPath: `${root}/feature_map.md` }),
  621. },
  622. zcodeAgentService: {
  623. conversationRowsRangeV4: vi.fn(async () => ({
  624. rows: [
  625. {
  626. rowId: 1,
  627. turnId: "turn-1",
  628. entityId: "entity-1",
  629. productTurnId: "product-1",
  630. createdAt: 1,
  631. createdAtSeq: 1,
  632. kind: "turnHeader" as const,
  633. origin: "userInput" as const,
  634. state: "completedSuccess" as const,
  635. startedAt: 1,
  636. endedAt: 2,
  637. },
  638. {
  639. rowId: 2,
  640. turnId: "turn-1",
  641. entityId: "entity-2",
  642. productTurnId: "product-1",
  643. createdAt: 2,
  644. createdAtSeq: 2,
  645. kind: "assistantText" as const,
  646. text: "已生成 feature_map.md",
  647. state: "complete" as const,
  648. },
  649. ],
  650. atSeq: 2,
  651. atRevision: 1,
  652. atLogEpoch: "epoch",
  653. hasMore: false,
  654. })),
  655. conversationFileChangesV4: vi.fn(fileChanges),
  656. },
  657. });
  658. const share = await service.publish(
  659. {
  660. workspacePath: root,
  661. sessionId: "session-1",
  662. title: "Feature map",
  663. accessMode: "public_importable",
  664. selection: { kind: "all" },
  665. clientRequestId: "publish-oversize",
  666. disclosureAcceptedAt: 9_000,
  667. },
  668. "publish-op-oversize",
  669. );
  670. await expect(
  671. service.importShare(
  672. { shareCode: share.share_code, clientRequestId: "import-oversize" },
  673. "operation-oversize",
  674. ),
  675. ).rejects.toMatchObject({
  676. kind: "invalid_contract",
  677. issues: [expect.objectContaining({ code: "artifact_changed", actual: 999_999, limit: 14 })],
  678. });
  679. expect(download).toHaveBeenCalled();
  680. expect(arrayBuffer).not.toHaveBeenCalled();
  681. });
  682. it("下载挂住时按超时以 network 失败,不会无限停在 downloading 阶段", async () => {
  683. const mdBytes = new TextEncoder().encode("# feature map\n");
  684. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-timeout-"));
  685. roots.push(root);
  686. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  687. const client = new ConversationShareHttpClient({
  688. apiClient,
  689. baseUrl: "https://api.example.com/api/v1",
  690. tokenProvider: async () => "owner",
  691. });
  692. // Bug 根因:download 兜底是裸 fetch,无 AbortSignal/超时;对象存储连接挂住时导入
  693. // 会停在 downloading 阶段直到 undici 默认 ~300s 兜底,体验上等于卡死。
  694. const fileChanges = async () => ({
  695. files: 1,
  696. additions: 1,
  697. deletions: 0,
  698. state: "active" as const,
  699. items: [
  700. {
  701. path: "feature_map.md",
  702. additions: 1,
  703. deletions: 0,
  704. writeCount: 1,
  705. toolNames: ["Write"],
  706. patches: [],
  707. },
  708. ],
  709. });
  710. const download = (_url: string, init?: { signal?: AbortSignal }) =>
  711. new Promise<Response>((_, reject) => {
  712. init?.signal?.addEventListener("abort", () => {
  713. reject(new DOMException("This operation was aborted", "AbortError"));
  714. });
  715. });
  716. const service = new ConversationShareService({
  717. client,
  718. conversationWorkspaceRoot: root,
  719. download,
  720. downloadTimeoutMs: 20,
  721. zcodeSessionService: {
  722. createSession: vi.fn(async () => ({ session: { sessionId: "s" } })) as never,
  723. listSessions: vi.fn(async () => []),
  724. },
  725. artifactSource: {
  726. read: async () => ({ bytes: mdBytes, canonicalPath: `${root}/feature_map.md` }),
  727. },
  728. zcodeAgentService: {
  729. conversationRowsRangeV4: vi.fn(async () => ({
  730. rows: [
  731. {
  732. rowId: 1,
  733. turnId: "turn-1",
  734. entityId: "entity-1",
  735. productTurnId: "product-1",
  736. createdAt: 1,
  737. createdAtSeq: 1,
  738. kind: "turnHeader" as const,
  739. origin: "userInput" as const,
  740. state: "completedSuccess" as const,
  741. startedAt: 1,
  742. endedAt: 2,
  743. },
  744. {
  745. rowId: 2,
  746. turnId: "turn-1",
  747. entityId: "entity-2",
  748. productTurnId: "product-1",
  749. createdAt: 2,
  750. createdAtSeq: 2,
  751. kind: "assistantText" as const,
  752. text: "已生成 feature_map.md",
  753. state: "complete" as const,
  754. },
  755. ],
  756. atSeq: 2,
  757. atRevision: 1,
  758. atLogEpoch: "epoch",
  759. hasMore: false,
  760. })),
  761. conversationFileChangesV4: vi.fn(fileChanges),
  762. },
  763. });
  764. const share = await service.publish(
  765. {
  766. workspacePath: root,
  767. sessionId: "session-1",
  768. title: "Feature map",
  769. accessMode: "public_importable",
  770. selection: { kind: "all" },
  771. clientRequestId: "publish-download-timeout",
  772. disclosureAcceptedAt: 9_000,
  773. },
  774. "publish-op-download-timeout",
  775. );
  776. await expect(
  777. service.importShare(
  778. { shareCode: share.share_code, clientRequestId: "import-download-timeout" },
  779. "operation-download-timeout",
  780. ),
  781. ).rejects.toMatchObject({
  782. kind: "network",
  783. message: "Conversation artifact download timed out",
  784. issues: [expect.objectContaining({ code: "unknown", phase: "downloading" })],
  785. });
  786. });
  787. it("回链跟随环境,不再写死生产站", async () => {
  788. // Bug 根因:兜底写死 https://zcode.z.ai/cn/share,测试环境(API base 走
  789. // zcode.z.ai)导入后点分割线会打开另一个环境的分享页。
  790. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-endpoint-"));
  791. roots.push(root);
  792. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  793. const client = new ConversationShareHttpClient({
  794. apiClient,
  795. baseUrl: "https://api.example.com/api/v1",
  796. tokenProvider: async () => "owner",
  797. });
  798. const build = (shareWebUrl?: string) =>
  799. new ConversationShareService({
  800. client,
  801. conversationWorkspaceRoot: root,
  802. ...(shareWebUrl ? { shareWebUrl } : {}),
  803. zcodeSessionService: {
  804. createSession: vi.fn(async () => ({
  805. session: { sessionId: "imported-session" },
  806. })) as never,
  807. listSessions: vi.fn(async () => []),
  808. },
  809. artifactSource: {
  810. read: async () => {
  811. throw new Error("unexpected artifact read");
  812. },
  813. },
  814. zcodeAgentService: {
  815. conversationRowsRangeV4: vi.fn(async () => ({
  816. rows: [
  817. {
  818. rowId: 1,
  819. turnId: "turn-1",
  820. entityId: "entity-1",
  821. productTurnId: "product-1",
  822. createdAt: 1,
  823. createdAtSeq: 1,
  824. kind: "turnHeader" as const,
  825. origin: "userInput" as const,
  826. state: "completedSuccess" as const,
  827. startedAt: 1,
  828. endedAt: 2,
  829. },
  830. ],
  831. atSeq: 1,
  832. atRevision: 1,
  833. atLogEpoch: "epoch",
  834. hasMore: false,
  835. })),
  836. conversationFileChangesV4: vi.fn(),
  837. },
  838. });
  839. const explicit = build("https://zcode.example.test/cn/share");
  840. const share = await explicit.publish(
  841. {
  842. workspacePath: root,
  843. sessionId: "session-1",
  844. title: "Endpoint",
  845. accessMode: "public_importable",
  846. selection: { kind: "all" },
  847. clientRequestId: "publish-endpoint",
  848. disclosureAcceptedAt: 9_000,
  849. },
  850. "publish-op-endpoint",
  851. );
  852. const imported = await explicit.importShare(
  853. { shareCode: share.share_code, clientRequestId: "import-endpoint" },
  854. "operation-endpoint",
  855. );
  856. // 显式 option 仍是最高优先级。
  857. expect(imported.shareUrl).toBe(
  858. `https://zcode.example.test/cn/share/${encodeURIComponent(share.share_code)}`,
  859. );
  860. // 未显式指定时按环境推导:origin 必须与 API base 用的同一个解析器一致,
  861. // 路径仍是规范 /cn/share/<code>(sharedContextImport schema 要求)。
  862. // 必须真的切一个非生产 endpoint,否则推导值与旧的写死值恰好相同,测不出回归。
  863. vi.stubEnv("ZCODE_BASE_URL", "https://zcode.z.ai");
  864. const derived = build();
  865. const secondShare = await derived.publish(
  866. {
  867. workspacePath: root,
  868. sessionId: "session-2",
  869. title: "Endpoint derived",
  870. accessMode: "public_importable",
  871. selection: { kind: "all" },
  872. clientRequestId: "publish-endpoint-2",
  873. disclosureAcceptedAt: 9_000,
  874. },
  875. "publish-op-endpoint-2",
  876. );
  877. const derivedImport = await derived.importShare(
  878. { shareCode: secondShare.share_code, clientRequestId: "import-endpoint-2" },
  879. "operation-endpoint-2",
  880. );
  881. const derivedUrl = new URL(derivedImport.shareUrl);
  882. expect(derivedUrl.origin).toBe("https://zcode.z.ai");
  883. expect(derivedUrl.origin).toBe(resolveRuntimeZCodeEndpointOrigin(process.env));
  884. expect(derivedUrl.pathname).toBe(`/cn/share/${encodeURIComponent(secondShare.share_code)}`);
  885. vi.unstubAllEnvs();
  886. });
  887. // Bug 回归(CR-02):createSession 成功后 rm(markerPath) / reportImportProgress 仍在
  888. // 同一个 try 内,catch 会 rm -rf importRoot,把已经安装进 workspace 且被新 session
  889. // 的 provenance 引用的 artifacts 删掉,用户拿到一个引用缺失文件的会话。
  890. // 失败半径必须止于 createSession 之前。
  891. it("createSession 成功后的失败不再删除已提交的 importRoot", async () => {
  892. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-commit-radius-"));
  893. roots.push(root);
  894. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  895. const client = new ConversationShareHttpClient({
  896. apiClient,
  897. baseUrl: "https://api.example.com/api/v1",
  898. tokenProvider: async () => "owner",
  899. });
  900. const service = new ConversationShareService({
  901. client,
  902. conversationWorkspaceRoot: root,
  903. zcodeSessionService: {
  904. createSession: vi.fn(async () => ({ session: { sessionId: "imported-session" } })) as never,
  905. listSessions: vi.fn(async () => []),
  906. },
  907. artifactSource: {
  908. read: async () => {
  909. throw new Error("unexpected artifact read");
  910. },
  911. },
  912. zcodeAgentService: {
  913. conversationRowsRangeV4: vi.fn(async () => ({
  914. rows: [
  915. {
  916. rowId: 1,
  917. turnId: "turn-1",
  918. entityId: "entity-1",
  919. productTurnId: "product-1",
  920. createdAt: 1,
  921. createdAtSeq: 1,
  922. kind: "turnHeader" as const,
  923. origin: "userInput" as const,
  924. state: "completedSuccess" as const,
  925. startedAt: 1,
  926. endedAt: 2,
  927. },
  928. ],
  929. atSeq: 1,
  930. atRevision: 1,
  931. atLogEpoch: "epoch",
  932. hasMore: false,
  933. })),
  934. conversationFileChangesV4: vi.fn(),
  935. },
  936. });
  937. const share = await service.publish(
  938. {
  939. workspacePath: root,
  940. sessionId: "session-1",
  941. title: "Shared Research",
  942. accessMode: "public_importable",
  943. selection: { kind: "all" },
  944. clientRequestId: "publish-commit-radius",
  945. disclosureAcceptedAt: 9_000,
  946. },
  947. "publish-op-commit-radius",
  948. );
  949. // Emitter.fire 不吞 listener 异常,这里精确复现「createSession 之后失败」。
  950. const subscription = service.onDynamicImportProgress("operation-commit-radius")((progress) => {
  951. if (progress.phase === "complete") {
  952. throw new Error("injected post-commit failure");
  953. }
  954. });
  955. try {
  956. await expect(
  957. service.importShare(
  958. { shareCode: share.share_code, clientRequestId: "import-commit-radius" },
  959. "operation-commit-radius",
  960. ),
  961. ).rejects.toThrow("injected post-commit failure");
  962. } finally {
  963. subscription.dispose();
  964. }
  965. const shareRootEntries = await readdir(join(root, ".zcode-share"));
  966. expect(shareRootEntries).toHaveLength(1);
  967. const importRoot = join(root, ".zcode-share", shareRootEntries[0]!);
  968. expect((await stat(join(importRoot, "shared-artifacts"))).isDirectory()).toBe(true);
  969. await expect(readFile(join(importRoot, "shared-conversation.json"), "utf8")).resolves.toContain(
  970. "formatVersion",
  971. );
  972. });
  973. // Bug 回归(CR-03):importIndexWriteChain 原来不 catch,首个写入失败后链条永久
  974. // rejected,之后每一次 persistCompletedImportIndex 都变成静默 no-op,导入索引永久
  975. // 丢失且没有自愈路径(marker 成功即删),再导入同一 share 会永久报 already in progress。
  976. it("索引写入失败一次后不会永久毒化写入链", async () => {
  977. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-index-chain-"));
  978. roots.push(root);
  979. const apiClient = new ConversationShareMockApiClient({ now: () => 10_000 });
  980. const client = new ConversationShareHttpClient({
  981. apiClient,
  982. baseUrl: "https://api.example.com/api/v1",
  983. tokenProvider: async () => "owner",
  984. });
  985. const rows = [
  986. {
  987. rowId: 1,
  988. turnId: "turn-1",
  989. entityId: "entity-1",
  990. productTurnId: "product-1",
  991. createdAt: 1,
  992. createdAtSeq: 1,
  993. kind: "turnHeader" as const,
  994. origin: "userInput" as const,
  995. state: "completedSuccess" as const,
  996. startedAt: 1,
  997. endedAt: 2,
  998. },
  999. ];
  1000. const service = new ConversationShareService({
  1001. client,
  1002. conversationWorkspaceRoot: root,
  1003. zcodeSessionService: {
  1004. createSession: vi.fn(async () => ({ session: { sessionId: "imported-session" } })) as never,
  1005. listSessions: vi.fn(async () => []),
  1006. },
  1007. artifactSource: {
  1008. read: async () => {
  1009. throw new Error("unexpected artifact read");
  1010. },
  1011. },
  1012. zcodeAgentService: {
  1013. conversationRowsRangeV4: vi.fn(async () => ({
  1014. rows,
  1015. atSeq: 1,
  1016. atRevision: 1,
  1017. atLogEpoch: "epoch",
  1018. hasMore: false,
  1019. })),
  1020. conversationFileChangesV4: vi.fn(),
  1021. },
  1022. });
  1023. const publishShare = async (suffix: string) =>
  1024. service.publish(
  1025. {
  1026. workspacePath: root,
  1027. sessionId: `session-${suffix}`,
  1028. title: `Shared ${suffix}`,
  1029. accessMode: "public_importable",
  1030. selection: { kind: "all" },
  1031. clientRequestId: `publish-index-${suffix}`,
  1032. disclosureAcceptedAt: 9_000,
  1033. },
  1034. `publish-op-index-${suffix}`,
  1035. );
  1036. // 用真实文件系统冲突让 rename 失败:索引路径先被一个非空目录占住。
  1037. const indexPath = join(root, ".zcode-share-imports.json");
  1038. await mkdir(indexPath, { recursive: true });
  1039. await writeFile(join(indexPath, "blocker"), "blocked", "utf8");
  1040. const firstShare = await publishShare("a");
  1041. await service.importShare(
  1042. { shareCode: firstShare.share_code, clientRequestId: "import-index-a" },
  1043. "operation-index-a",
  1044. );
  1045. await expect(readFile(indexPath, "utf8")).rejects.toThrow();
  1046. await rm(indexPath, { recursive: true, force: true });
  1047. const secondShare = await publishShare("b");
  1048. await service.importShare(
  1049. { shareCode: secondShare.share_code, clientRequestId: "import-index-b" },
  1050. "operation-index-b",
  1051. );
  1052. // 链条恢复后索引必须真的落盘,且两次导入都在里面。
  1053. const persisted = JSON.parse(await readFile(indexPath, "utf8")) as Record<string, unknown>;
  1054. const keys = Object.keys(persisted);
  1055. expect(keys.some((key) => key.startsWith(firstShare.share_code))).toBe(true);
  1056. expect(keys.some((key) => key.startsWith(secondShare.share_code))).toBe(true);
  1057. });
  1058. /**
  1059. * 跨版本导入:分享由比本端更新的 Desktop 发布。
  1060. *
  1061. * 这是本次加固前会硬失败的场景——row 上多一个 optional 字段就足以让本端重算出不同的
  1062. * projection_sha256,报「分享文件校验失败,已停止导入」并给一个永远不会成功的重试按钮。
  1063. */
  1064. it("导入更新版本发布的分享:未知字段不破坏完整性,未知 row kind 只被跳过", async () => {
  1065. const root = await mkdtemp(join(tmpdir(), "zcode-share-import-future-"));
  1066. roots.push(root);
  1067. // 一行带未来才有的 optional 字段,一行是本端完全不认识的 kind。
  1068. const rawRows = [
  1069. {
  1070. rowId: 1,
  1071. turnId: "turn-1",
  1072. productTurnId: "product-1",
  1073. createdAt: 1,
  1074. createdAtSeq: 1,
  1075. kind: "turnHeader",
  1076. origin: "userInput",
  1077. state: "completedSuccess",
  1078. startedAt: 1,
  1079. endedAt: 2,
  1080. },
  1081. {
  1082. rowId: 2,
  1083. turnId: "turn-1",
  1084. productTurnId: "product-1",
  1085. createdAt: 2,
  1086. createdAtSeq: 2,
  1087. kind: "userInput",
  1088. origin: "realUser",
  1089. text: "Continue this work",
  1090. futureFieldAddedLater: "ignored by this build",
  1091. },
  1092. {
  1093. rowId: 3,
  1094. turnId: "turn-1",
  1095. productTurnId: "product-1",
  1096. createdAt: 3,
  1097. createdAtSeq: 3,
  1098. kind: "videoClipAddedLater",
  1099. someFutureShape: { durationMs: 1_000 },
  1100. },
  1101. ];
  1102. const continuation = {
  1103. schema_version: 1,
  1104. import_grant_id: "grant-future",
  1105. import_grant_expires_at: 99_000,
  1106. share: {
  1107. share_id: "share-future",
  1108. title: "Future Share",
  1109. access_mode: "public_importable",
  1110. created_at: 1,
  1111. expires_at: 99_000,
  1112. },
  1113. rows: rawRows,
  1114. artifacts: [],
  1115. // 服务端按原始字节算摘要,本端必须能对得上。
  1116. integrity: {
  1117. projection_sha256: sha256ConversationShareJson(rawRows),
  1118. artifact_set_sha256: sha256ConversationShareJson([]),
  1119. },
  1120. // 服务端将来新增的顶层字段
  1121. viewCountAddedLater: 7,
  1122. };
  1123. const client = new ConversationShareHttpClient({
  1124. apiClient: {
  1125. request: async (url: string | URL) => {
  1126. if (!String(url).endsWith("/continuation")) {
  1127. throw new Error(`unexpected request: ${String(url)}`);
  1128. }
  1129. return new Response(JSON.stringify({ code: 0, msg: "", data: continuation }), {
  1130. status: 200,
  1131. headers: { "content-type": "application/json" },
  1132. });
  1133. },
  1134. } as never,
  1135. baseUrl: "https://api.example.com/api/v1",
  1136. tokenProvider: async () => "owner",
  1137. });
  1138. const createSession = vi.fn(async () => ({ session: { sessionId: "imported-future" } }));
  1139. const service = new ConversationShareService({
  1140. client,
  1141. conversationWorkspaceRoot: root,
  1142. zcodeSessionService: { createSession: createSession as never, listSessions: async () => [] },
  1143. artifactSource: {
  1144. read: async () => {
  1145. throw new Error("unexpected artifact read");
  1146. },
  1147. },
  1148. zcodeAgentService: {
  1149. conversationRowsRangeV4: vi.fn(),
  1150. conversationFileChangesV4: vi.fn(),
  1151. },
  1152. });
  1153. const imported = await service.importShare(
  1154. { shareCode: "share-future", clientRequestId: "import-future" },
  1155. "operation-future",
  1156. );
  1157. // 导入必须成功——这正是以前会挂的地方。
  1158. expect(imported.sessionId).toBe("imported-future");
  1159. const loaded = await service.getImportedConversation({
  1160. workspacePath: imported.workspacePath,
  1161. contextId: imported.contextId,
  1162. });
  1163. // 认得的两行照常呈现,认不出的那行被跳过并计数(UI 据此出软提示)。
  1164. expect(loaded?.rows.map((row) => row.kind)).toEqual(["turnHeader", "userInput"]);
  1165. expect(loaded?.unsupportedRowCount).toBe(1);
  1166. // 落盘副本保存原始 rows:用户升级之后能看到当时认不出的内容,不被永久抹掉。
  1167. const shareDirs = await readdir(join(imported.workspacePath, ".zcode-share"));
  1168. const persistedCopy = JSON.parse(
  1169. await readFile(
  1170. join(imported.workspacePath, ".zcode-share", shareDirs[0]!, "shared-conversation.json"),
  1171. "utf8",
  1172. ),
  1173. ) as { rows: unknown[] };
  1174. expect(persistedCopy.rows).toEqual(rawRows);
  1175. });
  1176. });