automations-run-now-host-mismatch.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import { readdir, readFile } from "node:fs/promises";
  2. import { homedir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import {
  6. TID_AUTOMATION_CARD,
  7. TID_AUTOMATION_CREATE_MANUALLY,
  8. TID_AUTOMATION_CREATE_MENU,
  9. TID_AUTOMATION_FORM_PROMPT,
  10. TID_AUTOMATION_FORM_SUBMIT,
  11. TID_AUTOMATION_FORM_TITLE,
  12. TID_AUTOMATION_FREQUENCY_OPTION,
  13. TID_AUTOMATION_RUN_NOW,
  14. TID_AUTOMATION_SCHEDULE_ADD,
  15. TID_AUTOMATIONS_OPEN,
  16. TID_TASK_ITEM,
  17. testId,
  18. } from "@zcode/shared/test-ids";
  19. import {
  20. clearAppData,
  21. clickTestIdByDom,
  22. clickTestIdByWebDriver,
  23. DEFAULT_WORKSPACE,
  24. pinE2ELocale,
  25. setInputValueByTestIdDom,
  26. waitForDefaultWorkspaceReady,
  27. } from "#e2e/helpers/desktop-app";
  28. import { getToastMessages } from "#e2e/helpers/conversation-session-toast";
  29. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  30. import {
  31. prepareV4ConversationE2E,
  32. selectV4TaskById,
  33. waitForV4Pane,
  34. waitForV4TimelineContaining,
  35. } from "#e2e/helpers/v4-conversation";
  36. import { UPSTREAM_MODEL, selectUpstreamModelById } from "#e2e/helpers/upstream-provider";
  37. // 与同名 upstream fixture 对齐:首次立即运行只需一条确定性文本回复,证明正常路径可派发。
  38. const MARKER = "E2E_AUTOMATION_RUN_NOW_HOST_MISMATCH";
  39. const RUN_PROMPT = `${MARKER} 回复一句确认`;
  40. const AUTOMATION_TITLE = "E2E_RUN_NOW_HOST_MISMATCH_TASK";
  41. const FINAL_TOKEN = "automation-run-now-host-mismatch-done";
  42. // 非本机 Host 的会话行归属;只写 tasks 行,不建 hosts / 项目行,模拟工单里会话行 host_id 不对的状态。
  43. const FOREIGN_HOST_ID = "remote:server:e2e";
  44. const HOST_MISMATCH_TOAST = "任务所属设备不符,无法运行";
  45. const GENERIC_FAILED_TOAST = "触发运行失败";
  46. describe("定时任务立即运行:会话归属不符提示 E2E", () => {
  47. after(async () => {
  48. await browser.electron.restoreAllMocks();
  49. await clearAppData();
  50. });
  51. it("正常立即运行提示不变;绑定会话 host_id 非本机时提示设备不符并记录 owner 诊断", async function () {
  52. this.timeout(240000);
  53. await waitForDefaultWorkspaceReady(90_000);
  54. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  55. // 首帧跟随宿主语言;seedSettings 对已启动的 renderer 无效,须用 pinE2ELocale。
  56. await pinE2ELocale("zh-CN");
  57. // 1) UI 创建一条带每日调度的手动任务。
  58. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, { timeoutMsg: "侧栏没有出现定时任务入口" });
  59. await clickTestIdByWebDriver(TID_AUTOMATION_CREATE_MENU, {
  60. timeoutMsg: "定时任务创建下拉没有出现",
  61. });
  62. await clickTestIdByDom(TID_AUTOMATION_CREATE_MANUALLY, {
  63. timeoutMsg: "创建下拉没有出现手动创建入口",
  64. });
  65. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_TITLE, AUTOMATION_TITLE);
  66. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_PROMPT, RUN_PROMPT);
  67. await selectUpstreamModelById(UPSTREAM_MODEL, { afterModelItemClick: () => true });
  68. await clickTestIdByWebDriver(TID_AUTOMATION_SCHEDULE_ADD, {
  69. timeoutMsg: "定时任务创建页没有添加日程入口",
  70. });
  71. await clickTestIdByDom(testId(TID_AUTOMATION_FREQUENCY_OPTION, "daily"), {
  72. timeoutMsg: "添加日程菜单没有每天选项",
  73. });
  74. await clickTestIdByDom(TID_AUTOMATION_FORM_SUBMIT, {
  75. timeoutMsg: "定时任务创建按钮不可点击",
  76. });
  77. await waitForAutomationCardText(AUTOMATION_TITLE, "已运行 0 次");
  78. // 2) 正常路径:立即运行成功派发,提示仍是「正在运行」,不出现失败提示。
  79. await clickAutomationCardByTitle(AUTOMATION_TITLE);
  80. await clickTestIdByDom(TID_AUTOMATION_RUN_NOW, {
  81. timeout: 15000,
  82. timeoutMsg: "定时任务编辑页没有立即运行按钮",
  83. });
  84. await waitForToast(`正在运行“${AUTOMATION_TITLE}”`, "正常立即运行没有出现运行中提示");
  85. expect((await getToastMessages()).some((text) => text.includes(GENERIC_FAILED_TOAST))).toBe(
  86. false,
  87. );
  88. const taskId = await waitForTaskItemContaining(MARKER);
  89. // 等执行轮真实结束,manual claim 释放后再重启;否则第二次触发会被判成 duplicate。
  90. await selectV4TaskById(taskId);
  91. await waitForV4TimelineContaining(FINAL_TOKEN, 90000);
  92. await waitForV4Pane(
  93. (snapshot) => snapshot.sessionId === taskId && !snapshot.canStop,
  94. "首次立即运行的执行会话没有完成",
  95. 90000,
  96. );
  97. // 3) 重启:CLI runtime 随进程退出,下次立即运行必须冷恢复会话,才会走到
  98. // runtime-materialization 的目录解析。进程退出后再改库,避免旧 Host 迟到写覆盖。
  99. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  100. afterElectronProcessExit: () => bindAutomationToForeignHostTask(AUTOMATION_TITLE, taskId),
  101. });
  102. await pinE2ELocale("zh-CN");
  103. expect(readTaskHostId(taskId)).toBe(FOREIGN_HOST_ID);
  104. // 4) 绑定会话归属不符:立即运行失败,提示具体原因而不是笼统的「触发运行失败」。
  105. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, { timeoutMsg: "重启后侧栏没有定时任务入口" });
  106. await clickAutomationCardByTitle(AUTOMATION_TITLE);
  107. await clickTestIdByDom(TID_AUTOMATION_RUN_NOW, {
  108. timeout: 15000,
  109. timeoutMsg: "重启后定时任务编辑页没有立即运行按钮",
  110. });
  111. await waitForToast(HOST_MISMATCH_TOAST, "会话归属不符时没有出现设备不符提示", 60000);
  112. expect((await getToastMessages()).some((text) => text.includes(GENERIC_FAILED_TOAST))).toBe(
  113. false,
  114. );
  115. // 5) 诊断:项目存储在抛错前打 warn,branch=owner 且带本次 taskId。
  116. await waitForHostMismatchDiagnostic(taskId);
  117. });
  118. });
  119. function tasksDatabasePath(): string {
  120. return join(homedir(), ".zcode", "v2", "tasks-index.sqlite");
  121. }
  122. function bindAutomationToForeignHostTask(title: string, taskId: string): void {
  123. // Node 内置 SQLite 只提供同步 DatabaseSync;此处在 Electron 进程退出后的屏障内一次写入并关闭。
  124. const database = new DatabaseSync(tasksDatabasePath());
  125. try {
  126. const bound = database
  127. .prepare("UPDATE automations SET target_task_id = ? WHERE title = ?")
  128. .run(taskId, title);
  129. if (bound.changes !== 1) throw new Error(`没有找到要绑定会话的定时任务:${title}`);
  130. const moved = database
  131. .prepare("UPDATE tasks SET host_id = ? WHERE task_id = ?")
  132. .run(FOREIGN_HOST_ID, taskId);
  133. if (moved.changes < 1) throw new Error(`tasks-index 中没有执行会话行:${taskId}`);
  134. } finally {
  135. database.close();
  136. }
  137. }
  138. function readTaskHostId(taskId: string): string | null {
  139. const database = new DatabaseSync(tasksDatabasePath(), { readOnly: true });
  140. try {
  141. const row = database.prepare("SELECT host_id FROM tasks WHERE task_id = ?").get(taskId) as
  142. | { host_id: string | null }
  143. | undefined;
  144. return row?.host_id ?? null;
  145. } finally {
  146. database.close();
  147. }
  148. }
  149. async function waitForHostMismatchDiagnostic(taskId: string): Promise<void> {
  150. const logDir = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR);
  151. expect(logDir).toBeTruthy();
  152. let matched: string[] = [];
  153. await browser.waitUntil(
  154. async () => {
  155. const files = (await readdir(logDir!)).filter((name) => name.endsWith(".log"));
  156. const lines = (await Promise.all(files.map((name) => readFile(join(logDir!, name), "utf8"))))
  157. .join("\n")
  158. .split("\n");
  159. matched = lines.filter(
  160. (line) => line.includes("project_storage.host_mismatch") && line.includes(taskId),
  161. );
  162. return matched.length > 0;
  163. },
  164. { timeout: 15000, timeoutMsg: `运行日志没有 host-mismatch 诊断:${taskId}` },
  165. );
  166. const diagnostic = matched.join("\n");
  167. // 精确断言分支:每条诊断都带 ownerHostId 字段名,只查 "owner" 区分不了 project / fork-parent 分支
  168. expect(diagnostic).toContain('"branch":"owner"');
  169. expect(diagnostic).toContain('"code":"project.host-mismatch.owner"');
  170. expect(diagnostic).toContain(`"rowHostId":"${FOREIGN_HOST_ID}"`);
  171. }
  172. async function waitForToast(expected: string, timeoutMsg: string, timeout = 20000) {
  173. let latest: string[] = [];
  174. await browser.waitUntil(
  175. async () => {
  176. latest = await getToastMessages();
  177. return latest.some((message) => message.includes(expected));
  178. },
  179. { timeout, timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latest)}` },
  180. );
  181. }
  182. async function clickAutomationCardByTitle(title: string): Promise<void> {
  183. let latestTitles: string[] = [];
  184. await browser.waitUntil(
  185. async () => {
  186. const result = await browser.execute(
  187. (cardTestId, expectedTitle) => {
  188. const cards = Array.from(
  189. document.querySelectorAll<HTMLElement>(`[data-testid="${cardTestId}"]`),
  190. );
  191. const target = cards.find((card) => card.innerText.includes(expectedTitle));
  192. target?.click();
  193. return { clicked: Boolean(target), titles: cards.map((card) => card.innerText) };
  194. },
  195. TID_AUTOMATION_CARD,
  196. title,
  197. );
  198. latestTitles = result.titles;
  199. return result.clicked;
  200. },
  201. {
  202. timeout: 15000,
  203. timeoutMsg: `没有找到定时任务卡片:${title}; latest=${latestTitles.join(" | ")}`,
  204. },
  205. );
  206. }
  207. async function waitForAutomationCardText(title: string, expectedText: string): Promise<string> {
  208. let latestText = "";
  209. await browser.waitUntil(
  210. async () => {
  211. latestText = await browser.execute(
  212. (cardTestId, expectedTitle) => {
  213. const cards = Array.from(
  214. document.querySelectorAll<HTMLElement>(`[data-testid="${cardTestId}"]`),
  215. );
  216. return cards.find((card) => card.innerText.includes(expectedTitle))?.innerText ?? "";
  217. },
  218. TID_AUTOMATION_CARD,
  219. title,
  220. );
  221. return latestText.includes(expectedText);
  222. },
  223. {
  224. timeout: 15000,
  225. timeoutMsg: `定时任务 Card 未显示“${expectedText}”:${title}; latest=${latestText}`,
  226. },
  227. );
  228. return latestText;
  229. }
  230. async function waitForTaskItemContaining(title: string): Promise<string> {
  231. let taskId: string | null = null;
  232. let latestTitles: string[] = [];
  233. await browser.waitUntil(
  234. async () => {
  235. const result = await browser.execute(
  236. (baseTestId, expectedTitle) => {
  237. const prefix = `${baseTestId}-`;
  238. const items = Array.from(
  239. document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}"]`),
  240. );
  241. const target = items.find((item) => item.innerText.includes(expectedTitle));
  242. return {
  243. taskId: target?.dataset.testid?.slice(prefix.length) ?? null,
  244. titles: items.map((item) => item.innerText),
  245. };
  246. },
  247. TID_TASK_ITEM,
  248. title,
  249. );
  250. taskId = result.taskId;
  251. latestTitles = result.titles;
  252. return Boolean(taskId);
  253. },
  254. {
  255. timeout: 15000,
  256. timeoutMsg: `立即运行后侧栏没有出现执行会话:${title}; latest=${latestTitles.join(" | ")}`,
  257. },
  258. );
  259. if (!taskId) throw new Error("立即运行后缺少执行会话 taskId");
  260. return taskId;
  261. }