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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. import { CODING_PLAN_TEAM_MOCK_BASE_URL_ENV } from "#e2e/helpers/coding-plan-mock-env";
  7. export const WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS = {
  8. "oauth:active_provider": "zai",
  9. "oauth:zai:access_token": "mock-token",
  10. "oauth:zai:user_info": JSON.stringify({
  11. id: "zcode-e2e-user",
  12. username: "ZCode E2E",
  13. displayName: "ZCode E2E",
  14. }),
  15. zcodejwttoken: "mock-token",
  16. };
  17. /** 单窗口真实 OAuth owner → RPC → renderer → Main 回归,只替换外部 relay。 */
  18. export async function prepareWebRemoteControlSessionEventsFixture(options: {
  19. credentialsFile: string;
  20. settingsFile: string;
  21. workspacePath: string;
  22. webUrl?: string;
  23. mobilePush?: boolean;
  24. additionalRelayUsers?: Record<string, string>;
  25. /** 上次启用远控时的 workspace;缺省为启动后会恢复的 workspacePath。 */
  26. lastEnabledWorkspacePath?: string;
  27. regionalDesktop?: boolean;
  28. }): Promise<() => Promise<void>> {
  29. let linkedProfileEnabled = false;
  30. // 用例经 /__e2e/client-configs 追加的公开配置(如草稿模型迁移规则),只合并进 client/configs。
  31. let extraClientConfigs: Record<string, unknown> = {};
  32. const relay = await createFakeRelayV2({
  33. users: {
  34. "mock-token": "zcode-e2e-user",
  35. ...(options.regionalDesktop ? { "mobile-own-token": "zcode-e2e-user" } : {}),
  36. ...options.additionalRelayUsers,
  37. },
  38. onHttp: (call) => {
  39. if (call.path === "/__e2e/client-configs" && call.method === "POST") {
  40. const configs = (call.body as { configs?: unknown } | undefined)?.configs;
  41. if (!configs || typeof configs !== "object" || Array.isArray(configs))
  42. return { status: 400, body: { code: 400, msg: "configs must be an object" } };
  43. extraClientConfigs = configs as Record<string, unknown>;
  44. return { status: 200, body: { ok: true } };
  45. }
  46. if (call.path === "/__e2e/linked-profile") {
  47. linkedProfileEnabled = true;
  48. return { status: 200, body: { ok: true } };
  49. }
  50. if (linkedProfileEnabled && call.path === "/api/v1/oauth/profile")
  51. return {
  52. status: 200,
  53. body: {
  54. code: 0,
  55. data: {
  56. user: { user_id: "zcode-e2e-user", name: "ZCode E2E" },
  57. bigmodel: { customer_id: "associated-customer", access_token: "linked-refreshed" },
  58. },
  59. },
  60. };
  61. if (options.mobilePush && call.path === "/api/v1/remote/notification/status")
  62. return {
  63. status: 200,
  64. body: {
  65. code: 0,
  66. data: { protocol_version: 1, event_transport: "http", status: "available" },
  67. },
  68. };
  69. // 回执 event_id 必须回显请求里的事件,Main 才会把上报判为 accepted。
  70. if (
  71. options.mobilePush &&
  72. call.method === "POST" &&
  73. call.path === "/api/v1/remote/notification/events"
  74. ) {
  75. const event = (call.body as { event?: { event_id?: string } } | undefined)?.event;
  76. return {
  77. status: 200,
  78. body: { code: 0, msg: "", data: { event_id: event?.event_id, status: "accepted" } },
  79. };
  80. }
  81. if (options.mobilePush && call.path === "/__e2e/push")
  82. return {
  83. status: 200,
  84. body: {
  85. messages: relay.messages,
  86. queries: relay.httpCalls.filter((x) => x.path === "/api/v1/remote/notification/status")
  87. .length,
  88. // 仅记录通知上报;用于断言关闭开关期间不发请求、打开后只上报新事件。
  89. notifications: relay.httpCalls
  90. .filter((x) => x.method === "POST" && x.path === "/api/v1/remote/notification/events")
  91. .map((x) => x.body),
  92. },
  93. };
  94. if (call.path.startsWith("/api/v1/remote/")) return;
  95. // 完整工作区会读取推荐场景;配置对象不能冒充场景数组,否则真实首页渲染会崩溃。
  96. if (call.path === "/api/v1/client/scenes")
  97. return { status: 200, body: { code: 0, msg: "", data: [] } };
  98. if (options.webUrl && !call.path.includes("config"))
  99. return {
  100. status: 503,
  101. body: { code: 503, msg: "not configured in mobile file-navigation fixture" },
  102. };
  103. return {
  104. status: 200,
  105. body: {
  106. code: 0,
  107. data: {
  108. configs: call.path === "/api/v1/client/configs" ? { ...extraClientConfigs } : {},
  109. builtinModels: [],
  110. config_version: "session-events",
  111. },
  112. },
  113. };
  114. },
  115. });
  116. const envPatch = {
  117. // 账号后台请求也必须走 loopback;合成凭据发到默认业务 API 会触发401并提前登出。
  118. ...(options.webUrl ? { VITE_ZCODE_E2E_STORE_BRIDGE: "1" } : {}),
  119. ZAI_BUSINESS_BASE_URL: relay.httpUrl,
  120. // Bug 原因:Highspeed 等团队套餐用例也复用此手机夹具,团队 mock 已接管 BigModel 业务 API;
  121. // 无条件改指 relay 会让团队入口校验收到 503,模型菜单没有团队行。两者都是本地 loopback。
  122. ...(process.env[CODING_PLAN_TEAM_MOCK_BASE_URL_ENV]
  123. ? {}
  124. : { BIGMODEL_API_BASE_URL: relay.httpUrl }),
  125. ZCODE_E2E_REMOTE_AUTH_GATE_URL: relay.httpUrl,
  126. ZCODE_BASE_URL: relay.httpUrl,
  127. ZCODE_ENDPOINT_ORIGIN: relay.httpUrl,
  128. ZCODE_TEST_BASE_URL: relay.httpUrl,
  129. ZCODE_WEB_REMOTE_CONTROL_RELAY_WS_URL: relay.wsUrl,
  130. ZCODE_WEB_REMOTE_CONTROL_URL: options.webUrl ?? `${relay.httpUrl}/remote/v4`,
  131. };
  132. const previous = Object.fromEntries(Object.keys(envPatch).map((key) => [key, process.env[key]]));
  133. Object.assign(process.env, envPatch);
  134. const webPort = options.webUrl ? new URL(options.webUrl).port : undefined;
  135. // 手机入口与 desktop relay 必须连接同一个隔离服务,不能沿用开发服务器的线上代理。
  136. const web = options.webUrl
  137. ? spawn(
  138. process.execPath,
  139. [
  140. resolve(import.meta.dirname, "../../../scripts/e2e-mobile-web-server.mjs"),
  141. webPort || "5173",
  142. ],
  143. {
  144. cwd: resolve(import.meta.dirname, "../../../../../packages/web"),
  145. // 原因:wdio CLI 给 worker 注入 FORCE_COLOR="0"/"1",picocolors 把任意非空值视为开启,
  146. // vite 会把端口染色成 `127.0.0.1:\x1b[1m5173`,下方就绪匹配永远失败,worker 无限等待。
  147. // NO_COLOR 优先于 FORCE_COLOR,保证就绪行是纯文本。
  148. env: { ...process.env, NO_COLOR: "1" },
  149. stdio: ["ignore", "pipe", "pipe"],
  150. },
  151. )
  152. : undefined;
  153. if (web) {
  154. await new Promise<void>((resolveReady, reject) => {
  155. web.once("error", reject);
  156. web.once("exit", (code) =>
  157. reject(new Error(`Mobile Web fixture exited before ready: ${code}`)),
  158. );
  159. web.stdout.on("data", (chunk) => {
  160. const origin = String(chunk).match(/http:\/\/127\.0\.0\.1:\d+/u)?.[0];
  161. // Vite 的重载通知写 stdout;原来只读 ready 会丢失手机操作中断的来源。
  162. // 只保留开发服务器生命周期,不转发页面控制台中的业务或配对数据。
  163. for (const line of String(chunk).split("\n")) {
  164. if (line.includes("[vite]") && !line.includes("[console."))
  165. process.stderr.write(`[mobile-web-fixture] ${line}\n`);
  166. }
  167. if (!origin) return;
  168. // 独立夹具可能避开已占用端口,手机配对必须使用 Vite 实际监听的端口。
  169. process.env.ZCODE_WEB_REMOTE_CONTROL_URL = new URL(
  170. new URL(options.webUrl!).pathname,
  171. origin,
  172. ).href;
  173. resolveReady();
  174. });
  175. web.stderr.on("data", (chunk) => process.stderr.write(chunk));
  176. });
  177. }
  178. const desktopCredentials = options.regionalDesktop
  179. ? {
  180. "oauth:active_provider": "zai_cn",
  181. "oauth:session_revision": "cn-mobile-initial",
  182. "oauth:zai_cn:access_token": "cn-upstream-not-relay",
  183. "oauth:zai_cn:user_info": JSON.stringify({ user_id: "zcode-e2e-user", name: "ZCode E2E" }),
  184. "oauth:linked_bigmodel": JSON.stringify({
  185. userId: "zcode-e2e-user",
  186. customerId: "associated-customer",
  187. accessToken: "linked-before",
  188. }),
  189. zcodejwttoken: "mock-token",
  190. }
  191. : WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS;
  192. await writeFile(options.credentialsFile, JSON.stringify(desktopCredentials), { mode: 0o600 });
  193. const settings = JSON.parse(await readFile(options.settingsFile, "utf8"));
  194. await writeFile(
  195. options.settingsFile,
  196. JSON.stringify({
  197. ...settings,
  198. zcodeEndpointOrigin: relay.httpUrl,
  199. webRemoteControlLastEnabledContext: options.mobilePush
  200. ? undefined
  201. : { workspacePath: options.lastEnabledWorkspacePath ?? options.workspacePath },
  202. }),
  203. );
  204. return async () => {
  205. if (web && web.exitCode === null) {
  206. const exited = once(web, "exit");
  207. web.kill();
  208. await exited;
  209. }
  210. await relay.close();
  211. for (const [key, value] of Object.entries(previous)) {
  212. if (value === undefined) delete process.env[key];
  213. else process.env[key] = value;
  214. }
  215. };
  216. }