workflowRunSettingsPopover.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. // @vitest-environment jsdom
  2. // 「配置」弹层(docs/dynamic-workflow/presentation.md「The settings popover」)与 run 卡上的 Configure 钮
  3. // (「The run card」)、转写里的设置行(「The settings turn」):真实 DOM 上钉字段、后果句、Apply 发出去的
  4. // 载荷、被拒的那一行,以及卡上按钮的位置与门控。纯规则在 workflowRunSettings.test.ts 里穷举。
  5. import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  6. import { createElement, createRef, type ReactNode } from "react";
  7. import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
  8. import { TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER } from "@zcode/shared";
  9. import type { CommandAck, WorkflowRunState } from "@zcode/shared/zcode-protocol-v4";
  10. import type { WorkflowRunCardSummary } from "@/ToolCallBlocks/shared.js";
  11. vi.mock("@/logger.js", () => ({ logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() } }));
  12. vi.mock("@/ControlHintTooltip.js", () => ({
  13. ControlHintTooltip: ({ children }: { children?: ReactNode }) => children,
  14. }));
  15. vi.mock("@/hooks/useWorkflowSubagentModelProviderName.js", () => ({
  16. useWorkflowSubagentModelProviderName: () => undefined,
  17. }));
  18. /** 模型清单:一个 provider、两个模型,其中一个有思考档。 */
  19. const VIEW = {
  20. revision: 1,
  21. providers: [
  22. {
  23. providerId: "zhipu",
  24. providerName: "Zhipu",
  25. config: { api: { type: "openai-chat-completions" } },
  26. models: [
  27. {
  28. modelId: "glm-5.3",
  29. config: { optionSpecs: { reasoningLevel: { values: [], map: "{}" } } },
  30. },
  31. {
  32. modelId: "glm-5.3-flash",
  33. config: { optionSpecs: { reasoningLevel: { values: ["low", "high"], map: "{}" } } },
  34. },
  35. ],
  36. },
  37. ],
  38. };
  39. const modelRead = vi.hoisted(() => ({
  40. state: { status: "ready", view: null as unknown } as { status: string; view?: unknown },
  41. }));
  42. vi.mock("@/hooks/useModelSelectionView.js", () => ({
  43. useModelSelectionView: () => ({ state: modelRead.state, reload: vi.fn() }),
  44. }));
  45. // eslint-disable-next-line import/first -- 必须在 mock 之后再引入被测组件。
  46. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  47. // eslint-disable-next-line import/first
  48. import {
  49. WorkflowRunSettingsPopover,
  50. type WorkflowRunSettingsHost,
  51. } from "@/components/workflow-timeline/WorkflowRunSettingsPopover.js";
  52. // eslint-disable-next-line import/first
  53. import { WorkflowRunDigest } from "@/components/workflow-timeline/WorkflowRunDigest.js";
  54. // eslint-disable-next-line import/first
  55. import { ConversationWorkflowDigests } from "@/v4/ConversationWorkflowDigests.js";
  56. // eslint-disable-next-line import/first
  57. import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
  58. beforeAll(() => {
  59. // Radix Popper 量尺寸用 ResizeObserver;jsdom 没有。
  60. globalThis.ResizeObserver ??= class {
  61. observe() {}
  62. unobserve() {}
  63. disconnect() {}
  64. } as unknown as typeof ResizeObserver;
  65. });
  66. beforeEach(() => {
  67. modelRead.state = { status: "ready", view: VIEW };
  68. });
  69. afterEach(() => {
  70. cleanup();
  71. });
  72. function runState(overrides: Partial<WorkflowRunState> = {}): WorkflowRunState {
  73. return {
  74. runId: "run-a",
  75. toolCallId: "tool-a",
  76. status: "running",
  77. usage: { spentTokens: 0, nodesUsed: 0 },
  78. actors: [],
  79. nodes: [],
  80. lastEventSequence: 0,
  81. concurrencyCeiling: 13,
  82. ...overrides,
  83. };
  84. }
  85. function hostWith(apply: (change: unknown) => Promise<CommandAck>): WorkflowRunSettingsHost {
  86. return {
  87. workspacePath: "/w",
  88. sessionModel: { providerId: "zhipu", modelId: "glm-5.3" },
  89. apply: apply as WorkflowRunSettingsHost["apply"],
  90. };
  91. }
  92. function renderPopover(
  93. run: WorkflowRunState,
  94. options: {
  95. locale?: "en-US" | "zh-CN";
  96. apply?: (change: unknown) => Promise<CommandAck>;
  97. onAccepted?: (accepted: unknown) => void;
  98. onOpenChange?: (open: boolean) => void;
  99. } = {},
  100. ) {
  101. const anchor = document.createElement("button");
  102. document.body.appendChild(anchor);
  103. const anchorRef = createRef<HTMLElement | null>() as { current: HTMLElement | null };
  104. anchorRef.current = anchor;
  105. const apply = options.apply ?? vi.fn(async () => ({ status: "accepted" }) as CommandAck);
  106. return {
  107. apply,
  108. view: render(
  109. createElement(
  110. ZCodeIntlProvider,
  111. { initialLocale: options.locale ?? "en-US" },
  112. createElement(WorkflowRunSettingsPopover, {
  113. anchorRef,
  114. host: hostWith(apply),
  115. onOpenChange: options.onOpenChange ?? vi.fn(),
  116. open: true,
  117. run,
  118. ...(options.onAccepted === undefined ? {} : { onAccepted: options.onAccepted }),
  119. }),
  120. ),
  121. ),
  122. };
  123. }
  124. describe("WorkflowRunSettingsPopover 字段", () => {
  125. it("起点是 run 自己的设置:模型名、默认并发提示;什么都没改时没有后果句、Apply 禁用", () => {
  126. renderPopover(
  127. runState({
  128. subagentModel: "zhipu/glm-5.3",
  129. concurrency: { cap: 13, ceiling: 13, limit: 4 },
  130. }),
  131. );
  132. expect(screen.getByText("Configure workflow")).toBeTruthy();
  133. expect(screen.getByTestId("workflow-run-settings-model-trigger").textContent).toContain(
  134. "glm-5.3",
  135. );
  136. expect(screen.getByTestId<HTMLInputElement>("workflow-run-settings-bound-value").value).toBe(
  137. "4",
  138. );
  139. expect(screen.getByTestId("workflow-run-settings-bound").textContent).toContain("default 13");
  140. // 后果句那一行留着高度、但是空的:第一次改动时页脚不往下跳。
  141. expect(screen.getByTestId("workflow-run-settings-consequence").textContent).toBe("");
  142. expect(screen.getByTestId<HTMLButtonElement>("workflow-run-settings-apply").disabled).toBe(
  143. true,
  144. );
  145. // glm-5.3 没有思考档:不画思考档控件。
  146. expect(screen.queryByTestId(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER)).toBeNull();
  147. });
  148. it("后果句跟着改动走:在跑的 run 只改并发念「就地生效」,改回原值又空下来", () => {
  149. renderPopover(
  150. runState({
  151. subagentModel: "zhipu/glm-5.3",
  152. concurrency: { cap: 13, ceiling: 13, limit: 4 },
  153. }),
  154. );
  155. const consequence = () => screen.getByTestId("workflow-run-settings-consequence").textContent;
  156. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-decrease"));
  157. expect(consequence()).toBe("Applies to this run right away; no new run is started.");
  158. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-increase"));
  159. expect(consequence()).toBe("");
  160. expect(screen.getByTestId<HTMLButtonElement>("workflow-run-settings-apply").disabled).toBe(
  161. true,
  162. );
  163. });
  164. it("zh-CN:跑在会话模型上、上限在默认——触发器带「会话模型」徽标,提示念「= 默认」,加号仍可按", () => {
  165. renderPopover(runState({ status: "stopped", stopReason: "user", resumable: true }), {
  166. locale: "zh-CN",
  167. });
  168. expect(screen.getByText("配置工作流")).toBeTruthy();
  169. expect(screen.getByTestId("workflow-run-settings-model-badge").textContent).toBe("会话模型");
  170. expect(screen.getByTestId("workflow-run-settings-bound").textContent).toContain("= 默认");
  171. // 默认是起点不是天花板:停在默认上照样能往上加。
  172. expect(
  173. screen.getByTestId<HTMLButtonElement>("workflow-run-settings-bound-increase").disabled,
  174. ).toBe(false);
  175. expect(screen.getByTestId("workflow-run-settings-consequence").textContent).toBe("");
  176. // 改了才有后果句:停下的 run 不论改哪一项都是另起一次接着跑。
  177. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-increase"));
  178. expect(screen.getByTestId("workflow-run-settings-consequence").textContent).toBe(
  179. "将以新设置另起一次运行接着跑,已完成的步骤会保留。",
  180. );
  181. });
  182. it("有思考档的模型:触发器旁边出现思考档控件", () => {
  183. renderPopover(runState({ subagentModel: "zhipu/glm-5.3-flash$low" }));
  184. expect(screen.getByTestId(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER)).toBeTruthy();
  185. });
  186. it("run 的模型已不在清单里:「不可用」徽标,改了别的也不能 Apply(agent 只会回 model_unavailable)", () => {
  187. renderPopover(runState({ subagentModel: "gone/model-x" }));
  188. expect(screen.getByTestId("workflow-run-settings-model-badge").textContent).toBe("unavailable");
  189. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-decrease"));
  190. expect(screen.getByTestId<HTMLButtonElement>("workflow-run-settings-apply").disabled).toBe(
  191. true,
  192. );
  193. });
  194. it("agent 没有模型目录:模型那一格换成一句话,上限仍可调", () => {
  195. modelRead.state = { status: "ready", view: { revision: 1, providers: [] } };
  196. renderPopover(runState());
  197. expect(screen.getByTestId("workflow-run-settings-model").textContent).toContain(
  198. "This agent has no model catalog; subagents stay on the session model.",
  199. );
  200. expect(screen.getByTestId("workflow-run-settings-bound-decrease")).toBeTruthy();
  201. });
  202. it("默认未知(老 CLI):没有默认提示,数字可以直接敲", () => {
  203. renderPopover(runState({ concurrencyCeiling: undefined, concurrency: undefined }));
  204. const input = screen.getByTestId<HTMLInputElement>("workflow-run-settings-bound-value");
  205. expect(input.value).toBe("");
  206. expect(screen.getByTestId("workflow-run-settings-bound").textContent).not.toContain("default");
  207. fireEvent.change(input, { target: { value: "5" } });
  208. expect(input.value).toBe("5");
  209. expect(screen.getByTestId<HTMLButtonElement>("workflow-run-settings-apply").disabled).toBe(
  210. false,
  211. );
  212. });
  213. });
  214. describe("WorkflowRunSettingsPopover Apply", () => {
  215. it("只发改过的那一项;被接受即关、把新 run 的两把钥匙交出去", async () => {
  216. const onAccepted = vi.fn();
  217. const onOpenChange = vi.fn();
  218. const { apply } = renderPopover(
  219. runState({ subagentModel: "zhipu/glm-5.3", concurrency: { cap: 13, ceiling: 13, limit: 4 } }),
  220. {
  221. apply: vi.fn(
  222. async () =>
  223. ({
  224. status: "accepted",
  225. commandId: "c",
  226. revisionAtDecision: 0,
  227. result: {
  228. type: "amendWorkflowRunSettings",
  229. runId: "run-b",
  230. toolCallId: "settings-1",
  231. supersededRunId: "run-a",
  232. },
  233. }) as CommandAck,
  234. ),
  235. onAccepted,
  236. onOpenChange,
  237. },
  238. );
  239. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-decrease"));
  240. fireEvent.click(screen.getByTestId("workflow-run-settings-apply"));
  241. expect(apply).toHaveBeenCalledWith({ maxConcurrency: 3 });
  242. await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
  243. expect(onAccepted).toHaveBeenCalledWith({ runId: "run-b", toolCallId: "settings-1" });
  244. });
  245. it("从默认往上加:发出的是那个数,不是 null(默认是起点不是天花板)", async () => {
  246. const { apply } = renderPopover(runState(), {
  247. apply: vi.fn(
  248. async () =>
  249. ({
  250. status: "accepted",
  251. commandId: "c",
  252. revisionAtDecision: 0,
  253. result: { type: "amendWorkflowRunSettings", runId: "run-a", toolCallId: "settings-2" },
  254. }) as CommandAck,
  255. ),
  256. });
  257. expect(screen.getByTestId<HTMLInputElement>("workflow-run-settings-bound-value").value).toBe(
  258. "13",
  259. );
  260. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-increase"));
  261. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-increase"));
  262. expect(screen.getByTestId("workflow-run-settings-bound").textContent).toContain("default 13");
  263. await act(async () => {
  264. fireEvent.click(screen.getByTestId("workflow-run-settings-apply"));
  265. });
  266. expect(apply).toHaveBeenCalledWith({ maxConcurrency: 15 });
  267. });
  268. it("被拒:弹层不关,原因一行 + 诊断等宽块,Apply 重新可点;再改一个字段那一行就收起", async () => {
  269. const onOpenChange = vi.fn();
  270. renderPopover(runState({ concurrency: { cap: 13, ceiling: 13, limit: 4 } }), {
  271. apply: vi.fn(
  272. async () =>
  273. ({
  274. status: "rejected",
  275. commandId: "c",
  276. revisionAtDecision: 0,
  277. reasonCode: "fault.command.workflowRunSettingsRejected.compile_failed",
  278. message: "L3:C1 Property 'ask' does not exist",
  279. }) as CommandAck,
  280. ),
  281. onOpenChange,
  282. });
  283. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-increase"));
  284. await act(async () => {
  285. fireEvent.click(screen.getByTestId("workflow-run-settings-apply"));
  286. });
  287. const rejection = await screen.findByTestId("workflow-run-settings-rejection");
  288. expect(rejection.textContent).toContain("no longer compiles");
  289. expect(rejection.querySelector("pre")?.textContent).toBe("L3:C1 Property 'ask' does not exist");
  290. expect(onOpenChange).not.toHaveBeenCalled();
  291. expect(screen.getByTestId<HTMLButtonElement>("workflow-run-settings-apply").disabled).toBe(
  292. false,
  293. );
  294. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-increase"));
  295. expect(screen.queryByTestId("workflow-run-settings-rejection")).toBeNull();
  296. });
  297. it("zh-CN 的拒绝词:能力缺席", async () => {
  298. renderPopover(runState({ concurrency: { cap: 13, ceiling: 13, limit: 4 } }), {
  299. locale: "zh-CN",
  300. apply: vi.fn(
  301. async () =>
  302. ({
  303. status: "rejected",
  304. commandId: "c",
  305. revisionAtDecision: 0,
  306. reasonCode: "fault.command.capabilityUnsupported",
  307. }) as CommandAck,
  308. ),
  309. });
  310. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-increase"));
  311. await act(async () => {
  312. fireEvent.click(screen.getByTestId("workflow-run-settings-apply"));
  313. });
  314. expect((await screen.findByTestId("workflow-run-settings-rejection")).textContent).toBe(
  315. "当前 agent 不支持从这里调整工作流设置。",
  316. );
  317. });
  318. });
  319. function summaryOf(run: WorkflowRunState): WorkflowRunCardSummary {
  320. return {
  321. runId: run.runId,
  322. toolCallId: run.toolCallId,
  323. status: run.status,
  324. ...(run.stopReason === undefined ? {} : { stopReason: run.stopReason }),
  325. nodesSettled: 0,
  326. nodesTotal: 0,
  327. run,
  328. ...(run.resumable === true ? { resumable: true as const } : {}),
  329. };
  330. }
  331. describe("run 卡上的 Configure", () => {
  332. function renderCard(run: WorkflowRunState, withHost: boolean) {
  333. return render(
  334. createElement(
  335. ZCodeIntlProvider,
  336. { initialLocale: "en-US" },
  337. createElement(WorkflowRunDigest, {
  338. graph: undefined,
  339. name: "implement-verify",
  340. runId: run.runId,
  341. summary: summaryOf(run),
  342. testIdKey: "t",
  343. onCancel: vi.fn(),
  344. onResume: vi.fn(),
  345. onOpenRun: vi.fn(),
  346. ...(withHost ? { settingsHost: hostWith(vi.fn()) } : {}),
  347. }),
  348. ),
  349. );
  350. }
  351. it("在 Stop 之前、⤢ 之前;点它在自己下方开弹层,aria-expanded 跟着翻", () => {
  352. const view = renderCard(runState(), true);
  353. const configure = view.getByTestId("workflow-digest-configure");
  354. const cancel = view.getByTestId("workflow-digest-cancel");
  355. expect(
  356. configure.compareDocumentPosition(cancel) & Node.DOCUMENT_POSITION_FOLLOWING,
  357. ).toBeTruthy();
  358. expect(configure.getAttribute("aria-label")).toBe("Configure workflow");
  359. fireEvent.click(configure);
  360. expect(configure.getAttribute("aria-expanded")).toBe("true");
  361. expect(screen.getByTestId("workflow-run-settings-popover")).toBeTruthy();
  362. });
  363. it("点弹层里的空白不会让卡收起(弹层的点击不冒泡到卡身)", () => {
  364. const view = renderCard(runState(), true);
  365. fireEvent.click(view.getByTestId("workflow-digest-configure"));
  366. fireEvent.click(screen.getByTestId("workflow-run-settings-consequence"));
  367. expect(screen.getByTestId("workflow-run-settings-popover")).toBeTruthy();
  368. });
  369. it("宿主没给(只读、灰度关、run 不能配置)就没有这枚钮", () => {
  370. const view = renderCard(runState(), false);
  371. expect(view.queryByTestId("workflow-digest-configure")).toBeNull();
  372. });
  373. function renderDigests(
  374. run: WorkflowRunState,
  375. settings?: unknown,
  376. extra: Record<string, unknown> = {},
  377. ) {
  378. const onAmendWorkflowRunSettings = vi.fn(async () => ({ status: "accepted" }) as CommandAck);
  379. const view = render(
  380. createElement(
  381. ZCodeIntlProvider,
  382. { initialLocale: "zh-CN" },
  383. createElement(ConversationWorkflowDigests, {
  384. turnKey: "t",
  385. digests: [
  386. {
  387. key: "k",
  388. toolCallId: run.toolCallId ?? "tool-a",
  389. runId: run.runId,
  390. name: "implement-verify",
  391. graph: undefined,
  392. summary: summaryOf(run),
  393. ...(settings === undefined ? {} : { settings }),
  394. ...extra,
  395. } as never,
  396. ],
  397. context: {
  398. sessionId: "parent-a",
  399. workspacePath: "/w",
  400. onAmendWorkflowRunSettings,
  401. } as unknown as ConversationRowRenderContext,
  402. }),
  403. ),
  404. );
  405. return { view, onAmendWorkflowRunSettings };
  406. }
  407. it.each([
  408. ["running", runState(), true],
  409. ["errored", runState({ status: "errored" }), true],
  410. ["completed", runState({ status: "completed" }), false],
  411. [
  412. "superseded",
  413. runState({ status: "stopped", stopReason: "superseded", supersededBy: "run-b" }),
  414. false,
  415. ],
  416. ] as const)("接线层按 run 状态门控:%s", (_case, run, shown) => {
  417. const { view } = renderDigests(run);
  418. expect(view.queryByTestId("workflow-digest-configure") !== null).toBe(shown);
  419. });
  420. it("Apply 走宿主的 onAmendWorkflowRunSettings,带上这张卡的 runId", async () => {
  421. const { view, onAmendWorkflowRunSettings } = renderDigests(
  422. runState({ concurrency: { cap: 13, ceiling: 13, limit: 4 } }),
  423. );
  424. fireEvent.click(view.getByTestId("workflow-digest-configure"));
  425. fireEvent.click(screen.getByTestId("workflow-run-settings-bound-decrease"));
  426. await act(async () => {
  427. fireEvent.click(screen.getByTestId("workflow-run-settings-apply"));
  428. });
  429. expect(onAmendWorkflowRunSettings).toHaveBeenCalledWith("run-a", { maxConcurrency: 3 });
  430. });
  431. it("设置轮:卡上方一行「已调整设置 · …」,普通卡没有", () => {
  432. const { view } = renderDigests(runState({ runId: "run-b", toolCallId: "settings-1" }), {
  433. amend: {
  434. predecessorRunId: "run-a",
  435. subagentModel: { to: "zhipu/glm-5.3-flash" },
  436. maxConcurrency: { from: 13, to: 4 },
  437. ceiling: 13,
  438. },
  439. });
  440. const row = view.getByTestId("workflow-settings-change-row");
  441. expect(row.textContent).toContain("已调整设置");
  442. expect(row.textContent).toContain("子代理改用 glm-5.3-flash");
  443. expect(row.textContent).toContain("最多 4 个同时运行");
  444. cleanup();
  445. const plain = renderDigests(runState());
  446. expect(plain.view.queryByTestId("workflow-settings-change-row")).toBeNull();
  447. });
  448. // 就地生效的设置轮(docs/dynamic-workflow/presentation.md「The settings turn」):那一行是全部,
  449. // 它点名的 run 的卡在它启动的那一轮里——这里再画一张会读成第二次运行。
  450. it("就地生效的设置轮:只有那一行,没有卡", () => {
  451. const { view } = renderDigests(
  452. runState({ concurrency: { cap: 13, ceiling: 13, limit: 4 } }),
  453. { amend: { maxConcurrency: { from: 13, to: 4 }, ceiling: 13 } },
  454. { rowOnly: true },
  455. );
  456. const row = view.getByTestId("workflow-settings-change-row");
  457. expect(row.textContent).toContain("已调整设置");
  458. expect(row.textContent).toContain("最多 4 个同时运行");
  459. // 卡身、Configure 钮、Stop 钮:一个都不在。
  460. expect(view.queryByTestId("workflow-digest-configure")).toBeNull();
  461. expect(view.queryByTestId("workflow-digest-cancel")).toBeNull();
  462. expect(view.container.querySelector('[data-testid^="workflow-run-digest-"]')).toBeNull();
  463. });
  464. });