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

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