remote-task-open.mjs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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}:getSessionLifecycle`]: null,
  165. [`${ServiceChannels.ZCodeAgent}:subscribeConversationV4`]: (input) => {
  166. traffic.subscriptions.push({
  167. workspacePath: input.workspacePath,
  168. workspaceIdentity: input.workspaceIdentity,
  169. sessionId: input.sessionId,
  170. });
  171. const subscriptionId = `sub-${traffic.subscriptions.length}`;
  172. snapshots.set(input.sessionId, () =>
  173. frames.fire(taskSnapshotFrame(input.sessionId, subscriptionId)),
  174. );
  175. return {
  176. ack: {
  177. subscriptionId,
  178. mode: "snapshot",
  179. logEpoch: "e2e",
  180. },
  181. };
  182. },
  183. [`${ServiceChannels.ZCodeAgent}:unsubscribeConversationV4`]: null,
  184. [`${ServiceChannels.ZCodeAgent}:conversationWorkflowRunsV4`]: { runs: [] },
  185. [`${ServiceChannels.ZCodeAgent}:conversationPlansV4`]: { plans: [] },
  186. },
  187. }),
  188. );
  189. };
  190. socket.onMessage((raw) => {
  191. const message = JSON.parse(String(raw));
  192. if (message.type === "auth_init")
  193. socket.send(
  194. JSON.stringify({
  195. type: "auth_ack",
  196. device_sid: "e2e-device",
  197. pair_status: "matched",
  198. }),
  199. );
  200. if (message.type === "pair_status_query")
  201. socket.send(JSON.stringify({ type: "pair_status_ack", pair_status: "matched" }));
  202. const payload = message.payload;
  203. if (!payload) return;
  204. if (payload.zcode_type === "rpc-frame" || payload.zcode_type === "rpc-frame-ack") {
  205. bridges.get(payload.bridgeSessionId)?.acceptPayload(payload);
  206. return;
  207. }
  208. const result = {
  209. windowControlSessionId: "e2e-device",
  210. desktopAppVersion: "3.15.1",
  211. workspaces,
  212. initialViewState: {
  213. activeWorkspaceKey: localPath,
  214. activeTaskId: "LOCAL_TASK",
  215. updatedAt: 1,
  216. },
  217. };
  218. if (payload.zcode_type === "bootstrap-request")
  219. send(socket, {
  220. zcode_type: "bootstrap-response",
  221. requestId: payload.requestId,
  222. success: true,
  223. result,
  224. });
  225. if (payload.zcode_type === "workspace-list-request")
  226. send(socket, {
  227. zcode_type: "workspace-list-response",
  228. requestId: payload.requestId,
  229. success: true,
  230. result,
  231. });
  232. if (payload.zcode_type === "mobile-view-state-update") {
  233. traffic.views.push(payload);
  234. send(socket, { zcode_type: "mobile-view-state-updated", requestId: payload.requestId });
  235. }
  236. if (payload.zcode_type === "workspace-bridge-open") {
  237. traffic.opens.push(payload);
  238. if (payload.workspaceKey === identity) {
  239. // 测试主动释放响应,断言等待阶段;不用定时器制造时序。
  240. pending = () => {
  241. if (failNext) {
  242. failNext = false;
  243. send(socket, {
  244. zcode_type: "workspace-bridge-error",
  245. requestId: payload.requestId,
  246. bridgeSessionId: payload.bridgeSessionId,
  247. bridgeGeneration: payload.bridgeGeneration,
  248. reason: "unexpected-error",
  249. error: "E2E_MRO01_BRIDGE_REJECTED",
  250. });
  251. } else ready(payload);
  252. };
  253. } else ready(payload);
  254. }
  255. });
  256. });
  257. try {
  258. await page.goto(
  259. new URL("/remote/v4?app_version=3.15.1&sid=e2e-device&mid=e2e-mid", origin).href,
  260. );
  261. const local = page.locator('[data-project-name="E2E_MRO01_LOCAL"]');
  262. const remote = page.locator('[data-project-name="E2E_MRO01_REMOTE"]');
  263. const onboarding = page.getByTestId("onboarding-page");
  264. const welcome = page.getByRole("dialog", { name: /欢迎使用 ZCode|Welcome to ZCode/ });
  265. await local.or(onboarding).or(welcome).first().waitFor();
  266. if (await onboarding.isVisible())
  267. await onboarding.getByRole("button", { name: /退出引导|Exit onboarding/ }).click();
  268. await local.or(welcome).first().waitFor();
  269. if (await welcome.isVisible())
  270. await welcome.getByRole("button", { name: /^(Close|关闭)$/ }).click();
  271. for (const row of [local, remote]) {
  272. await row.waitFor();
  273. const toggle = row.getByTestId("virtual-project-toggle");
  274. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  275. }
  276. const remoteTask = remote.getByText("E2E_MRO01_REMOTE_TASK", { exact: true });
  277. const home = page.locator('[data-mobile-page="home"]');
  278. const chat = page.locator('[data-mobile-page="chat"]');
  279. await home.waitFor();
  280. // 先实际打开本地历史再返回列表,确保失败场景持有可被误展示的旧会话。
  281. await local.getByText("E2E_MRO01_LOCAL_TASK", { exact: true }).click();
  282. await chat.waitFor();
  283. await assertEventually(() => snapshots.has("LOCAL_TASK"));
  284. snapshots.get("LOCAL_TASK")();
  285. await page.getByText("E2E_MRO01_LOCAL_TASK_HISTORY", { exact: true }).waitFor();
  286. await page.goBack();
  287. await home.waitFor();
  288. const subscriptionsBefore = traffic.subscriptions.length;
  289. await remoteTask.click();
  290. await assertEventually(() => Boolean(pending));
  291. assert.equal(await home.isVisible(), true, "等待远端 bridge 时必须保留列表");
  292. assert.equal(await chat.count(), 0, "不得提前展示旧本地会话");
  293. pending();
  294. pending = undefined;
  295. await page.getByText("E2E_MRO01_BRIDGE_REJECTED", { exact: true }).waitFor();
  296. assert.equal(await home.isVisible(), true);
  297. assert.equal(await chat.count(), 0);
  298. assert.equal(await page.getByText("[object Object]", { exact: true }).count(), 0);
  299. assert.equal(traffic.subscriptions.length, subscriptionsBefore);
  300. const prefix = `${theme}-${locale}`;
  301. await page.screenshot({
  302. path: resolve(artifacts, `${prefix}-failure.png`),
  303. fullPage: true,
  304. });
  305. await remoteTask.click();
  306. await assertEventually(() => Boolean(pending));
  307. assert.equal(await home.isVisible(), true);
  308. pending();
  309. pending = undefined;
  310. await chat.waitFor();
  311. await page.locator('[data-session-id="REMOTE_TASK"]').waitFor();
  312. await assertEventually(() =>
  313. traffic.subscriptions.some(
  314. (s) => s.sessionId === "REMOTE_TASK" && s.workspaceIdentity === identity,
  315. ),
  316. );
  317. snapshots.get("REMOTE_TASK")();
  318. await page.getByText("E2E_MRO01_REMOTE_TASK_HISTORY", { exact: true }).waitFor();
  319. assert.equal(
  320. await page.getByText("E2E_MRO01_LOCAL_TASK_HISTORY", { exact: true }).count(),
  321. 0,
  322. );
  323. assert.equal(await page.locator('[data-session-id="LOCAL_TASK"]').count(), 0);
  324. assert.deepEqual(
  325. traffic.opens
  326. .filter((p) => p.workspaceKey === identity)
  327. .map((p) => ({ taskId: p.taskId, hostId: p.taskHostId })),
  328. [
  329. { taskId: "REMOTE_TASK", hostId },
  330. { taskId: "REMOTE_TASK", hostId },
  331. ],
  332. );
  333. await page.screenshot({
  334. path: resolve(artifacts, `${prefix}-success.png`),
  335. fullPage: true,
  336. });
  337. // 返回列表再打开当前 workspace 的任务,不应再申请 bridge。
  338. await page.goBack();
  339. await home.waitFor();
  340. const opensBefore = traffic.opens.length;
  341. await page.getByText("E2E_MRO01_REMOTE_TASK", { exact: true }).click();
  342. await chat.waitFor();
  343. assert.equal(traffic.opens.length, opensBefore);
  344. const back = chat.getByRole("button", { name: /^(返回任务首页|Back to task home)$/u });
  345. await page.waitForFunction(() => history.state?.zcodeMobilePage === "chat");
  346. const chatHistoryLength = await page.evaluate(() => history.length);
  347. await back.click();
  348. await home.waitFor();
  349. await remoteTask.click();
  350. await chat.waitFor();
  351. assert.equal(await page.evaluate(() => history.length), chatHistoryLength);
  352. await page.goBack();
  353. await home.waitFor();
  354. await page.goForward();
  355. await chat.waitFor();
  356. // 只保留当前聊天历史项,复现浏览器已经无处可退的状态。
  357. const cdp = await h.context.newCDPSession(page);
  358. await cdp.send("Page.resetNavigationHistory");
  359. const { currentIndex } = await cdp.send("Page.getNavigationHistory");
  360. assert.equal(currentIndex, 0);
  361. await page.evaluate(() => history.replaceState({ ...history.state, e2eMarker: true }, ""));
  362. assert.equal(await page.evaluate(() => history.state?.zcodeMobilePage), "chat");
  363. const chatUrl = page.url();
  364. await back.click();
  365. await home.waitFor();
  366. assert.equal(page.url(), chatUrl);
  367. assert.equal(await page.evaluate(() => history.state?.e2eMarker), true);
  368. await page.reload({ waitUntil: "domcontentloaded" });
  369. await home.waitFor();
  370. await remoteTask.waitFor();
  371. assert.deepEqual(h.errors, []);
  372. results.push({ theme, locale, taskHomeArrow: "passed", result: "passed" });
  373. } catch (error) {
  374. await page.screenshot({ path: resolve(artifacts, "failure.png"), fullPage: true });
  375. console.error((await page.locator("body").innerText()).slice(-5000), h.errors);
  376. throw error;
  377. } finally {
  378. await writeFile(
  379. resolve(artifacts, `${theme}-${locale}-traffic.json`),
  380. JSON.stringify(traffic, null, 2),
  381. );
  382. await h.context.close();
  383. }
  384. }
  385. await writeFile(resolve(artifacts, "results.json"), JSON.stringify(results, null, 2));
  386. console.log(`MRO01 passed: ${results.length} configurations; ${artifacts}`);
  387. } finally {
  388. await browser.close();
  389. }