automationEditSessionCreatedDirtyState.test.ts 19 KB

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