automationEditSessionCreatedDirtyState.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. // @vitest-environment jsdom
  2. import { createElement, type ReactNode } from "react";
  3. import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  4. import {
  5. TID_AUTOMATION_SCHEDULE_ADD,
  6. TID_AUTOMATION_SCHEDULE_PREVIEW,
  7. type ZCodeAutomation,
  8. type ModelSelection,
  9. } from "@zcode/shared";
  10. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  11. const stableHookValues = vi.hoisted(() => ({
  12. configResult: { configOptions: [] },
  13. projectOptions: [] as Array<{
  14. workspacePath: string;
  15. workspaceIdentity?: string;
  16. remoteSessionId?: string;
  17. remoteTarget?: { type: "ssh"; host: string };
  18. label: string;
  19. workspacePurpose?: "project" | "conversation";
  20. }>,
  21. modelSelectionView: null as typeof modelSelectionView | null,
  22. modelSelectionTargets: [] as Array<{
  23. workspacePath: string | null | undefined;
  24. remoteSessionId?: string | null;
  25. workspaceIdentity?: string | null;
  26. remoteTarget?: unknown;
  27. }>,
  28. selectRegistrations: 0,
  29. effectiveSelection: undefined as ModelSelection | null | undefined,
  30. selectionInputs: [] as Array<{ selection: ModelSelection | null } | undefined>,
  31. locale: "zh-CN" as "zh-CN" | "en-US",
  32. services: { zcodeAgentService: {} },
  33. }));
  34. vi.mock("@/components/ui/select.js", async () => {
  35. const { createElement: h, useEffect } = await import("react");
  36. const passthrough = ({ children }: { children?: ReactNode }) => h("div", null, children);
  37. return {
  38. Select: ({
  39. children,
  40. onValueChange,
  41. value,
  42. }: {
  43. children?: ReactNode;
  44. onValueChange?: (value: string) => void;
  45. value?: string;
  46. }) => {
  47. useEffect(() => {
  48. const timer = window.setTimeout(() => {
  49. // 模拟 Radix Select 受控值与子项注册竞争、在表单初始化完成后发出的空值:
  50. // 这不是用户操作,消费方必须丢弃值域外的回调
  51. // (回归:仅打开详情返回就弹未保存提示)。
  52. onValueChange?.("");
  53. if (
  54. value &&
  55. ["hourly", "daily", "weekdays", "weekly", "monthly", "custom"].includes(value)
  56. ) {
  57. stableHookValues.selectRegistrations += 1;
  58. onValueChange?.(value);
  59. }
  60. }, 0);
  61. return () => window.clearTimeout(timer);
  62. }, []);
  63. return h("div", null, children);
  64. },
  65. SelectContent: passthrough,
  66. SelectItem: passthrough,
  67. SelectTrigger: passthrough,
  68. SelectValue: passthrough,
  69. };
  70. });
  71. vi.mock("@/settings/SettingsHeaderBreadcrumb.js", async () => {
  72. const { createElement: h } = await import("react");
  73. return {
  74. SettingsBreadcrumbReporter: ({
  75. items,
  76. onSectionSelect,
  77. }: {
  78. items: Array<{ label: string }>;
  79. onSectionSelect?: () => void;
  80. }) =>
  81. h(
  82. "button",
  83. {
  84. "data-testid": "automation-edit-breadcrumb-section",
  85. onClick: onSectionSelect,
  86. type: "button",
  87. },
  88. items[0]?.label,
  89. ),
  90. };
  91. });
  92. vi.mock("@/components/ui/dialog.js", async () => {
  93. const { createElement: h } = await import("react");
  94. const passthrough = ({ children }: { children?: ReactNode }) => h("div", null, children);
  95. return {
  96. Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
  97. open ? h("div", null, children) : null,
  98. DialogClose: passthrough,
  99. DialogContent: passthrough,
  100. DialogDescription: passthrough,
  101. DialogFooter: passthrough,
  102. DialogHeader: passthrough,
  103. DialogTitle: passthrough,
  104. };
  105. });
  106. vi.mock("@/components/ui/dropdown-menu.js", async () => {
  107. const { createElement: h } = await import("react");
  108. const passthrough = ({ children }: { children?: ReactNode }) => h("div", null, children);
  109. return {
  110. DropdownMenu: passthrough,
  111. DropdownMenuContent: passthrough,
  112. DropdownMenuItem: passthrough,
  113. DropdownMenuSeparator: () => h("hr"),
  114. DropdownMenuTrigger: passthrough,
  115. };
  116. });
  117. vi.mock("@/components/ui/popover.js", async () => {
  118. const { createElement: h } = await import("react");
  119. const passthrough = ({ children }: { children?: ReactNode }) => h("div", null, children);
  120. return {
  121. Popover: passthrough,
  122. PopoverContent: passthrough,
  123. PopoverTrigger: passthrough,
  124. };
  125. });
  126. vi.mock("@/components/ui/tooltip.js", async () => {
  127. const { createElement: h } = await import("react");
  128. const passthrough = ({ children }: { children?: ReactNode }) => h("div", null, children);
  129. return {
  130. Tooltip: passthrough,
  131. TooltipContent: passthrough,
  132. TooltipProvider: passthrough,
  133. TooltipTrigger: passthrough,
  134. };
  135. });
  136. vi.mock("@/ControlHintTooltip.js", () => ({
  137. ControlHintTooltip: ({ children }: { children: ReactNode }) => children,
  138. }));
  139. // 权限选择器复用会话 composer 的 ConfigSelect:这里保留真实实现,让上方 Select mock
  140. // 发出的注册竞争空值穿过它,守住“值域外回调不得标记未保存修改”的防护。
  141. vi.mock("@/chat-input-toolbar/RollingToolbarLabel.js", () => ({
  142. RollingToolbarLabel: ({ label }: { label: string }) => label,
  143. }));
  144. vi.mock("@/ModelConfigSelect.js", async () => {
  145. const { createElement: h } = await import("react");
  146. return {
  147. ModelConfigSelect: ({ triggerLabel }: { triggerLabel?: string }) =>
  148. h("span", { "data-testid": "automation-model-trigger-label" }, triggerLabel),
  149. };
  150. });
  151. vi.mock("@/chat-input-toolbar/ThoughtLevelCycleControl.js", () => ({
  152. ThoughtLevelCycleControl: () => null,
  153. }));
  154. vi.mock("@/ChatEmptyState.js", () => ({
  155. ChatEmptyWorkspacePreviewMenu: ({
  156. workspaceTabs,
  157. onSelectWorkspace,
  158. }: {
  159. workspaceTabs: Array<{ workspacePath: string; workspaceIdentity?: string; label: string }>;
  160. onSelectWorkspace: (workspace: {
  161. workspacePath: string;
  162. workspaceIdentity?: string;
  163. label: string;
  164. }) => void;
  165. }) =>
  166. createElement(
  167. "div",
  168. null,
  169. workspaceTabs.map((workspace) =>
  170. createElement(
  171. "button",
  172. {
  173. key: workspace.workspaceIdentity ?? workspace.workspacePath,
  174. type: "button",
  175. onClick: () => onSelectWorkspace(workspace),
  176. },
  177. workspace.label,
  178. ),
  179. ),
  180. ),
  181. }));
  182. vi.mock("@/hooks/useAutomationProjectOptions.js", () => ({
  183. useAutomationProjectOptions: () => stableHookValues.projectOptions,
  184. }));
  185. vi.mock("@/hooks/useZCodeConfig.js", () => ({
  186. useToolbarConfigOptions: () => stableHookValues.configResult,
  187. }));
  188. vi.mock("@/hooks/useServices.js", () => ({
  189. useOptionalServices: () => null,
  190. useServices: () => stableHookValues.services,
  191. }));
  192. vi.mock("@/hooks/useModelSelectionView.js", () => ({
  193. useModelSelectionView: (
  194. workspacePath: string | null | undefined,
  195. remoteSessionId?: string | null,
  196. workspaceIdentity?: string | null,
  197. remoteTarget?: unknown,
  198. input?: { selection: ModelSelection | null },
  199. ) => {
  200. stableHookValues.selectionInputs.push(input);
  201. stableHookValues.modelSelectionTargets.push({
  202. workspacePath,
  203. remoteSessionId,
  204. workspaceIdentity,
  205. remoteTarget,
  206. });
  207. return {
  208. state: stableHookValues.modelSelectionView
  209. ? {
  210. status: "ready" as const,
  211. view: {
  212. ...stableHookValues.modelSelectionView,
  213. ...(input
  214. ? {
  215. effectiveSelection:
  216. stableHookValues.effectiveSelection === undefined
  217. ? input.selection
  218. : stableHookValues.effectiveSelection,
  219. }
  220. : {}),
  221. },
  222. }
  223. : { status: "loading" as const },
  224. reload: vi.fn(),
  225. };
  226. },
  227. }));
  228. vi.mock("@/i18n/IntlProvider.js", () => ({
  229. useZCodeIntl: () => ({
  230. intl: {
  231. formatMessage: ({ id }: { id: string }) => {
  232. if (id === "automations.edit.titlePlaceholder") {
  233. return stableHookValues.locale === "zh-CN" ? "未命名定时任务" : "Untitled Automation";
  234. }
  235. return id;
  236. },
  237. },
  238. }),
  239. }));
  240. import { AutomationEditView } from "@/settings/AutomationEditView.js";
  241. const modelSelectionView = {
  242. revision: 1,
  243. providers: [
  244. {
  245. providerId: "provider",
  246. providerName: "DeepSeek Provider",
  247. config: {
  248. api: { type: "openai-chat-completions", baseUrl: "https://example.test" },
  249. },
  250. models: [
  251. {
  252. modelId: "deepseek-v4-flash",
  253. config: {
  254. optionSpecs: {
  255. reasoningLevel: { values: ["low", "high"], map: "{}" },
  256. maxOutputTokens: { max: 32_000, map: "{}" },
  257. },
  258. },
  259. },
  260. ],
  261. },
  262. ],
  263. };
  264. const sessionCreatedAutomation: ZCodeAutomation = {
  265. automationId: "automation-session-created",
  266. title: "每 10 分钟提醒",
  267. cronExpr: "*/10 * * * *",
  268. prompt: "提醒用户休息",
  269. model: "provider/deepseek-v4-flash",
  270. modelSelection: {
  271. providerId: "provider",
  272. modelId: "deepseek-v4-flash",
  273. options: { reasoningLevel: "low" },
  274. },
  275. mode: "edit",
  276. thoughtLevel: "low",
  277. workspaceKey: "/workspace",
  278. workspacePath: "/workspace",
  279. targetTaskId: "session-from-chat",
  280. locationKind: "local",
  281. recurring: true,
  282. scheduleRule: {
  283. unit: "minute",
  284. interval: 10,
  285. hour: 16,
  286. minute: 49,
  287. anchorAt: 1_784_887_300_020,
  288. weekdays: [1],
  289. monthDays: [1],
  290. monthlyMode: "date",
  291. },
  292. runCount: 0,
  293. enabled: true,
  294. lifecycleStatus: "active",
  295. dispatchStatus: "idle",
  296. dispatchAttempts: 0,
  297. createdAt: 1,
  298. updatedAt: 1,
  299. };
  300. const uiCreatedAutomation: ZCodeAutomation = {
  301. ...sessionCreatedAutomation,
  302. automationId: "automation-ui-created",
  303. };
  304. delete uiCreatedAutomation.targetTaskId;
  305. const sessionCreatedUiResetAutomation: ZCodeAutomation = {
  306. ...sessionCreatedAutomation,
  307. automationId: "automation-session-created-ui-reset",
  308. cronExpr: "0 9 * * *",
  309. scheduleRule: undefined,
  310. scheduleEditedByUser: true,
  311. };
  312. beforeEach(() => {
  313. stableHookValues.selectRegistrations = 0;
  314. stableHookValues.locale = "zh-CN";
  315. stableHookValues.projectOptions.length = 0;
  316. stableHookValues.modelSelectionView = null;
  317. stableHookValues.modelSelectionTargets.length = 0;
  318. stableHookValues.effectiveSelection = undefined;
  319. stableHookValues.selectionInputs.length = 0;
  320. Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
  321. configurable: true,
  322. value: vi.fn(),
  323. });
  324. });
  325. afterEach(cleanup);
  326. describe("AutomationEditView session-created dirty state", () => {
  327. it("原账号选择只派生展示,主动保存才采用有效选择", async () => {
  328. stableHookValues.modelSelectionView = modelSelectionView;
  329. stableHookValues.effectiveSelection = uiCreatedAutomation.modelSelection;
  330. const original = {
  331. ...uiCreatedAutomation.modelSelection!,
  332. providerId: "account:bigmodel-individual-coding-plan",
  333. };
  334. const editing = { ...uiCreatedAutomation, modelSelection: original };
  335. const onSubmit = vi.fn(async () => true);
  336. render(
  337. createElement(AutomationEditView, {
  338. editing,
  339. defaultWorkspacePath: "/workspace",
  340. saving: false,
  341. onSubmit,
  342. onBack: vi.fn(),
  343. }),
  344. );
  345. await waitFor(() =>
  346. expect(stableHookValues.selectionInputs.at(-1)).toEqual({ selection: original }),
  347. );
  348. expect(screen.getByTestId("automation-model-trigger-label").textContent).toBe(
  349. "DeepSeek Provider/deepseek-v4-flash",
  350. );
  351. expect(onSubmit).not.toHaveBeenCalled();
  352. expect(editing.modelSelection).toEqual(original);
  353. fireEvent.click(screen.getByRole("button", { name: "automations.form.save" }));
  354. await waitFor(() =>
  355. expect(onSubmit).toHaveBeenCalledWith(
  356. expect.objectContaining({
  357. input: expect.objectContaining({ modelSelection: uiCreatedAutomation.modelSelection }),
  358. }),
  359. ),
  360. );
  361. expect(editing.modelSelection).toEqual(original);
  362. });
  363. it("新建任务的自动默认标题会随语言切换更新且不覆盖用户输入", () => {
  364. const props = {
  365. editing: null,
  366. defaultWorkspacePath: "/workspace",
  367. saving: false,
  368. onSubmit: vi.fn(async () => true),
  369. onBack: vi.fn(),
  370. };
  371. const { rerender } = render(createElement(AutomationEditView, props));
  372. const titleInput = screen.getByLabelText<HTMLInputElement>("automations.form.title.label");
  373. expect(titleInput.value).toBe("未命名定时任务");
  374. stableHookValues.locale = "en-US";
  375. rerender(createElement(AutomationEditView, props));
  376. expect(titleInput.value).toBe("Untitled Automation");
  377. fireEvent.click(screen.getByTestId("automation-edit-breadcrumb-section"));
  378. expect(props.onBack).toHaveBeenCalledOnce();
  379. fireEvent.change(titleInput, { target: { value: "Keep my title" } });
  380. stableHookValues.locale = "zh-CN";
  381. rerender(createElement(AutomationEditView, props));
  382. expect(titleInput.value).toBe("Keep my title");
  383. });
  384. it("模板值进入表单后成为普通草稿,语言切换不覆盖用户编辑", () => {
  385. const props = {
  386. editing: null,
  387. initialDraft: {
  388. title: "远程模板标题",
  389. cronExpr: "0 9 * * 1-5",
  390. prompt: "远程模板指令",
  391. },
  392. defaultWorkspacePath: "/workspace",
  393. modelProviders: [],
  394. saving: false,
  395. onSubmit: vi.fn(async () => true),
  396. onBack: vi.fn(),
  397. };
  398. const { rerender } = render(createElement(AutomationEditView, props));
  399. const titleInput = screen.getByLabelText<HTMLInputElement>("automations.form.title.label");
  400. const promptInput = screen.getByLabelText<HTMLTextAreaElement>("automations.form.prompt.label");
  401. fireEvent.change(titleInput, { target: { value: "用户标题" } });
  402. fireEvent.change(promptInput, { target: { value: "用户编辑后的指令" } });
  403. stableHookValues.locale = "en-US";
  404. rerender(createElement(AutomationEditView, props));
  405. expect(titleInput.value).toBe("用户标题");
  406. expect(promptInput.value).toBe("用户编辑后的指令");
  407. });
  408. it("编辑任务时模型触发器与会话侧一致显示 providerName/modelName", () => {
  409. stableHookValues.modelSelectionView = modelSelectionView;
  410. render(
  411. createElement(AutomationEditView, {
  412. editing: sessionCreatedAutomation,
  413. defaultWorkspacePath: "/workspace",
  414. saving: false,
  415. onSubmit: vi.fn(async () => true),
  416. onBack: vi.fn(),
  417. }),
  418. );
  419. expect(screen.getByTestId("automation-model-trigger-label").textContent).toBe(
  420. "DeepSeek Provider/deepseek-v4-flash",
  421. );
  422. });
  423. it("切换目标项目后从对应 Host 读取模型视图且携带远程路由", async () => {
  424. stableHookValues.projectOptions.push(
  425. { workspacePath: "/local", label: "local" },
  426. {
  427. workspacePath: "/remote/project",
  428. workspaceIdentity: "ssh:server:/remote/project",
  429. remoteSessionId: "remote-session",
  430. remoteTarget: { type: "ssh", host: "server" },
  431. label: "remote",
  432. },
  433. );
  434. render(
  435. createElement(AutomationEditView, {
  436. editing: null,
  437. defaultWorkspacePath: "/local",
  438. saving: false,
  439. onSubmit: vi.fn(async () => true),
  440. onBack: vi.fn(),
  441. }),
  442. );
  443. fireEvent.click(screen.getByRole("button", { name: "remote" }));
  444. await waitFor(() => {
  445. expect(stableHookValues.modelSelectionTargets.at(-1)).toEqual({
  446. workspacePath: "/remote/project",
  447. remoteSessionId: "remote-session",
  448. workspaceIdentity: "ssh:server:/remote/project",
  449. remoteTarget: { type: "ssh", host: "server" },
  450. });
  451. });
  452. });
  453. it("编辑无项目任务时继续展示会话侧文案与图标", () => {
  454. const conversationWorkspacePath = "/Users/test/.zcode/workspace/default";
  455. stableHookValues.projectOptions.push({
  456. workspacePath: conversationWorkspacePath,
  457. label: "default",
  458. workspacePurpose: "conversation",
  459. });
  460. const conversationAutomation: ZCodeAutomation = {
  461. ...uiCreatedAutomation,
  462. workspaceKey: conversationWorkspacePath,
  463. workspacePath: conversationWorkspacePath,
  464. };
  465. const { container } = render(
  466. createElement(AutomationEditView, {
  467. editing: conversationAutomation,
  468. defaultWorkspacePath: "/workspace",
  469. saving: false,
  470. onSubmit: vi.fn(async () => true),
  471. onBack: vi.fn(),
  472. }),
  473. );
  474. const workspaceLabel = screen.getByText("chat.empty.workOutsideProject");
  475. const workspaceButton = workspaceLabel.closest("button");
  476. expect(workspaceButton?.querySelector(".lucide-message-circle")).not.toBeNull();
  477. expect(workspaceButton?.querySelector(".lucide-folder-open")).toBeNull();
  478. expect(container.textContent).not.toContain("default");
  479. });
  480. it("会话创建的分钟计划只显示自定义且仅打开返回不提示保存", async () => {
  481. const onBack = vi.fn();
  482. render(
  483. createElement(AutomationEditView, {
  484. editing: sessionCreatedAutomation,
  485. defaultWorkspacePath: "/workspace",
  486. saving: false,
  487. onSubmit: vi.fn(async () => true),
  488. onBack,
  489. }),
  490. );
  491. expect(screen.getByTestId(TID_AUTOMATION_SCHEDULE_PREVIEW).textContent).toBe(
  492. "automations.schedule.customMinutes",
  493. );
  494. expect(screen.queryByText("automations.customRepeat.compactFrequency")).not.toBeNull();
  495. expect(stableHookValues.selectRegistrations).toBe(0);
  496. // 等 Select 注册竞争的空值回调发出后再返回,复现“仅打开详情就被标记未保存”的回归。
  497. await act(async () => {
  498. await new Promise((resolve) => setTimeout(resolve, 5));
  499. });
  500. fireEvent.click(screen.getByRole("button", { name: sessionCreatedAutomation.title }));
  501. expect(onBack).toHaveBeenCalledOnce();
  502. expect(screen.queryByText("automations.unsaved.title")).toBeNull();
  503. });
  504. it("UI 创建的相同分钟计划仍使用可视化调度控件", async () => {
  505. render(
  506. createElement(AutomationEditView, {
  507. editing: uiCreatedAutomation,
  508. defaultWorkspacePath: "/workspace",
  509. saving: false,
  510. onSubmit: vi.fn(async () => true),
  511. onBack: vi.fn(),
  512. }),
  513. );
  514. await waitFor(() => {
  515. expect(screen.getByText("automations.customRepeat.compactFrequency")).toBeTruthy();
  516. expect(stableHookValues.selectRegistrations).toBeGreaterThan(0);
  517. });
  518. expect(screen.getByText("automations.customRepeat.compactFrequency")).toBeTruthy();
  519. });
  520. it("会话创建任务由用户重设调度后,重新打开仍恢复可视化调度控件", async () => {
  521. render(
  522. createElement(AutomationEditView, {
  523. editing: sessionCreatedUiResetAutomation,
  524. defaultWorkspacePath: "/workspace",
  525. saving: false,
  526. onSubmit: vi.fn(async () => true),
  527. onBack: vi.fn(),
  528. }),
  529. );
  530. await waitFor(() => {
  531. expect(stableHookValues.selectRegistrations).toBeGreaterThan(0);
  532. });
  533. expect(screen.getByTestId(TID_AUTOMATION_SCHEDULE_PREVIEW).textContent).toBe(
  534. "automations.schedule.daily",
  535. );
  536. });
  537. it("删除会话来源的自定义调度后切换到 UI 调度入口", () => {
  538. render(
  539. createElement(AutomationEditView, {
  540. editing: sessionCreatedAutomation,
  541. defaultWorkspacePath: "/workspace",
  542. saving: false,
  543. onSubmit: vi.fn(async () => true),
  544. onBack: vi.fn(),
  545. }),
  546. );
  547. fireEvent.click(screen.getByRole("button", { name: "common.delete" }));
  548. expect(screen.getByTestId(TID_AUTOMATION_SCHEDULE_ADD)).toBeTruthy();
  549. expect(screen.queryByText("automations.customRepeat.compactFrequency")).toBeNull();
  550. });
  551. });