workflowRunArtifactHooks.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. // @vitest-environment jsdom
  2. // 用户面产物的三条取数(docs/dynamic-workflow/authoring.md「How the user sees them」):
  3. //
  4. // 元数据 useWorkflowRunArtifacts 活投影摘要 ⊕ journal 全量(spec / versions 只有后者有)
  5. // 条目 useWorkflowRunArtifactData itemCount 抬升即增量续拉(看板是 journal 的投影)
  6. // 字节 useWorkflowRunArtifactBytes 分块拼 Uint8Array → Blob → objectUrl(卸载 revoke)
  7. //
  8. // ⚠ 术语:这里的 artifact 是脚本经 `artifact.*` 发布给用户看的产出,不是引擎内部那个
  9. // 「脚本顶层返回值」的同名词(spec 的「术语」表)。
  10. import { act, renderHook, waitFor } from "@testing-library/react";
  11. import { beforeEach, describe, expect, it, vi } from "vitest";
  12. import type {
  13. V4ConversationWorkflowRunArtifactDataParams,
  14. V4ConversationWorkflowRunArtifactDataResult,
  15. V4ConversationWorkflowRunArtifactReadParams,
  16. V4ConversationWorkflowRunArtifactReadResult,
  17. V4ConversationWorkflowRunArtifactsParams,
  18. V4ConversationWorkflowRunArtifactsResult,
  19. WorkflowRunArtifact,
  20. WorkflowRunArtifactSummary,
  21. } from "@zcode/shared/zcode-protocol-v4";
  22. vi.mock("@/logger.js", () => ({
  23. logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn() },
  24. }));
  25. const workflowRunArtifacts =
  26. vi.fn<
  27. (
  28. params: V4ConversationWorkflowRunArtifactsParams,
  29. ) => Promise<V4ConversationWorkflowRunArtifactsResult>
  30. >();
  31. const workflowRunArtifactData =
  32. vi.fn<
  33. (
  34. params: V4ConversationWorkflowRunArtifactDataParams,
  35. ) => Promise<V4ConversationWorkflowRunArtifactDataResult>
  36. >();
  37. const workflowRunArtifactRead =
  38. vi.fn<
  39. (
  40. params: V4ConversationWorkflowRunArtifactReadParams,
  41. ) => Promise<V4ConversationWorkflowRunArtifactReadResult>
  42. >();
  43. vi.mock("@/v4/V4ConversationContext.js", () => ({
  44. useV4Conversation: () => ({
  45. workflowRunArtifacts,
  46. workflowRunArtifactData,
  47. workflowRunArtifactRead,
  48. }),
  49. }));
  50. // eslint-disable-next-line import/first -- 必须在 context mock 之后再引入被测 hook。
  51. import { useWorkflowRunArtifacts } from "@/hooks/useWorkflowRunArtifacts.js";
  52. // eslint-disable-next-line import/first
  53. import { useWorkflowRunArtifactData } from "@/hooks/useWorkflowRunArtifactData.js";
  54. // eslint-disable-next-line import/first
  55. import {
  56. encodeBytesToBase64,
  57. useWorkflowRunArtifactBytes,
  58. } from "@/hooks/useWorkflowRunArtifactBytes.js";
  59. const SESSION = "parent-a";
  60. const RUN = "dwfrun-1";
  61. function journalRecord(overrides: Partial<WorkflowRunArtifact> = {}): WorkflowRunArtifact {
  62. return {
  63. id: "perf",
  64. kind: "chart",
  65. version: 1,
  66. versions: [
  67. { version: 1, publishedAt: 10, spec: { x: { field: "round" }, y: { field: "ms" } } },
  68. ],
  69. spec: { x: { field: "round" }, y: { field: "ms" } },
  70. itemCount: 0,
  71. ...overrides,
  72. };
  73. }
  74. function summary(overrides: Partial<WorkflowRunArtifactSummary> = {}): WorkflowRunArtifactSummary {
  75. return { id: "perf", kind: "chart", version: 1, itemCount: 0, ...overrides };
  76. }
  77. function itemsPage(
  78. from: number,
  79. count: number,
  80. hasMore: boolean,
  81. ): V4ConversationWorkflowRunArtifactDataResult {
  82. return {
  83. items: Array.from({ length: count }, (_unused, index) => ({
  84. sequence: from + index,
  85. siteId: "report#1",
  86. ordinal: from + index,
  87. item: { round: from + index, ms: 100 + index },
  88. })),
  89. hasMore,
  90. };
  91. }
  92. beforeEach(() => {
  93. workflowRunArtifacts.mockReset();
  94. workflowRunArtifactData.mockReset();
  95. workflowRunArtifactRead.mockReset();
  96. workflowRunArtifacts.mockResolvedValue({ artifacts: [] });
  97. workflowRunArtifactData.mockResolvedValue({ items: [], hasMore: false });
  98. });
  99. describe("useWorkflowRunArtifacts", () => {
  100. it("run 在活投影里:顺序与新鲜度归摘要,spec / versions 由 journal 补齐", async () => {
  101. workflowRunArtifacts.mockResolvedValue({
  102. artifacts: [journalRecord({ id: "book", kind: "file", spec: undefined }), journalRecord()],
  103. });
  104. const hook = renderHook(() =>
  105. useWorkflowRunArtifacts({
  106. sessionId: SESSION,
  107. runId: RUN,
  108. live: [summary({ itemCount: 3 }), summary({ id: "book", kind: "file" })],
  109. }),
  110. );
  111. // 等的是 **journal 那一半**:活投影已经能给出两条,所以 `toHaveLength(2)` 在第一帧就成立,
  112. // 用它当门会在负载高时抢在查询返回之前断言 spec(一条只在满载时红的用例)。
  113. await waitFor(() => expect(hook.result.current.artifacts[0]?.spec).toBeDefined());
  114. expect(hook.result.current.artifacts).toHaveLength(2);
  115. // 顺序跟着活投影(perf 在前),不是 journal 返回的顺序。
  116. expect(hook.result.current.artifacts.map((artifact) => artifact.id)).toEqual(["perf", "book"]);
  117. expect(hook.result.current.source).toBe("live");
  118. // itemCount 取活投影(刷新信号,落后一拍就少画一个点);spec 只有 journal 有。
  119. expect(hook.result.current.artifacts[0]?.itemCount).toBe(3);
  120. expect(hook.result.current.artifacts[0]?.spec).toEqual({
  121. x: { field: "round" },
  122. y: { field: "ms" },
  123. });
  124. expect(hook.result.current.artifacts[0]?.versions).toHaveLength(1);
  125. });
  126. it("run 不在活投影里(冷恢复 / 被 8-run 上限淘汰):整份清单走 journal", async () => {
  127. workflowRunArtifacts.mockResolvedValue({
  128. artifacts: [
  129. journalRecord({
  130. id: "audit",
  131. kind: "file",
  132. spec: undefined,
  133. version: 2,
  134. versions: [
  135. { version: 1, publishedAt: 1, bytes: 10 },
  136. { version: 2, publishedAt: 2, bytes: 4096, contentType: "application/pdf" },
  137. ],
  138. contentType: "application/pdf",
  139. }),
  140. ],
  141. });
  142. const hook = renderHook(() => useWorkflowRunArtifacts({ sessionId: SESSION, runId: RUN }));
  143. await waitFor(() => expect(hook.result.current.artifacts).toHaveLength(1));
  144. expect(hook.result.current.source).toBe("journal");
  145. // journal 的元素不带 bytes(字节挂在版本上)——从最新版上取。
  146. expect(hook.result.current.artifacts[0]?.bytes).toBe(4096);
  147. expect(hook.result.current.artifacts[0]?.version).toBe(2);
  148. });
  149. it("投影上界 32 拒新之后,journal 里多出来的产物仍然追加在末尾", async () => {
  150. workflowRunArtifacts.mockResolvedValue({
  151. artifacts: [
  152. journalRecord(),
  153. journalRecord({ id: "extra", kind: "markdown", spec: undefined }),
  154. ],
  155. });
  156. const hook = renderHook(() =>
  157. useWorkflowRunArtifacts({ sessionId: SESSION, runId: RUN, live: [summary()] }),
  158. );
  159. await waitFor(() => expect(hook.result.current.artifacts).toHaveLength(2));
  160. expect(hook.result.current.artifacts.map((artifact) => artifact.id)).toEqual(["perf", "extra"]);
  161. });
  162. // 交付物(docs/dynamic-workflow/authoring.md「Ids, tags and versions」):活投影按发布顺序 upsert,这里是它唯一的排序点。
  163. it("交付物带头(活投影把它排在第三也一样),旗子两个来源任一带上即算;其余保持发布顺序", async () => {
  164. workflowRunArtifacts.mockResolvedValue({
  165. artifacts: [
  166. journalRecord(),
  167. journalRecord({ id: "notes", kind: "markdown", spec: undefined }),
  168. journalRecord({
  169. id: "report",
  170. kind: "markdown",
  171. spec: undefined,
  172. description: "结论与修复建议",
  173. primary: true,
  174. }),
  175. ],
  176. });
  177. const hook = renderHook(() =>
  178. useWorkflowRunArtifacts({
  179. sessionId: SESSION,
  180. runId: RUN,
  181. // 活投影的摘要**没带**旗子(老 CLI):journal 补上之后仍然领头。
  182. live: [summary(), summary({ id: "notes", kind: "markdown" }), summary({ id: "report", kind: "markdown" })],
  183. }),
  184. );
  185. await waitFor(() => expect(hook.result.current.artifacts[0]?.id).toBe("report"));
  186. expect(hook.result.current.artifacts.map((artifact) => artifact.id)).toEqual([
  187. "report",
  188. "perf",
  189. "notes",
  190. ]);
  191. expect(hook.result.current.artifacts[0]?.primary).toBe(true);
  192. expect(hook.result.current.artifacts[0]?.description).toBe("结论与修复建议");
  193. expect("primary" in hook.result.current.artifacts[1]!).toBe(false);
  194. // 只有活投影带旗子(journal 还没回来):第一帧就领头。
  195. const liveOnly = renderHook(() =>
  196. useWorkflowRunArtifacts({
  197. sessionId: SESSION,
  198. runId: "dwfrun-2",
  199. live: [summary(), summary({ id: "report", kind: "markdown", primary: true })],
  200. }),
  201. );
  202. expect(liveOnly.result.current.artifacts.map((artifact) => artifact.id)).toEqual([
  203. "report",
  204. "perf",
  205. ]);
  206. });
  207. it("能力缺席不是错误:内容产物仍从活投影列得出来,只是 unavailable 抬起", async () => {
  208. workflowRunArtifacts.mockRejectedValue(new Error("fault.command.capabilityUnsupported"));
  209. const hook = renderHook(() =>
  210. useWorkflowRunArtifacts({
  211. sessionId: SESSION,
  212. runId: RUN,
  213. live: [summary({ id: "book", kind: "file", bytes: 12 })],
  214. }),
  215. );
  216. await waitFor(() => expect(hook.result.current.unavailable).toBe(true));
  217. expect(hook.result.current.error).toBeNull();
  218. expect(hook.result.current.artifacts).toHaveLength(1);
  219. expect(hook.result.current.artifacts[0]?.spec).toBeUndefined();
  220. });
  221. // 完成卡的 `+N` 据它写数字还是省略号(docs/dynamic-workflow/transcript-and-notifications.md「The card」)。
  222. it("complete:活投影在场即完整(上界 32 = 引擎上限);冷路径要等 journal 答过;能力缺席永不完整", async () => {
  223. const live = renderHook(() =>
  224. useWorkflowRunArtifacts({ sessionId: SESSION, runId: RUN, live: [summary()] }),
  225. );
  226. expect(live.result.current.complete).toBe(true);
  227. let resolve!: (value: { artifacts: WorkflowRunArtifact[] }) => void;
  228. workflowRunArtifacts.mockImplementation(
  229. () => new Promise<{ artifacts: WorkflowRunArtifact[] }>((r) => (resolve = r)),
  230. );
  231. const cold = renderHook(() => useWorkflowRunArtifacts({ sessionId: SESSION, runId: "dwfrun-c" }));
  232. expect(cold.result.current.complete).toBe(false);
  233. resolve({ artifacts: [journalRecord()] });
  234. await waitFor(() => expect(cold.result.current.complete).toBe(true));
  235. workflowRunArtifacts.mockRejectedValue(new Error("fault.command.capabilityUnsupported"));
  236. const old = renderHook(() => useWorkflowRunArtifacts({ sessionId: SESSION, runId: "dwfrun-o" }));
  237. await waitFor(() => expect(old.result.current.unavailable).toBe(true));
  238. expect(old.result.current.complete).toBe(false);
  239. });
  240. it("itemCount 变化**不**重查 journal,版本抬升才重查", async () => {
  241. workflowRunArtifacts.mockResolvedValue({ artifacts: [journalRecord()] });
  242. const hook = renderHook(
  243. (props: { live: readonly WorkflowRunArtifactSummary[] }) =>
  244. useWorkflowRunArtifacts({ sessionId: SESSION, runId: RUN, live: props.live }),
  245. {
  246. initialProps: {
  247. live: [summary({ itemCount: 1 })] as readonly WorkflowRunArtifactSummary[],
  248. },
  249. },
  250. );
  251. await waitFor(() => expect(workflowRunArtifacts).toHaveBeenCalledTimes(1));
  252. hook.rerender({ live: [summary({ itemCount: 2 })] });
  253. await act(async () => {});
  254. expect(workflowRunArtifacts).toHaveBeenCalledTimes(1);
  255. hook.rerender({ live: [summary({ itemCount: 2, version: 2 })] });
  256. await waitFor(() => expect(workflowRunArtifacts).toHaveBeenCalledTimes(2));
  257. });
  258. it("enabled 为 false 时一次都不查", async () => {
  259. renderHook(() =>
  260. useWorkflowRunArtifacts({ sessionId: SESSION, runId: RUN, enabled: false, live: [] }),
  261. );
  262. await act(async () => {});
  263. expect(workflowRunArtifacts).not.toHaveBeenCalled();
  264. });
  265. });
  266. describe("useWorkflowRunArtifactData", () => {
  267. it("首次整份重取,hasMore 为真就一路翻到排空", async () => {
  268. workflowRunArtifactData
  269. .mockResolvedValueOnce(itemsPage(1, 2, true))
  270. .mockResolvedValueOnce(itemsPage(3, 1, false));
  271. const hook = renderHook(() =>
  272. useWorkflowRunArtifactData({ sessionId: SESSION, runId: RUN, artifactId: "perf" }),
  273. );
  274. await waitFor(() => expect(hook.result.current.items).toHaveLength(3));
  275. expect(workflowRunArtifactData).toHaveBeenNthCalledWith(1, {
  276. sessionId: SESSION,
  277. runId: RUN,
  278. artifactId: "perf",
  279. limit: 200,
  280. });
  281. // 第二页从上一页末尾的 sequence 续上——不重不漏。
  282. expect(workflowRunArtifactData).toHaveBeenNthCalledWith(2, {
  283. sessionId: SESSION,
  284. runId: RUN,
  285. artifactId: "perf",
  286. afterSequence: 2,
  287. limit: 200,
  288. });
  289. });
  290. it("翻页没有 16 页的上限:一个已结束、打了 5,000 条标签的 run 看板画出全部条目", async () => {
  291. // 修复前最多翻 16 页 × 200 = 3,200 条就停,而已结束的 run 不会再有 itemCount 变化来续拉。
  292. const total = 5_000;
  293. const pages = Math.ceil(total / 200);
  294. for (let page = 0; page < pages; page += 1) {
  295. const from = 1 + page * 200;
  296. const count = Math.min(200, total - page * 200);
  297. workflowRunArtifactData.mockResolvedValueOnce(itemsPage(from, count, page < pages - 1));
  298. }
  299. const hook = renderHook(() =>
  300. useWorkflowRunArtifactData({ sessionId: SESSION, runId: RUN, artifactId: "perf" }),
  301. );
  302. await waitFor(() => expect(hook.result.current.items).toHaveLength(total));
  303. expect(workflowRunArtifactData).toHaveBeenCalledTimes(pages);
  304. expect(hook.result.current.items.at(-1)?.sequence).toBe(total);
  305. });
  306. it("一页没有让游标前进就停:一个总说 hasMore 的实现锁不死渲染线程", async () => {
  307. workflowRunArtifactData
  308. .mockResolvedValueOnce(itemsPage(1, 2, true))
  309. // 同一段 sequence 又来一遍,且仍说还有:游标没有前进。
  310. .mockResolvedValueOnce(itemsPage(1, 2, true))
  311. .mockResolvedValue(itemsPage(1, 2, true));
  312. const hook = renderHook(() =>
  313. useWorkflowRunArtifactData({ sessionId: SESSION, runId: RUN, artifactId: "perf" }),
  314. );
  315. await waitFor(() => expect(hook.result.current.loading).toBe(false));
  316. expect(workflowRunArtifactData).toHaveBeenCalledTimes(2);
  317. });
  318. it("给了 fields 就只让 CLI 取这些字段", async () => {
  319. workflowRunArtifactData.mockResolvedValueOnce({
  320. items: [{ sequence: 1, siteId: "report#1", ordinal: 1, fields: { round: 1 } }],
  321. hasMore: false,
  322. });
  323. const hook = renderHook(() =>
  324. useWorkflowRunArtifactData({
  325. sessionId: "parent-fields",
  326. runId: RUN,
  327. artifactId: "perf",
  328. fields: ["round", "ms"],
  329. }),
  330. );
  331. await waitFor(() => expect(hook.result.current.items).toHaveLength(1));
  332. expect(workflowRunArtifactData).toHaveBeenCalledWith({
  333. sessionId: "parent-fields",
  334. runId: RUN,
  335. artifactId: "perf",
  336. limit: 200,
  337. fields: ["round", "ms"],
  338. });
  339. expect(hook.result.current.items[0]?.fields).toEqual({ round: 1 });
  340. });
  341. it("老 CLI 拒收 fields 时退回取整条 item,并记住这个会话", async () => {
  342. // 老 CLI 的 strict schema 整条拒收带 fields 的请求;错误跨 JSON-RPC 后只剩 zod 的 message。
  343. const rejection = new Error(
  344. '[{"code":"unrecognized_keys","keys":["fields"],"path":[],"message":"Unrecognized key: \\"fields\\""}]',
  345. );
  346. workflowRunArtifactData
  347. .mockRejectedValueOnce(rejection)
  348. .mockResolvedValueOnce(itemsPage(1, 1, false))
  349. .mockResolvedValueOnce(itemsPage(1, 1, false));
  350. const request = { sessionId: "parent-old-cli", runId: RUN, artifactId: "perf" };
  351. const first = renderHook(() => useWorkflowRunArtifactData({ ...request, fields: ["round"] }));
  352. await waitFor(() => expect(first.result.current.items).toHaveLength(1));
  353. expect(first.result.current.error).toBeNull();
  354. expect(workflowRunArtifactData).toHaveBeenNthCalledWith(1, {
  355. ...request,
  356. limit: 200,
  357. fields: ["round"],
  358. });
  359. expect(workflowRunArtifactData).toHaveBeenNthCalledWith(2, { ...request, limit: 200 });
  360. // 同一会话的下一块看板不再撞一次拒绝。
  361. const second = renderHook(() =>
  362. useWorkflowRunArtifactData({ ...request, artifactId: "perf", fields: ["round"] }),
  363. );
  364. await waitFor(() => expect(second.result.current.items).toHaveLength(1));
  365. expect(workflowRunArtifactData).toHaveBeenNthCalledWith(3, { ...request, limit: 200 });
  366. });
  367. it("别的错误照常报出来,不当成老 CLI", async () => {
  368. workflowRunArtifactData.mockRejectedValueOnce(new Error("fault.workflowRunArtifactData.boom"));
  369. const hook = renderHook(() =>
  370. useWorkflowRunArtifactData({
  371. sessionId: "parent-other-error",
  372. runId: RUN,
  373. artifactId: "perf",
  374. fields: ["round"],
  375. }),
  376. );
  377. await waitFor(() => expect(hook.result.current.error).toContain("boom"));
  378. expect(workflowRunArtifactData).toHaveBeenCalledTimes(1);
  379. });
  380. it("itemCount 抬升即带 afterSequence 增量续拉", async () => {
  381. workflowRunArtifactData
  382. .mockResolvedValueOnce(itemsPage(1, 2, false))
  383. .mockResolvedValueOnce(itemsPage(3, 1, false));
  384. const hook = renderHook(
  385. (props: { itemCount: number }) =>
  386. useWorkflowRunArtifactData({
  387. sessionId: SESSION,
  388. runId: RUN,
  389. artifactId: "perf",
  390. itemCount: props.itemCount,
  391. }),
  392. { initialProps: { itemCount: 2 } },
  393. );
  394. await waitFor(() => expect(hook.result.current.items).toHaveLength(2));
  395. expect(workflowRunArtifactData).toHaveBeenCalledTimes(1);
  396. hook.rerender({ itemCount: 3 });
  397. await waitFor(() => expect(hook.result.current.items).toHaveLength(3));
  398. expect(workflowRunArtifactData).toHaveBeenLastCalledWith({
  399. sessionId: SESSION,
  400. runId: RUN,
  401. artifactId: "perf",
  402. afterSequence: 2,
  403. limit: 200,
  404. });
  405. });
  406. it("本地一条都还没有时,itemCount 抬升照样拉——脚本顶部声明的看板就是这样长出第一个点的", async () => {
  407. // 回归:旧实现在增量 effect 上有一条「items 为空就不拉」的门,于是一个「先声明、
  408. // 后每轮 report」的看板永远停在空态(首帧的整份重取只会取到零条)。
  409. workflowRunArtifactData
  410. .mockResolvedValueOnce({ items: [], hasMore: false })
  411. .mockResolvedValueOnce(itemsPage(1, 1, false));
  412. const hook = renderHook(
  413. (props: { itemCount: number }) =>
  414. useWorkflowRunArtifactData({
  415. sessionId: SESSION,
  416. runId: RUN,
  417. artifactId: "perf",
  418. itemCount: props.itemCount,
  419. }),
  420. { initialProps: { itemCount: 0 } },
  421. );
  422. await waitFor(() => expect(hook.result.current.loading).toBe(false));
  423. expect(hook.result.current.items).toHaveLength(0);
  424. hook.rerender({ itemCount: 1 });
  425. await waitFor(() => expect(hook.result.current.items).toHaveLength(1));
  426. });
  427. it("拉取途中来的刷新信号不丢:收尾前补拉一轮", async () => {
  428. // 回归:单飞门挡下的那一次如果直接丢掉,一个 run 的**最后一条** report 就永远画不出来
  429. // ——它之后不会再有 itemCount 变化来触发下一次拉取。
  430. let releaseFirst: (() => void) | undefined;
  431. workflowRunArtifactData.mockImplementationOnce(
  432. async () =>
  433. await new Promise<V4ConversationWorkflowRunArtifactDataResult>((resolve) => {
  434. releaseFirst = () => resolve(itemsPage(1, 1, false));
  435. }),
  436. );
  437. workflowRunArtifactData.mockResolvedValueOnce(itemsPage(2, 1, false));
  438. const hook = renderHook(
  439. (props: { itemCount: number }) =>
  440. useWorkflowRunArtifactData({
  441. sessionId: SESSION,
  442. runId: RUN,
  443. artifactId: "perf",
  444. itemCount: props.itemCount,
  445. }),
  446. { initialProps: { itemCount: 1 } },
  447. );
  448. await waitFor(() => expect(releaseFirst).toBeDefined());
  449. // 第一页还没回来就又来了一条 report:这一次会被单飞门挡下,但必须被记住。
  450. hook.rerender({ itemCount: 2 });
  451. await act(async () => {
  452. releaseFirst?.();
  453. });
  454. await waitFor(() => expect(hook.result.current.items).toHaveLength(2));
  455. expect(workflowRunArtifactData).toHaveBeenLastCalledWith({
  456. sessionId: SESSION,
  457. runId: RUN,
  458. artifactId: "perf",
  459. afterSequence: 1,
  460. limit: 200,
  461. });
  462. });
  463. it("换产物先清空再整份重取:别的看板的点不留在这块画布上", async () => {
  464. workflowRunArtifactData
  465. .mockResolvedValueOnce(itemsPage(1, 2, false))
  466. .mockResolvedValueOnce(itemsPage(9, 1, false));
  467. const hook = renderHook(
  468. (props: { artifactId: string }) =>
  469. useWorkflowRunArtifactData({
  470. sessionId: SESSION,
  471. runId: RUN,
  472. artifactId: props.artifactId,
  473. }),
  474. { initialProps: { artifactId: "perf" } },
  475. );
  476. await waitFor(() => expect(hook.result.current.items).toHaveLength(2));
  477. hook.rerender({ artifactId: "other" });
  478. await waitFor(() => expect(hook.result.current.items).toHaveLength(1));
  479. expect(hook.result.current.items[0]?.sequence).toBe(9);
  480. expect(workflowRunArtifactData).toHaveBeenLastCalledWith({
  481. sessionId: SESSION,
  482. runId: RUN,
  483. artifactId: "other",
  484. limit: 200,
  485. });
  486. });
  487. it("enabled 为 false(内容产物的 tab)时一次都不查", async () => {
  488. renderHook(() =>
  489. useWorkflowRunArtifactData({
  490. sessionId: SESSION,
  491. runId: RUN,
  492. artifactId: "perf",
  493. enabled: false,
  494. itemCount: 5,
  495. }),
  496. );
  497. await act(async () => {});
  498. expect(workflowRunArtifactData).not.toHaveBeenCalled();
  499. });
  500. it("能力缺席抬起 unavailable,而不是报一个错给用户看", async () => {
  501. workflowRunArtifactData.mockRejectedValue(new Error("fault.command.capabilityUnsupported"));
  502. const hook = renderHook(() =>
  503. useWorkflowRunArtifactData({ sessionId: SESSION, runId: RUN, artifactId: "perf" }),
  504. );
  505. await waitFor(() => expect(hook.result.current.unavailable).toBe(true));
  506. expect(hook.result.current.error).toBeNull();
  507. });
  508. });
  509. describe("useWorkflowRunArtifactBytes", () => {
  510. const created: string[] = [];
  511. const revoked: string[] = [];
  512. beforeEach(() => {
  513. created.length = 0;
  514. revoked.length = 0;
  515. // jsdom 没有 object URL:桩出来才能观察「换版本 / 卸载时 revoke」这条不变式。
  516. (URL as unknown as { createObjectURL: (blob: Blob) => string }).createObjectURL = (
  517. blob: Blob,
  518. ) => {
  519. const url = `blob:artifact-${created.length}-${blob.size}`;
  520. created.push(url);
  521. return url;
  522. };
  523. (URL as unknown as { revokeObjectURL: (url: string) => void }).revokeObjectURL = (
  524. url: string,
  525. ) => {
  526. revoked.push(url);
  527. };
  528. });
  529. function chunk(
  530. text: string,
  531. nextOffset: number | null,
  532. totalBytes: number,
  533. ): V4ConversationWorkflowRunArtifactReadResult {
  534. return {
  535. dataBase64: encodeBytesToBase64(new TextEncoder().encode(text) as Uint8Array<ArrayBuffer>),
  536. mediaType: "text/markdown",
  537. totalBytes,
  538. nextOffset,
  539. };
  540. }
  541. it("按 nextOffset 分块读到底,拼成一份完整字节 + Blob + objectUrl", async () => {
  542. workflowRunArtifactRead
  543. .mockResolvedValueOnce(chunk("hello ", 6, 11))
  544. .mockResolvedValueOnce(chunk("world", null, 11));
  545. const hook = renderHook(() =>
  546. useWorkflowRunArtifactBytes({
  547. sessionId: SESSION,
  548. runId: RUN,
  549. artifactId: "notes",
  550. version: 1,
  551. }),
  552. );
  553. await waitFor(() => expect(hook.result.current.bytes).not.toBeNull());
  554. expect(new TextDecoder().decode(hook.result.current.bytes!)).toBe("hello world");
  555. expect(hook.result.current.mediaType).toBe("text/markdown");
  556. expect(hook.result.current.totalBytes).toBe(11);
  557. expect(hook.result.current.blob?.type).toBe("text/markdown");
  558. expect(hook.result.current.objectUrl).toBe(created[0]);
  559. // 第二块的 offset 来自第一块的 nextOffset,limit 是附件那条既有的分块上界。
  560. expect(workflowRunArtifactRead).toHaveBeenNthCalledWith(2, {
  561. sessionId: SESSION,
  562. runId: RUN,
  563. artifactId: "notes",
  564. version: 1,
  565. offset: 6,
  566. limit: 512 * 1024,
  567. });
  568. });
  569. it("翻版本会 revoke 上一版的 objectUrl(否则每翻一版漏一份字节)", async () => {
  570. workflowRunArtifactRead
  571. .mockResolvedValueOnce(chunk("v1", null, 2))
  572. .mockResolvedValueOnce(chunk("v2 body", null, 7));
  573. const hook = renderHook(
  574. (props: { version: number }) =>
  575. useWorkflowRunArtifactBytes({
  576. sessionId: SESSION,
  577. runId: RUN,
  578. artifactId: "notes",
  579. version: props.version,
  580. }),
  581. { initialProps: { version: 1 } },
  582. );
  583. await waitFor(() => expect(hook.result.current.objectUrl).toBe(created[0]));
  584. hook.rerender({ version: 2 });
  585. await waitFor(() => expect(hook.result.current.objectUrl).toBe(created[1]));
  586. expect(revoked).toContain(created[0]);
  587. });
  588. it("卸载时 revoke", async () => {
  589. workflowRunArtifactRead.mockResolvedValueOnce(chunk("bye", null, 3));
  590. const hook = renderHook(() =>
  591. useWorkflowRunArtifactBytes({
  592. sessionId: SESSION,
  593. runId: RUN,
  594. artifactId: "notes",
  595. version: 1,
  596. }),
  597. );
  598. await waitFor(() => expect(hook.result.current.objectUrl).toBe(created[0]));
  599. hook.unmount();
  600. expect(revoked).toContain(created[0]);
  601. });
  602. it("预置看板(enabled 为 false)不读一个字节", async () => {
  603. renderHook(() =>
  604. useWorkflowRunArtifactBytes({
  605. sessionId: SESSION,
  606. runId: RUN,
  607. artifactId: "perf",
  608. version: 1,
  609. enabled: false,
  610. }),
  611. );
  612. await act(async () => {});
  613. expect(workflowRunArtifactRead).not.toHaveBeenCalled();
  614. });
  615. it("读失败落到 error,而不是留一个半截的 Blob", async () => {
  616. workflowRunArtifactRead.mockRejectedValueOnce(new Error("store gone"));
  617. const hook = renderHook(() =>
  618. useWorkflowRunArtifactBytes({
  619. sessionId: SESSION,
  620. runId: RUN,
  621. artifactId: "notes",
  622. version: 1,
  623. }),
  624. );
  625. await waitFor(() => expect(hook.result.current.error).toBe("store gone"));
  626. expect(hook.result.current.bytes).toBeNull();
  627. expect(hook.result.current.objectUrl).toBeNull();
  628. });
  629. });