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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. }): Promise<() => Promise<void>> {
  23. const relay = await createFakeRelayV2({
  24. users: { "mock-token": "zcode-e2e-user" },
  25. onHttp: (call) => {
  26. if (call.path.startsWith("/api/v1/remote/")) return;
  27. // 完整工作区会读取推荐场景;配置对象不能冒充场景数组,否则真实首页渲染会崩溃。
  28. if (call.path === "/api/v1/client/scenes")
  29. return { status: 200, body: { code: 0, msg: "", data: [] } };
  30. if (options.webUrl && !call.path.includes("config"))
  31. return {
  32. status: 503,
  33. body: { code: 503, msg: "not configured in mobile file-navigation fixture" },
  34. };
  35. return {
  36. status: 200,
  37. body: {
  38. code: 0,
  39. data: { configs: {}, builtinModels: [], config_version: "session-events" },
  40. },
  41. };
  42. },
  43. });
  44. const envPatch = {
  45. // 账号后台请求也必须走 loopback;合成凭据发到默认业务 API 会触发401并提前登出。
  46. ...(options.webUrl ? { VITE_ZCODE_E2E_STORE_BRIDGE: "1" } : {}),
  47. ZAI_BUSINESS_BASE_URL: relay.httpUrl,
  48. ZCODE_E2E_REMOTE_AUTH_GATE_URL: relay.httpUrl,
  49. ZCODE_BASE_URL: relay.httpUrl,
  50. ZCODE_ENDPOINT_ORIGIN: relay.httpUrl,
  51. ZCODE_TEST_BASE_URL: relay.httpUrl,
  52. ZCODE_WEB_REMOTE_CONTROL_RELAY_WS_URL: relay.wsUrl,
  53. ZCODE_WEB_REMOTE_CONTROL_URL: options.webUrl ?? `${relay.httpUrl}/remote/v4`,
  54. };
  55. const previous = Object.fromEntries(Object.keys(envPatch).map((key) => [key, process.env[key]]));
  56. Object.assign(process.env, envPatch);
  57. // 手机入口与 desktop relay 必须连接同一个隔离服务,不能沿用开发服务器的线上代理。
  58. const web = options.webUrl
  59. ? spawn(
  60. process.execPath,
  61. [
  62. resolve(import.meta.dirname, "../../../../../node_modules/vite/bin/vite.js"),
  63. "--host",
  64. "127.0.0.1",
  65. "--port",
  66. "5173",
  67. "--strictPort",
  68. ],
  69. {
  70. cwd: resolve(import.meta.dirname, "../../../../../packages/web"),
  71. // 原因:wdio CLI 给 worker 注入 FORCE_COLOR="0"/"1",picocolors 把任意非空值视为开启,
  72. // vite 会把端口染色成 `127.0.0.1:\x1b[1m5173`,下方就绪匹配永远失败,worker 无限等待。
  73. // NO_COLOR 优先于 FORCE_COLOR,保证就绪行是纯文本。
  74. env: { ...process.env, NO_COLOR: "1" },
  75. stdio: ["ignore", "pipe", "pipe"],
  76. },
  77. )
  78. : undefined;
  79. if (web) {
  80. await new Promise<void>((resolveReady, reject) => {
  81. web.once("error", reject);
  82. web.once("exit", (code) =>
  83. reject(new Error(`Mobile Web fixture exited before ready: ${code}`)),
  84. );
  85. web.stdout.on("data", (chunk) => {
  86. if (String(chunk).includes("http://127.0.0.1:5173")) resolveReady();
  87. });
  88. web.stderr.on("data", (chunk) => process.stderr.write(chunk));
  89. });
  90. }
  91. await writeFile(options.credentialsFile, JSON.stringify(WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS), {
  92. mode: 0o600,
  93. });
  94. const settings = JSON.parse(await readFile(options.settingsFile, "utf8"));
  95. await writeFile(
  96. options.settingsFile,
  97. JSON.stringify({
  98. ...settings,
  99. zcodeEndpointOrigin: relay.httpUrl,
  100. webRemoteControlLastEnabledContext: { workspacePath: options.workspacePath },
  101. }),
  102. );
  103. return async () => {
  104. if (web && web.exitCode === null) {
  105. const exited = once(web, "exit");
  106. web.kill();
  107. await exited;
  108. }
  109. await relay.close();
  110. for (const [key, value] of Object.entries(previous)) {
  111. if (value === undefined) delete process.env[key];
  112. else process.env[key] = value;
  113. }
  114. };
  115. }