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

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