off-peak-create-manage.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import { DatabaseSync } from "node:sqlite";
  2. import { join } from "node:path";
  3. import {
  4. TID_CONFIRM_DIALOG_CONFIRM,
  5. TID_OFFPEAK_ACTION_CONTINUE,
  6. TID_OFFPEAK_ACTION_DELETE,
  7. TID_OFFPEAK_ACTION_PAUSE,
  8. TID_OFFPEAK_CARD,
  9. TID_OFFPEAK_CARD_MENU,
  10. TID_OFFPEAK_CREATE_BUTTON,
  11. TID_OFFPEAK_EDIT_SUBMIT,
  12. TID_OFFPEAK_EDIT_VIEW,
  13. TID_OFFPEAK_FORM_INSTRUCTIONS,
  14. TID_OFFPEAK_FORM_TITLE,
  15. TID_OFFPEAK_TAB,
  16. TID_AUTOMATIONS_OPEN,
  17. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  18. TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM,
  19. testId,
  20. } from "@zcode/shared/test-ids";
  21. import {
  22. DEFAULT_WORKSPACE,
  23. clearAppData,
  24. clickTestIdByDom,
  25. clickTestIdByWebDriver,
  26. getE2EAppDataPaths,
  27. restoreElectronRendererContentSize,
  28. setInputValueByTestIdDom,
  29. setCurrentElectronRendererContentSize,
  30. type ElectronRendererContentSizeSnapshot,
  31. waitForTestIdByDom,
  32. } from "#e2e/helpers/desktop-app";
  33. import {
  34. ensureUpstreamModelForE2E,
  35. selectUpstreamModelById,
  36. UPSTREAM_SECONDARY_MODEL,
  37. } from "#e2e/helpers/upstream-provider";
  38. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  39. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  40. import {
  41. restartIntoWorkspace,
  42. seedBigModelConnectionSelection,
  43. seedBigModelOAuthCredential,
  44. } from "#e2e/helpers/model-provider-restart";
  45. let rendererSizeSnapshot: ElectronRendererContentSizeSnapshot | undefined;
  46. /**
  47. * 闲时任务「表单创建 → 列表回显 → Pause → Continue → 删除」端到端。
  48. *
  49. * 由进程内 mock 网关驱动(wdio.conf startOffPeakE2EMock 设 ZCODE_OFFPEAK_MOCK=1):
  50. * host 起网关、灰度强制开启、票据在本 spec 窗口内保持 queued。全程只碰 UI + 本地 sqlite
  51. * + 进程内网关的取号/状态接口,不派发模型请求,因此确定性。
  52. * 完整 run(派发→running→completed)、敏感批准、重启续跑见 coverage matrix 的 OPF/OPA/OPR。
  53. */
  54. describe("闲时任务表单创建与管理 E2E", () => {
  55. afterEach(async function () {
  56. if (this.currentTest?.state === "failed") {
  57. console.info("[SR87 idle diagnosis]", await browser.execute(() => document.body.innerText));
  58. }
  59. });
  60. after(async () => {
  61. if (rendererSizeSnapshot) {
  62. await restoreElectronRendererContentSize(rendererSizeSnapshot);
  63. }
  64. await browser.electron.restoreAllMocks();
  65. await clearAppData();
  66. });
  67. it("表单创建闲时任务后列表回显,可 Pause / Continue 并删除", async function () {
  68. this.timeout(150000);
  69. // 登录 + workspace 就绪即可进入 Automations 主视图;mock 网关免真实 provider。
  70. await prepareV4ConversationE2E({ skipProvider: true });
  71. await seedCurrentAccount();
  72. // 修复原因:Electron 41 不支持 WebDriver window/rect;通过 BrowserWindow 固定宽屏,
  73. // 才能稳定验证 Tooltip 首选右侧时不会因窄窗碰撞策略翻转。
  74. // 只固定宽度以命中右侧 Tooltip 布局;高度受 macOS work area 限制,不能硬编码 960px。
  75. rendererSizeSnapshot = await setCurrentElectronRendererContentSize(1440);
  76. // 1) 打开 Automations 主视图(侧栏入口)。
  77. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  78. timeoutMsg: "侧栏没有出现 Automations 入口",
  79. });
  80. // 2) 创建入口按页签展示;先进入闲时任务,不能在 scheduled 页签找闲时创建按钮。
  81. // 空列表没有 tab,直接显示两类创建入口;已有任务时才按页签分流。
  82. if (await browser.$(`[data-testid="${TID_OFFPEAK_TAB}"]`).isExisting())
  83. await selectIdleTimeTab();
  84. await clickTestIdByDom(TID_OFFPEAK_CREATE_BUTTON, {
  85. timeoutMsg: "闲时任务创建按钮没有出现(灰度未命中?)",
  86. });
  87. // 3) 模型可预选,档位必须显式选择,不能依赖历史自动补默认的行为。
  88. await selectOffPeakReasoning();
  89. const title = `E2E_OFFPEAK_${Date.now()}`;
  90. await setInputValueByTestIdDom(TID_OFFPEAK_FORM_TITLE, title, {
  91. timeoutMsg: "闲时任务标题输入没有出现",
  92. });
  93. await setInputValueByTestIdDom(
  94. TID_OFFPEAK_FORM_INSTRUCTIONS,
  95. "整理今天改动的文件并生成一份摘要",
  96. { timeoutMsg: "闲时任务 instructions 输入没有出现" },
  97. );
  98. await clickTestIdByDom(TID_OFFPEAK_EDIT_SUBMIT, {
  99. timeoutMsg: "闲时任务创建提交按钮不可点击",
  100. });
  101. // 4) 创建成功回列表后默认仍停留在定时任务 tab;闲时任务不会在该 tab 混排,
  102. // 必须切换到「闲时任务」再验证回显。
  103. await selectIdleTimeTab();
  104. await browser.waitUntil(
  105. async () => (await offPeakCardTitles()).some((t) => t.includes(title)),
  106. {
  107. timeout: 20000,
  108. timeoutMsg: `闲时任务列表没有回显新建卡片:${title}`,
  109. },
  110. );
  111. // 5) Pause:新建任务必须先暂停,避免检查详情期间被 scheduler 派发。
  112. await openOffPeakCardMenu({
  113. timeoutMsg: "卡片操作菜单没有出现",
  114. });
  115. await assertMenuHintDoesNotSelectAction(TID_OFFPEAK_ACTION_PAUSE, "right");
  116. // 修复原因:窄窗口里 right 提示会被 Radix 翻到菜单内部的 left,必须验证其改为上方后
  117. // 与菜单完全不相交;该尺寸覆盖用户缩小桌面窗口后的单列卡片布局。
  118. await browser.keys("Escape");
  119. await setCurrentElectronRendererContentSize(900, 720);
  120. await openOffPeakCardMenu({
  121. timeoutMsg: "窄窗口下卡片操作菜单没有出现",
  122. });
  123. await assertMenuHintDoesNotSelectAction(TID_OFFPEAK_ACTION_PAUSE, "top");
  124. await clickTestIdByDom(TID_OFFPEAK_ACTION_PAUSE, {
  125. timeoutMsg: "卡片菜单没有 Pause 项",
  126. });
  127. await setCurrentElectronRendererContentSize(1440);
  128. await openOffPeakCardMenu({
  129. timeoutMsg: "Pause 后重新打开卡片菜单失败",
  130. });
  131. await waitForTestIdByDom(TID_OFFPEAK_ACTION_CONTINUE, {
  132. timeoutMsg: "Pause 后菜单没有出现 Continue,状态未切 paused",
  133. });
  134. // 6) 卡片主点击进入任务详情,History 可达且空态不保留创建 CTA。
  135. await browser.execute((cardTid) => {
  136. const card = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  137. (item) => item.dataset.testid === cardTid,
  138. );
  139. card?.click();
  140. }, TID_OFFPEAK_CARD);
  141. await waitForTestIdByDom(TID_OFFPEAK_EDIT_VIEW, {
  142. timeoutMsg: "点击闲时任务卡片没有进入任务详情",
  143. });
  144. const editView = await browser.$(`[data-testid="${TID_OFFPEAK_EDIT_VIEW}"]`);
  145. const editViewButtons = await editView.$$("button");
  146. let historyButton: WebdriverIO.Element | undefined;
  147. for (const button of editViewButtons) {
  148. if (/History|历史/.test(await button.getText())) {
  149. historyButton = button;
  150. break;
  151. }
  152. }
  153. if (!historyButton) {
  154. throw new Error("任务详情里没有 History 入口");
  155. }
  156. // 修复原因:Radix tab 在 pointer/mouse down 阶段切换值,HTMLElement.click() 只派发
  157. // click 事件,旧 E2E 虽找到 History 按钮却没有真正切换 tab。
  158. await historyButton.click();
  159. await browser.waitUntil(
  160. async () =>
  161. browser.execute(
  162. (viewTid, submitTid) => {
  163. const view = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  164. (item) => item.dataset.testid === viewTid,
  165. );
  166. return !Array.from(view?.querySelectorAll<HTMLElement>("[data-testid]") ?? []).some(
  167. (item) => item.dataset.testid === submitTid,
  168. );
  169. },
  170. TID_OFFPEAK_EDIT_VIEW,
  171. TID_OFFPEAK_EDIT_SUBMIT,
  172. ),
  173. {
  174. timeout: 5000,
  175. timeoutMsg: "History 详情态仍显示创建或保存 CTA",
  176. },
  177. );
  178. // 详情页返回已迁到 Settings header breadcrumb。旧 case 点击编辑区的“第一个按钮”,
  179. // 会随 Settings/History 控件排序变成非返回动作,导致仍停留在详情页。
  180. await clickAutomationsBreadcrumbBack();
  181. await browser.waitUntil(
  182. async () => (await offPeakCardTitles()).some((t) => t.includes(title)),
  183. {
  184. timeout: 10000,
  185. timeoutMsg: "从闲时任务详情返回后列表没有恢复",
  186. },
  187. );
  188. // 7) Continue:点 Continue → 菜单重新出现 Pause(状态回 queued)。
  189. await openOffPeakCardMenu({
  190. timeoutMsg: "返回列表后重新打开卡片菜单失败",
  191. });
  192. await assertMenuHintDoesNotSelectAction(TID_OFFPEAK_ACTION_CONTINUE, "right");
  193. await clickTestIdByDom(TID_OFFPEAK_ACTION_CONTINUE, {
  194. timeoutMsg: "卡片菜单没有 Continue 项",
  195. });
  196. await openOffPeakCardMenu({
  197. timeoutMsg: "Continue 后重新打开卡片菜单失败",
  198. });
  199. await waitForTestIdByDom(TID_OFFPEAK_ACTION_PAUSE, {
  200. timeoutMsg: "Continue 后菜单没有回到 Pause,状态未回 queued",
  201. });
  202. // 8) 删除:菜单点删除 → 二次确认 → 卡片消失。
  203. await clickTestIdByDom(TID_OFFPEAK_ACTION_DELETE, {
  204. timeoutMsg: "卡片菜单没有删除项",
  205. });
  206. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM, {
  207. timeoutMsg: "删除二次确认弹窗没有出现",
  208. });
  209. await browser.waitUntil(
  210. async () => !(await offPeakCardTitles()).some((t) => t.includes(title)),
  211. { timeout: 15000, timeoutMsg: `删除后卡片仍然存在:${title}` },
  212. );
  213. });
  214. it("F-OFFPEAK-004:等待运行期间切换普通聊天计划不会重绑已保存闲时任务", async function () {
  215. this.timeout(150000);
  216. // 后续设置与文件夹具绑定默认项目,不能使用分配新虚拟目录的全局新建。
  217. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  218. await prepareV4ConversationE2E();
  219. await ensureUpstreamModelForE2E(UPSTREAM_SECONDARY_MODEL);
  220. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, { timeoutMsg: "侧栏没有 Automations 入口" });
  221. await clickTestIdByDom(TID_OFFPEAK_CREATE_BUTTON, { timeoutMsg: "闲时任务创建按钮没有出现" });
  222. await selectOffPeakReasoning();
  223. const title = `E2E_OFFPEAK_SWITCH_${Date.now()}`;
  224. await setInputValueByTestIdDom(TID_OFFPEAK_FORM_TITLE, title);
  225. await setInputValueByTestIdDom(
  226. TID_OFFPEAK_FORM_INSTRUCTIONS,
  227. "等待期间切换普通聊天的模型连接,闲时任务仍使用创建时快照。",
  228. );
  229. await clickTestIdByDom(TID_OFFPEAK_EDIT_SUBMIT, { timeoutMsg: "闲时任务提交按钮不可用" });
  230. const before = await waitForOffPeakModelSelection(title);
  231. expect(before.providerId).toContain("offpeak");
  232. // 后续设置与文件夹具绑定默认项目,不能使用分配新虚拟目录的全局新建。
  233. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  234. await selectUpstreamModelById(UPSTREAM_SECONDARY_MODEL);
  235. const after = await waitForOffPeakModelSelection(title);
  236. expect(after).toEqual(before);
  237. expect(await readOffPeakStatus(title)).toBe("queued");
  238. });
  239. });
  240. /** 当前产品把定时与闲时任务分 tab 展示,按本地化标签选中闲时 tab。 */
  241. async function selectIdleTimeTab(): Promise<void> {
  242. const tabList = await browser.$(`[data-testid="${TID_OFFPEAK_TAB}"]`);
  243. const buttons = await tabList.$$("button");
  244. for (const button of buttons) {
  245. if (/Idle-time task|闲时任务/u.test(await button.getText())) {
  246. await button.click();
  247. return;
  248. }
  249. }
  250. throw new Error("闲时任务列表没有闲时 tab");
  251. }
  252. async function seedCurrentAccount(): Promise<void> {
  253. // 网关 mock 只替代取号,不替代 Registry 的账号模型。使用隔离的账号控制面。
  254. await restartIntoWorkspace({
  255. afterElectronProcessExit: async () => {
  256. await seedBigModelConnectionSelection({ kind: "individual-coding-plan" });
  257. await seedBigModelOAuthCredential();
  258. },
  259. });
  260. }
  261. async function selectOffPeakReasoning(): Promise<void> {
  262. await clickTestIdByWebDriver(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER);
  263. await clickTestIdByWebDriver(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, "high"));
  264. }
  265. /** Settings header 中的 Automations breadcrumb 是编辑详情返回列表的真实入口。 */
  266. async function clickAutomationsBreadcrumbBack(): Promise<void> {
  267. const buttons = await browser.$$("nav[aria-label] button");
  268. for (const button of buttons) {
  269. if (/Automations|自动化/u.test(await button.getText())) {
  270. await button.click();
  271. return;
  272. }
  273. }
  274. throw new Error("闲时任务详情没有返回 Automations 列表的 breadcrumb 入口");
  275. }
  276. /** 当前列表里所有闲时任务卡片文本(含标题)。 */
  277. async function offPeakCardTitles(): Promise<string[]> {
  278. return browser.execute((cardTid) => {
  279. return Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  280. .filter((item) => item.dataset.testid === cardTid)
  281. .map((item) => item.textContent?.trim() ?? "");
  282. }, TID_OFFPEAK_CARD);
  283. }
  284. /** 桌面端卡片菜单仅在 hover 后显示;Radix trigger 还需要真实 pointerdown。 */
  285. async function openOffPeakCardMenu({ timeoutMsg }: { timeoutMsg: string }): Promise<void> {
  286. const card = await browser.$(`[data-testid="${TID_OFFPEAK_CARD}"]`);
  287. const menu = await browser.$(`[data-testid="${TID_OFFPEAK_CARD_MENU}"]`);
  288. // 缩窗后列表容器会产生滚动。先将卡片滚回视区并在卡片上真实悬停;按钮的显示
  289. // 由 group-hover 的 CSS transition 驱动。Electron 41 缩窗后 ChromeDriver 的
  290. // waitForClickable 会把已可见、可用且位于 viewport 内的按钮误判为不可点击,
  291. // 因此按已核验的 DOM 交互前置条件直接发出真实 WebDriver click。
  292. await card.scrollIntoView();
  293. await card.moveTo();
  294. await browser.waitUntil(
  295. () =>
  296. browser
  297. .execute((menuTestId) => {
  298. const menu = document.querySelector<HTMLElement>(`[data-testid="${menuTestId}"]`);
  299. if (!(menu instanceof HTMLButtonElement)) return { present: false };
  300. const rect = menu.getBoundingClientRect();
  301. return {
  302. disabled: menu.disabled,
  303. opacity: getComputedStyle(menu).opacity,
  304. present: true,
  305. visible:
  306. rect.bottom > 0 &&
  307. rect.left > 0 &&
  308. rect.right < window.innerWidth &&
  309. rect.top < window.innerHeight,
  310. };
  311. }, TID_OFFPEAK_CARD_MENU)
  312. .then(
  313. (state) => state.present && !state.disabled && state.opacity === "1" && state.visible,
  314. ),
  315. { timeout: 5_000, timeoutMsg },
  316. );
  317. try {
  318. await menu.click();
  319. } catch (error) {
  320. const opened = await browser.execute((menuTestId) => {
  321. const trigger = document.querySelector<HTMLElement>(`[data-testid="${menuTestId}"]`);
  322. return trigger?.getAttribute("aria-expanded") === "true";
  323. }, TID_OFFPEAK_CARD_MENU);
  324. // Electron 41 + ChromeDriver 在 resize 后会出现“html 拦截 click”的误报,但同一条
  325. // 原生 pointer 链已经让 Radix trigger 进入 aria-expanded=true。只在菜单真实打开时
  326. // 继续,未打开仍保留原始异常,避免把真正的点击失败吞掉。
  327. if (!opened) throw error;
  328. }
  329. }
  330. /**
  331. * Pause / Continue 的信息图标嵌在可选择菜单项内:提示必须避开菜单,
  332. * 且点击图标只能查看说明,不能冒泡执行父级动作。
  333. */
  334. async function assertMenuHintDoesNotSelectAction(
  335. actionTestId: string,
  336. expectedSide: "right" | "top",
  337. ): Promise<void> {
  338. const action = await browser.$(`[data-testid="${actionTestId}"]`);
  339. const hintTrigger = await action.$(":scope > span:last-child");
  340. await hintTrigger.moveTo();
  341. await browser.waitUntil(
  342. async () => {
  343. const tooltip = await browser.$('[role="tooltip"]');
  344. return tooltip.isDisplayed();
  345. },
  346. {
  347. timeout: 5000,
  348. timeoutMsg: `操作提示没有出现:${actionTestId}`,
  349. },
  350. );
  351. const geometry = await browser.execute(() => {
  352. const menu = document.querySelector<HTMLElement>('[role="menu"]');
  353. // Portal 会保留关闭中的 tooltip 节点;只能读取当前 open 节点,否则 data-side
  354. // 为空会把实际 right/top 布局误报为失败。
  355. const tooltip = Array.from(document.querySelectorAll<HTMLElement>('[role="tooltip"]')).find(
  356. (item) => item.dataset.state !== "closed",
  357. );
  358. if (!menu || !tooltip) {
  359. return null;
  360. }
  361. const menuRect = menu.getBoundingClientRect();
  362. const tooltipRect = tooltip.getBoundingClientRect();
  363. return {
  364. menuRight: menuRect.right,
  365. menuTop: menuRect.top,
  366. tooltipBottom: tooltipRect.bottom,
  367. tooltipLeft: tooltipRect.left,
  368. tooltipWidth: tooltipRect.width,
  369. };
  370. });
  371. expect(geometry).not.toBeNull();
  372. // Radix 的 data-side 是内部实现属性,并非页面对用户的承诺;实际几何关系才是
  373. // tooltip 避让菜单的行为契约。
  374. if (expectedSide === "right") {
  375. expect(geometry?.tooltipLeft ?? 0).toBeGreaterThanOrEqual(
  376. geometry?.menuRight ?? Number.POSITIVE_INFINITY,
  377. );
  378. } else {
  379. expect(geometry?.tooltipBottom ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
  380. geometry?.menuTop ?? 0,
  381. );
  382. }
  383. expect(geometry?.tooltipWidth ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(320);
  384. await hintTrigger.click();
  385. await browser.waitUntil(
  386. async () => {
  387. const currentAction = await browser.$(`[data-testid="${actionTestId}"]`);
  388. return currentAction.isDisplayed();
  389. },
  390. {
  391. timeout: 2000,
  392. timeoutMsg: `点击信息图标错误触发了父级动作:${actionTestId}`,
  393. },
  394. );
  395. }
  396. async function waitForOffPeakModelSelection(title: string): Promise<{
  397. modelId: string;
  398. providerId: string;
  399. }> {
  400. let selection: { modelId: string; providerId: string } | null = null;
  401. await browser.waitUntil(
  402. async () => {
  403. selection = readOffPeakModelSelection(title);
  404. return selection !== null;
  405. },
  406. { timeout: 30000, interval: 500, timeoutMsg: `闲时任务没有保存模型选择:${title}` },
  407. );
  408. if (!selection) throw new Error(`闲时任务模型选择为空:${title}`);
  409. return selection;
  410. }
  411. function readOffPeakModelSelection(title: string): { modelId: string; providerId: string } | null {
  412. const database = new DatabaseSync(join(getE2EAppDataPaths().appDataDir, "tasks-index.sqlite"), {
  413. readOnly: true,
  414. });
  415. try {
  416. const row = database
  417. .prepare("SELECT model_selection FROM off_peak_tasks WHERE title = ?")
  418. .get(title) as { model_selection: string | null } | undefined;
  419. if (!row?.model_selection) return null;
  420. const parsed = JSON.parse(row.model_selection) as { modelId?: string; providerId?: string };
  421. return parsed.modelId && parsed.providerId
  422. ? { modelId: parsed.modelId, providerId: parsed.providerId }
  423. : null;
  424. } finally {
  425. database.close();
  426. }
  427. }
  428. function readOffPeakStatus(title: string): string | null {
  429. const database = new DatabaseSync(join(getE2EAppDataPaths().appDataDir, "tasks-index.sqlite"), {
  430. readOnly: true,
  431. });
  432. try {
  433. const row = database.prepare("SELECT status FROM off_peak_tasks WHERE title = ?").get(title) as
  434. | { status: string }
  435. | undefined;
  436. return row?.status ?? null;
  437. } finally {
  438. database.close();
  439. }
  440. }