mobile-event-push.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import { readFile, readdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. TID_SETTINGS_BACK_BUTTON,
  5. TID_SETTINGS_PAGE,
  6. TID_SETTINGS_SECTION_NAV,
  7. TID_TASK_SETTINGS_BUTTON,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import { clickTestIdByDom, readSettings } from "#e2e/helpers/desktop-app";
  11. import {
  12. prepareV4ConversationE2E,
  13. sendV4Prompt,
  14. waitForV4Pane,
  15. startNewV4Draft,
  16. } from "#e2e/helpers/v4-conversation";
  17. const MOBILE_PUSH_SWITCH = "settings-mobile-push-switch";
  18. interface PushEvidence {
  19. queries: number;
  20. notifications: Array<{
  21. device_sid: string;
  22. event: { kind: string; run_id: string; event_id: string };
  23. }>;
  24. }
  25. /** E2E 的 Main 日志有独立目录,不能用生产配置目录推测测试日志位置。 */
  26. async function readPushLogLines(): Promise<
  27. Array<{ line: string; fields: Record<string, string> }>
  28. > {
  29. const logDir = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR);
  30. if (!logDir) throw new Error("missing E2E runtime log directory");
  31. const logFiles = (await readdir(logDir)).filter((name) => name.endsWith(".log"));
  32. const logs = (
  33. await Promise.all(logFiles.map((name) => readFile(join(logDir, name), "utf8")))
  34. ).join("\n");
  35. return logs
  36. .split("\n")
  37. .filter((line) => line.includes("[mobile-push]"))
  38. .map((line) => {
  39. const json = line.slice(line.indexOf("{"));
  40. try {
  41. return { line, fields: JSON.parse(json) as Record<string, string> };
  42. } catch {
  43. return { line, fields: {} };
  44. }
  45. });
  46. }
  47. /** 真实设置页切换开关;返回切换后设置文件里的值,证明写入的是唯一数据源。 */
  48. async function setMobilePushSwitch(enabled: boolean) {
  49. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 15_000 });
  50. await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).waitForDisplayed({ timeout: 15_000 });
  51. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "general"), { timeout: 15_000 });
  52. const toggle = $(`[data-testid="${MOBILE_PUSH_SWITCH}"]`);
  53. await toggle.waitForDisplayed({ timeout: 15_000 });
  54. const target = enabled ? "checked" : "unchecked";
  55. if ((await toggle.getAttribute("data-state")) !== target)
  56. await clickTestIdByDom(MOBILE_PUSH_SWITCH, { timeout: 15_000 });
  57. await browser.waitUntil(async () => (await toggle.getAttribute("data-state")) === target, {
  58. timeout: 15_000,
  59. timeoutMsg: `手机推送开关没有切到 ${target}`,
  60. });
  61. await browser.waitUntil(async () => (await readSettings()).mobilePushEnabled === enabled, {
  62. timeout: 15_000,
  63. timeoutMsg: `设置文件没有写入 mobilePushEnabled=${enabled}`,
  64. });
  65. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  66. }
  67. /** 发送一条 prompt 并等待该轮完成;回复文本固定,标识当前轮已落到 timeline。 */
  68. async function sendAndWaitComplete(prompt: string) {
  69. await sendV4Prompt(prompt);
  70. await waitForV4Pane(
  71. (pane) =>
  72. pane.sessionId !== "draft" && !pane.canStop && pane.timelineText.includes("mobile-push-ok"),
  73. `该轮没有完成: ${prompt}`,
  74. 60_000,
  75. );
  76. }
  77. /** MP01/MP02:真实 Electron Main/凭据/HTTP/WS,只替换外部 server。MP13:本机推送开关。 */
  78. describe("移动端事件通知连接", () => {
  79. it("自动 HTTP 资格查询不连接远控,关闭远控后释放连接且仍有通知资格", async function () {
  80. this.timeout(120_000);
  81. const origin = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL,
  82. artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR;
  83. if (!origin || !artifacts) throw new Error("missing mobile push fixture");
  84. const evidence = async () =>
  85. (await (await fetch(`${origin}/__e2e/push`)).json()) as {
  86. queries: number;
  87. messages: Array<{
  88. message: { type: string; device_sid?: string };
  89. }>;
  90. };
  91. const devices = async () =>
  92. (
  93. await (
  94. await fetch(`${origin}/api/v1/remote/device`, {
  95. headers: { Authorization: "Bearer mock-token" },
  96. })
  97. ).json()
  98. ).data as Array<{ device_sid: string; online: boolean }>;
  99. await browser.waitUntil(async () => (await evidence()).queries > 0, {
  100. timeout: 45_000,
  101. timeoutMsg: "未查询 HTTP 通知资格",
  102. });
  103. expect((await devices()).filter((d) => d.online)).toHaveLength(0);
  104. expect((await evidence()).messages.some((m) => m.message.type === "auth_init")).toBe(false);
  105. await browser.waitUntil(
  106. async () => {
  107. if (await $('[data-testid="onboarding-page"]').isDisplayed()) await browser.keys("Escape");
  108. for (const button of await $$(
  109. 'button[aria-label="Mobile remote control"],button[aria-label="移动端远程控制"]',
  110. ))
  111. if (await button.isDisplayed()) {
  112. await button.click();
  113. return true;
  114. }
  115. return false;
  116. },
  117. { timeout: 60_000 },
  118. );
  119. // 由真实远控弹窗启用控制,不直接调用内部 manager。
  120. const card = $('[data-testid="web-remote-control-connection-card"]');
  121. await card.waitForDisplayed({ timeout: 40_000 });
  122. await browser.waitUntil(async () => (await devices()).some((d) => d.online), {
  123. timeout: 40_000,
  124. });
  125. expect((await devices()).filter((d) => d.online)).toHaveLength(1);
  126. await card.$("button").waitForEnabled({ timeout: 40_000 });
  127. await card.$("button").click();
  128. await browser.waitUntil(async () => (await devices()).every((d) => !d.online), {
  129. timeout: 10_000,
  130. });
  131. const pushLogs = (await readPushLogLines()).map((entry) => entry.line).join("\n");
  132. expect(pushLogs).toContain("eligibility");
  133. expect(pushLogs).toContain('"status":"available"');
  134. expect(pushLogs).not.toContain("mock-token");
  135. expect(pushLogs).not.toContain("x-auth-sign");
  136. await writeFile(join(artifacts, "mobile-push-logs.txt"), pushLogs);
  137. await writeFile(
  138. join(artifacts, "mobile-push-connection.json"),
  139. JSON.stringify(await evidence(), null, 2),
  140. );
  141. });
  142. it("MP13 关闭手机推送通知后不上报,重新打开后只上报新事件", async function () {
  143. this.timeout(240_000);
  144. const origin = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL,
  145. artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR;
  146. if (!origin || !artifacts) throw new Error("missing mobile push fixture");
  147. const evidence = async () =>
  148. (await (await fetch(`${origin}/__e2e/push`)).json()) as PushEvidence;
  149. // MP01 末尾可能还停在远控弹窗;先关闭,再回到可发送的会话。
  150. await browser.keys("Escape");
  151. await prepareV4ConversationE2E();
  152. // 资格已在 MP01 确认;这里再确认一次,避免单独运行本例时事件早于资格。
  153. await browser.waitUntil(async () => (await evidence()).queries > 0, {
  154. timeout: 45_000,
  155. timeoutMsg: "未查询 HTTP 通知资格",
  156. });
  157. await setMobilePushSwitch(false);
  158. await startNewV4Draft();
  159. await sendAndWaitComplete("E2E_MOBILE_PUSH_DISABLED");
  160. // 关闭期间的事件由 Main 在读取设置后跳过;跳过日志是这轮事件已处理完的唯一信号。
  161. let disabledLine: Record<string, string> | undefined;
  162. await browser.waitUntil(
  163. async () => {
  164. disabledLine = (await readPushLogLines()).find(
  165. ({ fields }) =>
  166. fields.reason === "user_disabled" &&
  167. fields.result === "skipped" &&
  168. fields.kind === "task_completed",
  169. )?.fields;
  170. return Boolean(disabledLine);
  171. },
  172. { timeout: 30_000, timeoutMsg: "关闭期间没有 user_disabled 的 task_completed 日志" },
  173. );
  174. const afterDisabled = await evidence();
  175. expect(afterDisabled.notifications).toHaveLength(0);
  176. await setMobilePushSwitch(true);
  177. await sendAndWaitComplete("E2E_MOBILE_PUSH_ENABLED");
  178. await browser.waitUntil(async () => (await evidence()).notifications.length > 0, {
  179. timeout: 30_000,
  180. timeoutMsg: "重新打开后没有上报新事件",
  181. });
  182. const afterEnabled = await evidence();
  183. expect(afterEnabled.notifications).toHaveLength(1);
  184. const posted = afterEnabled.notifications[0]!;
  185. expect(posted.event.kind).toBe("task_completed");
  186. const started = (await readPushLogLines()).filter(
  187. ({ fields }) => fields.result === "http_started" && fields.kind === "task_completed",
  188. );
  189. // 第一轮(关闭)与第二轮(打开)各有一次 http_started;上报的必须是第二轮,且不补发第一轮。
  190. expect(started).toHaveLength(2);
  191. expect(started[0]!.fields.run_id).toBe(disabledLine!.run_id);
  192. expect(posted.event.run_id).toBe(started[1]!.fields.run_id);
  193. expect(posted.event.run_id).not.toBe(disabledLine!.run_id);
  194. expect(posted.event.event_id).not.toBe(disabledLine!.event_id);
  195. const logs = (await readPushLogLines()).map((entry) => entry.line).join("\n");
  196. expect(logs).not.toContain("mock-token");
  197. await writeFile(join(artifacts, "mobile-push-switch-logs.txt"), logs);
  198. await writeFile(
  199. join(artifacts, "mobile-push-switch-evidence.json"),
  200. JSON.stringify({ afterDisabled, afterEnabled }, null, 2),
  201. );
  202. });
  203. });