remote-task-open.mjs 15 KB

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