web-remote-control-session-events-fixture.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import { resolve } from "node:path";
  2. import { spawn } from "node:child_process";
  3. import { once } from "node:events";
  4. import { readFile, writeFile } from "node:fs/promises";
  5. import { createFakeRelayV2 } from "@zcode/shared/testing/fake-relay-v2";
  6. export const WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS = {
  7. "oauth:active_provider": "zai",
  8. "oauth:zai:access_token": "mock-token",
  9. "oauth:zai:user_info": JSON.stringify({
  10. id: "zcode-e2e-user",
  11. username: "ZCode E2E",
  12. displayName: "ZCode E2E",
  13. }),
  14. zcodejwttoken: "mock-token",
  15. };
  16. /** 单窗口真实 OAuth owner → RPC → renderer → Main 回归,只替换外部 relay。 */
  17. export async function prepareWebRemoteControlSessionEventsFixture(options: {
  18. credentialsFile: string;
  19. settingsFile: string;
  20. workspacePath: string;
  21. webUrl?: string;
  22. mobilePush?: boolean;
  23. }): Promise<() => Promise<void>> {
  24. const relay = await createFakeRelayV2({
  25. users: { "mock-token": "zcode-e2e-user" },
  26. onHttp: (call) => {
  27. if (options.mobilePush && call.path === "/api/v1/remote/notification/status")
  28. return {
  29. status: 200,
  30. body: {
  31. code: 0,
  32. data: { protocol_version: 1, event_transport: "http", status: "available" },
  33. },
  34. };
  35. if (options.mobilePush && call.path === "/__e2e/push")
  36. return {
  37. status: 200,
  38. body: {
  39. messages: relay.messages,
  40. queries: relay.httpCalls.filter((x) => x.path === "/api/v1/remote/notification/status")
  41. .length,
  42. },
  43. };
  44. if (call.path.startsWith("/api/v1/remote/")) return;
  45. // 完整工作区会读取推荐场景;配置对象不能冒充场景数组,否则真实首页渲染会崩溃。
  46. if (call.path === "/api/v1/client/scenes")
  47. return { status: 200, body: { code: 0, msg: "", data: [] } };
  48. if (options.webUrl && !call.path.includes("config"))
  49. return {
  50. status: 503,
  51. body: { code: 503, msg: "not configured in mobile file-navigation fixture" },
  52. };
  53. return {
  54. status: 200,
  55. body: {
  56. code: 0,
  57. data: { configs: {}, builtinModels: [], config_version: "session-events" },
  58. },
  59. };
  60. },
  61. });
  62. const envPatch = {
  63. // 账号后台请求也必须走 loopback;合成凭据发到默认业务 API 会触发401并提前登出。
  64. ...(options.webUrl ? { VITE_ZCODE_E2E_STORE_BRIDGE: "1" } : {}),
  65. ZAI_BUSINESS_BASE_URL: relay.httpUrl,
  66. ZCODE_E2E_REMOTE_AUTH_GATE_URL: relay.httpUrl,
  67. ZCODE_BASE_URL: relay.httpUrl,
  68. ZCODE_ENDPOINT_ORIGIN: relay.httpUrl,
  69. ZCODE_TEST_BASE_URL: relay.httpUrl,
  70. ZCODE_WEB_REMOTE_CONTROL_RELAY_WS_URL: relay.wsUrl,
  71. ZCODE_WEB_REMOTE_CONTROL_URL: options.webUrl ?? `${relay.httpUrl}/remote/v4`,
  72. };
  73. const previous = Object.fromEntries(Object.keys(envPatch).map((key) => [key, process.env[key]]));
  74. Object.assign(process.env, envPatch);
  75. const webPort = options.webUrl ? new URL(options.webUrl).port : undefined;
  76. // 手机入口与 desktop relay 必须连接同一个隔离服务,不能沿用开发服务器的线上代理。
  77. const web = options.webUrl
  78. ? spawn(
  79. process.execPath,
  80. [
  81. resolve(import.meta.dirname, "../../../scripts/e2e-mobile-web-server.mjs"),
  82. webPort || "5173",
  83. ],
  84. {
  85. cwd: resolve(import.meta.dirname, "../../../../../packages/web"),
  86. // 原因:wdio CLI 给 worker 注入 FORCE_COLOR="0"/"1",picocolors 把任意非空值视为开启,
  87. // vite 会把端口染色成 `127.0.0.1:\x1b[1m5173`,下方就绪匹配永远失败,worker 无限等待。
  88. // NO_COLOR 优先于 FORCE_COLOR,保证就绪行是纯文本。
  89. env: { ...process.env, NO_COLOR: "1" },
  90. stdio: ["ignore", "pipe", "pipe"],
  91. },
  92. )
  93. : undefined;
  94. if (web) {
  95. await new Promise<void>((resolveReady, reject) => {
  96. web.once("error", reject);
  97. web.once("exit", (code) =>
  98. reject(new Error(`Mobile Web fixture exited before ready: ${code}`)),
  99. );
  100. web.stdout.on("data", (chunk) => {
  101. const origin = String(chunk).match(/http:\/\/127\.0\.0\.1:\d+/u)?.[0];
  102. // Vite 的重载通知写 stdout;原来只读 ready 会丢失手机操作中断的来源。
  103. // 只保留开发服务器生命周期,不转发页面控制台中的业务或配对数据。
  104. for (const line of String(chunk).split("\n")) {
  105. if (line.includes("[vite]") && !line.includes("[console."))
  106. process.stderr.write(`[mobile-web-fixture] ${line}\n`);
  107. }
  108. if (!origin) return;
  109. // 独立夹具可能避开已占用端口,手机配对必须使用 Vite 实际监听的端口。
  110. process.env.ZCODE_WEB_REMOTE_CONTROL_URL = new URL(
  111. new URL(options.webUrl!).pathname,
  112. origin,
  113. ).href;
  114. resolveReady();
  115. });
  116. web.stderr.on("data", (chunk) => process.stderr.write(chunk));
  117. });
  118. }
  119. await writeFile(options.credentialsFile, JSON.stringify(WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS), {
  120. mode: 0o600,
  121. });
  122. const settings = JSON.parse(await readFile(options.settingsFile, "utf8"));
  123. await writeFile(
  124. options.settingsFile,
  125. JSON.stringify({
  126. ...settings,
  127. zcodeEndpointOrigin: relay.httpUrl,
  128. webRemoteControlLastEnabledContext: options.mobilePush
  129. ? undefined
  130. : { workspacePath: options.workspacePath },
  131. }),
  132. );
  133. return async () => {
  134. if (web && web.exitCode === null) {
  135. const exited = once(web, "exit");
  136. web.kill();
  137. await exited;
  138. }
  139. await relay.close();
  140. for (const [key, value] of Object.entries(previous)) {
  141. if (value === undefined) delete process.env[key];
  142. else process.env[key] = value;
  143. }
  144. };
  145. }