conversation-session-automation-pause-self.test.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { homedir } from "node:os";
  2. import { join } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import {
  5. TID_AUTOMATION_CARD,
  6. TID_AUTOMATION_CREATE_MANUALLY,
  7. TID_AUTOMATION_CREATE_MENU,
  8. TID_AUTOMATION_FORM_PROMPT,
  9. TID_AUTOMATION_FORM_SUBMIT,
  10. TID_AUTOMATION_FORM_TITLE,
  11. TID_AUTOMATION_FREQUENCY_OPTION,
  12. TID_AUTOMATION_RUN_NOW,
  13. TID_AUTOMATION_SCHEDULE_ADD,
  14. TID_AUTOMATIONS_OPEN,
  15. TID_TASK_ITEM,
  16. testId,
  17. } from "@zcode/shared/test-ids";
  18. import {
  19. clearAppData,
  20. clickTestIdByDom,
  21. clickTestIdByWebDriver,
  22. pinE2ELocale,
  23. setInputValueByTestIdDom,
  24. waitForDefaultWorkspaceReady,
  25. } from "#e2e/helpers/desktop-app";
  26. import {
  27. getUpstreamRequestToolNames,
  28. waitForUpstreamRequest,
  29. } from "#e2e/helpers/conversation-session-network";
  30. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  31. import {
  32. prepareV4ConversationE2E,
  33. selectV4TaskById,
  34. waitForV4Pane,
  35. waitForV4TimelineContaining,
  36. } from "#e2e/helpers/v4-conversation";
  37. import { UPSTREAM_MODEL, selectUpstreamModelById } from "#e2e/helpers/upstream-provider";
  38. // 与同名 upstream fixture 对齐:执行轮首个响应固定调用无参数 CronPauseSelf,
  39. // 暂停目标只能来自 Host 准入注入的本轮 automationId,不允许 fixture 传任何 id。
  40. const MARKER = "E2E_AUTOMATION_PAUSE_SELF";
  41. const RUN_PROMPT = `${MARKER} 检查停止条件;条件已满足时调用 CronPauseSelf 暂停本任务`;
  42. const AUTOMATION_TITLE = "E2E_PAUSE_SELF_TASK";
  43. const FINAL_TOKEN = "E2E_AUTOMATION_PAUSE_SELF_DONE";
  44. describe("automation 执行轮通过 CronPauseSelf 暂停自身 E2E", () => {
  45. after(async () => {
  46. await browser.electron.restoreAllMocks();
  47. await clearAppData();
  48. });
  49. it("UI 创建 → 立即运行 → CronPauseSelf → 任务转 paused → 列表卡片显示已暂停", async function () {
  50. this.timeout(150000);
  51. await waitForDefaultWorkspaceReady(90_000);
  52. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  53. // 首帧跟随宿主语言,mac runner 上是英文;seedSettings 对已启动的 renderer 无效,须用 pinE2ELocale。
  54. await pinE2ELocale("zh-CN");
  55. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  56. timeoutMsg: "侧栏没有出现定时任务入口",
  57. });
  58. await clickTestIdByWebDriver(TID_AUTOMATION_CREATE_MENU, {
  59. timeoutMsg: "定时任务创建下拉没有出现",
  60. });
  61. await clickTestIdByDom(TID_AUTOMATION_CREATE_MANUALLY, {
  62. timeoutMsg: "创建下拉没有出现手动创建入口",
  63. });
  64. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_TITLE, AUTOMATION_TITLE);
  65. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_PROMPT, RUN_PROMPT);
  66. // 账号 mock 会提供默认模型;表单明确选择 case 的回放模型,不依赖工作区默认值。
  67. await selectUpstreamModelById(UPSTREAM_MODEL, { afterModelItemClick: () => true });
  68. // 新建态默认无日程;显式添加每天,保证暂停前任务是带调度的 active 状态。
  69. await clickTestIdByWebDriver(TID_AUTOMATION_SCHEDULE_ADD, {
  70. timeoutMsg: "定时任务创建页没有添加日程入口",
  71. });
  72. await clickTestIdByDom(testId(TID_AUTOMATION_FREQUENCY_OPTION, "daily"), {
  73. timeoutMsg: "添加日程菜单没有每天选项",
  74. });
  75. await clickTestIdByDom(TID_AUTOMATION_FORM_SUBMIT, {
  76. timeoutMsg: "定时任务创建按钮不可点击",
  77. });
  78. const initialCardText = await waitForAutomationCardText(AUTOMATION_TITLE, "已运行 0 次");
  79. expect(initialCardText).toContain("下次运行");
  80. expect(initialCardText).not.toContain("已暂停");
  81. const createdRecord = readAutomationRecordByTitle(AUTOMATION_TITLE);
  82. expect(createdRecord).toMatchObject({ enabled: 1, lifecycleStatus: "active" });
  83. await clickAutomationCardByTitle(AUTOMATION_TITLE);
  84. await clickTestIdByDom(TID_AUTOMATION_RUN_NOW, {
  85. timeout: 15000,
  86. timeoutMsg: "定时任务编辑页没有立即运行按钮",
  87. });
  88. // 任务行会截断长标题;用不会被截断的稳定 marker 定位,不能拿完整 prompt 匹配可见文本。
  89. const taskId = await waitForTaskItemContaining(MARKER);
  90. await selectV4TaskById(taskId);
  91. await waitForV4TimelineContaining(RUN_PROMPT);
  92. // CronPauseSelf 按普通工具行展示,不生成任何卡片。
  93. await waitForToolCallBlockByToolName("CronPauseSelf", 60000);
  94. await waitForV4TimelineContaining(FINAL_TOKEN, 90000);
  95. await waitForV4Pane(
  96. (snapshot) => snapshot.sessionId === taskId && !snapshot.canStop,
  97. "定时任务执行会话没有完成",
  98. 90000,
  99. );
  100. // 执行轮工具面:只读 CronList + 只作用于本轮的 CronPauseSelf;三个写工具必须被隐藏。
  101. const runRequest = { lastUserMessageIncludes: [RUN_PROMPT] };
  102. await waitForUpstreamRequest(runRequest, "没有捕获到定时任务立即运行的 provider 请求");
  103. const runToolNames = await getUpstreamRequestToolNames(runRequest);
  104. expect(runToolNames).toContain("CronList");
  105. expect(runToolNames).toContain("CronPauseSelf");
  106. expect(runToolNames).not.toContain("CronCreate");
  107. expect(runToolNames).not.toContain("CronUpdate");
  108. expect(runToolNames).not.toContain("CronDelete");
  109. // Host 条件暂停只改 enabled / lifecycle_status;manual run 的累计次数与原调度保留。
  110. const pausedRecord = readAutomationRecordByTitle(AUTOMATION_TITLE);
  111. expect(pausedRecord).toMatchObject({
  112. automationId: createdRecord!.automationId,
  113. enabled: 0,
  114. lifecycleStatus: "paused",
  115. runCount: 1,
  116. });
  117. expect(pausedRecord!.nextRunAt).toBe(createdRecord!.nextRunAt);
  118. // 没有推送:列表在重新挂载时读取状态,原 Card 显示“已暂停”且不再显示“下次运行”。
  119. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  120. timeoutMsg: "执行完成后无法返回定时任务列表",
  121. });
  122. const pausedCardText = await waitForAutomationCardText(AUTOMATION_TITLE, "已暂停");
  123. expect(pausedCardText).toContain("已运行 1 次");
  124. expect(pausedCardText).not.toContain("下次运行");
  125. });
  126. });
  127. interface AutomationRecord {
  128. automationId: string;
  129. enabled: number;
  130. lifecycleStatus: string;
  131. nextRunAt: number | null;
  132. runCount: number;
  133. }
  134. function automationDatabasePath(): string {
  135. return join(homedir(), ".zcode", "v2", "tasks-index.sqlite");
  136. }
  137. function readAutomationRecordByTitle(title: string): AutomationRecord | null {
  138. // Node 内置 SQLite 目前只提供同步 DatabaseSync;E2E 每次仅做一次只读查询并立即关闭。
  139. const database = new DatabaseSync(automationDatabasePath(), { readOnly: true });
  140. try {
  141. const row = database
  142. .prepare(
  143. `SELECT automation_id, enabled, lifecycle_status, next_run_at, run_count
  144. FROM automations
  145. WHERE title = ?`,
  146. )
  147. .get(title) as
  148. | {
  149. automation_id: string;
  150. enabled: number;
  151. lifecycle_status: string;
  152. next_run_at: number | null;
  153. run_count: number;
  154. }
  155. | undefined;
  156. return row
  157. ? {
  158. automationId: row.automation_id,
  159. enabled: row.enabled,
  160. lifecycleStatus: row.lifecycle_status,
  161. nextRunAt: row.next_run_at,
  162. runCount: row.run_count,
  163. }
  164. : null;
  165. } finally {
  166. database.close();
  167. }
  168. }
  169. async function clickAutomationCardByTitle(title: string): Promise<void> {
  170. let latestTitles: string[] = [];
  171. await browser.waitUntil(
  172. async () => {
  173. const result = await browser.execute(
  174. (cardTestId, expectedTitle) => {
  175. const cards = Array.from(
  176. document.querySelectorAll<HTMLElement>(`[data-testid="${cardTestId}"]`),
  177. );
  178. const target = cards.find((card) => card.innerText.includes(expectedTitle));
  179. target?.click();
  180. return { clicked: Boolean(target), titles: cards.map((card) => card.innerText) };
  181. },
  182. TID_AUTOMATION_CARD,
  183. title,
  184. );
  185. latestTitles = result.titles;
  186. return result.clicked;
  187. },
  188. {
  189. timeout: 15000,
  190. timeoutMsg: `没有找到刚创建的定时任务卡片:${title}; latest=${latestTitles.join(" | ")}`,
  191. },
  192. );
  193. }
  194. async function waitForAutomationCardText(title: string, expectedText: string): Promise<string> {
  195. let latestText = "";
  196. await browser.waitUntil(
  197. async () => {
  198. latestText = await browser.execute(
  199. (cardTestId, expectedTitle) => {
  200. const cards = Array.from(
  201. document.querySelectorAll<HTMLElement>(`[data-testid="${cardTestId}"]`),
  202. );
  203. return cards.find((card) => card.innerText.includes(expectedTitle))?.innerText ?? "";
  204. },
  205. TID_AUTOMATION_CARD,
  206. title,
  207. );
  208. return latestText.includes(expectedText);
  209. },
  210. {
  211. timeout: 15000,
  212. timeoutMsg: `定时任务 Card 未显示“${expectedText}”:${title}; latest=${latestText}`,
  213. },
  214. );
  215. return latestText;
  216. }
  217. async function waitForTaskItemContaining(title: string): Promise<string> {
  218. let taskId: string | null = null;
  219. let latestTitles: string[] = [];
  220. await browser.waitUntil(
  221. async () => {
  222. const result = await browser.execute(
  223. (baseTestId, expectedTitle) => {
  224. const prefix = `${baseTestId}-`;
  225. const items = Array.from(
  226. document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}"]`),
  227. );
  228. const target = items.find((item) => item.innerText.includes(expectedTitle));
  229. return {
  230. taskId: target?.dataset.testid?.slice(prefix.length) ?? null,
  231. titles: items.map((item) => item.innerText),
  232. };
  233. },
  234. TID_TASK_ITEM,
  235. title,
  236. );
  237. taskId = result.taskId;
  238. latestTitles = result.titles;
  239. return Boolean(taskId);
  240. },
  241. {
  242. // run_now 由当前 host 直接派发,不等待 scheduler tick。
  243. timeout: 12000,
  244. timeoutMsg: `立即运行未直接派发,12 秒内侧栏没有出现执行会话:${title}; latest=${latestTitles.join(" | ")}`,
  245. },
  246. );
  247. if (!taskId) throw new Error("立即运行后缺少执行会话 taskId");
  248. return taskId;
  249. }