savedWorkflowGlobalGroup.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // @vitest-environment jsdom
  2. // 全局工作流组(docs/dynamic-workflow/launch.md):顶部固定「全局」组,空也显示;载体走
  3. // useServices().zcodeAgentService,RPC 带 { scope: "global" }。卡片 / 实参窗 / 移动窗 / 详情页换桩,
  4. // 只看组的状态流与全局语义(运行带 scope、修订 / 创建落到本地项目、移到项目、-32602 提示、运行行项目列)。
  5. import { createElement } from "react";
  6. import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  7. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  8. import {
  9. TID_WORKFLOWS_CREATE_VIA_CHAT,
  10. TID_WORKFLOWS_LIST,
  11. TID_WORKFLOW_ACTION_DELETE,
  12. TID_WORKFLOW_ACTION_MOVE,
  13. TID_WORKFLOW_CARD,
  14. TID_WORKFLOW_CARD_RUN,
  15. TID_WORKFLOW_DETAIL,
  16. TID_WORKFLOW_GLOBAL_GROUP,
  17. testId,
  18. type ZCodeSavedWorkflowEntry,
  19. type ZCodeSavedWorkflowRun,
  20. type ZCodeWorkflowsListResult,
  21. } from "@zcode/shared";
  22. import type { AutomationWorkspaceOption } from "@/settings/automationWorkspaceOptions.js";
  23. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  24. import { resetSavedWorkflowStoreForTests } from "@/store/savedWorkflowStore.js";
  25. const confirmMock = vi.fn(async () => true);
  26. const toastMock = vi.fn();
  27. const fileWatcherService = {
  28. watch: vi.fn(async () => ({ id: "watch-1" })),
  29. onDynamicChange: vi.fn(() => () => ({ dispose: vi.fn() })),
  30. unwatch: vi.fn(async () => {}),
  31. };
  32. const listResult: { current: ZCodeWorkflowsListResult | (() => never) } = {
  33. current: { workflows: [], invalid: [], dir: "/home/.zcode/workflows" },
  34. };
  35. const runsResult: { current: ZCodeSavedWorkflowRun[] } = { current: [] };
  36. const agent = {
  37. listSavedWorkflows: vi.fn(async () => {
  38. const value = listResult.current;
  39. if (typeof value === "function") return value();
  40. return value;
  41. }),
  42. listSavedWorkflowRuns: vi.fn(async () => ({ runs: runsResult.current })),
  43. deleteSavedWorkflow: vi.fn(async () => ({
  44. ok: true as const,
  45. path: "/home/.zcode/workflows/x.dwf.ts",
  46. })),
  47. moveSavedWorkflow: vi.fn(async () => ({
  48. ok: true as const,
  49. from: "/home/.zcode/workflows/x.dwf.ts",
  50. to: "/a/.zcode/workflows/x.dwf.ts",
  51. })),
  52. getSavedWorkflow: vi.fn(),
  53. updateSavedWorkflowMeta: vi.fn(),
  54. };
  55. vi.mock("@/hooks/useServices.js", () => ({
  56. useServices: () => ({ zcodeAgentService: agent, fileWatcherService }),
  57. }));
  58. vi.mock("@/hooks/useConfirmDialog.js", () => ({ useConfirmDialog: () => confirmMock }));
  59. vi.mock("@/components/ui/toast.js", () => ({ toast: (...args: unknown[]) => toastMock(...args) }));
  60. vi.mock("@/ControlHintTooltip.js", () => ({
  61. ControlHintTooltip: ({ children }: { children: unknown }) => children,
  62. }));
  63. vi.mock("@/settings/saved-workflows/SavedWorkflowCard.js", () => ({
  64. SavedWorkflowCard: ({
  65. entry,
  66. onOpen,
  67. onRun,
  68. onRevise,
  69. onMove,
  70. onDelete,
  71. }: {
  72. entry: ZCodeSavedWorkflowEntry;
  73. onOpen: (entry: ZCodeSavedWorkflowEntry) => void;
  74. onRun: (entry: ZCodeSavedWorkflowEntry) => void;
  75. onRevise: (entry: ZCodeSavedWorkflowEntry) => void;
  76. onMove?: (entry: ZCodeSavedWorkflowEntry) => void;
  77. onDelete: (entry: ZCodeSavedWorkflowEntry) => void;
  78. }) =>
  79. createElement(
  80. "div",
  81. { "data-testid": testId(TID_WORKFLOW_CARD, entry.name) },
  82. entry.name,
  83. createElement(
  84. "button",
  85. { type: "button", "data-testid": `open-${entry.name}`, onClick: () => onOpen(entry) },
  86. "open",
  87. ),
  88. createElement(
  89. "button",
  90. {
  91. type: "button",
  92. "data-testid": testId(TID_WORKFLOW_CARD_RUN, entry.name),
  93. onClick: () => onRun(entry),
  94. },
  95. "run",
  96. ),
  97. createElement(
  98. "button",
  99. { type: "button", "data-testid": `revise-${entry.name}`, onClick: () => onRevise(entry) },
  100. "revise",
  101. ),
  102. onMove
  103. ? createElement(
  104. "button",
  105. {
  106. type: "button",
  107. "data-testid": testId(TID_WORKFLOW_ACTION_MOVE, entry.name),
  108. onClick: () => onMove(entry),
  109. },
  110. "move",
  111. )
  112. : null,
  113. createElement(
  114. "button",
  115. {
  116. type: "button",
  117. "data-testid": testId(TID_WORKFLOW_ACTION_DELETE, entry.name),
  118. onClick: () => onDelete(entry),
  119. },
  120. "delete",
  121. ),
  122. ),
  123. }));
  124. // 直接启动器换桩:组只负责按类型开窗 / 直发;launch 编排与导航由 useSavedWorkflowLauncher 单测覆盖。
  125. const launchMock = vi.fn(async () => ({
  126. ok: true as const,
  127. sessionId: "s-1",
  128. runId: "r-1",
  129. toolCallId: "launch-1",
  130. }));
  131. const clearErrorMock = vi.fn();
  132. vi.mock("@/settings/saved-workflows/useSavedWorkflowLauncher.js", () => ({
  133. useSavedWorkflowLauncher: () => ({
  134. launch: launchMock,
  135. pending: false,
  136. error: null,
  137. clearError: clearErrorMock,
  138. }),
  139. }));
  140. vi.mock("@/settings/saved-workflows/SavedWorkflowLaunchDialog.js", () => ({
  141. SavedWorkflowLaunchDialog: ({
  142. entry,
  143. targets,
  144. defaultTargetKey,
  145. onSubmit,
  146. }: {
  147. entry: ZCodeSavedWorkflowEntry | null;
  148. targets?: readonly AutomationWorkspaceOption[];
  149. defaultTargetKey?: string | null;
  150. onSubmit: (
  151. entry: ZCodeSavedWorkflowEntry,
  152. args: Record<string, unknown>,
  153. target?: AutomationWorkspaceOption,
  154. ) => void;
  155. }) =>
  156. entry
  157. ? createElement(
  158. "div",
  159. {
  160. "data-testid": "launch-dialog",
  161. "data-targets": (targets ?? []).map((t) => t.workspacePath).join(","),
  162. "data-default": defaultTargetKey ?? "",
  163. },
  164. createElement(
  165. "button",
  166. {
  167. type: "button",
  168. "data-testid": "launch-submit",
  169. onClick: () => onSubmit(entry, {}, targets?.[0]),
  170. },
  171. "go",
  172. ),
  173. )
  174. : null,
  175. }));
  176. vi.mock("@/settings/saved-workflows/SavedWorkflowMoveDialog.js", () => ({
  177. SavedWorkflowMoveDialog: ({
  178. open,
  179. targets,
  180. onSubmit,
  181. }: {
  182. open: boolean;
  183. targets: readonly AutomationWorkspaceOption[];
  184. onSubmit: (target: AutomationWorkspaceOption) => void;
  185. }) =>
  186. open
  187. ? createElement(
  188. "div",
  189. { "data-testid": "move-dialog" },
  190. createElement(
  191. "button",
  192. {
  193. type: "button",
  194. "data-testid": "move-submit",
  195. onClick: () => targets[0] && onSubmit(targets[0]),
  196. },
  197. "move",
  198. ),
  199. )
  200. : null,
  201. }));
  202. vi.mock("@/settings/saved-workflows/SavedWorkflowDetailView.js", () => ({
  203. SavedWorkflowDetailView: ({
  204. name,
  205. projectLabel,
  206. runs,
  207. resolveRunProject,
  208. onMove,
  209. }: {
  210. name: string;
  211. projectLabel: string;
  212. runs: readonly ZCodeSavedWorkflowRun[];
  213. resolveRunProject?: (run: ZCodeSavedWorkflowRun) => { label: string; canOpen: boolean } | null;
  214. onMove?: () => void;
  215. }) =>
  216. createElement(
  217. "div",
  218. { "data-testid": TID_WORKFLOW_DETAIL, "data-name": name, "data-project": projectLabel },
  219. ...runs.map((run) => {
  220. const project = resolveRunProject ? resolveRunProject(run) : null;
  221. return createElement("div", {
  222. key: run.runId,
  223. "data-testid": `run-${run.runId}`,
  224. "data-run-project": project?.label ?? "",
  225. "data-run-canopen": project?.canOpen ? "yes" : "no",
  226. });
  227. }),
  228. createElement(
  229. "button",
  230. { type: "button", "data-testid": "detail-move", onClick: () => onMove?.() },
  231. "move",
  232. ),
  233. ),
  234. }));
  235. const { SavedWorkflowGlobalGroup } =
  236. await import("@/settings/saved-workflows/SavedWorkflowGlobalGroup.js");
  237. function entry(
  238. name: string,
  239. overrides: Partial<ZCodeSavedWorkflowEntry> = {},
  240. ): ZCodeSavedWorkflowEntry {
  241. return {
  242. name,
  243. description: `${name} 的说明`,
  244. scope: "global",
  245. path: `/home/.zcode/workflows/${name}.dwf.ts`,
  246. ...overrides,
  247. };
  248. }
  249. const ALPHA: AutomationWorkspaceOption = { workspacePath: "/a", label: "Alpha" };
  250. const keyOfA = "/a";
  251. function mount(props: Partial<Parameters<typeof SavedWorkflowGlobalGroup>[0]> = {}) {
  252. const onNavigateToLaunchedRun = vi.fn();
  253. const onCreateViaChat = vi.fn();
  254. const onOpenWorkflowRun = vi.fn();
  255. const onStateChange = vi.fn();
  256. const onOpenDetail = vi.fn();
  257. const onBack = vi.fn();
  258. const onMoved = vi.fn();
  259. const utils = render(
  260. createElement(
  261. ZCodeIntlProvider,
  262. { initialLocale: "zh-CN" },
  263. createElement(SavedWorkflowGlobalGroup, {
  264. refreshSeq: 0,
  265. mode: { kind: "list" },
  266. onStateChange,
  267. onOpenDetail,
  268. onBack,
  269. onNavigateToLaunchedRun,
  270. onCreateViaChat,
  271. onOpenWorkflowRun,
  272. localProjects: [ALPHA],
  273. activeProjectKey: keyOfA,
  274. onMoved,
  275. ...props,
  276. }),
  277. ),
  278. );
  279. return {
  280. ...utils,
  281. onNavigateToLaunchedRun,
  282. onCreateViaChat,
  283. onOpenWorkflowRun,
  284. onStateChange,
  285. onOpenDetail,
  286. onBack,
  287. onMoved,
  288. };
  289. }
  290. describe("SavedWorkflowGlobalGroup", () => {
  291. beforeEach(() => {
  292. resetSavedWorkflowStoreForTests();
  293. listResult.current = { workflows: [], invalid: [], dir: "/home/.zcode/workflows" };
  294. runsResult.current = [];
  295. vi.clearAllMocks();
  296. confirmMock.mockResolvedValue(true);
  297. });
  298. afterEach(() => {
  299. cleanup();
  300. });
  301. it("空也渲染:头行「全局」+ 副标 +「通过对话创建」,正文一行空态;回报 { loaded:true, empty:true }", async () => {
  302. const { onStateChange } = mount();
  303. await screen.findByTestId(TID_WORKFLOW_GLOBAL_GROUP);
  304. expect(screen.getByText("全局")).toBeTruthy();
  305. expect(screen.getByText("对所有项目可见")).toBeTruthy();
  306. expect(screen.getByTestId(testId(TID_WORKFLOWS_CREATE_VIA_CHAT, "global"))).toBeTruthy();
  307. expect(screen.getByText(/还没有全局工作流/)).toBeTruthy();
  308. await waitFor(() =>
  309. expect(onStateChange).toHaveBeenLastCalledWith("global", {
  310. loaded: true,
  311. empty: true,
  312. count: 0,
  313. }),
  314. );
  315. // RPC 带 scope: "global"(无 workspace)
  316. expect(agent.listSavedWorkflows).toHaveBeenCalledWith({ scope: "global" });
  317. expect(agent.listSavedWorkflowRuns).toHaveBeenCalledWith({ scope: "global", limit: 50 });
  318. });
  319. it("有货:列出卡片,头行数量;运行始终弹实参窗,提交带 scope:global 的文案与选中项目", async () => {
  320. listResult.current = {
  321. workflows: [entry("research")],
  322. invalid: [],
  323. dir: "/home/.zcode/workflows",
  324. };
  325. mount();
  326. await screen.findByTestId(testId(TID_WORKFLOWS_LIST, "global"));
  327. // 无实参也弹窗
  328. fireEvent.click(screen.getByTestId(testId(TID_WORKFLOW_CARD_RUN, "research")));
  329. const dialog = await screen.findByTestId("launch-dialog");
  330. expect(dialog.getAttribute("data-targets")).toBe("/a");
  331. expect(dialog.getAttribute("data-default")).toBe(keyOfA);
  332. fireEvent.click(screen.getByTestId("launch-submit"));
  333. await waitFor(() => expect(launchMock).toHaveBeenCalledTimes(1));
  334. // 全局档直接启动:目标 = 选中的「运行于」项目,scope = global。
  335. expect(launchMock.mock.calls[0]?.[0]).toEqual({ workspacePath: "/a" });
  336. expect(launchMock.mock.calls[0]?.[1]).toEqual({ name: "research", scope: "global", args: {} });
  337. });
  338. it("「通过对话创建」落到活动本地项目,文案为全局;修订同理", async () => {
  339. listResult.current = {
  340. workflows: [entry("research")],
  341. invalid: [],
  342. dir: "/home/.zcode/workflows",
  343. };
  344. const { onCreateViaChat } = mount();
  345. await screen.findByTestId(testId(TID_WORKFLOW_CARD, "research"));
  346. fireEvent.click(screen.getByTestId(testId(TID_WORKFLOWS_CREATE_VIA_CHAT, "global")));
  347. expect(onCreateViaChat.mock.calls[0]?.[1]).toEqual({ workspacePath: "/a" });
  348. expect(onCreateViaChat.mock.calls[0]?.[0]).toContain('scope: "global"');
  349. fireEvent.click(screen.getByTestId("revise-research"));
  350. expect(onCreateViaChat.mock.calls[1]?.[0]).toContain("请修订已保存的工作流");
  351. expect(onCreateViaChat.mock.calls[1]?.[1]).toEqual({ workspacePath: "/a" });
  352. });
  353. it("没有本地项目时:创建按钮禁用,运行提交无 target 不发起", async () => {
  354. listResult.current = {
  355. workflows: [entry("research")],
  356. invalid: [],
  357. dir: "/home/.zcode/workflows",
  358. };
  359. const { onCreateViaChat } = mount({ localProjects: [], activeProjectKey: null });
  360. await screen.findByTestId(testId(TID_WORKFLOW_CARD, "research"));
  361. expect(
  362. (screen.getByTestId(testId(TID_WORKFLOWS_CREATE_VIA_CHAT, "global")) as HTMLButtonElement)
  363. .disabled,
  364. ).toBe(true);
  365. fireEvent.click(screen.getByTestId(testId(TID_WORKFLOW_CARD_RUN, "research")));
  366. fireEvent.click(await screen.findByTestId("launch-submit")); // targets 为空,target undefined
  367. expect(launchMock).not.toHaveBeenCalled();
  368. expect(onCreateViaChat).not.toHaveBeenCalled();
  369. });
  370. it("删除:确认后带 scope:global 调 delete 并 toast", async () => {
  371. listResult.current = {
  372. workflows: [entry("research")],
  373. invalid: [],
  374. dir: "/home/.zcode/workflows",
  375. };
  376. mount();
  377. await screen.findByTestId(testId(TID_WORKFLOW_CARD, "research"));
  378. fireEvent.click(screen.getByTestId(testId(TID_WORKFLOW_ACTION_DELETE, "research")));
  379. await waitFor(() =>
  380. expect(agent.deleteSavedWorkflow).toHaveBeenCalledWith({ scope: "global", name: "research" }),
  381. );
  382. expect(toastMock).toHaveBeenCalledWith("已删除工作流「research」");
  383. });
  384. it("移到项目:move 窗提交 → move(目标项目, 无 to) 成功 toast + onMoved", async () => {
  385. listResult.current = {
  386. workflows: [entry("research")],
  387. invalid: [],
  388. dir: "/home/.zcode/workflows",
  389. };
  390. const { onMoved } = mount();
  391. await screen.findByTestId(testId(TID_WORKFLOW_CARD, "research"));
  392. fireEvent.click(screen.getByTestId(testId(TID_WORKFLOW_ACTION_MOVE, "research")));
  393. fireEvent.click(await screen.findByTestId("move-submit"));
  394. await waitFor(() =>
  395. expect(agent.moveSavedWorkflow).toHaveBeenCalledWith({
  396. workspacePath: "/a",
  397. name: "research",
  398. }),
  399. );
  400. await waitFor(() => expect(onMoved).toHaveBeenCalledTimes(1));
  401. expect(toastMock).toHaveBeenCalledWith("已移到 Alpha");
  402. });
  403. it("移到项目:target_exists → toast 目标已有同名,不 onMoved", async () => {
  404. listResult.current = {
  405. workflows: [entry("research")],
  406. invalid: [],
  407. dir: "/home/.zcode/workflows",
  408. };
  409. agent.moveSavedWorkflow.mockResolvedValueOnce({
  410. ok: false as const,
  411. reason: "target_exists" as const,
  412. } as never);
  413. const { onMoved } = mount();
  414. await screen.findByTestId(testId(TID_WORKFLOW_CARD, "research"));
  415. fireEvent.click(screen.getByTestId(testId(TID_WORKFLOW_ACTION_MOVE, "research")));
  416. fireEvent.click(await screen.findByTestId("move-submit"));
  417. await waitFor(() => expect(agent.moveSavedWorkflow).toHaveBeenCalledTimes(1));
  418. expect(toastMock).toHaveBeenCalledWith("目标位置已有同名工作流");
  419. expect(onMoved).not.toHaveBeenCalled();
  420. });
  421. it("详情:projectLabel=「全局」,运行行项目列——cwd 命中本地项目→label 可开,否则 basename 不可开", async () => {
  422. listResult.current = {
  423. workflows: [entry("research")],
  424. invalid: [],
  425. dir: "/home/.zcode/workflows",
  426. };
  427. runsResult.current = [
  428. {
  429. runId: "r-a",
  430. name: "research",
  431. status: "completed",
  432. createdAt: 1,
  433. updatedAt: 2,
  434. spentTokens: 0,
  435. cwd: "/a",
  436. parentSessionId: "s1",
  437. toolCallId: "t1",
  438. },
  439. {
  440. runId: "r-x",
  441. name: "research",
  442. status: "completed",
  443. createdAt: 3,
  444. updatedAt: 4,
  445. spentTokens: 0,
  446. cwd: "/somewhere/other",
  447. },
  448. ];
  449. mount({ mode: { kind: "detail", name: "research" } });
  450. const detail = await screen.findByTestId(TID_WORKFLOW_DETAIL);
  451. expect(detail.getAttribute("data-project")).toBe("全局");
  452. await waitFor(() => expect(screen.getByTestId("run-r-a")).toBeTruthy());
  453. expect(screen.getByTestId("run-r-a").getAttribute("data-run-project")).toBe("Alpha");
  454. expect(screen.getByTestId("run-r-a").getAttribute("data-run-canopen")).toBe("yes");
  455. expect(screen.getByTestId("run-r-x").getAttribute("data-run-project")).toBe("other");
  456. expect(screen.getByTestId("run-r-x").getAttribute("data-run-canopen")).toBe("no");
  457. });
  458. it("旧 agent 不支持(-32602):正文显示「当前 agent 不支持全局工作流」", async () => {
  459. listResult.current = () => {
  460. throw Object.assign(new Error("Invalid params"), { code: -32602 });
  461. };
  462. mount();
  463. await waitFor(() => expect(screen.getByText(/当前 agent 不支持全局工作流/)).toBeTruthy());
  464. });
  465. });