remote-project-directory.mjs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // MRO02:真实 Web 页面、RPC、Host 项目服务和隔离 SQLite;不发送模型请求。
  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-project-directory.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 {
  11. BufferReader,
  12. deserialize,
  13. Emitter,
  14. VSBuffer,
  15. } from "../../../../../../../rpc/src/index.ts";
  16. import { taskSnapshotFrame } from "./remote-task-open.fixture.mjs";
  17. import { createProjectDirectoryFixture } from "./remote-project-directory.fixture.mjs";
  18. import { createDeviceSwitchDesktopBridge } from "./remote-device-switch.helpers.mjs";
  19. import {
  20. setup,
  21. assertEventually,
  22. } from "../../../authentication/manual-review/pending/remote-login-v2.helpers.mjs";
  23. const origin = process.env.REMOTE_LOGIN_E2E_ORIGIN || "http://127.0.0.1:5178";
  24. const artifacts = resolve(process.env.MRO02_ARTIFACTS || ".tmp/remote-project-directory-e2e");
  25. await mkdir(artifacts, { recursive: true });
  26. const browser = await chromium.launch({ channel: "chrome", headless: true });
  27. const results = [];
  28. const configurations = [1024, 390].flatMap((width) =>
  29. ["zai-light", "zai-dark"].flatMap((theme) =>
  30. ["zh-CN", "en-US"].map((locale) => ({ width, theme, locale })),
  31. ),
  32. );
  33. const selectedConfigurations = process.env.MRO02_WIDTH
  34. ? configurations.filter(({ width }) => width === Number(process.env.MRO02_WIDTH))
  35. : configurations;
  36. try {
  37. for (const configuration of process.env.MRO02_FIRST_ONLY
  38. ? selectedConfigurations.slice(0, 1)
  39. : selectedConfigurations) {
  40. const { width, theme, locale } = configuration;
  41. const prefix = `${width}-${theme}-${locale}`;
  42. const fixture = await createProjectDirectoryFixture(artifacts);
  43. const h = await setup(browser, { width, theme, locale, signedIn: true });
  44. const { page } = h;
  45. page.setDefaultTimeout(15_000);
  46. const bridges = new Map();
  47. const snapshots = new Map();
  48. const directoryReadinessRecovery = {
  49. bridgeSessionId: null,
  50. droppedRequests: 0,
  51. replayedRequests: 0,
  52. matchedSignals: 0,
  53. capabilityCalls: 0,
  54. };
  55. let droppedCapabilityFrame;
  56. fixture.traffic.directoryReadinessRecovery = directoryReadinessRecovery;
  57. let view = { activeWorkspaceKey: fixture.localPath, activeTaskId: "LOCAL_TASK", updatedAt: 1 };
  58. const send = (socket, payload) => socket.send(JSON.stringify({ type: "data", payload }));
  59. fixture.traffic.navigations = [];
  60. page.on("framenavigated", (frame) => {
  61. if (frame === page.mainFrame()) fixture.traffic.navigations.push(frame.url());
  62. });
  63. page.on("console", (message) => {
  64. if (message.type() === "error") fixture.traffic.errors.push(message.text());
  65. });
  66. await page.routeWebSocket(/\/api\/v1\/remote\/ws2(?:\?|$)/, (socket) => {
  67. const ownBridges = [];
  68. socket.onClose(() => {
  69. for (const bridge of ownBridges) bridge.dispose();
  70. });
  71. socket.onMessage((raw) => {
  72. const message = JSON.parse(String(raw));
  73. if (message.type === "auth_init")
  74. socket.send(
  75. JSON.stringify({ type: "auth_ack", device_sid: "e2e-device", pair_status: "matched" }),
  76. );
  77. if (message.type === "pair_status_query")
  78. socket.send(JSON.stringify({ type: "pair_status_ack", pair_status: "matched" }));
  79. const payload = message.payload;
  80. if (!payload) return;
  81. if (payload.zcode_type === "rpc-frame" || payload.zcode_type === "rpc-frame-ack") {
  82. if (
  83. payload.zcode_type === "rpc-frame" &&
  84. payload.bridgeSessionId === directoryReadinessRecovery.bridgeSessionId &&
  85. payload.fragmentCount === 1
  86. ) {
  87. const header = deserialize(
  88. new BufferReader(VSBuffer.wrap(Buffer.from(payload.dataBase64, "base64"))),
  89. );
  90. if (header[2] === "window-project-changes" && header[3] === "getCapabilities") {
  91. if (!droppedCapabilityFrame) {
  92. droppedCapabilityFrame = payload;
  93. directoryReadinessRecovery.droppedRequests++;
  94. // 只在 relay 边界丢帧,原 matched 消息驱动浏览器 main 的真实 send-ready 回调。
  95. directoryReadinessRecovery.matchedSignals++;
  96. socket.send(JSON.stringify({ type: "pair_status_ack", pair_status: "matched" }));
  97. return;
  98. }
  99. assert.deepEqual(payload, droppedCapabilityFrame, "recover the same unacked frame");
  100. directoryReadinessRecovery.replayedRequests++;
  101. }
  102. }
  103. bridges.get(payload.bridgeSessionId)?.acceptPayload(payload);
  104. return;
  105. }
  106. const result = {
  107. windowControlSessionId: "e2e-device",
  108. desktopAppVersion: "3.15.1",
  109. workspaces: fixture.workspaces,
  110. initialViewState: view,
  111. };
  112. if (payload.zcode_type === "bootstrap-request")
  113. send(socket, {
  114. zcode_type: "bootstrap-response",
  115. requestId: payload.requestId,
  116. success: true,
  117. result,
  118. });
  119. if (payload.zcode_type === "workspace-list-request")
  120. send(socket, {
  121. zcode_type: "workspace-list-response",
  122. requestId: payload.requestId,
  123. success: true,
  124. result,
  125. });
  126. if (payload.zcode_type === "mobile-view-state-update") {
  127. fixture.traffic.views.push(payload);
  128. view = payload.viewState;
  129. send(socket, { zcode_type: "mobile-view-state-updated", requestId: payload.requestId });
  130. }
  131. if (payload.zcode_type !== "workspace-bridge-open") return;
  132. fixture.traffic.opens.push(payload);
  133. const target = fixture.workspaces.find(
  134. (item) => (item.workspaceIdentity || item.workspacePath) === payload.workspaceKey,
  135. );
  136. assert.ok(target, "MRO02 only opens fixture workspaces");
  137. const remoteBridge = target.kind === "remote";
  138. const bridge = {
  139. ...target,
  140. workspaceKey: payload.workspaceKey,
  141. bridgeSessionId: payload.bridgeSessionId,
  142. bridgeGeneration: payload.bridgeGeneration,
  143. initialTaskId: payload.taskId,
  144. ...(remoteBridge ? { capabilities: { windowProjectDirectory: true } } : {}),
  145. };
  146. if (remoteBridge && !directoryReadinessRecovery.bridgeSessionId)
  147. directoryReadinessRecovery.bridgeSessionId = bridge.bridgeSessionId;
  148. const frames = new Emitter();
  149. const channels = fixture.channels(remoteBridge);
  150. // relay RPC 首帧只能在客户端收到 ready、登记桥接代际后发送,顺序沿用共享夹具。
  151. send(socket, {
  152. zcode_type: "workspace-bridge-ready",
  153. requestId: payload.requestId,
  154. bridgeSessionId: payload.bridgeSessionId,
  155. bridgeGeneration: payload.bridgeGeneration,
  156. bridge,
  157. });
  158. const desktopBridge = createDeviceSwitchDesktopBridge(socket, bridge, {
  159. locale,
  160. theme,
  161. events: {
  162. ...channels.events,
  163. [`${ServiceChannels.ZCodeAgent}:onDynamicConversationFrame`]: frames.event,
  164. },
  165. responses: {
  166. ...channels.responses,
  167. "window-project-changes:getCapabilities": (...args) => {
  168. if (bridge.bridgeSessionId === directoryReadinessRecovery.bridgeSessionId)
  169. directoryReadinessRecovery.capabilityCalls++;
  170. return channels.responses["window-project-changes:getCapabilities"](...args);
  171. },
  172. [`${ServiceChannels.SettingsSync}:getFirstRunPromptState`]: { handled: true },
  173. [`${ServiceChannels.ZCodeAgent}:helloConversationV4`]: {
  174. kind: "hello",
  175. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  176. connectionId: bridge.bridgeSessionId,
  177. clientMode: "web-remote-replayable",
  178. deliveryProfile: "replayable",
  179. serverTime: 1,
  180. auth: {},
  181. capabilities: {
  182. nativeDialogs: false,
  183. localTerminal: false,
  184. binaryFrames: true,
  185. compression: "none",
  186. },
  187. },
  188. [`${ServiceChannels.ZCodeAgent}:initializeConversationV4`]: null,
  189. [`${ServiceChannels.ZCodeAgent}:subscribeConversationV4`]: (input) => {
  190. const subscriptionId = `sub-${bridge.bridgeSessionId}-${input.sessionId}`;
  191. snapshots.set(input.sessionId, () =>
  192. frames.fire(taskSnapshotFrame(input.sessionId, subscriptionId)),
  193. );
  194. return { ack: { subscriptionId, mode: "snapshot", logEpoch: "e2e" } };
  195. },
  196. [`${ServiceChannels.ZCodeAgent}:unsubscribeConversationV4`]: null,
  197. [`${ServiceChannels.ZCodeAgent}:conversationWorkflowRunsV4`]: { runs: [] },
  198. [`${ServiceChannels.ZCodeAgent}:conversationPlansV4`]: { plans: [] },
  199. },
  200. });
  201. bridges.set(bridge.bridgeSessionId, desktopBridge);
  202. ownBridges.push(desktopBridge);
  203. });
  204. });
  205. const local = () => page.locator(`[data-project-id="${fixture.local.id}"]`);
  206. const remote = () => page.locator(`[data-project-id="${fixture.remote.id}"]`);
  207. const home = page.locator('[data-mobile-page="home"]');
  208. const chat = page.locator('[data-mobile-page="chat"]');
  209. const returnHome = async () => {
  210. if (width < 768 && (await chat.isVisible())) {
  211. await page.goBack();
  212. await home.waitFor();
  213. }
  214. };
  215. const directoryVisible = async (phase) => {
  216. await local().waitFor();
  217. await remote().waitFor();
  218. await page.getByText("E2E_MRO02_PINNED_TASK", { exact: true }).first().waitFor();
  219. assert.equal(
  220. await page.locator(`[data-project-id="${fixture.hidden.id}"]`).count(),
  221. 0,
  222. `${phase}: unadded Source project must stay hidden`,
  223. );
  224. assert.equal(
  225. await page.getByText("E2E_MRO02_NOT_ADDED_TASK", { exact: true }).count(),
  226. 0,
  227. `${phase}: unadded Source task must stay hidden`,
  228. );
  229. };
  230. const openTask = async (row, title) => {
  231. const toggle = row.getByTestId("virtual-project-toggle");
  232. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  233. await row.getByText(title, { exact: true }).first().click();
  234. };
  235. try {
  236. await page.goto(
  237. new URL("/remote/v4?app_version=3.15.1&sid=e2e-device&mid=e2e-mid", origin).href,
  238. );
  239. const onboarding = page.getByTestId("onboarding-page");
  240. const welcome = page.getByRole("dialog", { name: /欢迎使用 ZCode|Welcome to ZCode/ });
  241. await local().or(onboarding).or(welcome).first().waitFor();
  242. if (await onboarding.isVisible())
  243. await onboarding.getByRole("button", { name: /退出引导|Exit onboarding/ }).click();
  244. await local().or(welcome).first().waitFor();
  245. if (await welcome.isVisible())
  246. await welcome.getByRole("button", { name: /^(Close|关闭)$/ }).click();
  247. await directoryVisible("initial local");
  248. await openTask(remote(), "E2E_MRO02_REMOTE_TASK");
  249. await page.locator('[data-session-id="REMOTE_TASK"]').waitFor();
  250. const assertRemoteHeader = async () => {
  251. const header = page.getByTestId("workspace-path");
  252. await header.waitFor({ state: "visible" });
  253. await page
  254. .locator(
  255. `[data-testid="workspace-path"][aria-description="${locale === "zh-CN" ? "已连接" : "Connected"}"]`,
  256. )
  257. .waitFor({ state: "visible" });
  258. // bridge 登记早于目录读取完成;连接就绪不代表设备名就绪,按名称条件等待避免误读占位文字。
  259. await header
  260. .locator("[data-workspace-device-name]")
  261. .filter({ hasText: /^example\.test$/ })
  262. .waitFor({ state: "visible" });
  263. };
  264. await assertRemoteHeader();
  265. await assertEventually(() => snapshots.has("REMOTE_TASK"));
  266. snapshots.get("REMOTE_TASK")();
  267. await returnHome();
  268. await directoryVisible("remote bridge");
  269. assert.equal(directoryReadinessRecovery.droppedRequests, 1, "drop one capability request");
  270. assert.equal(directoryReadinessRecovery.matchedSignals, 1, "signal send-ready after loss");
  271. assert.equal(directoryReadinessRecovery.replayedRequests, 1, "pending request is replayed");
  272. assert.equal(directoryReadinessRecovery.capabilityCalls, 1, "capability service runs once");
  273. assert.ok(
  274. fixture.traffic.calls.some(
  275. (call) => call.channel === "window-project" && call.method === "readTree",
  276. ),
  277. "remote sidebar must read the window directory channel",
  278. );
  279. // 此处检查浏览器里真实注册的 Source RPC 代理,不把侧栏新通道误用于工作区消费者。
  280. const source = await page.evaluate(
  281. async (modulePath) => {
  282. const { getRemoteWorkspaceSession } = await import(modulePath);
  283. const services = getRemoteWorkspaceSession("mro02-remote-scope").services;
  284. return {
  285. tree: await services.projectService.readTree(),
  286. directory: await services.remoteProjectService.readDirectory(),
  287. };
  288. },
  289. `/@fs/${resolve("packages/ui/src/store/remoteWorkspaceSessionStore.ts").replaceAll("\\", "/").replace(/^\/+/, "")}`,
  290. );
  291. assert.deepEqual(
  292. new Set(source.tree.projects.map((project) => project.id)),
  293. new Set([fixture.remote.id, fixture.hidden.id]),
  294. );
  295. assert.deepEqual(source.directory, { hosts: [], entries: [] });
  296. // 窗口真实服务修改本机项目,仅发窗口项目事件;remote 原广播保持 Source 语义。
  297. await fixture.windowProject.saveProject({
  298. id: fixture.local.id,
  299. name: "E2E_MRO02_LOCAL_RENAMED",
  300. });
  301. await page.locator('[data-project-name="E2E_MRO02_LOCAL_RENAMED"]').waitFor();
  302. await local().getByTestId("virtual-project-menu").click();
  303. await page.getByTestId("virtual-project-pin").click();
  304. await assertEventually(
  305. () =>
  306. fixture.windowRepository
  307. .readTree()
  308. .projects.find((project) => project.id === fixture.local.id)?.pinned === true,
  309. );
  310. assert.ok(
  311. fixture.traffic.calls.some(
  312. (call) =>
  313. call.channel === "window-project" &&
  314. call.method === "saveProject" &&
  315. call.args[0]?.id === fixture.local.id,
  316. ),
  317. "project writes must use the same window owner as reads",
  318. );
  319. await page.screenshot({ path: resolve(artifacts, `${prefix}-remote.png`), fullPage: true });
  320. await page.reload();
  321. await assertEventually(() => fixture.traffic.opens.at(-1)?.workspaceKey === fixture.identity);
  322. if (width < 768) {
  323. await home.or(chat).first().waitFor();
  324. await returnHome();
  325. }
  326. if (width >= 768) await assertRemoteHeader();
  327. await directoryVisible("reload remote");
  328. await openTask(local(), "E2E_MRO02_LOCAL_TASK");
  329. await page.locator('[data-session-id="LOCAL_TASK"]').waitFor();
  330. await returnHome();
  331. await directoryVisible("return local");
  332. assert.equal(fixture.traffic.opens.at(-1).workspaceKey, fixture.localPath);
  333. assert.deepEqual(h.errors, []);
  334. await page.screenshot({ path: resolve(artifacts, `${prefix}-returned.png`), fullPage: true });
  335. results.push({ ...configuration, result: "passed" });
  336. } catch (error) {
  337. await page.screenshot({ path: resolve(artifacts, `${prefix}-failure.png`), fullPage: true });
  338. await writeFile(
  339. resolve(artifacts, `${prefix}-failure.txt`),
  340. `${error.stack}\n\n${await page.locator("body").innerText()}\n${JSON.stringify(h.errors)}`,
  341. );
  342. throw error;
  343. } finally {
  344. await writeFile(
  345. resolve(artifacts, `${prefix}-traffic.json`),
  346. JSON.stringify(fixture.traffic, null, 2),
  347. );
  348. await h.context.close();
  349. fixture.dispose();
  350. }
  351. }
  352. await writeFile(resolve(artifacts, "results.json"), JSON.stringify(results, null, 2));
  353. console.log(`MRO02 passed: ${results.length} configurations; ${artifacts}`);
  354. } finally {
  355. await browser.close();
  356. }