workflowWorkspaceSidePane.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. // 章头的横线从左长出。
  240. expect(chapters[0]!.querySelector(".wf-ws-rule")).toBeTruthy();
  241. const cards = view.getAllByTestId("workflow-workspace-card");
  242. expect(cards[0]!.getAttribute("data-phase-id")).toBe("phase#a");
  243. expect(cards[2]!.getAttribute("data-phase-id")).toBe("phase#b");
  244. // 表头第二行:整本日志簿的三个数。
  245. const summary = view.getByTestId("workflow-workspace-summary").textContent;
  246. expect(summary).toContain("2 phases");
  247. expect(summary).toContain("4 steps");
  248. cleanup();
  249. setSnapshot({ run: run(), withGraph: false });
  250. const bare = renderPane();
  251. await waitFor(() => expect(bare.getAllByTestId("workflow-workspace-card")).toHaveLength(4));
  252. expect(bare.queryByTestId("workflow-workspace-chapter")).toBeNull();
  253. expect(bare.getAllByTestId("workflow-workspace-card")[0]!.hasAttribute("data-phase-id")).toBe(
  254. false,
  255. );
  256. expect(bare.getByTestId("workflow-workspace-summary").textContent).not.toContain("phases");
  257. });
  258. it("状态词:跑完的命令说 exit n,非零红;失败行说 code(超时说 timed out)", async () => {
  259. workflowRunWorkspace.mockResolvedValue({
  260. nodes: [
  261. NODES[2]!,
  262. {
  263. ...NODES[3]!,
  264. status: "failed",
  265. error: { code: "DriverError", message: "command timed out after 300000ms" },
  266. },
  267. ],
  268. });
  269. const view = renderPane();
  270. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-status")).toHaveLength(2));
  271. const [exit, timedOut] = view.getAllByTestId("workflow-workspace-status");
  272. expect(exit!.textContent).toBe("exit 1");
  273. expect(exit!.getAttribute("data-failed")).toBe("true");
  274. expect(exit!.className).toContain("text-destructive");
  275. expect(timedOut!.textContent).toBe("timed out");
  276. });
  277. it("收起的命令露出输出的尾巴(peek,正文按卡取一次);展开是完整面板:$ 命令行、stdout、单独成段的 stderr、页脚 + Copy", async () => {
  278. const view = renderPane();
  279. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-card")).toHaveLength(4));
  280. // 只有跑完的命令取正文(jsdom 没有 IntersectionObserver → 视作立刻可见);running 的不取。
  281. await waitFor(() => expect(workflowRunNodeResult).toHaveBeenCalledTimes(1));
  282. expect(workflowRunNodeResult).toHaveBeenCalledWith({
  283. sessionId: "parent-a",
  284. runId: "dwfrun-1",
  285. siteId: "world-read#2",
  286. ordinal: 1,
  287. });
  288. const terminal = view.getAllByTestId("workflow-workspace-card")[2]!;
  289. const peek = () => terminal.querySelector('[data-testid="workflow-workspace-peek"]');
  290. await waitFor(() => expect(peek()!.textContent).toContain("1 failed"));
  291. expect(terminal.querySelector('[data-testid="workflow-workspace-card-body"]')).toBeNull();
  292. await act(async () => {
  293. fireEvent.click(terminal);
  294. });
  295. await waitFor(() => expect(view.getByTestId("workflow-workspace-card-footer")).toBeTruthy());
  296. // 展开不再读:peek 已经把正文放进缓存。
  297. expect(workflowRunNodeResult).toHaveBeenCalledTimes(1);
  298. expect(terminal.getAttribute("aria-expanded")).toBe("true");
  299. expect(peek()).toBeNull();
  300. const body = view.getByTestId("workflow-workspace-card-body");
  301. expect(body.textContent).toContain("pnpm test");
  302. expect(body.textContent).toContain("1 failed");
  303. expect(view.getByTestId("workflow-workspace-stderr").textContent).toContain("boom");
  304. const footer = view.getByTestId("workflow-workspace-card-footer");
  305. expect(footer.textContent).toContain("exit 1");
  306. expect(footer.textContent).toContain("1.3s");
  307. expect(footer.textContent).toContain("9 B");
  308. expect(footer.querySelector('[data-testid="workflow-workspace-copy"]')).toBeTruthy();
  309. // 正文里的点击不折叠。
  310. await act(async () => {
  311. fireEvent.click(body);
  312. });
  313. expect(terminal.getAttribute("aria-expanded")).toBe("true");
  314. // 键盘:Enter 收起。
  315. await act(async () => {
  316. fireEvent.keyDown(terminal, { key: "Enter" });
  317. });
  318. expect(terminal.getAttribute("aria-expanded")).toBe("false");
  319. });
  320. it("Read 卡只有摘要行:不可展开,文件芯片开代码查看器(相对路径补成工作区绝对路径)", async () => {
  321. const view = renderPane();
  322. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-card")).toHaveLength(4));
  323. const read = view.getAllByTestId("workflow-workspace-card")[1]!;
  324. const chip = read.querySelector("button[title]")!;
  325. fireEvent.click(chip);
  326. expect(onOpenCodeViewer).toHaveBeenCalledWith({
  327. type: "file",
  328. title: "a.ts",
  329. path: "/workspace/src/a.ts",
  330. });
  331. // Read 从不取正文(只有那条跑完的命令为 peek 取过)。
  332. expect(workflowRunNodeResult).not.toHaveBeenCalledWith(
  333. expect.objectContaining({ siteId: "world-read#1" }),
  334. );
  335. });
  336. it("活投影说是缓存命中的行带 replayed 芯片", async () => {
  337. setSnapshot({
  338. run: run({
  339. nodes: [
  340. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok", cached: true },
  341. ] as WorkflowRunState["nodes"],
  342. }),
  343. });
  344. const view = renderPane();
  345. await waitFor(() => expect(view.getAllByTestId("workflow-workspace-replayed")).toHaveLength(1));
  346. expect(view.getAllByTestId("workflow-workspace-card")[0]!.textContent).toContain("replayed");
  347. });
  348. it("落点:从一站开滚到该站的第一张卡并亮一下;还没到的站滚到末尾", async () => {
  349. const scrolled: string[] = [];
  350. Element.prototype.scrollIntoView = function scrollIntoView() {
  351. scrolled.push((this as HTMLElement).getAttribute("data-site-id") ?? "?");
  352. };
  353. const view = renderPane(tabOf({ focusPhaseId: "phase#b" }));
  354. await waitFor(() => expect(scrolled).toEqual(["world-read#2"]));
  355. const landed = view.getAllByTestId("workflow-workspace-card")[2]!;
  356. expect(landed.className).toContain("wf-ws-landed");
  357. expect(view.getAllByTestId("workflow-workspace-card")[0]!.className).not.toContain(
  358. "wf-ws-landed",
  359. );
  360. cleanup();
  361. const toEnd = vi.fn();
  362. HTMLElement.prototype.scrollTo = toEnd as never;
  363. renderPane(tabOf({ focusPhaseId: "phase#zzz" }));
  364. await waitFor(() => expect(toEnd).toHaveBeenCalled());
  365. });
  366. it("表头:终端瓦片 · SCRIPT 眉题 · run 名 · run 灯与词;清单到齐前没有第二行", async () => {
  367. const view = renderPane();
  368. expect(view.getByTestId("workflow-workspace-title").textContent).toBe("Fan-out review");
  369. expect(view.getByTestId("workflow-workspace-run-status").textContent).toBe("Running");
  370. expect(view.getByTestId("workflow-workspace-pane").textContent).toContain("Script");
  371. expect(view.queryByTestId("workflow-workspace-summary")).toBeNull();
  372. await waitFor(() => expect(view.getByTestId("workflow-workspace-summary")).toBeTruthy());
  373. });
  374. it("整个 run 还没碰过工作区:占位,双语可读", async () => {
  375. workflowRunWorkspace.mockResolvedValue({ nodes: [] });
  376. const en = renderPane();
  377. await waitFor(() => expect(en.getByTestId("workflow-workspace-not-started")).toBeTruthy());
  378. expect(en.getByTestId("workflow-workspace-not-started").textContent).toContain(
  379. "The script has not run anything yet",
  380. );
  381. cleanup();
  382. const zh = renderPane(tabOf(), "zh-CN");
  383. await waitFor(() => expect(zh.getByTestId("workflow-workspace-not-started")).toBeTruthy());
  384. expect(zh.getByTestId("workflow-workspace-not-started").textContent).toContain(
  385. "脚本还没执行任何步骤",
  386. );
  387. });
  388. it("能力缺席(老 CLI):说清读不到,而不是当成空 run", async () => {
  389. workflowRunWorkspace.mockRejectedValue(new Error("fault.command.capabilityUnsupported"));
  390. const view = renderPane();
  391. await waitFor(() => expect(view.getByTestId("workflow-workspace-unavailable")).toBeTruthy());
  392. expect(view.queryByTestId("workflow-workspace-not-started")).toBeNull();
  393. });
  394. it("清单被网关截尾时页尾说明只显示前 N 步", async () => {
  395. workflowRunWorkspace.mockResolvedValue({ nodes: NODES, truncated: true });
  396. const view = renderPane();
  397. await waitFor(() => expect(view.getByTestId("workflow-workspace-truncated")).toBeTruthy());
  398. expect(view.getByTestId("workflow-workspace-truncated").textContent).toContain("first 4 steps");
  399. });
  400. });