remote-task-open.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // MRO01:真实 Web 入口与 RPC 帧;受控桌面 bridge 成功/失败,不发送模型请求。
  2. // 启动:pnpm --filter @zcode/web exec vite --host 127.0.0.1 --port 5178 --strictPort
  3. // 运行:pnpm exec tsx packages/web/test/e2e/remote-control/projects/manual-review/pending/remote-task-open.mjs
  4. import assert from "node:assert/strict";
  5. import { mkdir, writeFile } from "node:fs/promises";
  6. import { resolve } from "node:path";
  7. import { chromium } from "playwright-core";
  8. import { ServiceChannels } from "@zcode/shared";
  9. import { V4_WIRE_PROTOCOL_VERSION } from "@zcode/shared/zcode-protocol-v4";
  10. import { Emitter } from "../../../../../../../rpc/src/index.ts";
  11. import { taskSnapshotFrame } from "./remote-task-open.fixture.mjs";
  12. import { createDeviceSwitchDesktopBridge } from "./remote-device-switch.helpers.mjs";
  13. import {
  14. setup,
  15. assertEventually,
  16. } from "../../../authentication/manual-review/pending/remote-login-v2.helpers.mjs";
  17. const origin = process.env.REMOTE_LOGIN_E2E_ORIGIN || "http://127.0.0.1:5178";
  18. const artifacts = resolve(".tmp/remote-task-open-e2e");
  19. await mkdir(artifacts, { recursive: true });
  20. const browser = await chromium.launch({ channel: "chrome", headless: true });
  21. const results = [];
  22. const hostId = "remote:server:e2e-source";
  23. const localPath = "/workspace/local";
  24. const remotePath = "/workspace/remote";
  25. const identity = `${hostId}:${remotePath}`;
  26. const project = (id, hostId, rootPath) => ({
  27. id,
  28. hostId,
  29. name: `E2E_MRO01_${id}`,
  30. roots: [{ rootPath, position: 0, isPrimary: true }],
  31. nameOverridden: true,
  32. pinned: false,
  33. deleted: false,
  34. position: 0,
  35. createdAt: 1,
  36. updatedAt: 2,
  37. });
  38. const projects = [project("LOCAL", "local", localPath), project("REMOTE", hostId, remotePath)];
  39. const task = (taskId, projectId, hostId, workspacePath, workspaceIdentity) => ({
  40. taskId,
  41. projectId,
  42. hostId,
  43. workspacePath,
  44. workspaceIdentity,
  45. title: `E2E_MRO01_${taskId}`,
  46. createdAt: 1,
  47. updatedAt: 2,
  48. pinned: false,
  49. archived: false,
  50. mode: "default",
  51. status: "completed",
  52. });
  53. const tasks = [
  54. task("LOCAL_TASK", "LOCAL", "local", localPath),
  55. task("REMOTE_TASK", "REMOTE", hostId, remotePath, identity),
  56. ];
  57. const workspaces = [
  58. { workspacePath: localPath, kind: "local", label: "Local" },
  59. {
  60. workspacePath: remotePath,
  61. workspaceIdentity: identity,
  62. remoteSessionId: "remote-scope",
  63. kind: "remote",
  64. label: "Remote",
  65. connectionState: "connected",
  66. },
  67. ];
  68. const directory = {
  69. hosts: [
  70. {
  71. id: hostId,
  72. membershipId: "member",
  73. kind: "server",
  74. target: { kind: "server", serverId: "e2e-source", url: "https://example.test" },
  75. position: 0,
  76. connectionStatus: "online",
  77. },
  78. ],
  79. entries: [
  80. {
  81. id: "entry",
  82. hostId,
  83. projectId: "REMOTE",
  84. name: projects[1].name,
  85. roots: projects[1].roots,
  86. legacyWorkspace: null,
  87. lastSyncedAt: 1,
  88. },
  89. ],
  90. };
  91. try {
  92. for (const theme of ["zai-light", "zai-dark"])
  93. for (const locale of ["zh-CN", "en-US"]) {
  94. const h = await setup(browser, { width: 390, theme, locale, signedIn: true });
  95. const { page } = h;
  96. page.setDefaultTimeout(15000);
  97. const traffic = { opens: [], views: [], subscriptions: [], errors: [] };
  98. const bridges = new Map();
  99. const snapshots = new Map();
  100. let pending;
  101. let failNext = true;
  102. const send = (socket, payload) => socket.send(JSON.stringify({ type: "data", payload }));
  103. page.on("console", (message) => {
  104. if (message.type() === "error") traffic.errors.push(message.text());
  105. });
  106. await page.routeWebSocket(/\/api\/v1\/remote\/ws2(?:\?|$)/, (socket) => {
  107. socket.onClose(() => {
  108. for (const bridge of bridges.values()) bridge.dispose();
  109. });
  110. const ready = (request) => {
  111. const target = workspaces.find(
  112. (item) => (item.workspaceIdentity || item.workspacePath) === request.workspaceKey,
  113. );
  114. assert.ok(target);
  115. const bridge = {
  116. ...target,
  117. workspaceKey: request.workspaceKey,
  118. bridgeSessionId: request.bridgeSessionId,
  119. bridgeGeneration: request.bridgeGeneration,
  120. initialTaskId: request.taskId,
  121. };
  122. const frames = new Emitter();
  123. send(socket, {
  124. zcode_type: "workspace-bridge-ready",
  125. requestId: request.requestId,
  126. bridgeSessionId: request.bridgeSessionId,
  127. bridgeGeneration: request.bridgeGeneration,
  128. bridge,
  129. });
  130. bridges.set(
  131. bridge.bridgeSessionId,
  132. createDeviceSwitchDesktopBridge(socket, bridge, {
  133. locale,
  134. theme,
  135. events: {
  136. [`${ServiceChannels.ZCodeAgent}:onDynamicConversationFrame`]: frames.event,
  137. },
  138. responses: {
  139. [`${ServiceChannels.SettingsSync}:getFirstRunPromptState`]: { handled: true },
  140. [`${ServiceChannels.ZCodeAgent}:helloConversationV4`]: {
  141. kind: "hello",
  142. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  143. connectionId: bridge.bridgeSessionId,
  144. clientMode: "web-remote-replayable",
  145. deliveryProfile: "replayable",
  146. serverTime: 1,
  147. auth: {},
  148. capabilities: {
  149. nativeDialogs: false,
  150. localTerminal: false,
  151. binaryFrames: true,
  152. compression: "none",
  153. },
  154. },
  155. [`${ServiceChannels.ZCodeAgent}:initializeConversationV4`]: null,
  156. [`${ServiceChannels.Project}:readTree`]: (params) => ({
  157. projects: projects.filter((p) => p.hostId === (params?.hostId || "local")),
  158. tasks: tasks.filter((t) => t.hostId === (params?.hostId || "local")),
  159. }),
  160. [`${ServiceChannels.RemoteProjects}:readDirectory`]: directory,
  161. [`${ServiceChannels.RemoteProjects}:refreshEntry`]: null,
  162. [`${ServiceChannels.ZCodeTask}:getTaskMeta`]: (input) =>
  163. tasks.find((t) => t.taskId === input.taskId) ?? null,
  164. [`${ServiceChannels.ZCodeAgent}:subscribeConversationV4`]: (input) => {
  165. traffic.subscriptions.push({
  166. workspacePath: input.workspacePath,
  167. workspaceIdentity: input.workspaceIdentity,
  168. sessionId: input.sessionId,
  169. });
  170. const subscriptionId = `sub-${traffic.subscriptions.length}`;
  171. snapshots.set(input.sessionId, () =>
  172. frames.fire(taskSnapshotFrame(input.sessionId, subscriptionId)),
  173. );
  174. return {
  175. ack: {
  176. subscriptionId,
  177. mode: "snapshot",
  178. logEpoch: "e2e",
  179. },
  180. };
  181. },
  182. [`${ServiceChannels.ZCodeAgent}:unsubscribeConversationV4`]: null,
  183. [`${ServiceChannels.ZCodeAgent}:conversationWorkflowRunsV4`]: { runs: [] },
  184. [`${ServiceChannels.ZCodeAgent}:conversationPlansV4`]: { plans: [] },
  185. },
  186. }),
  187. );
  188. };
  189. socket.onMessage((raw) => {
  190. const message = JSON.parse(String(raw));
  191. if (message.type === "auth_init")
  192. socket.send(
  193. JSON.stringify({
  194. type: "auth_ack",
  195. device_sid: "e2e-device",
  196. pair_status: "matched",
  197. }),
  198. );
  199. if (message.type === "pair_status_query")
  200. socket.send(JSON.stringify({ type: "pair_status_ack", pair_status: "matched" }));
  201. const payload = message.payload;
  202. if (!payload) return;
  203. if (payload.zcode_type === "rpc-frame" || payload.zcode_type === "rpc-frame-ack") {
  204. bridges.get(payload.bridgeSessionId)?.acceptPayload(payload);
  205. return;
  206. }
  207. const result = {
  208. windowControlSessionId: "e2e-device",
  209. desktopAppVersion: "3.15.1",
  210. workspaces,
  211. initialViewState: {
  212. activeWorkspaceKey: localPath,
  213. activeTaskId: "LOCAL_TASK",
  214. updatedAt: 1,
  215. },
  216. };
  217. if (payload.zcode_type === "bootstrap-request")
  218. send(socket, {
  219. zcode_type: "bootstrap-response",
  220. requestId: payload.requestId,
  221. success: true,
  222. result,
  223. });
  224. if (payload.zcode_type === "workspace-list-request")
  225. send(socket, {
  226. zcode_type: "workspace-list-response",
  227. requestId: payload.requestId,
  228. success: true,
  229. result,
  230. });
  231. if (payload.zcode_type === "mobile-view-state-update") {
  232. traffic.views.push(payload);
  233. send(socket, { zcode_type: "mobile-view-state-updated", requestId: payload.requestId });
  234. }
  235. if (payload.zcode_type === "workspace-bridge-open") {
  236. traffic.opens.push(payload);
  237. if (payload.workspaceKey === identity) {
  238. // 测试主动释放响应,断言等待阶段;不用定时器制造时序。
  239. pending = () => {
  240. if (failNext) {
  241. failNext = false;
  242. send(socket, {
  243. zcode_type: "workspace-bridge-error",
  244. requestId: payload.requestId,
  245. bridgeSessionId: payload.bridgeSessionId,
  246. bridgeGeneration: payload.bridgeGeneration,
  247. reason: "unexpected-error",
  248. error: "E2E_MRO01_BRIDGE_REJECTED",
  249. });
  250. } else ready(payload);
  251. };
  252. } else ready(payload);
  253. }
  254. });
  255. });
  256. try {
  257. await page.goto(
  258. new URL("/remote/v4?app_version=3.15.1&sid=e2e-device&mid=e2e-mid", origin).href,
  259. );
  260. const local = page.locator('[data-project-name="E2E_MRO01_LOCAL"]');
  261. const remote = page.locator('[data-project-name="E2E_MRO01_REMOTE"]');
  262. const onboarding = page.getByTestId("onboarding-page");
  263. const welcome = page.getByRole("dialog", { name: /欢迎使用 ZCode|Welcome to ZCode/ });
  264. await local.or(onboarding).or(welcome).first().waitFor();
  265. if (await onboarding.isVisible())
  266. await onboarding.getByRole("button", { name: /退出引导|Exit onboarding/ }).click();
  267. await local.or(welcome).first().waitFor();
  268. if (await welcome.isVisible())
  269. await welcome.getByRole("button", { name: /^(Close|关闭)$/ }).click();
  270. for (const row of [local, remote]) {
  271. await row.waitFor();
  272. const toggle = row.getByTestId("virtual-project-toggle");
  273. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  274. }
  275. const remoteTask = remote.getByText("E2E_MRO01_REMOTE_TASK", { exact: true });
  276. const home = page.locator('[data-mobile-page="home"]');
  277. const chat = page.locator('[data-mobile-page="chat"]');
  278. await home.waitFor();
  279. // 先实际打开本地历史再返回列表,确保失败场景持有可被误展示的旧会话。
  280. await local.getByText("E2E_MRO01_LOCAL_TASK", { exact: true }).click();
  281. await chat.waitFor();
  282. await assertEventually(() => snapshots.has("LOCAL_TASK"));
  283. snapshots.get("LOCAL_TASK")();
  284. await page.getByText("E2E_MRO01_LOCAL_TASK_HISTORY", { exact: true }).waitFor();
  285. await page.goBack();
  286. await home.waitFor();
  287. const subscriptionsBefore = traffic.subscriptions.length;
  288. await remoteTask.click();
  289. await assertEventually(() => Boolean(pending));
  290. assert.equal(await home.isVisible(), true, "等待远端 bridge 时必须保留列表");
  291. assert.equal(await chat.count(), 0, "不得提前展示旧本地会话");
  292. pending();
  293. pending = undefined;
  294. await page.getByText("E2E_MRO01_BRIDGE_REJECTED", { exact: true }).waitFor();
  295. assert.equal(await home.isVisible(), true);
  296. assert.equal(await chat.count(), 0);
  297. assert.equal(await page.getByText("[object Object]", { exact: true }).count(), 0);
  298. assert.equal(traffic.subscriptions.length, subscriptionsBefore);
  299. const prefix = `${theme}-${locale}`;
  300. await page.screenshot({
  301. path: resolve(artifacts, `${prefix}-failure.png`),
  302. fullPage: true,
  303. });
  304. await remoteTask.click();
  305. await assertEventually(() => Boolean(pending));
  306. assert.equal(await home.isVisible(), true);
  307. pending();
  308. pending = undefined;
  309. await chat.waitFor();
  310. await page.locator('[data-session-id="REMOTE_TASK"]').waitFor();
  311. await assertEventually(() =>
  312. traffic.subscriptions.some(
  313. (s) => s.sessionId === "REMOTE_TASK" && s.workspaceIdentity === identity,
  314. ),
  315. );
  316. snapshots.get("REMOTE_TASK")();
  317. await page.getByText("E2E_MRO01_REMOTE_TASK_HISTORY", { exact: true }).waitFor();
  318. assert.equal(
  319. await page.getByText("E2E_MRO01_LOCAL_TASK_HISTORY", { exact: true }).count(),
  320. 0,
  321. );
  322. assert.equal(await page.locator('[data-session-id="LOCAL_TASK"]').count(), 0);
  323. assert.deepEqual(
  324. traffic.opens
  325. .filter((p) => p.workspaceKey === identity)
  326. .map((p) => ({ taskId: p.taskId, hostId: p.taskHostId })),
  327. [
  328. { taskId: "REMOTE_TASK", hostId },
  329. { taskId: "REMOTE_TASK", hostId },
  330. ],
  331. );
  332. await page.screenshot({
  333. path: resolve(artifacts, `${prefix}-success.png`),
  334. fullPage: true,
  335. });
  336. // 返回列表再打开当前 workspace 的任务,不应再申请 bridge。
  337. await page.goBack();
  338. await home.waitFor();
  339. const opensBefore = traffic.opens.length;
  340. await page.getByText("E2E_MRO01_REMOTE_TASK", { exact: true }).click();
  341. await chat.waitFor();
  342. assert.equal(traffic.opens.length, opensBefore);
  343. assert.deepEqual(h.errors, []);
  344. results.push({ theme, locale, result: "passed" });
  345. } catch (error) {
  346. await page.screenshot({ path: resolve(artifacts, "failure.png"), fullPage: true });
  347. console.error((await page.locator("body").innerText()).slice(-5000), h.errors);
  348. throw error;
  349. } finally {
  350. await writeFile(
  351. resolve(artifacts, `${theme}-${locale}-traffic.json`),
  352. JSON.stringify(traffic, null, 2),
  353. );
  354. await h.context.close();
  355. }
  356. }
  357. await writeFile(resolve(artifacts, "results.json"), JSON.stringify(results, null, 2));
  358. console.log(`MRO01 passed: ${results.length} configurations; ${artifacts}`);
  359. } finally {
  360. await browser.close();
  361. }