workflowRunDirectorySidePane.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // @vitest-environment jsdom
  2. // dwf run 目录页(docs/dynamic-workflow/presentation.md「Other places a run appears」):
  3. // 任务岛页脚行 →(本文件)→ 已有的 `workflow-run` 详情页,与 subagent 的三步形状同构。
  4. //
  5. // 分桶/剔除/截断的规则在 workflowRunDirectoryModel.test.ts 里穷举,取数与重试语义在
  6. // useWorkflowRunJournalSummaries.test.ts 里;这里只钉「那些结果真的接到了 DOM 上」、
  7. // 行点击发出什么,以及三种空态在屏幕上可分辨。
  8. import { createElement, useEffect, useState, type ReactNode } from "react";
  9. import { act, cleanup, fireEvent, render } from "@testing-library/react";
  10. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  11. import type { V4ConversationWorkflowRunSummary } from "@zcode/shared/zcode-protocol-v4";
  12. import type { WorkflowRunDirectorySidePaneTab } from "@/lib/workspaceSidePane.js";
  13. vi.mock("@/logger.js", () => ({
  14. logger: { debug: vi.fn(), warn: vi.fn() },
  15. }));
  16. // 租约与投影:页面拿投影**只当新鲜度触发器**(行仍然只渲染 journal 摘要)。
  17. // layer 必须是稳定引用——租约 effect 以它为依赖,每次渲染换新对象会打成无限循环。
  18. const release = vi.fn();
  19. const acquire = vi.fn(() => ({ release }));
  20. const layer = { acquire };
  21. vi.mock("@/v4/V4ConversationContext.js", () => ({
  22. V4PaneConversationProvider: ({ children }: { children: ReactNode }) => children,
  23. useV4Conversation: () => ({ layer }),
  24. }));
  25. let snapshot: { workflowRuns?: { revision: number; runs: unknown[] } } | null = null;
  26. // 投影桩必须**真的会推**:被测内容组件是 memo 的,props 不变时 rerender 根本不会重渲染它。
  27. // 读模块变量的桩因此会假装「投影更新了但界面没反应」——那正好是本轮要修的 bug 的形状,
  28. // 桩不能自己制造它。这里用一个最小订阅,与生产里 useConversationProjection 的语义一致。
  29. const projectionListeners = new Set<() => void>();
  30. function pushProjection(next: typeof snapshot) {
  31. snapshot = next;
  32. for (const listener of projectionListeners) listener();
  33. }
  34. vi.mock("@/v4/useConversationProjection.js", () => ({
  35. useConversationProjection: () => {
  36. const [, forceRender] = useState(0);
  37. useEffect(() => {
  38. const listener = () => forceRender((generation) => generation + 1);
  39. projectionListeners.add(listener);
  40. return () => {
  41. projectionListeners.delete(listener);
  42. };
  43. }, []);
  44. return { snapshot };
  45. },
  46. }));
  47. // 取数 hook 换成桩:它自己的行为(能力缺席终局、live 重试、refreshKey)有专属用例,
  48. // 这里要钉的是**页面向它要了什么**(limit 必须与任务岛计数同深度,否则两处口径会分叉;
  49. // refreshKey 必须真的接上,否则跑完的 run 永远留在「运行中」)以及三种返回长什么样。
  50. let summaries: readonly V4ConversationWorkflowRunSummary[] | null = null;
  51. let optionsSeen:
  52. | { sessionId: string | null; live: boolean; limit?: number; refreshKey?: number | string }
  53. | undefined;
  54. const refreshKeysSeen: (number | string | undefined)[] = [];
  55. vi.mock("@/hooks/useWorkflowRunJournalSummaries.js", () => ({
  56. useWorkflowRunJournalSummaries: (options: {
  57. sessionId: string | null;
  58. live: boolean;
  59. limit?: number;
  60. refreshKey?: number | string;
  61. }) => {
  62. optionsSeen = options;
  63. if (refreshKeysSeen.at(-1) !== options.refreshKey) refreshKeysSeen.push(options.refreshKey);
  64. return summaries;
  65. },
  66. }));
  67. // eslint-disable-next-line import/first -- 必须在全部 mock 之后再引入被测组件。
  68. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  69. // eslint-disable-next-line import/first
  70. import { WorkflowRunDirectorySidePane } from "@/app-shell/WorkflowRunDirectorySidePane.js";
  71. // eslint-disable-next-line import/first
  72. import {
  73. WORKFLOW_RUN_DIRECTORY_LIMIT,
  74. workflowRunDirectoryRefreshKey,
  75. } from "@/v4/workflowRunDirectoryModel.js";
  76. const tab: WorkflowRunDirectorySidePaneTab = {
  77. id: "workflow-directory:%2Fworkspace:parent-a",
  78. type: "workflow-directory",
  79. workspaceKey: "/workspace",
  80. workspacePath: "/workspace",
  81. parentSessionId: "parent-a",
  82. };
  83. const onOpenWorkflowRun = vi.fn();
  84. function summary(
  85. overrides: Partial<V4ConversationWorkflowRunSummary> &
  86. Pick<V4ConversationWorkflowRunSummary, "runId">,
  87. ): V4ConversationWorkflowRunSummary {
  88. return {
  89. toolCallId: `call-${overrides.runId}`,
  90. status: "completed",
  91. resumable: false,
  92. ...overrides,
  93. };
  94. }
  95. /** 触发器那一侧的输入:投影里的 run(只有身份与状态对键有意义)。 */
  96. function projectionRun(runId: string, status: "running" | "pending" | "completed" | "errored") {
  97. return {
  98. runId,
  99. toolCallId: `call-${runId}`,
  100. status,
  101. usage: { spentTokens: 0, nodesUsed: 0 },
  102. actors: [],
  103. nodes: [],
  104. lastEventSequence: 0,
  105. };
  106. }
  107. function renderPane(locale: "en-US" | "zh-CN" = "en-US") {
  108. return render(
  109. createElement(
  110. ZCodeIntlProvider,
  111. { initialLocale: locale },
  112. createElement(WorkflowRunDirectorySidePane, { tab, onOpenWorkflowRun }),
  113. ),
  114. );
  115. }
  116. function rows(pane: ReturnType<typeof renderPane>, section: "running" | "ended") {
  117. return [
  118. ...pane.container.querySelectorAll(
  119. `[data-workflow-directory-section="${section}"] [data-run-id]`,
  120. ),
  121. ];
  122. }
  123. beforeEach(() => {
  124. summaries = null;
  125. optionsSeen = undefined;
  126. refreshKeysSeen.length = 0;
  127. snapshot = null;
  128. acquire.mockClear();
  129. release.mockClear();
  130. onOpenWorkflowRun.mockReset();
  131. });
  132. afterEach(() => {
  133. cleanup();
  134. });
  135. describe("WorkflowRunDirectorySidePane", () => {
  136. it("按会话取一页 journal,深度与任务岛计数同一个常量(口径分叉就是「岛说 5、页面 4」)", () => {
  137. summaries = [];
  138. renderPane();
  139. expect(optionsSeen?.sessionId).toBe("parent-a");
  140. expect(optionsSeen?.live).toBe(true);
  141. expect(optionsSeen?.limit).toBe(WORKFLOW_RUN_DIRECTORY_LIMIT);
  142. });
  143. // ── 自动刷新(实测 bug:跑完的 run 不会自己挪到「已结束」)──
  144. //
  145. // 失效的形状是「页面一个信号都没有」:hook 首答即收口,那一页在 pane 的余生里冻住。
  146. // 所以这里钉的是**信号接上了**,而不是某个具体键值。
  147. it("把投影派生出的 refreshKey 交给取数 hook(缺了它那一页会永远冻住)", () => {
  148. summaries = [];
  149. snapshot = { workflowRuns: { revision: 1, runs: [projectionRun("r-1", "running")] } };
  150. renderPane();
  151. expect(optionsSeen?.refreshKey).toBe(
  152. workflowRunDirectoryRefreshKey([projectionRun("r-1", "running")] as never),
  153. );
  154. });
  155. it("run 跑完时 refreshKey 变化 → hook 重取 → 那一行自己挪到「已结束」", () => {
  156. summaries = [summary({ runId: "r-1", status: "running" })];
  157. snapshot = { workflowRuns: { revision: 1, runs: [projectionRun("r-1", "running")] } };
  158. const pane = renderPane();
  159. expect(rows(pane, "running").map((row) => row.getAttribute("data-run-id"))).toEqual(["r-1"]);
  160. const keyWhileRunning = optionsSeen?.refreshKey;
  161. // 引擎结算 → 投影翻终态;journal 的下一答随之把这条 run 归到已结束。
  162. act(() => {
  163. summaries = [summary({ runId: "r-1", status: "completed" })];
  164. pushProjection({ workflowRuns: { revision: 2, runs: [projectionRun("r-1", "completed")] } });
  165. });
  166. expect(optionsSeen?.refreshKey).not.toBe(keyWhileRunning);
  167. expect(rows(pane, "running")).toEqual([]);
  168. expect(rows(pane, "ended").map((row) => row.getAttribute("data-run-id"))).toEqual(["r-1"]);
  169. });
  170. it("节点级进度不抬 refreshKey:开着的页面不会因为引擎事件反复读 journal", () => {
  171. summaries = [summary({ runId: "r-1", status: "running" })];
  172. snapshot = { workflowRuns: { revision: 1, runs: [projectionRun("r-1", "running")] } };
  173. renderPane();
  174. // 同一个 run 在跑,只是又结算了一个节点(revision 也抬了)——键必须不动。
  175. act(() => {
  176. pushProjection({
  177. workflowRuns: {
  178. revision: 2,
  179. runs: [
  180. {
  181. ...projectionRun("r-1", "running"),
  182. nodes: [{ siteId: "ask#1", ordinal: 1, phase: "settled", outcome: "ok" }],
  183. lastEventSequence: 7,
  184. },
  185. ],
  186. },
  187. });
  188. });
  189. expect(refreshKeysSeen).toHaveLength(1);
  190. });
  191. it("按会话取租约,卸载时放掉(投影只当触发器,但租约照样是租约)", () => {
  192. summaries = [];
  193. const pane = renderPane();
  194. expect(acquire).toHaveBeenCalledWith("parent-a");
  195. expect(release).not.toHaveBeenCalled();
  196. pane.unmount();
  197. expect(release).toHaveBeenCalledTimes(1);
  198. });
  199. it("两段各自渲染并带计数:运行中与已结束", () => {
  200. summaries = [
  201. summary({ runId: "r-run", status: "running", label: "find-flaky-tests" }),
  202. summary({ runId: "r-done", status: "completed", label: "review-changes" }),
  203. summary({ runId: "r-cancel", status: "stopped", label: "migrate-imports" }),
  204. ];
  205. const pane = renderPane();
  206. expect(rows(pane, "running").map((row) => row.getAttribute("data-run-id"))).toEqual(["r-run"]);
  207. expect(rows(pane, "ended").map((row) => row.getAttribute("data-run-id"))).toEqual([
  208. "r-done",
  209. "r-cancel",
  210. ]);
  211. expect(pane.getByTestId("workflow-run-directory-running-count").textContent).toContain("1");
  212. expect(pane.getByTestId("workflow-run-directory-ended-count").textContent).toContain("2");
  213. expect(pane.getByText("find-flaky-tests")).toBeTruthy();
  214. });
  215. it("行点击开详情页,参数带全(runId + toolCallId + 展示名做标题兜底)", () => {
  216. summaries = [summary({ runId: "r-done", label: "review-changes" })];
  217. const pane = renderPane();
  218. fireEvent.click(pane.container.querySelector("[data-run-id='r-done']") as Element);
  219. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  220. workspacePath: "/workspace",
  221. parentSessionId: "parent-a",
  222. runId: "r-done",
  223. toolCallId: "call-r-done",
  224. workflowName: "review-changes",
  225. });
  226. });
  227. it("没有 label 的 run 用既有的兜底名,绝不显示裸 runId", () => {
  228. summaries = [summary({ runId: "dwfrun-8f21" })];
  229. const pane = renderPane();
  230. expect(pane.queryByText("dwfrun-8f21")).toBeNull();
  231. expect(pane.getByText("Workflow script")).toBeTruthy();
  232. });
  233. it("状态词复用既有词汇表;stopped 行跟原因词,errored 行跟 failureCode(决策 15)", () => {
  234. summaries = [
  235. summary({
  236. runId: "r-stop",
  237. status: "stopped",
  238. stopReason: "interrupted",
  239. failureCode: "Interrupted",
  240. resumable: true,
  241. } as never),
  242. summary({ runId: "r-fail", status: "errored", failureCode: "DriverError" }),
  243. summary({ runId: "r-done", status: "completed" }),
  244. ];
  245. const pane = renderPane();
  246. const stopped = pane.container.querySelector("[data-run-id='r-stop']") as HTMLElement;
  247. expect(stopped.textContent).toContain("Stopped");
  248. expect(stopped.textContent).toContain("process exited");
  249. expect(stopped.textContent).not.toContain("Interrupted");
  250. const failed = pane.container.querySelector("[data-run-id='r-fail']") as HTMLElement;
  251. expect(failed.textContent).toContain("Errored");
  252. expect(failed.textContent).toContain("DriverError");
  253. const completed = pane.container.querySelector("[data-run-id='r-done']") as HTMLElement;
  254. expect(completed.textContent).toContain("Completed");
  255. expect(completed.textContent).not.toContain("DriverError");
  256. });
  257. it("取满一页才提示截断——静默截断会读成「就这些」", () => {
  258. summaries = Array.from({ length: WORKFLOW_RUN_DIRECTORY_LIMIT - 1 }, (_unused, index) =>
  259. summary({ runId: `r-${index}` }),
  260. );
  261. const short = renderPane();
  262. expect(short.queryByTestId("workflow-run-directory-truncated")).toBeNull();
  263. cleanup();
  264. summaries = Array.from({ length: WORKFLOW_RUN_DIRECTORY_LIMIT }, (_unused, index) =>
  265. summary({ runId: `r-${index}` }),
  266. );
  267. const full = renderPane();
  268. expect(full.getByTestId("workflow-run-directory-truncated").textContent).toContain("64");
  269. });
  270. it("三种空态可分辨:一条都没有 / 只是某一段空 / 根本列不出来", () => {
  271. summaries = [];
  272. const empty = renderPane();
  273. expect(empty.getByTestId("workflow-run-directory-empty")).toBeTruthy();
  274. expect(empty.queryByTestId("workflow-run-directory-unavailable")).toBeNull();
  275. cleanup();
  276. summaries = [summary({ runId: "r-run", status: "running" })];
  277. const onlyRunning = renderPane();
  278. expect(onlyRunning.queryByTestId("workflow-run-directory-empty")).toBeNull();
  279. expect(onlyRunning.getByTestId("workflow-run-directory-ended-empty")).toBeTruthy();
  280. cleanup();
  281. // 能力缺席 / 还没查到:hook 给 null。**不是**「没有运行」,所以不能借用空态文案。
  282. summaries = null;
  283. const unavailable = renderPane();
  284. expect(unavailable.getByTestId("workflow-run-directory-unavailable")).toBeTruthy();
  285. expect(unavailable.queryByTestId("workflow-run-directory-empty")).toBeNull();
  286. // 也不是报错:没有 alert,屏幕上不出现失败语气。
  287. expect(unavailable.container.querySelector("[role='alert']")).toBeNull();
  288. });
  289. it("中文文案(分区标题与状态词都走 i18n,不写死英文)", () => {
  290. summaries = [
  291. summary({ runId: "r-run", status: "running" }),
  292. summary({ runId: "r-fail", status: "errored" }),
  293. ];
  294. const pane = renderPane("zh-CN");
  295. // 分区标题是「标题 · 计数」的组合节点,所以按子串匹配(计数本身另有 testid)。
  296. expect(pane.getByText(/正在运行/)).toBeTruthy();
  297. expect(pane.getByText(/已结束/)).toBeTruthy();
  298. expect(
  299. (pane.container.querySelector("[data-run-id='r-fail']") as HTMLElement).textContent,
  300. ).toContain("出错");
  301. });
  302. });