workflowWorkspaceSidePane.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. // @vitest-environment jsdom
  2. // 脚本 transcript 面板(docs/dynamic-workflow/transcript-and-notifications.md「The panel」;视觉:日志簿,
  3. // docs/dynamic-workflow/presentation.md「The pill」视觉修订):一个 run 的
  4. // files.* / git.* / world.run 回放成章节 + 两行条目 + 时间标尺 + 命令输出的尾巴。钉的是
  5. // 「清单接到了 DOM 上」——章头、动词与对象、结果行、状态词、peek 与展开、占位、落点——
  6. // 派生规则在 workflowWorkspaceTranscript.test.ts 与 workflowWorkspaceLogbook.test.ts。
  7. import { createElement, type ReactNode } from "react";
  8. import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";
  9. import { beforeEach, describe, expect, it, vi } from "vitest";
  10. import type {
  11. V4ConversationWorkflowRunNodeResultResult,
  12. V4ConversationWorkflowRunWorkspaceResult,
  13. WorkflowRunState,
  14. } from "@zcode/shared/zcode-protocol-v4";
  15. import type { WorkflowWorkspaceSidePaneTab } from "@/lib/workspaceSidePane.js";
  16. vi.mock("@/logger.js", () => ({
  17. logger: { debug: vi.fn(), warn: vi.fn() },
  18. }));
  19. const release = vi.fn();
  20. const layer = { acquire: vi.fn(() => ({ release })) };
  21. const workflowRunWorkspace = vi.fn<() => Promise<V4ConversationWorkflowRunWorkspaceResult>>();
  22. const workflowRunNodeResult = vi.fn<() => Promise<V4ConversationWorkflowRunNodeResultResult>>();
  23. const onOpenCodeViewer = vi.fn();
  24. const conversation = { layer, workflowRunWorkspace, workflowRunNodeResult };
  25. vi.mock("@/v4/V4ConversationContext.js", () => ({
  26. V4PaneConversationProvider: ({ children }: { children: ReactNode }) => children,
  27. useV4Conversation: () => conversation,
  28. }));
  29. let snapshot: unknown = null;
  30. vi.mock("@/v4/useConversationProjection.js", () => ({
  31. useConversationProjection: () => ({ snapshot }),
  32. }));
  33. // eslint-disable-next-line import/first -- 必须在全部 mock 之后再引入被测组件。
  34. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  35. // eslint-disable-next-line import/first
  36. import { WorkflowWorkspaceSidePane } from "@/app-shell/WorkflowWorkspaceSidePane.js";
  37. // eslint-disable-next-line import/first
  38. import { openWorkflowWorkspaceSidePane } from "@/lib/workspaceSidePane.js";
  39. // eslint-disable-next-line import/first
  40. import { resetWorkflowRunNodeResultCache } from "@/hooks/useWorkflowRunNodeResult.js";
  41. // eslint-disable-next-line import/first
  42. import { resetWorkspaceEntryOpenState } from "@/app-shell/workflowWorkspaceLogbook.js";
  43. function tabOf(
  44. overrides: Partial<WorkflowWorkspaceSidePaneTab> = {},
  45. ): WorkflowWorkspaceSidePaneTab {
  46. const state = openWorkflowWorkspaceSidePane(null, {
  47. workspaceKey: "/workspace",
  48. workspacePath: "/workspace",
  49. parentSessionId: "parent-a",
  50. toolCallId: "tool-wf-1",
  51. runId: "dwfrun-1",
  52. workflowName: "Fan-out review",
  53. });
  54. return { ...(state.tabs[0] as WorkflowWorkspaceSidePaneTab), ...overrides };
  55. }
  56. const GRAPH = {
  57. steps: [
  58. { id: "ask#1", kind: "ask", label: "plan", lane: "actor#1", phase: "phase#a" },
  59. { id: "world-read#1", kind: "world-read", label: "glob", lane: "workspace", phase: "phase#a" },
  60. {
  61. id: "world-read#2",
  62. kind: "world-read",
  63. label: "run tests",
  64. lane: "workspace",
  65. phase: "phase#b",
  66. },
  67. ],
  68. lanes: [{ id: "actor#1", name: "planner" }, { id: "workspace" }],
  69. participants: [
  70. { id: "phase#a:actor#1", phase: "phase#a", lane: "actor#1", steps: ["ask#1"] },
  71. { id: "phase#a:workspace", phase: "phase#a", lane: "workspace", steps: ["world-read#1"] },
  72. { id: "phase#b:workspace", phase: "phase#b", lane: "workspace", steps: ["world-read#2"] },
  73. ],
  74. handoffs: [],
  75. phases: [
  76. { id: "phase#a", name: "plan", line: 1 },
  77. { id: "phase#b", name: "verify", line: 5 },
  78. ],
  79. phaseEdges: [{ from: "phase#a", to: "phase#b" }],
  80. exits: ["phase#b"],
  81. };
  82. function run(overrides: Partial<WorkflowRunState> = {}): WorkflowRunState {
  83. return {
  84. runId: "dwfrun-1",
  85. toolCallId: "tool-wf-1",
  86. status: "running",
  87. usage: { spentTokens: 0, nodesUsed: 0 },
  88. actors: [],
  89. nodes: [],
  90. lastEventSequence: 3,
  91. ...overrides,
  92. };
  93. }
  94. function setSnapshot(options: { run?: WorkflowRunState; withGraph?: boolean } = {}) {
  95. snapshot = {
  96. rows: {
  97. window:
  98. options.withGraph === false
  99. ? []
  100. : [
  101. {
  102. kind: "toolCall",
  103. rowId: "row-1",
  104. toolCallId: "tool-wf-1",
  105. toolName: "CreateWorkflow",
  106. status: "success",
  107. inputText: "",
  108. display: {
  109. kind: "create_workflow",
  110. ok: true,
  111. errorCount: 0,
  112. diagnostics: [],
  113. causalityGraph: GRAPH,
  114. },
  115. },
  116. ],
  117. },
  118. ...(options.run ? { workflowRuns: { revision: 1, runs: [options.run] } } : {}),
  119. };
  120. }
  121. const NODES: V4ConversationWorkflowRunWorkspaceResult["nodes"] = [
  122. {
  123. siteId: "world-read#1",
  124. ordinal: 1,
  125. kind: "world-read",
  126. op: "glob",
  127. args: ["src/**/*.ts"],
  128. status: "completed",
  129. summary: { resultBytes: 30, resultCount: 2 },
  130. createdAt: 1_000,
  131. updatedAt: 1_120,
  132. },
  133. {
  134. siteId: "world-read#1",
  135. ordinal: 2,
  136. kind: "world-read",
  137. op: "read",
  138. args: ["src/a.ts"],
  139. status: "completed",
  140. summary: { resultBytes: 20 },
  141. createdAt: 1_200,
  142. updatedAt: 1_210,
  143. },
  144. {
  145. siteId: "world-read#2",
  146. ordinal: 1,
  147. kind: "world-run",
  148. op: "run",
  149. args: ["pnpm", ["test"]],
  150. status: "completed",
  151. summary: { resultBytes: 60, exitCode: 1, stdoutBytes: 9, stderrBytes: 4 },
  152. createdAt: 2_000,
  153. updatedAt: 3_300,
  154. },
  155. {
  156. siteId: "world-read#2",
  157. ordinal: 2,
  158. kind: "world-run",
  159. op: "run",
  160. args: ["pnpm", ["test"]],
  161. status: "running",
  162. createdAt: 4_000,
  163. updatedAt: 4_000,
  164. },
  165. ];
  166. function renderPane(tab = tabOf(), locale: "en-US" | "zh-CN" = "en-US") {
  167. return render(
  168. createElement(
  169. ZCodeIntlProvider,
  170. { initialLocale: locale },
  171. createElement(WorkflowWorkspaceSidePane, { tab, focused: true, onOpenCodeViewer }),
  172. ),
  173. );
  174. }
  175. beforeEach(() => {
  176. cleanup();
  177. resetWorkflowRunNodeResultCache();
  178. resetWorkspaceEntryOpenState();
  179. layer.acquire.mockClear();
  180. release.mockClear();
  181. onOpenCodeViewer.mockClear();
  182. workflowRunWorkspace.mockReset();
  183. workflowRunNodeResult.mockReset();
  184. workflowRunWorkspace.mockResolvedValue({ nodes: NODES });
  185. workflowRunNodeResult.mockResolvedValue({
  186. status: "completed",
  187. result: { exitCode: 1, stdout: "1 failed\n", stderr: "boom" },
  188. truncated: false,
  189. totalBytes: 60,
  190. });
  191. setSnapshot({ run: run() });
  192. });
  193. describe("WorkflowWorkspaceSidePane", () => {
  194. it("订阅父会话、按 run 查清单,卡片按执行顺序、按 op 分种类", async () => {
  195. const view = renderPane();
  196. expect(layer.acquire).toHaveBeenCalledWith("parent-a");
  197. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-card")).toHaveLength(4));
  198. expect(workflowRunWorkspace).toHaveBeenCalledWith({ sessionId: "parent-a", runId: "dwfrun-1" });
  199. const cards = view.getAllByTestId("workflow-workspace-card");
  200. expect(cards.map((card) => card.getAttribute("data-site-id"))).toEqual([
  201. "world-read#1",
  202. "world-read#1",
  203. "world-read#2",
  204. "world-read#2",
  205. ]);
  206. // 两行条目:动词 + 对象,然后结果行;右侧是相对第一张卡的时刻。
  207. expect(cards[0]!.textContent).toContain("Searched");
  208. expect(cards[0]!.textContent).toContain("src/**/*.ts");
  209. expect(cards[0]!.textContent).toContain("2 files");
  210. expect(cards[1]!.textContent).toContain("Read");
  211. expect(cards[1]!.textContent).toContain("a.ts");
  212. expect(cards[2]!.textContent).toContain("Ran");
  213. expect(cards[2]!.textContent).toContain("pnpm test");
  214. const whenOf = (card: HTMLElement) =>
  215. card.querySelector('[data-testid="workflow-workspace-when"]')!.textContent;
  216. expect(cards.map(whenOf)).toEqual(["+0:00", "+0:00", "+0:01", "now"]);
  217. // running 的那张:动词说「Running」并扫光,结果行说开始于多久前。
  218. expect(cards[3]!.textContent).toContain("Running");
  219. expect(cards[3]!.textContent).toContain("started");
  220. expect(cards[3]!.querySelector(".wf-ws-shine")).toBeTruthy();
  221. expect(cards[3]!.getAttribute("data-status")).toBe("running");
  222. // Read 不可展开;其余是按钮语义。
  223. expect(cards[1]!.getAttribute("role")).toBeNull();
  224. expect(cards[2]!.getAttribute("role")).toBe("button");
  225. // 首批依次到场:每张错 24 ms。
  226. expect(cards[1]!.style.animationDelay).toBe("24ms");
  227. });
  228. it("阶段是章:章头带名字、步数与时长,卡按执行顺序落在章里;图不可得时没有章头", async () => {
  229. const view = renderPane();
  230. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-card")).toHaveLength(4));
  231. const chapters = view.getAllByTestId("workflow-workspace-chapter");
  232. expect(chapters.map((chapter) => chapter.getAttribute("data-phase-id"))).toEqual([
  233. "phase#a",
  234. "phase#b",
  235. ]);
  236. expect(chapters[0]!.textContent).toContain("plan");
  237. expect(chapters[0]!.textContent).toContain("2 steps");
  238. expect(chapters[1]!.textContent).toContain("verify");
  239. const cards = view.getAllByTestId("workflow-workspace-card");
  240. expect(cards[0]!.getAttribute("data-phase-id")).toBe("phase#a");
  241. expect(cards[2]!.getAttribute("data-phase-id")).toBe("phase#b");
  242. // 表头第二行:整本日志簿的三个数。
  243. const summary = view.getByTestId("workflow-workspace-summary").textContent;
  244. expect(summary).toContain("2 phases");
  245. expect(summary).toContain("4 steps");
  246. cleanup();
  247. setSnapshot({ run: run(), withGraph: false });
  248. const bare = renderPane();
  249. await waitFor(() => expect(bare.getAllByTestId("workflow-workspace-card")).toHaveLength(4));
  250. expect(bare.queryByTestId("workflow-workspace-chapter")).toBeNull();
  251. expect(bare.getAllByTestId("workflow-workspace-card")[0]!.hasAttribute("data-phase-id")).toBe(
  252. false,
  253. );
  254. expect(bare.getByTestId("workflow-workspace-summary").textContent).not.toContain("phases");
  255. });
  256. it("状态词:跑完的命令说 exit n,非零红;失败行说 code(超时说 timed out)", async () => {
  257. workflowRunWorkspace.mockResolvedValue({
  258. nodes: [
  259. NODES[2]!,
  260. {
  261. ...NODES[3]!,
  262. status: "failed",
  263. error: { code: "DriverError", message: "command timed out after 300000ms" },
  264. },
  265. ],
  266. });
  267. const view = renderPane();
  268. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-status")).toHaveLength(2));
  269. const [exit, timedOut] = view.getAllByTestId("workflow-workspace-status");
  270. expect(exit!.textContent).toBe("exit 1");
  271. expect(exit!.getAttribute("data-failed")).toBe("true");
  272. expect(exit!.className).toContain("text-destructive");
  273. expect(timedOut!.textContent).toBe("timed out");
  274. });
  275. it("收起的命令露出输出的尾巴(peek,正文按卡取一次);展开是完整面板:$ 命令行、stdout、单独成段的 stderr、页脚 + Copy", async () => {
  276. const view = renderPane();
  277. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-card")).toHaveLength(4));
  278. // 只有跑完的命令取正文(jsdom 没有 IntersectionObserver → 视作立刻可见);running 的不取。
  279. await waitFor(() => expect(workflowRunNodeResult).toHaveBeenCalledTimes(1));
  280. expect(workflowRunNodeResult).toHaveBeenCalledWith({
  281. sessionId: "parent-a",
  282. runId: "dwfrun-1",
  283. siteId: "world-read#2",
  284. ordinal: 1,
  285. });
  286. const terminal = view.getAllByTestId("workflow-workspace-card")[2]!;
  287. const peek = () => terminal.querySelector('[data-testid="workflow-workspace-peek"]');
  288. await waitFor(() => expect(peek()!.textContent).toContain("1 failed"));
  289. expect(terminal.querySelector('[data-testid="workflow-workspace-card-body"]')).toBeNull();
  290. await act(async () => {
  291. fireEvent.click(terminal);
  292. });
  293. await waitFor(() => expect(view.getByTestId("workflow-workspace-card-footer")).toBeTruthy());
  294. // 展开不再读:peek 已经把正文放进缓存。
  295. expect(workflowRunNodeResult).toHaveBeenCalledTimes(1);
  296. expect(terminal.getAttribute("aria-expanded")).toBe("true");
  297. expect(peek()).toBeNull();
  298. const body = view.getByTestId("workflow-workspace-card-body");
  299. expect(body.textContent).toContain("pnpm test");
  300. expect(body.textContent).toContain("1 failed");
  301. expect(view.getByTestId("workflow-workspace-stderr").textContent).toContain("boom");
  302. const footer = view.getByTestId("workflow-workspace-card-footer");
  303. expect(footer.textContent).toContain("exit 1");
  304. expect(footer.textContent).toContain("1.3s");
  305. expect(footer.textContent).toContain("9 B");
  306. expect(footer.querySelector('[data-testid="workflow-workspace-copy"]')).toBeTruthy();
  307. // 正文里的点击不折叠。
  308. await act(async () => {
  309. fireEvent.click(body);
  310. });
  311. expect(terminal.getAttribute("aria-expanded")).toBe("true");
  312. // 键盘:Enter 收起。
  313. await act(async () => {
  314. fireEvent.keyDown(terminal, { key: "Enter" });
  315. });
  316. expect(terminal.getAttribute("aria-expanded")).toBe("false");
  317. });
  318. it("Read 卡只有摘要行:不可展开,文件芯片开代码查看器(相对路径补成工作区绝对路径)", async () => {
  319. const view = renderPane();
  320. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-card")).toHaveLength(4));
  321. const read = view.getAllByTestId("workflow-workspace-card")[1]!;
  322. const chip = read.querySelector("button[title]")!;
  323. fireEvent.click(chip);
  324. expect(onOpenCodeViewer).toHaveBeenCalledWith({
  325. type: "file",
  326. title: "a.ts",
  327. path: "/workspace/src/a.ts",
  328. });
  329. // Read 从不取正文(只有那条跑完的命令为 peek 取过)。
  330. expect(workflowRunNodeResult).not.toHaveBeenCalledWith(
  331. expect.objectContaining({ siteId: "world-read#1" }),
  332. );
  333. });
  334. it("活投影说是缓存命中的行带 replayed 芯片", async () => {
  335. setSnapshot({
  336. run: run({
  337. nodes: [
  338. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok", cached: true },
  339. ] as WorkflowRunState["nodes"],
  340. }),
  341. });
  342. const view = renderPane();
  343. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-replayed")).toHaveLength(1));
  344. expect(view.getAllByTestId("workflow-workspace-card")[0]!.textContent).toContain("replayed");
  345. });
  346. it("落点:从一站开滚到该站的第一张卡并亮一下;还没到的站滚到末尾", async () => {
  347. const scrolled: string[] = [];
  348. Element.prototype.scrollIntoView = function scrollIntoView() {
  349. scrolled.push((this as HTMLElement).getAttribute("data-site-id") ?? "?");
  350. };
  351. const view = renderPane(tabOf({ focusPhaseId: "phase#b" }));
  352. await waitFor(() => expect(scrolled).toEqual(["world-read#2"]));
  353. const landed = view.getAllByTestId("workflow-workspace-card")[2]!;
  354. expect(landed.className).toContain("wf-ws-landed");
  355. expect(view.getAllByTestId("workflow-workspace-card")[0]!.className).not.toContain(
  356. "wf-ws-landed",
  357. );
  358. cleanup();
  359. const toEnd = vi.fn();
  360. HTMLElement.prototype.scrollTo = toEnd as never;
  361. renderPane(tabOf({ focusPhaseId: "phase#zzz" }));
  362. await waitFor(() => expect(toEnd).toHaveBeenCalled());
  363. });
  364. it("表头:终端瓦片 · SCRIPT 眉题 · run 名 · run 灯与词;清单到齐前没有第二行", async () => {
  365. const view = renderPane();
  366. expect(view.getByTestId("workflow-workspace-title").textContent).toBe("Fan-out review");
  367. expect(view.getByTestId("workflow-workspace-run-status").textContent).toBe("Running");
  368. expect(view.getByTestId("workflow-workspace-pane").textContent).toContain("Script");
  369. expect(view.queryByTestId("workflow-workspace-summary")).toBeNull();
  370. await waitFor(() => expect(view.getByTestId("workflow-workspace-summary")).toBeTruthy());
  371. });
  372. it("整个 run 还没碰过工作区:占位,双语可读", async () => {
  373. workflowRunWorkspace.mockResolvedValue({ nodes: [] });
  374. const en = renderPane();
  375. await waitFor(() => expect(en.getByTestId("workflow-workspace-not-started")).toBeTruthy());
  376. expect(en.getByTestId("workflow-workspace-not-started").textContent).toContain(
  377. "The script has not run anything yet",
  378. );
  379. cleanup();
  380. const zh = renderPane(tabOf(), "zh-CN");
  381. await waitFor(() => expect(zh.getByTestId("workflow-workspace-not-started")).toBeTruthy());
  382. expect(zh.getByTestId("workflow-workspace-not-started").textContent).toContain(
  383. "脚本还没执行任何步骤",
  384. );
  385. });
  386. it("能力缺席(老 CLI):说清读不到,而不是当成空 run", async () => {
  387. workflowRunWorkspace.mockRejectedValue(new Error("fault.command.capabilityUnsupported"));
  388. const view = renderPane();
  389. await waitFor(() => expect(view.getByTestId("workflow-workspace-unavailable")).toBeTruthy());
  390. expect(view.queryByTestId("workflow-workspace-not-started")).toBeNull();
  391. });
  392. it("清单被网关截尾时页尾说明只显示前 N 步", async () => {
  393. workflowRunWorkspace.mockResolvedValue({ nodes: NODES, truncated: true });
  394. const view = renderPane();
  395. await waitFor(() => expect(view.getByTestId("workflow-workspace-truncated")).toBeTruthy());
  396. expect(view.getByTestId("workflow-workspace-truncated").textContent).toContain("first 4 steps");
  397. });
  398. });