conversation-session-r3-mobile-startup-restore.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { type WebRemoteControlStatus } from "@zcode/shared";
  4. import { TID_V4_COMPOSER_INPUT, TID_V4_SESSION_PANE, testId } from "@zcode/shared/test-ids";
  5. import { readSettings } from "#e2e/helpers/desktop-app";
  6. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  7. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  8. import {
  9. bringRemoteDeviceOnline,
  10. readRemoteDockerContainer,
  11. takeRemoteDeviceOffline,
  12. } from "#e2e/helpers/remote-docker-target";
  13. import { waitForRendererAfterColdRestart } from "#e2e/helpers/ssh-remote-lifecycle";
  14. import {
  15. connectSSHWorkspace,
  16. prepareSSHConnectionPage,
  17. readRemoteTabSnapshot,
  18. readSSHRuntimeConfig,
  19. } from "#e2e/helpers/ssh-remote-p0";
  20. const CASE_MARKER = "E2E_R3_MOBILE_STARTUP_RESTORE";
  21. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-startup");
  22. const CHROME =
  23. process.env.R3_MOBILE_CHROME?.trim() ||
  24. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
  25. const MOBILE_VIEWPORT = { width: 390, height: 844 };
  26. async function remoteStatus() {
  27. const serialized = await browser.execute(async () => {
  28. const bridge = (
  29. window as Window & { zcode?: { getWebRemoteControlStatus(): Promise<{ status: string }> } }
  30. ).zcode;
  31. if (!bridge) throw new Error("缺少 preload 远控接口");
  32. // WebDriver 把返回对象的 error 字段当成协议错误;序列化后再在测试端还原真实状态。
  33. return JSON.stringify(await bridge.getWebRemoteControlStatus());
  34. });
  35. return JSON.parse(serialized) as WebRemoteControlStatus;
  36. }
  37. async function onlineDevices(origin: string) {
  38. const response = await fetch(`${origin}/api/v1/remote/device`, {
  39. headers: { Authorization: "Bearer mock-token" },
  40. });
  41. const devices = (await response.json()).data as Array<{ device_sid: string; online: boolean }>;
  42. return devices.filter((device) => device.online).map((device) => device.device_sid);
  43. }
  44. describe(`${CASE_MARKER}: 上次远控目标是 SSH 项目,重启时远端离线`, () => {
  45. it("AUTH-09-R: 远端离线时恢复设备连接,手机可配对,远端恢复后手机进入该项目,桌面弹窗沿用原连接", async function () {
  46. this.timeout(15 * 60_000);
  47. const origin = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL;
  48. if (!origin) throw new Error(`${CASE_MARKER}: 缺少 loopback relay fixture`);
  49. const container = readRemoteDockerContainer(CASE_MARKER);
  50. const config = readSSHRuntimeConfig(CASE_MARKER);
  51. const workspacePath = config.workspacePaths[0];
  52. const facts: Record<string, unknown> = {};
  53. await mkdir(artifactDir, { recursive: true });
  54. // 1. 连接 SSH 项目,在该项目打开远控弹窗,使它成为上次启用目标。
  55. await prepareSSHConnectionPage(CASE_MARKER);
  56. const connected = await connectSSHWorkspace({ caseMarker: CASE_MARKER, config, workspacePath });
  57. const identity = connected.workspaceIdentity;
  58. if (!identity) throw new Error(`${CASE_MARKER}: SSH 项目缺少 workspaceIdentity`);
  59. const projectId = await $(`[data-project-workspace-identity="${identity}"]`).getAttribute(
  60. "data-project-id",
  61. );
  62. if (!projectId) throw new Error(`${CASE_MARKER}: SSH 项目缺少 projectId`);
  63. const trigger = $('button[aria-label="移动端远程控制"]');
  64. await trigger.waitForClickable({ timeout: 30_000 });
  65. await trigger.click();
  66. await browser.waitUntil(
  67. async () => {
  68. const status = await remoteStatus();
  69. return status.status === "running" && status.workspaceIdentity === identity;
  70. },
  71. { timeout: 60_000, timeoutMsg: `${CASE_MARKER}: 在 SSH 项目开启远控失败` },
  72. );
  73. await browser.keys("Escape");
  74. await browser.waitUntil(
  75. async () => {
  76. const settings = await readSettings();
  77. const lastActive = settings.lastActiveWorkspace as { workspaceIdentity?: string } | null;
  78. return (
  79. settings.webRemoteControlLastEnabledContext?.workspaceIdentity === identity &&
  80. lastActive?.workspaceIdentity === identity
  81. );
  82. },
  83. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 上次启用目标或激活项目未写入 SSH 项目` },
  84. );
  85. // 2. 远端离线后重启:窗口只恢复断开的 SSH 项目,启动重连会失败。
  86. await takeRemoteDeviceOffline(container);
  87. let mobileBrowser: { close(): Promise<void> } | null = null;
  88. try {
  89. await reloadElectronSessionPreservingBrowserProfile(browser);
  90. await waitForRendererAfterColdRestart(CASE_MARKER);
  91. // 3. 修复点:远端没连上也要恢复设备连接,初始目标仍是上次的 SSH 项目。
  92. await browser.waitUntil(async () => (await remoteStatus()).status === "running", {
  93. timeout: 60_000,
  94. timeoutMsg: `${CASE_MARKER}: 远端离线时重启未自动恢复远控`,
  95. });
  96. const restored = await remoteStatus();
  97. expect(restored.workspaceIdentity).toBe(identity);
  98. expect(restored.remoteSessionId).toBeUndefined();
  99. expect((await readRemoteTabSnapshot(identity)).remoteSessionId).toBeNull();
  100. await browser.waitUntil(async () => (await onlineDevices(origin)).length === 1, {
  101. timeout: 10_000,
  102. timeoutMsg: `${CASE_MARKER}: 自动恢复后 relay 上没有在线设备`,
  103. });
  104. facts.restored = {
  105. status: restored.status,
  106. workspaceIdentityMatches: restored.workspaceIdentity === identity,
  107. remoteSessionId: restored.remoteSessionId ?? null,
  108. };
  109. // 4. 手机用恢复后的链接配对。没有可 bridge 的工作区,手机进入 home-only,列出离线的 SSH 项目。
  110. const pairUrl = restored.connectUrl;
  111. if (!pairUrl?.startsWith("http")) throw new Error(`${CASE_MARKER}: 恢复后没有配对链接`);
  112. const { chromium } = await import("playwright-core");
  113. const launched = await chromium.launch({ headless: true, executablePath: CHROME });
  114. mobileBrowser = launched;
  115. const context = await launched.newContext({
  116. viewport: MOBILE_VIEWPORT,
  117. isMobile: true,
  118. hasTouch: true,
  119. locale: "zh-CN",
  120. });
  121. await seedMobileFixtureLogin(context);
  122. const mobile = await context.newPage();
  123. const workspaceRow = mobile.locator(`[data-home-only-workspace="${identity}"]`);
  124. await openMobilePairingPage(mobile, pairUrl, {
  125. artifactDir,
  126. caseMarker: CASE_MARKER,
  127. phase: "offline-remote-pairing",
  128. readySelector: `[data-home-only-workspace="${identity}"]`,
  129. });
  130. await browser.waitUntil(async () => Boolean((await remoteStatus()).mobileConnected), {
  131. timeout: 60_000,
  132. timeoutMsg: `${CASE_MARKER}: 桌面未看到手机连接`,
  133. });
  134. // 合成账号首次进入会弹会话迁移引导;它与本用例无关,取消后再操作首页。
  135. const dismissMigration = async () => {
  136. const cancel = mobile.getByTestId("onboarding-wizard-cancel");
  137. if (await cancel.isVisible()) {
  138. await cancel.click();
  139. await mobile.getByTestId("onboarding-migration-dialog").waitFor({ state: "hidden" });
  140. }
  141. };
  142. await dismissMigration();
  143. // 离线行带“ · 连接”动作;可 bridge 后该动作消失,行也不再禁用。
  144. expect(await workspaceRow.textContent()).toContain(" · ");
  145. await mobile.screenshot({
  146. path: resolve(artifactDir, "mobile-offline-remote-home.png"),
  147. fullPage: true,
  148. animations: "disabled",
  149. });
  150. // 5. 远端恢复;手机点离线行交给桌面重连,再点同一行进入项目并新建草稿。
  151. await bringRemoteDeviceOnline(container, { host: config.host, port: config.port });
  152. await workspaceRow.click();
  153. await browser.waitUntil(
  154. async () => Boolean((await readRemoteTabSnapshot(identity)).remoteSessionId),
  155. { timeout: 120_000, timeoutMsg: `${CASE_MARKER}: 手机触发的重连没有恢复 SSH 项目` },
  156. );
  157. await mobile.waitForFunction(
  158. (key: string) => {
  159. const row = document.querySelector<HTMLButtonElement>(
  160. `[data-home-only-workspace=${JSON.stringify(key)}]`,
  161. );
  162. return Boolean(row && !row.disabled && !row.textContent?.includes(" · "));
  163. },
  164. identity,
  165. { timeout: 60_000 },
  166. );
  167. await workspaceRow.click();
  168. // 打开工作区后手机可能直接显示该工作区的草稿,也可能先显示项目列表;两种落点都要进入同一个草稿。
  169. const projectCard = mobile.locator(`[data-project-id="${projectId}"]`);
  170. const composer = mobile.getByTestId(TID_V4_COMPOSER_INPUT).first();
  171. const pane = mobile.getByTestId(testId(TID_V4_SESSION_PANE, "workspace-main"));
  172. const onboarding = mobile.getByTestId("onboarding-page");
  173. try {
  174. await composer.or(projectCard).or(onboarding).first().waitFor({ timeout: 60_000 });
  175. // 切到远端 Host 后 Root 重建,隔离账号会再次看到职业引导;沿用配对 helper 的三步跳过。
  176. if (await onboarding.isVisible()) {
  177. for (const step of [1, 2, 3]) {
  178. await onboarding
  179. .locator('li[aria-current="step"]')
  180. .filter({ hasText: `${step}.` })
  181. .waitFor();
  182. await onboarding.getByRole("button", { name: /^(跳过|Skip)$/u }).click();
  183. }
  184. // 偏好保存后引导会自行关闭;仍可见时才点退出,与配对 helper 的判定一致。
  185. await mobile.waitForFunction(() => {
  186. const page = document.querySelector('[data-testid="onboarding-page"]');
  187. return (
  188. !page ||
  189. Array.from(page.querySelectorAll("button")).some(
  190. (button) =>
  191. /^(开始使用|Get started)$/u.test(button.textContent?.trim() ?? "") &&
  192. !button.disabled,
  193. )
  194. );
  195. });
  196. if (await onboarding.isVisible())
  197. await onboarding.getByRole("button", { name: /退出引导|Exit onboarding/u }).click();
  198. await onboarding.waitFor({ state: "hidden", timeout: 30_000 });
  199. facts.onboardingAfterSwitch = true;
  200. }
  201. await composer.or(projectCard).first().waitFor({ timeout: 60_000 });
  202. await dismissMigration();
  203. const landing = (await composer.isVisible()) ? "composer" : "project-list";
  204. if (landing === "project-list")
  205. await projectCard.getByTestId("virtual-project-create-task").click();
  206. await composer.waitFor({ timeout: 60_000 });
  207. expect(await pane.getAttribute("data-session-id")).toBe("draft");
  208. facts.mobileLanding = landing;
  209. } catch (error) {
  210. facts.mobileFailure = {
  211. url: new URL(mobile.url()).pathname,
  212. testIds: await mobile.evaluate(() =>
  213. [
  214. ...new Set(
  215. [...document.querySelectorAll("[data-testid]")].map((e) =>
  216. e.getAttribute("data-testid"),
  217. ),
  218. ),
  219. ].slice(0, 80),
  220. ),
  221. mobilePage: await mobile.evaluate(
  222. () =>
  223. document.querySelector("[data-mobile-page]")?.getAttribute("data-mobile-page") ??
  224. null,
  225. ),
  226. };
  227. await mobile
  228. .screenshot({
  229. path: resolve(artifactDir, "mobile-enter-remote-failure.png"),
  230. fullPage: true,
  231. })
  232. .catch(() => undefined);
  233. throw error;
  234. }
  235. const afterReconnect = await remoteStatus();
  236. // 同一次设备连接:手机进入项目不能靠重启远控。
  237. expect(afterReconnect.sessionId).toBe(restored.sessionId);
  238. expect(afterReconnect.mobileConnected).toBe(true);
  239. await mobile.screenshot({
  240. path: resolve(artifactDir, "mobile-reconnected-remote-draft.png"),
  241. fullPage: true,
  242. animations: "disabled",
  243. });
  244. facts.afterReconnect = {
  245. sameDeviceSession: afterReconnect.sessionId === restored.sessionId,
  246. mobileConnected: afterReconnect.mobileConnected,
  247. mobilePane: "draft",
  248. };
  249. await context.close();
  250. // 6. 手机断开后在该 SSH 项目打开远控弹窗:远控以未连接目标启动、远端之后连上,
  251. // 弹窗也要判为同一会话,不能重启 device relay。重启会换新 runtime,丢掉手机上报的位置。
  252. await browser.waitUntil(async () => (await remoteStatus()).mobileConnected === false, {
  253. timeout: 60_000,
  254. timeoutMsg: `${CASE_MARKER}: 关闭手机后桌面仍显示手机已连接`,
  255. });
  256. const tab = await readRemoteTabSnapshot(identity);
  257. expect(tab.activeWorkspaceIdentity).toBe(identity);
  258. if (!tab.remoteSessionId) throw new Error(`${CASE_MARKER}: SSH tab 缺少 remoteSessionId`);
  259. // 冷重启后旧元素引用失效,重新查询入口。
  260. const reopenTrigger = $('button[aria-label="移动端远程控制"]');
  261. await reopenTrigger.waitForClickable({ timeout: 30_000 });
  262. await reopenTrigger.click();
  263. const stop = $('[data-testid="web-remote-control-connection-card"] button');
  264. // 停止按钮在弹窗完成状态同步(复用或重启都会等到结果)后才可用。
  265. await stop.waitForEnabled({ timeout: 60_000 });
  266. const afterDialog = await remoteStatus();
  267. await browser.keys("Escape");
  268. facts.dialogAfterReconnect = {
  269. sameDeviceSession: afterDialog.sessionId === restored.sessionId,
  270. keptMobileViewState: afterDialog.mobileViewState?.activeWorkspaceKey === identity,
  271. remoteSessionIdMatchesTab: afterDialog.remoteSessionId === tab.remoteSessionId,
  272. };
  273. expect(afterDialog.sessionId).toBe(restored.sessionId);
  274. expect(afterDialog.mobileViewState?.activeWorkspaceKey).toBe(identity);
  275. expect(afterDialog.remoteSessionId).toBe(tab.remoteSessionId);
  276. } finally {
  277. await mobileBrowser?.close().catch(() => undefined);
  278. await bringRemoteDeviceOnline(container, { host: config.host, port: config.port }).catch(
  279. () => undefined,
  280. );
  281. await writeFile(
  282. resolve(artifactDir, "remote-startup-restore-ssh.json"),
  283. JSON.stringify(facts, null, 2),
  284. );
  285. }
  286. });
  287. });