conversation-session-automation-cron-update.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  2. import { homedir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import {
  6. testId,
  7. TID_AUTOMATION_CREATE_MANUALLY,
  8. TID_AUTOMATION_CREATE_MENU,
  9. TID_AUTOMATION_CUSTOM_CONFIRM,
  10. TID_AUTOMATION_CUSTOM_INTERVAL_SELECT,
  11. TID_AUTOMATION_CUSTOM_REPEAT_EDIT,
  12. TID_AUTOMATION_FORM_PROMPT,
  13. TID_AUTOMATION_FORM_SUBMIT,
  14. TID_AUTOMATION_FORM_TITLE,
  15. TID_AUTOMATION_FREQUENCY_OPTION,
  16. TID_AUTOMATION_SCHEDULE_ADD,
  17. TID_AUTOMATION_SCHEDULE_PREVIEW,
  18. TID_AUTOMATIONS_LIST,
  19. TID_AUTOMATIONS_OPEN,
  20. TID_CRON_CREATE_CARD,
  21. TID_CRON_CREATE_OPEN,
  22. } from "@zcode/shared/test-ids";
  23. import {
  24. clearAppData,
  25. DEFAULT_WORKSPACE,
  26. clickTestIdByDom,
  27. clickTestIdByWebDriver,
  28. setInputValueByTestIdDom,
  29. waitForTestIdByDom,
  30. } from "#e2e/helpers/desktop-app";
  31. import {
  32. expandAssistantHistoriesWithContent,
  33. getToolCallDiagnostics,
  34. } from "#e2e/helpers/conversation-session-tool-diagnostics";
  35. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  36. import {
  37. approveV4Permission,
  38. prepareV4ConversationE2E,
  39. sendV4Prompt,
  40. waitForV4Pane,
  41. waitForV4TimelineContaining,
  42. } from "#e2e/helpers/v4-conversation";
  43. // 与同名 upstream fixture 对齐:CronList 返回 UI 创建任务的真实 automationId,
  44. // replay server 再把该 ID 注入 CronUpdate,禁止用固定或猜测的 ID 绕过查询链路。
  45. const MARKER = "E2E_AUTOMATION_CRON_UPDATE";
  46. const ORIGINAL_TITLE = "E2E_CRON_UPDATE_ORIGINAL";
  47. const UPDATED_TITLE = "E2E_CRON_UPDATE_UPDATED";
  48. const ORIGINAL_PROMPT = "E2E_CRON_UPDATE_ORIGINAL_PROMPT";
  49. const UPDATED_PROMPT = "E2E_CRON_UPDATE_UPDATED_PROMPT";
  50. const FINAL_TOKEN = "E2E_CRON_UPDATE_DONE";
  51. const UPDATED_INTERVAL = 200;
  52. const UPDATED_COMPATIBLE_CRON = "30 10 * * *";
  53. describe("会话内 CronUpdate 更新既有定时任务 E2E", () => {
  54. after(async () => {
  55. await browser.electron.restoreAllMocks();
  56. await clearAppData();
  57. });
  58. it("UI 创建 → CronList → CronUpdate → 更新卡片 → 同一任务详情", async function () {
  59. this.timeout(150000);
  60. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  61. // 先通过真实 UI 创建 workspace 内的既有任务,确保 CronList 查询的不是 fixture 伪造记录。
  62. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  63. timeoutMsg: "侧栏没有出现定时任务入口",
  64. });
  65. await clickTestIdByWebDriver(TID_AUTOMATION_CREATE_MENU, {
  66. timeoutMsg: "定时任务创建下拉没有出现",
  67. });
  68. await clickTestIdByDom(TID_AUTOMATION_CREATE_MANUALLY, {
  69. timeoutMsg: "创建下拉没有出现手动创建入口",
  70. });
  71. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_TITLE, ORIGINAL_TITLE);
  72. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_PROMPT, ORIGINAL_PROMPT);
  73. // MR 1622 后新建态默认不带日程;显式选择每天,避免依赖已移除的隐式默认 cron。
  74. await clickTestIdByWebDriver(TID_AUTOMATION_SCHEDULE_ADD, {
  75. timeoutMsg: "定时任务创建页没有添加调度入口",
  76. });
  77. await clickTestIdByDom(testId(TID_AUTOMATION_FREQUENCY_OPTION, "daily"), {
  78. timeoutMsg: "添加调度菜单没有每天选项",
  79. });
  80. await clickTestIdByDom(TID_AUTOMATION_FORM_SUBMIT, {
  81. timeoutMsg: "定时任务创建按钮不可点击",
  82. });
  83. await waitForTestIdByDom(TID_AUTOMATIONS_LIST, {
  84. timeout: 15000,
  85. timeoutMsg: "创建后没有回到定时任务列表",
  86. });
  87. const originalAutomation = await waitForAutomationRecordByTitle(ORIGINAL_TITLE);
  88. // 普通 desktop-continuous 会话先查询真实 ID,再对同一条记录执行 patch 更新。
  89. // CronList 按 workspace 查询;全局草稿不属于刚才创建 Automation 的项目。
  90. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  91. await sendV4Prompt(`${MARKER} 请先查询并更新已有的定时任务`);
  92. await waitForV4TimelineContaining(MARKER);
  93. // 自动 compact 会回收早期 tool output;在批准前按 DOM 轨迹确认只走
  94. // CronList → CronUpdate。真实 ID 则由 replay server 从 CronList tool_result
  95. // 动态注入,最终再与创建前落库的 automationId 对账。
  96. await waitForToolCallBlockByToolName("CronUpdate", 60000);
  97. await expandAssistantHistoriesWithContent();
  98. const pendingDiagnostics = await getToolCallDiagnostics(null);
  99. const pendingToolNames = pendingDiagnostics.blocks.map((block) => block.toolName);
  100. expect(pendingToolNames).toContain("CronList");
  101. expect(pendingToolNames).toContain("CronUpdate");
  102. expect(pendingToolNames).not.toContain("CronCreate");
  103. expect(pendingToolNames).not.toContain("CronDelete");
  104. await approveV4Permission();
  105. await waitForV4TimelineContaining(FINAL_TOKEN, 90000);
  106. await waitForV4Pane(
  107. (snapshot) =>
  108. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  109. "CronUpdate 会话没有完成",
  110. 90000,
  111. );
  112. // 更新成功卡片复用定时任务卡片样式,但必须展示更新后的定义。
  113. await waitForTestIdByDom(TID_CRON_CREATE_CARD, {
  114. timeout: 15000,
  115. timeoutMsg: "CronUpdate 完成后没有渲染更新成功卡片",
  116. });
  117. const cardText = await readTestIdText(TID_CRON_CREATE_CARD);
  118. expect(cardText).toContain(UPDATED_TITLE);
  119. expect(cardText).toContain(String(UPDATED_INTERVAL));
  120. expect(cardText).toContain("10:30");
  121. const updatedAutomation = readAutomationRecordById(originalAutomation.automationId);
  122. expect(updatedAutomation).toMatchObject({
  123. automationId: originalAutomation.automationId,
  124. cronExpr: UPDATED_COMPATIBLE_CRON,
  125. prompt: UPDATED_PROMPT,
  126. title: UPDATED_TITLE,
  127. scheduleRule: {
  128. unit: "daily",
  129. interval: UPDATED_INTERVAL,
  130. hour: 10,
  131. minute: 30,
  132. },
  133. });
  134. expect(countAutomationRecords()).toBe(1);
  135. // Bug 回归:最终确认只渲染普通文本,不应把回复误投影成 text 伪文件代码块。
  136. expect(await countTextCodeBlocksInCardTurn()).toBe(0);
  137. await clickTestIdByDom(TID_CRON_CREATE_OPEN, {
  138. timeoutMsg: "CronUpdate 卡片没有可点击的定时任务详情按钮",
  139. });
  140. await waitForTestIdByDom(TID_AUTOMATION_FORM_TITLE, {
  141. timeout: 15000,
  142. timeoutMsg: "没有跳转到更新后的定时任务详情",
  143. });
  144. expect(await readTestIdValue(TID_AUTOMATION_FORM_TITLE)).toBe(UPDATED_TITLE);
  145. expect(await readTestIdValue(TID_AUTOMATION_FORM_PROMPT)).toBe(UPDATED_PROMPT);
  146. const schedulePreview = await readTestIdText(TID_AUTOMATION_SCHEDULE_PREVIEW);
  147. expect(schedulePreview).toContain(String(UPDATED_INTERVAL));
  148. expect(schedulePreview).toContain("10:30");
  149. await clickTestIdByDom(TID_AUTOMATION_CUSTOM_REPEAT_EDIT, {
  150. timeoutMsg: "CronUpdate 后没有自定义重复编辑入口",
  151. });
  152. await waitForTestIdByDom(TID_AUTOMATION_CUSTOM_INTERVAL_SELECT, {
  153. timeout: 10000,
  154. timeoutMsg: "CronUpdate 后没有复原 200 天的自定义间隔",
  155. });
  156. expect(await readTestIdValue(TID_AUTOMATION_CUSTOM_INTERVAL_SELECT)).toBe(
  157. String(UPDATED_INTERVAL),
  158. );
  159. await clickTestIdByDom(TID_AUTOMATION_CUSTOM_CONFIRM, {
  160. timeoutMsg: "CronUpdate 的自定义重复编辑无法关闭",
  161. });
  162. });
  163. });
  164. interface AutomationRecord {
  165. automationId: string;
  166. cronExpr: string;
  167. prompt: string;
  168. scheduleRule?: Record<string, unknown>;
  169. title: string;
  170. }
  171. function automationDatabasePath(): string {
  172. return join(homedir(), ".zcode", "v2", "tasks-index.sqlite");
  173. }
  174. function readAutomationRecordById(automationId: string): AutomationRecord | null {
  175. // Node 内置 SQLite 目前只提供同步 DatabaseSync;E2E 每次仅做一次只读查询并立即关闭。
  176. const database = new DatabaseSync(automationDatabasePath(), {
  177. readOnly: true,
  178. });
  179. try {
  180. const row = database
  181. .prepare(
  182. `SELECT automation_id, title, cron_expr, prompt, schedule_rule
  183. FROM automations
  184. WHERE automation_id = ?`,
  185. )
  186. .get(automationId) as
  187. | {
  188. automation_id: string;
  189. cron_expr: string;
  190. prompt: string;
  191. schedule_rule: string | null;
  192. title: string;
  193. }
  194. | undefined;
  195. return row
  196. ? {
  197. automationId: row.automation_id,
  198. cronExpr: row.cron_expr,
  199. prompt: row.prompt,
  200. ...(row.schedule_rule
  201. ? {
  202. scheduleRule: JSON.parse(row.schedule_rule) as Record<string, unknown>,
  203. }
  204. : {}),
  205. title: row.title,
  206. }
  207. : null;
  208. } finally {
  209. database.close();
  210. }
  211. }
  212. async function waitForAutomationRecordByTitle(title: string): Promise<AutomationRecord> {
  213. let record: AutomationRecord | null = null;
  214. await browser.waitUntil(
  215. async () => {
  216. const database = new DatabaseSync(automationDatabasePath(), {
  217. readOnly: true,
  218. });
  219. try {
  220. const row = database
  221. .prepare(
  222. `SELECT automation_id, title, cron_expr, prompt
  223. FROM automations
  224. WHERE title = ?`,
  225. )
  226. .get(title) as
  227. | {
  228. automation_id: string;
  229. cron_expr: string;
  230. prompt: string;
  231. title: string;
  232. }
  233. | undefined;
  234. record = row
  235. ? {
  236. automationId: row.automation_id,
  237. cronExpr: row.cron_expr,
  238. prompt: row.prompt,
  239. title: row.title,
  240. }
  241. : null;
  242. return record !== null;
  243. } finally {
  244. database.close();
  245. }
  246. },
  247. {
  248. timeout: 10000,
  249. timeoutMsg: `没有在 automation 数据库中找到 ${title}`,
  250. },
  251. );
  252. if (!record) throw new Error(`automation 数据库记录为空:${title}`);
  253. return record;
  254. }
  255. function countAutomationRecords(): number {
  256. const database = new DatabaseSync(automationDatabasePath(), {
  257. readOnly: true,
  258. });
  259. try {
  260. const row = database.prepare("SELECT COUNT(*) AS count FROM automations").get() as {
  261. count: number;
  262. };
  263. return row.count;
  264. } finally {
  265. database.close();
  266. }
  267. }
  268. async function readTestIdText(currentTestId: string): Promise<string> {
  269. return browser.execute((testId) => {
  270. const element = document.querySelector<HTMLElement>(`[data-testid="${testId}"]`);
  271. return element?.innerText.trim() ?? "";
  272. }, currentTestId);
  273. }
  274. async function readTestIdValue(currentTestId: string): Promise<string> {
  275. return browser.execute((testId) => {
  276. const element = document.querySelector<HTMLInputElement | HTMLTextAreaElement>(
  277. `[data-testid="${testId}"]`,
  278. );
  279. return element?.value ?? "";
  280. }, currentTestId);
  281. }
  282. async function countTextCodeBlocksInCardTurn(): Promise<number> {
  283. return browser.execute((cardTestId) => {
  284. const card = document.querySelector<HTMLElement>(`[data-testid="${cardTestId}"]`);
  285. const turn = card?.closest<HTMLElement>("[data-turn-id]");
  286. return turn?.querySelectorAll('[data-language="text"]').length ?? -1;
  287. }, TID_CRON_CREATE_CARD);
  288. }