remote-device-switch.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // MD07:真实 Web 入口,受控 relay/桌面响应;不替代真机 OAuth/线上部署验收。
  2. // 启动:pnpm --filter @zcode/web exec vite --host 127.0.0.1 --port 5178 --strictPort
  3. // 运行:pnpm exec tsx packages/web/test/e2e/remote-control/projects/manual-review/pending/remote-device-switch.mjs
  4. import assert from "node:assert/strict";
  5. import { mkdir, writeFile } from "node:fs/promises";
  6. import { resolve } from "node:path";
  7. import { chromium } from "playwright-core";
  8. import { TID_AUTOMATIONS_OPEN, TID_TASK_NEW_BUTTON } from "@zcode/shared/test-ids";
  9. import { createDeviceSwitchDesktopBridge } from "./remote-device-switch.helpers.mjs";
  10. import {
  11. setup,
  12. mixedDevices,
  13. assertEventually,
  14. } from "../../../authentication/manual-review/pending/remote-login-v2.helpers.mjs";
  15. const origin = process.env.REMOTE_LOGIN_E2E_ORIGIN || "http://127.0.0.1:5178";
  16. const artifacts = resolve(".tmp/remote-device-switch-e2e");
  17. await mkdir(artifacts, { recursive: true });
  18. const browser = await chromium.launch({ channel: "chrome", headless: true });
  19. const results = [];
  20. const longName = "Alice’s MacBook Pro — 研发与测试工作站 / Development workstation";
  21. try {
  22. for (const width of process.env.REMOTE_DEVICE_E2E_WIDTH
  23. ? [Number(process.env.REMOTE_DEVICE_E2E_WIDTH)]
  24. : [390, 1024])
  25. for (const mode of ["home-only", "bridge"])
  26. for (const theme of ["zai-light", "zai-dark"])
  27. for (const locale of ["zh-CN", "en-US"]) {
  28. const h = await setup(browser, { width, theme, locale, signedIn: true });
  29. const { page } = h;
  30. page.setDefaultTimeout(15_000);
  31. const connections = [];
  32. const send = (socket, payload) => socket.send(JSON.stringify({ type: "data", payload }));
  33. await page.routeWebSocket(/\/api\/v1\/remote\/ws2(?:\?|$)/, (socket) => {
  34. const connection = { socket, sid: undefined, closed: false, holdBootstrap: false };
  35. connections.push(connection);
  36. socket.onClose(() => {
  37. connection.closed = true;
  38. connection.bridge?.dispose();
  39. });
  40. socket.onMessage((raw) => {
  41. const message = JSON.parse(String(raw));
  42. if (message.type === "auth_init") {
  43. connection.sid = message.device_sid;
  44. const device = mixedDevices.find((item) => item.device_sid === connection.sid);
  45. assert.ok(device?.online);
  46. assert.equal(new URL(socket.url()).searchParams.get("mid"), device.device_mid);
  47. socket.send(
  48. JSON.stringify({
  49. type: "auth_ack",
  50. device_sid: connection.sid,
  51. pair_status: "matched",
  52. }),
  53. );
  54. }
  55. if (message.type === "pair_status_query")
  56. socket.send(JSON.stringify({ type: "pair_status_ack", pair_status: "matched" }));
  57. const payload = message.payload;
  58. if (payload?.zcode_type === "rpc-frame" || payload?.zcode_type === "rpc-frame-ack") {
  59. connection.bridge?.acceptPayload(payload);
  60. return;
  61. }
  62. const workspace = {
  63. workspacePath: "/workspace/device-switch",
  64. workspaceIdentity: `remote:ssh:${connection.sid}:/workspace/device-switch`,
  65. label: `E2E_DEVICE_${connection.sid}`,
  66. kind: "remote",
  67. connectionState: mode === "bridge" ? "connected" : "disconnected",
  68. ...(mode === "bridge" ? { remoteSessionId: `remote-${connection.sid}` } : {}),
  69. };
  70. connection.result ??= { workspaces: [workspace] };
  71. if (payload?.zcode_type === "workspace-bridge-open") {
  72. const bridge = {
  73. ...workspace,
  74. workspaceKey: workspace.workspaceIdentity,
  75. bridgeSessionId: payload.bridgeSessionId,
  76. bridgeGeneration: payload.bridgeGeneration,
  77. };
  78. send(socket, {
  79. zcode_type: "workspace-bridge-ready",
  80. requestId: payload.requestId,
  81. bridgeSessionId: payload.bridgeSessionId,
  82. bridgeGeneration: payload.bridgeGeneration,
  83. bridge,
  84. });
  85. connection.bridge = createDeviceSwitchDesktopBridge(socket, bridge, {
  86. locale,
  87. theme,
  88. });
  89. }
  90. if (payload?.zcode_type === "bootstrap-request") {
  91. const response = {
  92. zcode_type: "bootstrap-response",
  93. requestId: payload.requestId,
  94. success: true,
  95. result: {
  96. windowControlSessionId: connection.sid,
  97. desktopAppVersion: "3.13.0",
  98. ...connection.result,
  99. },
  100. };
  101. if (connection.holdBootstrap) connection.pendingBootstrap = response;
  102. else send(socket, response);
  103. }
  104. if (payload?.zcode_type === "workspace-list-request")
  105. send(socket, {
  106. ...(connection.failList
  107. ? {
  108. zcode_type: "app-error",
  109. reason: "unexpected-error",
  110. error: "E2E_REFRESH_FAILED",
  111. }
  112. : {
  113. zcode_type: "workspace-list-response",
  114. success: true,
  115. result: connection.result,
  116. }),
  117. requestId: payload.requestId,
  118. });
  119. });
  120. });
  121. const hasBridgeSession = (sid) =>
  122. page.evaluate(
  123. async ({ url, sid }) => {
  124. const store = await import(url);
  125. return Boolean(store.getRemoteWorkspaceSession(`remote-${sid}`));
  126. },
  127. {
  128. url: `/@fs${resolve("packages/ui/src/store/remoteWorkspaceSessionStore.ts")}`,
  129. sid,
  130. },
  131. );
  132. // 手机 home 与宽屏共用项目侧栏,设备入口是导航首行的整行按钮:可读名称“切换设备”,行内显示电脑名。
  133. const buttonName = () => (locale === "zh-CN" ? "切换设备" : "Switch device");
  134. const waitForHome = async (name) => {
  135. const button = page.getByRole("button", { name: buttonName(), exact: true });
  136. const onboarding = page.getByTestId("onboarding-page");
  137. const startupDialog = page.getByRole("dialog");
  138. // 首启可能显示职业引导、欢迎页或迁移提示,不能假定 home-only 必定进入职业引导。
  139. await button.or(onboarding).or(startupDialog).first().waitFor();
  140. if (await onboarding.isVisible()) {
  141. await onboarding.getByRole("button", { name: /退出引导|Exit onboarding/ }).click();
  142. }
  143. await button.or(startupDialog).first().waitFor();
  144. if (await startupDialog.isVisible())
  145. await startupDialog.getByRole("button", { name: /^(Close|关闭)$/ }).click();
  146. await button.waitFor();
  147. await button.getByText(name, { exact: true }).waitFor();
  148. const navigation = page.getByTestId("sidebar-primary-navigation");
  149. // RSNAV01:远控不承载这两个主视图;初次连接、切换设备和刷新都不能露出无效入口。
  150. assert.equal(await navigation.getByTestId(TID_AUTOMATIONS_OPEN).count(), 0);
  151. assert.equal(await navigation.getByTestId("plugin-store-sidebar-open").count(), 0);
  152. assert.equal(await navigation.getByTestId(TID_TASK_NEW_BUTTON).isVisible(), true);
  153. assert.equal(
  154. await navigation.evaluate(
  155. (node, label) => node.firstElementChild?.ariaLabel === label,
  156. buttonName(),
  157. ),
  158. true,
  159. "设备行必须是导航首行,位于“新建任务”之上",
  160. );
  161. // 长电脑名单行截断,不再撑高设备行。
  162. const [rowHeight, nameClipped] = await button.evaluate((node) => {
  163. const label = node.querySelector("span");
  164. return [node.getBoundingClientRect().height, label.scrollWidth > label.clientWidth];
  165. });
  166. assert.equal(rowHeight, 32);
  167. assert.equal(nameClipped, name === longName);
  168. return button;
  169. };
  170. try {
  171. const url = new URL("/remote/v4?app_version=3.13.0&sid=e2e-device&mid=e2e-mid", origin);
  172. url.searchParams.set("name", longName);
  173. await page.goto(url.href, { waitUntil: "domcontentloaded" });
  174. const button = await waitForHome(longName);
  175. assert.equal(h.traffic.lists, 0, "扫码连接不先请求账号设备列表");
  176. if (mode === "bridge") assert.equal(await hasBridgeSession("e2e-device"), true);
  177. await page.evaluate(() => document.fonts.ready);
  178. assert.equal(
  179. await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
  180. false,
  181. );
  182. const filename = `connected-${width}-${mode}-${theme}-${locale}.png`;
  183. await page.screenshot({ path: resolve(artifacts, filename), fullPage: true });
  184. const first = connections[0];
  185. // 触发真实恢复请求并延迟响应,切换后旧请求不可重新挂载首页。
  186. first.holdBootstrap = true;
  187. first.socket.send(JSON.stringify({ type: "pair_status_ack", pair_status: "waiting" }));
  188. first.socket.send(JSON.stringify({ type: "pair_status_ack", pair_status: "matched" }));
  189. await assertEventually(() => Boolean(first.pendingBootstrap));
  190. await button.click();
  191. await page.getByRole("heading", { name: /选择电脑|Choose a computer/ }).waitFor();
  192. await assertEventually(() => first.closed);
  193. if (mode === "bridge") assert.equal(await hasBridgeSession("e2e-device"), false);
  194. send(first.socket, first.pendingBootstrap);
  195. assert.equal(new URL(page.url()).searchParams.has("sid"), false);
  196. assert.equal(new URL(page.url()).searchParams.has("name"), false);
  197. assert.equal(new URL(page.url()).searchParams.get("app_version"), "3.13.0");
  198. assert.equal(
  199. await page.evaluate(() => localStorage.getItem("zcode-web-remote-last-device-sid")),
  200. "e2e-device",
  201. );
  202. await page.getByRole("button", { name: /Alice’s MacBook/ }).waitFor();
  203. await page.getByRole("button", { name: /^(刷新|Refresh)$/ }).click();
  204. await assertEventually(() => h.traffic.lists === 2);
  205. assert.equal(connections.length, 1, "最近设备仍在线,列表和刷新也不能自动连回去");
  206. assert.equal(h.traffic.tokens, 1);
  207. await page.getByRole("button", { name: /Workstation/ }).click();
  208. await waitForHome("Workstation");
  209. assert.equal(new URL(page.url()).searchParams.get("sid"), "second");
  210. assert.equal(new URL(page.url()).searchParams.get("mid"), "d67e89f0-other");
  211. assert.equal(connections.length, 2);
  212. assert.equal(connections[1].sid, "second");
  213. if (mode === "bridge") {
  214. assert.equal(await hasBridgeSession("e2e-device"), false);
  215. assert.equal(await hasBridgeSession("second"), true);
  216. }
  217. assert.equal(await page.getByText(`E2E_DEVICE_e2e-device`, { exact: true }).count(), 0);
  218. // 应用就绪由下方真实首页断言确认,不等待外部字体等非关键资源的 load。
  219. await page.reload({ waitUntil: "domcontentloaded" });
  220. await waitForHome("Workstation");
  221. assert.equal(connections.at(-1).sid, "second");
  222. assert.equal(h.traffic.lists, 2, "刷新按新 SID 直连,不重新选设备");
  223. assert.deepEqual(h.errors, []);
  224. results.push({
  225. width,
  226. mode,
  227. theme,
  228. locale,
  229. result: "passed",
  230. screenshot: filename,
  231. });
  232. } catch (error) {
  233. console.error(error);
  234. await page.screenshot({ path: resolve(artifacts, "failure.png"), fullPage: true });
  235. console.error(await page.locator("body").innerText(), h.errors);
  236. throw error;
  237. } finally {
  238. await h.context.close();
  239. }
  240. }
  241. await writeFile(resolve(artifacts, "results.json"), JSON.stringify(results, null, 2));
  242. console.log(`MD07 passed: ${results.length} configurations; ${artifacts}`);
  243. } finally {
  244. await browser.close();
  245. }