conversation-session-project-device-selection.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. import { BufferReader, BufferWriter, deserialize, serialize, VSBuffer } from "@zcode/rpc";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import {
  5. ServiceChannels,
  6. PlatformChannels,
  7. InternalChannels,
  8. buildRemoteHostWorkspaceIdentity,
  9. } from "@zcode/shared";
  10. import {
  11. TID_VIRTUAL_PROJECT_CREATE_TASK,
  12. TID_TASK_ITEM,
  13. TID_TASK_SETTINGS_BUTTON,
  14. TID_SETTINGS_SECTION_NAV,
  15. TID_SETTINGS_BACK_BUTTON,
  16. TID_REMOTE_KIND_SSH,
  17. TID_CONFIRM_DIALOG_CONFIRM,
  18. testId,
  19. } from "@zcode/shared/test-ids";
  20. import { clickTestIdByDom, clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  21. import { selectRemoteDeviceMenuItem } from "#e2e/helpers/remote-project-actions";
  22. import {
  23. selectNativeProjectDirectories,
  24. selectRemoteProjectDirectory,
  25. } from "#e2e/helpers/project-sidebar";
  26. import { selectV4TaskById, prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  27. import {
  28. installHandoffRpcProbe,
  29. callHandoffHost,
  30. restoreHandoffProbes,
  31. } from "#e2e/helpers/remote-project-handoff-probe";
  32. import {
  33. fillSSHPasswordSettings,
  34. readSSHRuntimeConfig,
  35. clickLastEnabledSSHDialogButton,
  36. waitForSSHDirectoryStep,
  37. waitForRemoteTab,
  38. } from "#e2e/helpers/ssh-remote-p0";
  39. import type { RemoteProjectDirectory, VirtualProject } from "@zcode/services";
  40. const marker = "E2E_PROJECT_DEVICE_SELECTION";
  41. const projectName = `${marker}_${Date.now()}`;
  42. interface DirectoryDelay {
  43. request?: number[];
  44. restore(): void;
  45. }
  46. declare global {
  47. interface Window {
  48. __projectDirectoryDelay?: DirectoryDelay;
  49. __taskFixtureRemotePort?: MessagePort;
  50. __taskFixturePortListener?: (event: MessageEvent) => void;
  51. }
  52. }
  53. // 保留真实 SSH 连接,只阻挡完成响应,让活动页签断言覆盖连接进行中。
  54. declare global {
  55. var __projectConnectionRestore: (() => void) | undefined;
  56. }
  57. async function activeTabId() {
  58. return browser.execute(
  59. () =>
  60. (
  61. window as Window & {
  62. __zcodeTabStoreE2E?: { getState(): { activeTabId: string | null } };
  63. }
  64. ).__zcodeTabStoreE2E!.getState().activeTabId,
  65. );
  66. }
  67. async function holdProjectConnection() {
  68. const originalTab = await activeTabId();
  69. expect(originalTab).toBeTruthy();
  70. await browser.electron.execute((electron, channel) => {
  71. const handlers = (
  72. electron.ipcMain as unknown as {
  73. _invokeHandlers: Map<string, (...args: unknown[]) => Promise<unknown>>;
  74. }
  75. )._invokeHandlers;
  76. const original = handlers.get(channel)!;
  77. let release!: () => void;
  78. const barrier = new Promise<void>((resolve) => {
  79. release = resolve;
  80. });
  81. handlers.set(channel, async (...args) => {
  82. const result = await original(...args);
  83. await barrier;
  84. return result;
  85. });
  86. globalThis.__projectConnectionRestore = () => {
  87. release();
  88. handlers.set(channel, original);
  89. };
  90. }, PlatformChannels.ConnectRemote);
  91. return originalTab;
  92. }
  93. async function assertProjectConnectionStaysInPlace(originalTab: string | null) {
  94. await $('[data-testid="ssh-dialog"]').waitForDisplayed();
  95. expect(await activeTabId()).toBe(originalTab);
  96. expect(await $("[data-settings-content-frame]").isDisplayed()).toBe(false);
  97. await browser.electron.execute(() => globalThis.__projectConnectionRestore?.());
  98. }
  99. async function holdDirectoryRequest() {
  100. await browser.execute(
  101. (channel, remoteChannel) => {
  102. const original = MessagePort.prototype.postMessage;
  103. const probe: DirectoryDelay = {
  104. restore() {
  105. MessagePort.prototype.postMessage = original;
  106. delete window.__projectDirectoryDelay;
  107. },
  108. };
  109. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  110. const text = message instanceof Uint8Array ? new TextDecoder().decode(message) : "";
  111. if (
  112. !probe.request &&
  113. text.includes(channel) &&
  114. !text.includes(remoteChannel) &&
  115. text.includes("readDirectory")
  116. ) {
  117. probe.request = Array.from(message as Uint8Array);
  118. return;
  119. }
  120. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  121. };
  122. window.__projectDirectoryDelay = probe;
  123. },
  124. ServiceChannels.Project,
  125. ServiceChannels.RemoteProjects,
  126. );
  127. }
  128. async function releaseDirectoryRequest() {
  129. const bytes = await browser.execute(() => {
  130. const probe = window.__projectDirectoryDelay!;
  131. const request = probe.request!;
  132. probe.restore();
  133. return request;
  134. });
  135. const header = deserialize(new BufferReader(VSBuffer.wrap(Uint8Array.from(bytes)))) as [
  136. number,
  137. number,
  138. ];
  139. const prefixes = [201, 202, 203].map((type) => {
  140. const writer = new BufferWriter();
  141. serialize(writer, [type, header[1]]);
  142. return Array.from(writer.buffer.buffer);
  143. });
  144. await browser.execute(
  145. (request, replies) => window.__remoteProjectHandoffRpc!.call(request, replies),
  146. bytes,
  147. prefixes,
  148. );
  149. }
  150. async function openForm() {
  151. await $('[data-testid="project-section"]').moveTo();
  152. await $('[data-testid="virtual-project-add"]').click();
  153. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  154. }
  155. async function chooseDevice(id: string) {
  156. await $('[data-testid="virtual-project-device"]').click();
  157. await $(`[role="option"][data-device-id="${id}"]`).click();
  158. }
  159. async function readDirectory() {
  160. return callHandoffHost<RemoteProjectDirectory>(ServiceChannels.RemoteProjects, "readDirectory");
  161. }
  162. describe(marker, () => {
  163. afterEach(async () => {
  164. await browser.saveScreenshot(join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "last-state.png"));
  165. });
  166. after(async () => {
  167. await browser.electron.execute(() => globalThis.__projectConnectionRestore?.());
  168. await browser.execute(() => {
  169. window.__projectDirectoryDelay?.restore();
  170. if (window.__taskFixturePortListener)
  171. window.removeEventListener("message", window.__taskFixturePortListener);
  172. });
  173. await restoreHandoffProbes();
  174. await browser.electron.restoreAllMocks();
  175. await clearAppData();
  176. });
  177. it("RDUX15-01/06/07/08/09/17 本地零/多目录、已识别无项目设备、在线选择和离线显式连接", async function () {
  178. this.timeout(15 * 60_000);
  179. const config = readSSHRuntimeConfig(marker);
  180. await prepareV4ConversationE2E({ skipProvider: true });
  181. await installHandoffRpcProbe();
  182. await browser.execute(() => {
  183. (
  184. window as Window & { __testActions?: { setLocale(locale: string): void } }
  185. ).__testActions?.setLocale("zh-CN");
  186. });
  187. await openForm();
  188. expect(await $('[data-testid="virtual-project-type-next"]').isExisting()).toBe(false);
  189. expect(await $('[data-testid="virtual-project-device"]').getText()).toContain("此电脑");
  190. await $('[data-testid="virtual-project-name"]').setValue(`${projectName}_EMPTY`);
  191. // 字段顺序为名称 → 设备 → 文件夹;名称默认聚焦,设备在其后一个焦点位。
  192. await browser.keys("Tab");
  193. expect(await browser.execute(() => document.activeElement?.getAttribute("data-testid"))).toBe(
  194. "virtual-project-device",
  195. );
  196. await browser.keys("ArrowDown");
  197. await $('[role="option"]').waitForDisplayed();
  198. await browser.keys("Escape");
  199. await $('[data-testid="virtual-project-save"]').click();
  200. await $(`[data-project-name="${projectName}_EMPTY"]`).waitForDisplayed();
  201. await openForm();
  202. await $('[data-testid="virtual-project-name"]').setValue(`${projectName}_INVALID`);
  203. await selectNativeProjectDirectories([
  204. join(DEFAULT_WORKSPACE, "missing-device-test-directory"),
  205. ]);
  206. await $('[data-testid="virtual-project-save"]').click();
  207. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  208. await $('[data-testid="project-folder-trust-confirm"]').click();
  209. await $('[role="dialog"] [role="alert"]').waitForDisplayed();
  210. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(
  211. `${projectName}_INVALID`,
  212. );
  213. expect(await $(`[data-project-name="${projectName}_INVALID"]`).isExisting()).toBe(false);
  214. await browser.keys("Escape");
  215. const paths = [
  216. join(DEFAULT_WORKSPACE, ".e2e-device", "one"),
  217. join(DEFAULT_WORKSPACE, ".e2e-device", "two"),
  218. ];
  219. await Promise.all(paths.map((path) => mkdir(path, { recursive: true })));
  220. await openForm();
  221. await $('[data-testid="virtual-project-name"]').setValue(`${projectName}_MULTI`);
  222. await selectNativeProjectDirectories(paths);
  223. expect(await $$('[data-testid="virtual-project-root-row"]').length).toBe(2);
  224. await $('[data-testid="virtual-project-save"]').click();
  225. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  226. await $('[data-testid="project-folder-trust-confirm"]').click();
  227. await $(`[data-project-name="${projectName}_MULTI"]`).waitForDisplayed();
  228. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  229. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  230. await $("[data-settings-content-frame]").$('.//button[normalize-space(.)="新建连接"]').click();
  231. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  232. await fillSSHPasswordSettings(config);
  233. await clickLastEnabledSSHDialogButton(marker);
  234. expect(await waitForSSHDirectoryStep(marker)).toBe("closed");
  235. const before = await readDirectory();
  236. expect(before.entries).toHaveLength(0);
  237. const host = before.hosts[0]!;
  238. // 明确移除本机项目成员,不删已识别设备;验证 Source 全集而非项目 open set。
  239. await callHandoffHost(ServiceChannels.RemoteProjects, "removeHost", [host.id]);
  240. expect((await readDirectory()).hosts).toHaveLength(0);
  241. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  242. await openForm();
  243. await $('[data-testid="virtual-project-name"]').setValue(projectName);
  244. await selectNativeProjectDirectories([paths[0]!]);
  245. await chooseDevice(host.id);
  246. await browser.keys("Escape");
  247. expect(await $('[data-testid="virtual-project-device"]').getText()).toContain("此电脑");
  248. expect(await $('[data-testid="virtual-project-root-name"]').getAttribute("title")).toBe(
  249. paths[0],
  250. );
  251. await chooseDevice(host.id);
  252. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  253. expect(await $$('[data-testid="virtual-project-root-row"]').length).toBe(0);
  254. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(projectName);
  255. expect((await readDirectory()).entries).toHaveLength(0);
  256. await holdDirectoryRequest();
  257. await $('[data-testid="virtual-project-browse"]').click();
  258. await browser.waitUntil(() =>
  259. browser.execute(() => Boolean(window.__projectDirectoryDelay?.request)),
  260. );
  261. await $('[data-testid="virtual-project-directory-browser"]')
  262. .$('.//button[normalize-space(.)="取消"]')
  263. .click();
  264. await chooseDevice("local");
  265. await releaseDirectoryRequest();
  266. expect(await $('[data-testid="virtual-project-directory-browser"]').isExisting()).toBe(false);
  267. expect(await $('[data-testid="virtual-project-device"]').getText()).toContain("此电脑");
  268. expect(await $$('[data-testid="virtual-project-root-row"]').length).toBe(0);
  269. await chooseDevice(host.id);
  270. await selectRemoteProjectDirectory(config.workspacePaths[0]);
  271. expect((await readDirectory()).hosts).toHaveLength(0);
  272. expect((await readDirectory()).entries).toHaveLength(0);
  273. await $('[data-testid="virtual-project-save"]').click();
  274. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  275. await $('[data-testid="project-folder-trust-confirm"]').click();
  276. await $(`[data-project-name="${projectName}"]`).waitForDisplayed();
  277. const created = await readDirectory();
  278. expect(created.entries).toHaveLength(1);
  279. expect(created.entries[0]!.roots[0]!.rootPath).toBe(config.workspacePaths[0]);
  280. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  281. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  282. // RDUX-13:断开在设备行「更多」菜单里。
  283. const sourceId = await $("[data-source-server-card]").getAttribute("data-source-server-card");
  284. if (!sourceId) throw new Error(`${marker}: 缺少设备行`);
  285. await selectRemoteDeviceMenuItem(sourceId, ["断开", "Disconnect"], marker);
  286. await $('[data-source-server-card] [data-remote-connection-status="offline"]').waitForExist();
  287. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  288. await openForm();
  289. await $('[data-testid="virtual-project-name"]').setValue(`${projectName}_OFFLINE`);
  290. await chooseDevice(host.id);
  291. expect(await $('[data-testid="virtual-project-browse"]').getText()).toContain(
  292. "连接并选择文件夹",
  293. );
  294. expect((await readDirectory()).hosts[0]!.connectionStatus).toBe("offline");
  295. const directoryOriginTab = await holdProjectConnection();
  296. await $('[data-testid="virtual-project-browse"]').click();
  297. await assertProjectConnectionStaysInPlace(directoryOriginTab);
  298. expect(await waitForSSHDirectoryStep(marker)).toBe("directory");
  299. await $('[data-testid="virtual-project-directory-browser"]').waitForDisplayed();
  300. await selectRemoteProjectDirectory(config.workspacePaths[1]);
  301. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(
  302. `${projectName}_OFFLINE`,
  303. );
  304. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  305. for (const locale of ["zh-CN", "en-US"])
  306. for (const theme of ["light", "dark"]) {
  307. await browser.execute(
  308. (language, color) => {
  309. const actions = (
  310. window as Window & {
  311. __testActions?: { setLocale(locale: string): void; setTheme(theme: string): void };
  312. }
  313. ).__testActions;
  314. actions?.setLocale(language);
  315. actions?.setTheme(color);
  316. },
  317. locale,
  318. theme,
  319. );
  320. for (const width of [1440, 480]) {
  321. await browser.electron.execute((electron, size) => {
  322. electron.BrowserWindow.getAllWindows()
  323. .find((window) => window.isVisible())
  324. ?.setSize(size, 900);
  325. }, width);
  326. await browser.executeAsync((done) =>
  327. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  328. );
  329. await browser.executeAsync((done) => {
  330. const dialog = document
  331. .querySelector('[data-testid="virtual-project-name"]')
  332. ?.closest('[role="dialog"]');
  333. const animations = (dialog?.getAnimations({ subtree: true }) ?? []).filter(
  334. (animation) =>
  335. animation.playState === "running" &&
  336. animation.effect?.getComputedTiming().iterations !== Infinity,
  337. );
  338. void Promise.all(
  339. animations.map((animation) => animation.finished.catch(() => undefined)),
  340. ).then(() => requestAnimationFrame(() => done()));
  341. });
  342. const layout = await browser.execute(() => {
  343. const bounds = document
  344. .querySelector('[data-testid="virtual-project-save"]')!
  345. .getBoundingClientRect();
  346. return {
  347. right: bounds.right,
  348. bottom: bounds.bottom,
  349. width: innerWidth,
  350. height: innerHeight,
  351. };
  352. });
  353. expect(layout.right).toBeLessThanOrEqual(layout.width);
  354. expect(layout.bottom).toBeLessThanOrEqual(layout.height);
  355. await browser.saveScreenshot(join(artifacts, `project-${locale}-${theme}-${width}.png`));
  356. }
  357. }
  358. await writeFile(
  359. join(artifacts, "project-device-facts.json"),
  360. JSON.stringify(
  361. { before, created, platform: process.platform, unverified: ["WSL", "mobile"] },
  362. null,
  363. 2,
  364. ),
  365. );
  366. await browser.electron.execute((electron) => {
  367. electron.BrowserWindow.getAllWindows()
  368. .find((window) => window.isVisible())
  369. ?.setSize(1440, 900);
  370. });
  371. await $('[data-testid="virtual-project-save"]').click();
  372. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  373. await $('[data-testid="project-folder-trust-confirm"]').click();
  374. // 窄屏视觉矩阵会收起侧栏;恢复宽窗口不会替用户展开,先通过原按钮恢复可见性再断言行。
  375. if (!(await $('[data-testid="sidebar"]').isDisplayed())) {
  376. await $('button[aria-label="切换侧边栏"], button[aria-label="Toggle sidebar"]').click();
  377. }
  378. await $(`[data-project-name="${projectName}_OFFLINE"]`).waitForDisplayed();
  379. expect((await readDirectory()).entries).toHaveLength(2);
  380. await callHandoffHost(ServiceChannels.SourceServerManagement, "disconnectSource", [
  381. host.id.slice("remote:server:".length),
  382. ]);
  383. await openForm();
  384. await chooseDevice(host.id);
  385. await browser.waitUntil(async () =>
  386. /离线|Offline/.test(await $('[data-testid="virtual-project-device"]').getText()),
  387. );
  388. expect(
  389. await $(
  390. '[data-testid="virtual-project-device"] [data-testid="virtual-project-device-status"]',
  391. ).getAttribute("data-status"),
  392. ).toBe("offline");
  393. // 已有项目入口随设备整体移动,位于名称之后、源文件夹之前。
  394. expect(await $('[data-testid="virtual-project-existing"]').getText()).toMatch(
  395. /添加到侧栏|Add to sidebar/,
  396. );
  397. expect(
  398. await browser.execute(() => {
  399. const entry = document.querySelector('[data-testid="virtual-project-existing"]')!;
  400. const name = document.querySelector('[data-testid="virtual-project-name"]')!;
  401. const device = document.querySelector('[data-testid="virtual-project-device"]')!;
  402. const browse = document.querySelector('[data-testid="virtual-project-browse"]')!;
  403. return [name, device, entry].every((element, index) =>
  404. Boolean(
  405. element.compareDocumentPosition([device, entry, browse][index]!) &
  406. Node.DOCUMENT_POSITION_FOLLOWING,
  407. ),
  408. );
  409. }),
  410. ).toBe(true);
  411. const existingOriginTab = await holdProjectConnection();
  412. await $('[data-testid="virtual-project-existing"]').click();
  413. await assertProjectConnectionStaysInPlace(existingOriginTab);
  414. await $('[data-testid="remote-project-back"]').waitForDisplayed();
  415. // 返回按钮在标题左侧,不在列表底部。
  416. expect(
  417. await browser.execute(() => {
  418. const back = document.querySelector('[data-testid="remote-project-back"]')!;
  419. const title = back.closest('[role="dialog"]')!.querySelector('[data-slot="dialog-title"]')!;
  420. return Boolean(back.compareDocumentPosition(title) & Node.DOCUMENT_POSITION_FOLLOWING);
  421. }),
  422. ).toBe(true);
  423. expect(await $('[data-testid="virtual-project-directory-browser"]').isExisting()).toBe(false);
  424. expect(await $$('[data-testid="remote-project-pick"]').length).toBeGreaterThan(0);
  425. await $('[data-testid="remote-project-back"]').click();
  426. await browser.keys("Escape");
  427. });
  428. it("RDUX15-01/02 从真实本地和远端任务默认设备,断线与快照刷新不覆盖选择", async function () {
  429. this.timeout(5 * 60_000);
  430. await browser.execute(() => {
  431. (
  432. window as Window & { __testActions?: { setLocale(locale: string): void } }
  433. ).__testActions?.setLocale("zh-CN");
  434. });
  435. const localProjects = await callHandoffHost<VirtualProject[]>(
  436. ServiceChannels.Project,
  437. "readProjects",
  438. );
  439. const local = localProjects.find((project) =>
  440. project.roots.some((root) => root.rootPath === DEFAULT_WORKSPACE),
  441. )!;
  442. const localTaskId = await createHistoryTask({
  443. workspacePath: DEFAULT_WORKSPACE,
  444. projectId: local.id,
  445. });
  446. await openTask(localTaskId, local.id);
  447. await openForm();
  448. await expectSelectedDevice("local");
  449. await browser.keys("Escape");
  450. const remote = (await readDirectory()).entries.find((entry) => entry.name === projectName)!;
  451. const path = remote.roots[0]!.rootPath;
  452. const identity = buildRemoteHostWorkspaceIdentity(remote.hostId, path);
  453. const section = $(
  454. `[data-project-id="${remote.projectId}"][data-project-host="${remote.hostId}"]`,
  455. );
  456. await browser.execute(
  457. (channel, sourceId) => {
  458. const listener = (event: MessageEvent) => {
  459. if (
  460. event.data?.type === channel &&
  461. event.data.sourceServerId === sourceId &&
  462. event.ports[0]
  463. )
  464. window.__taskFixtureRemotePort = event.ports[0];
  465. };
  466. window.__taskFixturePortListener = listener;
  467. window.addEventListener("message", listener);
  468. },
  469. InternalChannels.ScopedServicePort,
  470. remote.hostId.slice("remote:server:".length),
  471. );
  472. await section.moveTo();
  473. await section.$(`[data-testid="${TID_VIRTUAL_PROJECT_CREATE_TASK}"]`).click();
  474. await waitForRemoteTab({ caseMarker: marker, expectedIdentity: identity, expectedPath: path });
  475. const remoteTaskId = await createHistoryTask(
  476. {
  477. workspacePath: path,
  478. workspaceIdentity: identity,
  479. projectId: remote.projectId!,
  480. },
  481. true,
  482. );
  483. await openTask(remoteTaskId, remote.projectId!);
  484. const remoteTask = $(`[data-testid="${testId(TID_TASK_ITEM, remoteTaskId)}"]`);
  485. const taskDetails = $('[data-testid="remote-identity-details"]');
  486. // 选任务的 helper 使用 DOM 点击,鼠标仍可能停在项目行内;先移出再产生真实 hover 进入。
  487. const outside = await browser.execute(() => ({ x: innerWidth - 24, y: 24 }));
  488. await browser.action("pointer").move(outside).perform();
  489. await taskDetails.waitForDisplayed({ reverse: true });
  490. await section.$('[data-testid="virtual-project-toggle"]').moveTo();
  491. await taskDetails.waitForDisplayed();
  492. expect(await taskDetails.$("strong").getText()).toBe(projectName);
  493. expect(await taskDetails.getText()).toContain(projectName);
  494. expect(await taskDetails.getText()).toContain(path);
  495. expect(await taskDetails.$$("button")).toHaveLength(0);
  496. await taskDetails.moveTo();
  497. expect(await taskDetails.isDisplayed()).toBe(true);
  498. await $('[data-testid="virtual-project-add"]').moveTo();
  499. await taskDetails.waitForDisplayed({ reverse: true });
  500. // 先验证项目详情确实可打开,再持续观察会话 hover,避免把浮层延迟误判为“不展示”。
  501. await remoteTask.moveTo();
  502. const taskHover = await browser.executeAsync((done) => {
  503. const observed = { identityDetailsOpened: false, sessionRowDetailsOpened: false };
  504. const check = () => {
  505. if (document.querySelector('[data-testid="remote-identity-details"][data-state="open"]'))
  506. observed.identityDetailsOpened = true;
  507. // 远程会话行显示任务卡(cwd/活动/分支),但不复用项目身份详情。
  508. if (document.querySelector('[data-testid="task-row-details"][data-state="open"]'))
  509. observed.sessionRowDetailsOpened = true;
  510. };
  511. const observer = new MutationObserver(check);
  512. observer.observe(document.body, { childList: true, subtree: true, attributes: true });
  513. check();
  514. setTimeout(() => {
  515. observer.disconnect();
  516. done(observed);
  517. }, 700);
  518. });
  519. expect(taskHover).toEqual({
  520. identityDetailsOpened: false,
  521. sessionRowDetailsOpened: true,
  522. });
  523. await browser.saveScreenshot(
  524. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "task-hover-no-identity.png"),
  525. );
  526. await openForm();
  527. await expectSelectedDevice(remote.hostId);
  528. await chooseDevice("local");
  529. const sourceId = remote.hostId.slice("remote:server:".length);
  530. await callHandoffHost(ServiceChannels.SourceServerManagement, "renameSource", [
  531. sourceId,
  532. "Snapshot refreshed device",
  533. ]);
  534. await expectSelectedDevice("local");
  535. await browser.keys("Escape");
  536. await openForm();
  537. await expectSelectedDevice(remote.hostId);
  538. await callHandoffHost(ServiceChannels.SourceServerManagement, "disconnectSource", [sourceId]);
  539. await browser.waitUntil(async () =>
  540. (await $('[data-testid="virtual-project-device"]').getText()).includes("离线"),
  541. );
  542. await expectSelectedDevice(remote.hostId);
  543. await browser.keys("Escape");
  544. await openForm();
  545. await expectSelectedDevice(remote.hostId);
  546. expect(await $('[data-testid="virtual-project-browse"]').getText()).toContain(
  547. "连接并选择文件夹",
  548. );
  549. await browser.keys("Escape");
  550. });
  551. });
  552. async function openTask(taskId: string, projectId: string) {
  553. const task = $(`[data-testid="${testId(TID_TASK_ITEM, taskId)}"]`);
  554. const toggle = $(`[data-project-id="${projectId}"] [data-testid="virtual-project-toggle"]`);
  555. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  556. await task.waitForDisplayed({ timeout: 30_000 });
  557. await selectV4TaskById(taskId, 30_000);
  558. }
  559. async function expectSelectedDevice(id: string) {
  560. await $('[data-testid="virtual-project-device"]').click();
  561. const selected = $(`[role="option"][data-device-id="${id}"]`);
  562. await selected.waitForDisplayed();
  563. expect(await selected.getAttribute("aria-selected")).toBe("true");
  564. await browser.keys("Escape");
  565. }
  566. async function createHistoryTask(
  567. target: {
  568. workspacePath: string;
  569. workspaceIdentity?: string;
  570. projectId: string;
  571. },
  572. remote = false,
  573. ) {
  574. // 空 createSession 是草稿,正式任务前置走公开历史导入,不发送模型请求。
  575. const call = remote ? callRemoteFixture : callHandoffHost;
  576. const snapshot = await call<{ session: { sessionId: string } }>(
  577. ServiceChannels.ZCodeAgent,
  578. "createSession",
  579. [
  580. {
  581. ...target,
  582. persistence: "immediate",
  583. importedHistory: {
  584. source: "claudeCode",
  585. title: "E2E_CURRENT_TASK_FIXTURE",
  586. messages: [
  587. { role: "user", content: "E2E_CURRENT_TASK_FIXTURE" },
  588. { role: "assistant", content: "Fixture ready" },
  589. ],
  590. },
  591. },
  592. ],
  593. );
  594. const taskId = snapshot.session.sessionId;
  595. await call(ServiceChannels.ZCodeTask, "resumeTask", [
  596. {
  597. taskId,
  598. workspacePath: target.workspacePath,
  599. ...(target.workspaceIdentity ? { workspaceIdentity: target.workspaceIdentity } : {}),
  600. },
  601. ]);
  602. return taskId;
  603. }
  604. let fixtureRequestId = -19300;
  605. async function callRemoteFixture<T>(
  606. channel: string,
  607. command: string,
  608. args: unknown[] = [],
  609. ): Promise<T> {
  610. const id = fixtureRequestId--;
  611. const writer = new BufferWriter();
  612. serialize(writer, [100, id, channel, command]);
  613. serialize(writer, args);
  614. const prefixes = [201, 202, 203].map((type) => {
  615. const prefix = new BufferWriter();
  616. serialize(prefix, [type, id]);
  617. return Array.from(prefix.buffer.buffer);
  618. });
  619. const reply = await browser.execute(
  620. (request, signatures) => {
  621. const port = window.__taskFixtureRemotePort;
  622. if (!port) throw new Error("Scoped task fixture port unavailable");
  623. return new Promise<number[]>((resolve) => {
  624. const receive = (event: MessageEvent) => {
  625. if (
  626. !(event.data instanceof Uint8Array) ||
  627. !signatures.some((prefix) => prefix.every((byte, index) => event.data[index] === byte))
  628. )
  629. return;
  630. port.removeEventListener("message", receive);
  631. resolve(Array.from(event.data));
  632. };
  633. port.addEventListener("message", receive);
  634. port.postMessage(Uint8Array.from(request));
  635. });
  636. },
  637. Array.from(writer.buffer.buffer),
  638. prefixes,
  639. );
  640. const reader = new BufferReader(VSBuffer.wrap(Uint8Array.from(reply)));
  641. const header = deserialize(reader) as [number, number];
  642. const body = deserialize(reader);
  643. if (header[0] !== 201) throw new Error(typeof body === "string" ? body : body.message);
  644. return body as T;
  645. }