mobile-remote-onboarding.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // ONBOARD-REMOTE-01:真实引导组件、远程服务装配、手机 attachment allowlist 与 WebSocket RPC 的浏览器边界回归。
  2. // 首页按钮/Root key 重建由夹具驱动;不覆盖真实 relay 配对或 SSH/WSL/Docker transport。
  3. // R3 下 SSH/WSL/Docker 与 Server 都走 Source 全转发,引导记录 owner 是 Source,不是本机 Local Host。
  4. // 运行:pnpm exec tsx packages/desktop/test/e2e/remote-control/connection/manual-review/pending/mobile-remote-onboarding.mjs
  5. import assert from "node:assert/strict";
  6. import { mkdtemp, mkdir, rm } from "node:fs/promises";
  7. import { tmpdir } from "node:os";
  8. import { resolve } from "node:path";
  9. import { fileURLToPath } from "node:url";
  10. import { chromium } from "playwright-core";
  11. import { createServer } from "vite";
  12. import react from "@vitejs/plugin-react";
  13. import tailwindcss from "@tailwindcss/vite";
  14. import { WebSocketServer } from "ws";
  15. import { ChannelServer, Emitter, Event, SocketProtocol, VSBuffer } from "@zcode/rpc";
  16. import {
  17. IBroadcastService,
  18. IOnboardingRecordService,
  19. ISettingService,
  20. ServiceCollection,
  21. } from "@zcode/services";
  22. import { setDataBaseDir } from "@zcode/services/node";
  23. import { createOnboardingRecordService } from "../../../../../../../services/src/onboarding/onboardingRecordService.js";
  24. import { createServerRemoteWorkspaceServiceCollection } from "../../../../../../src/host/remoteWorkspaceServiceCollection.js";
  25. import { exposeWindowHostAttachmentServices } from "../../../../../../src/host/windowHostAttachmentRpcPolicy.js";
  26. const repoRoot = fileURLToPath(new URL("../../../../../../../../", import.meta.url));
  27. const artifacts = resolve(repoRoot, ".tmp/mobile-remote-onboarding-e2e");
  28. const dataDir = await mkdtemp(resolve(tmpdir(), "onboarding-remote-e2e-"));
  29. await mkdir(artifacts, { recursive: true });
  30. setDataBaseDir(dataDir);
  31. const localRecord = createOnboardingRecordService({
  32. loadUserId: async () => "desktop-user",
  33. hasExistingLocalTask: async () => false,
  34. });
  35. const sourceRecord = createOnboardingRecordService({
  36. loadUserId: async () => "source-user",
  37. hasExistingLocalTask: async () => false,
  38. });
  39. const broadcastService = { onMessage: Event.None, send: async () => {} };
  40. const connectionServices = new Proxy(
  41. {
  42. onboardingRecordService: sourceRecord,
  43. zcodeAgentService: { onDynamicSessionRuntimePreferencesRequest: () => Event.None },
  44. },
  45. { get: (target, key) => target[key] ?? {} },
  46. );
  47. const clientConfigService = { getSnapshot: async () => ({ pluginStoreOrder: null }) };
  48. // 真实 Host 传入的 sourceServices 含本机记录服务;用例借此证明远程集合不会回落到本机记录。
  49. const sourceServices = new ServiceCollection().register(IOnboardingRecordService, localRecord);
  50. const targetKinds = ["ssh", "server"];
  51. const collections = Object.fromEntries(
  52. targetKinds.map((targetKind) => [
  53. targetKind,
  54. createServerRemoteWorkspaceServiceCollection({
  55. clientConfigService,
  56. connectionServices,
  57. targetKind,
  58. sourceServices,
  59. }),
  60. ]),
  61. );
  62. // settings 故意没有 onboardingOccupation,确保通过来自真实记录 owner 的判定进入任务。
  63. for (const services of Object.values(collections)) {
  64. services.register(ISettingService, {
  65. get: async () => ({ locale: "zh-CN" }),
  66. update: async () => {},
  67. });
  68. services.register(IBroadcastService, broadcastService);
  69. }
  70. const entryId = resolve(repoRoot, "packages/desktop/onboarding-e2e-entry.js");
  71. const entry = `
  72. import React, { useState } from 'react';
  73. import { createRoot } from 'react-dom/client';
  74. import { connectViaWebSocket } from '@zcode/client';
  75. import { Event } from '@zcode/rpc';
  76. import { ServiceProvider } from '@/hooks/useServices.js';
  77. import { PlatformProvider } from '@/hooks/usePlatform.js';
  78. import { StoreProvider } from '@/store/StoreProvider.js';
  79. import { ZCodeIntlProvider } from '@/i18n/IntlProvider.js';
  80. import { OccupationOnboarding } from '@/onboarding/OccupationOnboarding.js';
  81. import '@/styles.css';
  82. const h = React.createElement;
  83. const platform = { getDeviceId: () => 'browser-onboarding', reportTelemetryEvent: async () => {} };
  84. const broadcast = { onMessage: Event.None, send: async () => {} };
  85. function Fixture() {
  86. const [bridge, setBridge] = useState(null);
  87. const open = async () => {
  88. const services = await connectViaWebSocket('ws://' + location.host + '/onboarding-rpc?kind=' + new URLSearchParams(location.search).get('kind'));
  89. setBridge({services, id: crypto.randomUUID()});
  90. };
  91. return h(React.Fragment, null,
  92. h('button', {onClick: open}, '新建远程任务'),
  93. bridge && h(ServiceProvider, {key: bridge.id, services: bridge.services},
  94. h(PlatformProvider, {platform}, h(StoreProvider, {broadcastService: broadcast},
  95. h(ZCodeIntlProvider, null,
  96. h(OccupationOnboarding, null, h('div', {'data-testid': 'task-draft', 'data-bridge-id': bridge.id}, '远程任务草稿')))))));
  97. }
  98. createRoot(document.getElementById('root')).render(h(Fixture));
  99. `;
  100. const vite = await createServer({
  101. configFile: false,
  102. root: repoRoot,
  103. plugins: [
  104. {
  105. name: "onboarding-e2e-fixture",
  106. resolveId: (id) => (id === "/onboarding-e2e-entry.js" ? entryId : undefined),
  107. load: (id) => (id === entryId ? entry : undefined),
  108. configureServer(server) {
  109. server.middlewares.use(async (req, res, next) => {
  110. if (!req.url?.startsWith("/onboarding-fixture?")) return next();
  111. res.setHeader("Content-Type", "text/html");
  112. res.end(
  113. await server.transformIndexHtml(
  114. req.url,
  115. '<div id="root"></div><script type="module" src="/onboarding-e2e-entry.js"></script>',
  116. ),
  117. );
  118. });
  119. },
  120. },
  121. react(),
  122. tailwindcss(),
  123. ],
  124. resolve: { alias: { "@": resolve(repoRoot, "packages/ui/src") } },
  125. server: { host: "127.0.0.1", port: 0 },
  126. optimizeDeps: { entries: [], include: ["react", "react-dom/client", "react/jsx-runtime"] },
  127. });
  128. const wsServer = new WebSocketServer({ noServer: true });
  129. const rpcErrors = [];
  130. wsServer.on("connection", (socket, req) => {
  131. const kind = new URL(req.url, "http://localhost").searchParams.get("kind");
  132. const onData = new Emitter();
  133. const onClose = new Emitter();
  134. const protocol = new SocketProtocol({
  135. onData: onData.event,
  136. onClose: onClose.event,
  137. onEnd: Event.None,
  138. write: (buffer) => socket.send(buffer.buffer),
  139. end: () => socket.close(),
  140. drain: async () => {},
  141. dispose: () => {},
  142. });
  143. const server = new ChannelServer(protocol, "mobile-onboarding", 1000);
  144. // 与真实手机 attachment 相同的 allowlist;漏放行 onboarding-record 时调用会超时。
  145. exposeWindowHostAttachmentServices({
  146. server,
  147. services: collections[kind],
  148. clientMode: "web-remote-replayable",
  149. });
  150. socket.on("message", (data) => onData.fire(VSBuffer.wrap(new Uint8Array(data))));
  151. socket.on("error", (error) => rpcErrors.push(error.message));
  152. socket.on("close", () => {
  153. onClose.fire();
  154. server.dispose();
  155. onData.dispose();
  156. onClose.dispose();
  157. });
  158. });
  159. vite.httpServer.on("upgrade", (req, socket, head) => {
  160. if (req.url?.startsWith("/onboarding-rpc?"))
  161. wsServer.handleUpgrade(req, socket, head, (ws) => wsServer.emit("connection", ws, req));
  162. });
  163. let browser;
  164. try {
  165. await vite.listen();
  166. const origin = `http://127.0.0.1:${vite.httpServer.address().port}`;
  167. browser = await chromium.launch({ channel: "chrome", headless: true });
  168. for (const kind of targetKinds) {
  169. const owner = sourceRecord;
  170. const other = localRecord;
  171. for (const completed of [true, false]) {
  172. await owner.clearRecords();
  173. if (completed)
  174. await owner.appendRecord("browser-onboarding", {
  175. occupation: "developer",
  176. interfaceMode: "coding",
  177. memoryEnabled: false,
  178. proactiveSuggestionsEnabled: false,
  179. completedAt: "2026-10-09T00:00:00.000Z",
  180. });
  181. const context = await browser.newContext({
  182. viewport: { width: 390, height: 844 },
  183. locale: "zh-CN",
  184. });
  185. const page = await context.newPage();
  186. const errors = [];
  187. page.on("pageerror", (error) => errors.push(error.message));
  188. page.on("console", (message) => {
  189. if (message.text().includes("occupation-onboarding") && message.type() === "warning")
  190. errors.push(message.text());
  191. });
  192. page.setDefaultTimeout(15_000);
  193. try {
  194. await page.goto(`${origin}/onboarding-fixture?kind=${kind}`);
  195. await page.getByRole("button", { name: "新建远程任务", exact: true }).click();
  196. const onboarding = page.getByTestId("onboarding-page");
  197. const draft = page.getByTestId("task-draft");
  198. if (!completed) {
  199. await onboarding.waitFor();
  200. await page.keyboard.press("Escape");
  201. }
  202. await draft.waitFor();
  203. // 关闭的 RPC 已落盘后再重新挂载,避免把写入途中的第二次点击混进本次接线回归。
  204. await assertEventually(async () => !(await owner.shouldOnboard("browser-onboarding")));
  205. const previousBridgeId = await draft.getAttribute("data-bridge-id");
  206. await page.getByRole("button", { name: "新建远程任务", exact: true }).click();
  207. await page.waitForFunction((previous) => {
  208. const current = document
  209. .querySelector('[data-testid="task-draft"]')
  210. ?.getAttribute("data-bridge-id");
  211. return Boolean(current && current !== previous);
  212. }, previousBridgeId);
  213. await draft.waitFor();
  214. assert.equal(await onboarding.count(), 0);
  215. assert.equal(
  216. await other.shouldOnboard("browser-onboarding"),
  217. true,
  218. "不能写入另一侧身份的记录",
  219. );
  220. assert.deepEqual(errors, []);
  221. await page.screenshot({
  222. path: resolve(artifacts, `${kind}-${completed ? "completed" : "dismissed"}.png`),
  223. });
  224. console.log(`PASS ONBOARD-REMOTE-01 ${kind} ${completed ? "completed" : "dismissed"}`);
  225. } catch (error) {
  226. await page.screenshot({ path: resolve(artifacts, "failure.png") });
  227. console.error(await page.locator("body").innerText(), errors);
  228. throw error;
  229. } finally {
  230. await context.close();
  231. }
  232. }
  233. }
  234. assert.deepEqual(rpcErrors, []);
  235. } finally {
  236. await browser?.close();
  237. for (const socket of wsServer.clients) socket.terminate();
  238. await new Promise((done) => wsServer.close(done));
  239. await vite.close();
  240. setDataBaseDir(null);
  241. await rm(dataDir, { recursive: true, force: true });
  242. }
  243. async function assertEventually(predicate) {
  244. for (let attempt = 0; attempt < 50; attempt += 1) {
  245. if (await predicate()) return;
  246. await new Promise((done) => setTimeout(done, 20));
  247. }
  248. assert.fail("引导关闭记录未落盘");
  249. }