remote-device-switch.mjs 13 KB

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