conversation-session-existing-remote-project.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import { BufferReader, BufferWriter, deserialize, serialize, VSBuffer } from "@zcode/rpc";
  2. import { join } from "node:path";
  3. import { writeFile } from "node:fs/promises";
  4. import { ServiceChannels, InternalChannels, buildRemoteHostWorkspaceIdentity } from "@zcode/shared";
  5. import {
  6. TID_VIRTUAL_PROJECT_CREATE_TASK,
  7. TID_TASK_SETTINGS_BUTTON,
  8. TID_SETTINGS_SECTION_NAV,
  9. TID_SETTINGS_BACK_BUTTON,
  10. TID_REMOTE_KIND_SSH,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import type { RemoteProjectDirectory, ProjectTree, VirtualProject } from "@zcode/services";
  14. import { clickTestIdByDom, clearAppData } from "#e2e/helpers/desktop-app";
  15. import { prepareV4ConversationE2E, selectV4TaskById } from "#e2e/helpers/v4-conversation";
  16. import {
  17. installHandoffRpcProbe,
  18. callHandoffHost,
  19. restoreHandoffProbes,
  20. } from "#e2e/helpers/remote-project-handoff-probe";
  21. import {
  22. fillSSHPasswordSettings,
  23. readSSHRuntimeConfig,
  24. clickLastEnabledSSHDialogButton,
  25. waitForSSHDirectoryStep,
  26. waitForRemoteTab,
  27. } from "#e2e/helpers/ssh-remote-p0";
  28. const marker = "E2E_EXISTING_REMOTE_PROJECT";
  29. declare global {
  30. interface Window {
  31. __existingProjectListRequest?: number[];
  32. __restoreExistingProjectList?: () => void;
  33. }
  34. }
  35. let selectedHostId: string;
  36. async function openForm() {
  37. // 窄窗口会按原产品规则收起侧栏;恢复尺寸后仍须用可见入口显式展开。
  38. if (
  39. await browser.execute(() => {
  40. const panel = document.querySelector("[data-workspace-sidebar-panel]");
  41. return panel?.classList.contains("pointer-events-none") ?? false;
  42. })
  43. )
  44. await $('button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]').click();
  45. await browser.waitUntil(() =>
  46. browser.execute(() => {
  47. const panel = document.querySelector("[data-workspace-sidebar-panel]");
  48. return panel ? getComputedStyle(panel).opacity === "1" : false;
  49. }),
  50. );
  51. await $('[data-purpose-section-drag-trigger="projects"]').moveTo();
  52. await $('[data-testid="virtual-project-add"]').click();
  53. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  54. await $('[data-testid="virtual-project-device"]').click();
  55. await $(`[role="option"][data-device-id="${selectedHostId}"]`).click();
  56. }
  57. async function openList() {
  58. await $('[data-testid="virtual-project-existing"]').click();
  59. await $('[data-testid="remote-project-back"]').waitForDisplayed({ timeout: 90_000 });
  60. }
  61. async function directory() {
  62. return callHandoffHost<RemoteProjectDirectory>(ServiceChannels.RemoteProjects, "readDirectory");
  63. }
  64. async function holdList(hostId: string) {
  65. await browser.execute(
  66. (channel, id) => {
  67. const original = MessagePort.prototype.postMessage;
  68. window.__restoreExistingProjectList = () => {
  69. MessagePort.prototype.postMessage = original;
  70. delete window.__restoreExistingProjectList;
  71. };
  72. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  73. const text = message instanceof Uint8Array ? new TextDecoder().decode(message) : "";
  74. if (
  75. !window.__existingProjectListRequest &&
  76. text.includes(channel) &&
  77. text.includes("readTree") &&
  78. text.includes(id)
  79. ) {
  80. window.__existingProjectListRequest = Array.from(message as Uint8Array);
  81. return;
  82. }
  83. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  84. };
  85. },
  86. ServiceChannels.Project,
  87. hostId,
  88. );
  89. }
  90. async function releaseList() {
  91. const request = await browser.execute(() => {
  92. const value = window.__existingProjectListRequest!;
  93. window.__restoreExistingProjectList?.();
  94. delete window.__existingProjectListRequest;
  95. return value;
  96. });
  97. const header = deserialize(new BufferReader(VSBuffer.wrap(Uint8Array.from(request)))) as [
  98. number,
  99. number,
  100. ];
  101. const prefixes = [201, 202, 203].map((type) => {
  102. const writer = new BufferWriter();
  103. serialize(writer, [type, header[1]]);
  104. return Array.from(writer.buffer.buffer);
  105. });
  106. await browser.execute(
  107. (bytes, signatures) => window.__remoteProjectHandoffRpc!.call(bytes, signatures),
  108. request,
  109. prefixes,
  110. );
  111. }
  112. describe(marker, () => {
  113. afterEach(async function () {
  114. if (this.currentTest?.state !== "failed") return;
  115. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  116. await browser.saveScreenshot(join(artifacts, "failure.png"));
  117. const state = await browser.execute(() => ({
  118. dialogs: Array.from(document.querySelectorAll('[role="dialog"]')).map((item) => ({
  119. text: item.textContent,
  120. state: item.getAttribute("data-state"),
  121. })),
  122. panel: document.querySelector("[data-workspace-sidebar-panel]")?.getAttribute("class"),
  123. bodyPointerEvents: getComputedStyle(document.body).pointerEvents,
  124. }));
  125. await writeFile(join(artifacts, "failure-state.json"), JSON.stringify(state, null, 2));
  126. });
  127. after(async () => {
  128. await browser.execute(() => {
  129. window.__restoreExistingProjectList?.();
  130. if (window.__taskFixturePortListener)
  131. window.removeEventListener("message", window.__taskFixturePortListener);
  132. });
  133. await restoreHandoffProbes();
  134. await browser.electron.restoreAllMocks();
  135. await clearAppData();
  136. });
  137. it("RDUX15-15/16/20 preserves original project and task identity, draft, and cancelled list", async function () {
  138. this.timeout(15 * 60_000);
  139. const config = readSSHRuntimeConfig(marker);
  140. await prepareV4ConversationE2E({ skipProvider: true });
  141. await installHandoffRpcProbe();
  142. await browser.execute(() =>
  143. (
  144. window as Window & { __testActions?: { setLocale(locale: string): void } }
  145. ).__testActions?.setLocale("zh-CN"),
  146. );
  147. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  148. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  149. await $("[data-settings-content-frame]").$('.//button[normalize-space(.)="新建连接"]').click();
  150. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  151. await fillSSHPasswordSettings(config);
  152. await clickLastEnabledSSHDialogButton(marker);
  153. expect(await waitForSSHDirectoryStep(marker)).toBe("closed");
  154. const host = (await directory()).hosts[0]!;
  155. selectedHostId = host.id;
  156. const sourceId = host.id.slice("remote:server:".length);
  157. const path = config.workspacePaths[0]!;
  158. const first = await callHandoffHost<VirtualProject>(ServiceChannels.Project, "saveProject", [
  159. { hostId: host.id, roots: [path], name: marker + " original" },
  160. ]);
  161. const second = await callHandoffHost<VirtualProject>(ServiceChannels.Project, "saveProject", [
  162. {
  163. hostId: host.id,
  164. roots: [path],
  165. name: marker + " second identity with a long project name",
  166. },
  167. ]);
  168. expect(first.id).not.toBe(second.id);
  169. const setupEntry = await callHandoffHost<{ id: string }>(
  170. ServiceChannels.RemoteProjects,
  171. "addEntry",
  172. [
  173. {
  174. hostId: host.id,
  175. expectedMembershipId: host.membershipId,
  176. project: { projectId: first.id, name: first.name, roots: first.roots },
  177. },
  178. ],
  179. );
  180. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  181. await browser.execute(
  182. (channel, id) => {
  183. const listener = (event: MessageEvent) => {
  184. if (event.data?.type === channel && event.data.sourceServerId === id && event.ports[0])
  185. window.__taskFixtureRemotePort = event.ports[0];
  186. };
  187. window.__taskFixturePortListener = listener;
  188. window.addEventListener("message", listener);
  189. },
  190. InternalChannels.ScopedServicePort,
  191. sourceId,
  192. );
  193. const row = $(`[data-project-id="${first.id}"][data-project-host="${host.id}"]`);
  194. await row.waitForDisplayed();
  195. await row.moveTo();
  196. await row.$(`[data-testid="${TID_VIRTUAL_PROJECT_CREATE_TASK}"]`).click();
  197. const identity = buildRemoteHostWorkspaceIdentity(host.id, path);
  198. await waitForRemoteTab({ caseMarker: marker, expectedIdentity: identity, expectedPath: path });
  199. const taskId = await createHistoryTask(
  200. { workspacePath: path, workspaceIdentity: identity, projectId: first.id },
  201. true,
  202. );
  203. await callHandoffHost(ServiceChannels.RemoteProjects, "removeEntry", [setupEntry.id]);
  204. expect((await directory()).entries).toHaveLength(0);
  205. const beforeProjectIds = (
  206. await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [{ hostId: host.id }])
  207. ).projects
  208. .map((project) => project.id)
  209. .sort();
  210. await openForm();
  211. await $('[data-testid="virtual-project-name"]').setValue("Retained new project draft");
  212. await openList();
  213. const pick = $(`[data-testid="remote-project-pick"][data-project-id="${first.id}"]`);
  214. await pick.waitForDisplayed();
  215. expect(await pick.getText()).toContain(path);
  216. expect(
  217. await $(`[data-testid="remote-project-pick"][data-project-id="${second.id}"]`).isDisplayed(),
  218. ).toBe(true);
  219. await $('[data-testid="remote-project-back"]').click();
  220. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(
  221. "Retained new project draft",
  222. );
  223. await browser.waitUntil(() =>
  224. browser.execute(
  225. () => document.activeElement?.getAttribute("data-testid") === "virtual-project-existing",
  226. ),
  227. );
  228. await holdList(host.id);
  229. await openList();
  230. await browser.waitUntil(() =>
  231. browser.execute(() => Boolean(window.__existingProjectListRequest)),
  232. );
  233. await $('[data-testid="remote-project-back"]').click();
  234. await $('[data-testid="virtual-project-device"]').click();
  235. await $('[role="option"][data-device-id="local"]').click();
  236. await releaseList();
  237. expect(await $('[data-testid="remote-project-back"]').isExisting()).toBe(false);
  238. expect((await directory()).entries).toHaveLength(0);
  239. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(
  240. "Retained new project draft",
  241. );
  242. await $('[data-testid="virtual-project-device"]').click();
  243. await $(`[role="option"][data-device-id="${host.id}"]`).click();
  244. await openList();
  245. await pick.waitForDisplayed();
  246. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  247. for (const locale of ["zh-CN", "en-US"])
  248. for (const theme of ["light", "dark"]) {
  249. await browser.execute(
  250. (language, color) => {
  251. const actions = (
  252. window as Window & {
  253. __testActions?: { setLocale(locale: string): void; setTheme(theme: string): void };
  254. }
  255. ).__testActions;
  256. actions?.setLocale(language);
  257. actions?.setTheme(color);
  258. },
  259. locale,
  260. theme,
  261. );
  262. for (const width of [1440, 480]) {
  263. await browser.electron.execute(
  264. (electron, size) =>
  265. electron.BrowserWindow.getAllWindows()
  266. .find((window) => window.isVisible())
  267. ?.setSize(size, 900),
  268. width,
  269. );
  270. await browser.executeAsync((done) =>
  271. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  272. );
  273. expect(await $('[data-testid="remote-project-back"]').isDisplayed()).toBe(true);
  274. const rows = await browser.execute(() =>
  275. Array.from(document.querySelectorAll('[data-testid="remote-project-pick"]')).map(
  276. (button) => {
  277. const row = button.getBoundingClientRect();
  278. const content = button.querySelector("span")!.getBoundingClientRect();
  279. return {
  280. rowTop: row.top,
  281. rowBottom: row.bottom,
  282. contentTop: content.top,
  283. contentBottom: content.bottom,
  284. scrollTop: button.parentElement!.scrollTop,
  285. };
  286. },
  287. ),
  288. );
  289. await writeFile(
  290. join(artifacts, `existing-project-rows-${locale}-${theme}-${width}.json`),
  291. JSON.stringify(rows, null, 2),
  292. );
  293. for (const row of rows) {
  294. expect(row.contentTop).toBeGreaterThanOrEqual(row.rowTop - 1);
  295. expect(row.contentBottom).toBeLessThanOrEqual(row.rowBottom + 1);
  296. }
  297. await browser.executeAsync((done) => {
  298. const dialog = document
  299. .querySelector('[data-testid="remote-project-back"]')
  300. ?.closest('[role="dialog"]');
  301. const animations = (dialog?.getAnimations({ subtree: true }) ?? []).filter(
  302. (animation) =>
  303. animation.playState === "running" &&
  304. animation.effect?.getComputedTiming().iterations !== Infinity,
  305. );
  306. void Promise.all(
  307. animations.map((animation) => animation.finished.catch(() => undefined)),
  308. ).then(() => requestAnimationFrame(() => done()));
  309. });
  310. const layout = await browser.execute(() => {
  311. const bounds = document
  312. .querySelector('[data-testid="remote-project-back"]')!
  313. .getBoundingClientRect();
  314. return {
  315. right: bounds.right,
  316. bottom: bounds.bottom,
  317. width: innerWidth,
  318. height: innerHeight,
  319. };
  320. });
  321. expect(layout.right).toBeLessThanOrEqual(layout.width);
  322. expect(layout.bottom).toBeLessThanOrEqual(layout.height);
  323. await browser.saveScreenshot(
  324. join(artifacts, `existing-project-${locale}-${theme}-${width}.png`),
  325. );
  326. }
  327. }
  328. await browser.electron.execute((electron) =>
  329. electron.BrowserWindow.getAllWindows()
  330. .find((window) => window.isVisible())
  331. ?.setSize(1440, 900),
  332. );
  333. await pick.click();
  334. await $('[data-testid="remote-project-back"]').waitForExist({ reverse: true });
  335. let entries = (await directory()).entries;
  336. expect(entries).toHaveLength(1);
  337. expect(entries[0]!.projectId).toBe(first.id);
  338. expect(entries[0]!.roots).toEqual(first.roots);
  339. await openForm();
  340. await openList();
  341. await pick.waitForDisplayed();
  342. await pick.click();
  343. await $('[data-testid="remote-project-back"]').waitForExist({ reverse: true });
  344. expect((await directory()).entries).toHaveLength(1);
  345. expect((await directory()).entries[0]!.id).toBe(entries[0]!.id);
  346. await openForm();
  347. await openList();
  348. await $(`[data-testid="remote-project-pick"][data-project-id="${second.id}"]`).click();
  349. await $('[data-testid="remote-project-back"]').waitForExist({ reverse: true });
  350. entries = (await directory()).entries;
  351. expect(entries).toHaveLength(2);
  352. expect(new Set(entries.map((entry) => entry.projectId))).toEqual(
  353. new Set([first.id, second.id]),
  354. );
  355. const tree = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  356. { hostId: host.id },
  357. ]);
  358. expect(tree.projects.map((project) => project.id).sort()).toEqual(beforeProjectIds);
  359. expect(tree.tasks.find((task) => task.taskId === taskId)?.projectId).toBe(first.id);
  360. const original = $(`[data-project-id="${first.id}"][data-project-host="${host.id}"]`);
  361. const toggle = original.$('[data-testid="virtual-project-toggle"]');
  362. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  363. await selectV4TaskById(taskId, 30_000);
  364. await browser.waitUntil(async () => (await $("body").getText()).includes("Fixture ready"), {
  365. timeout: 30_000,
  366. });
  367. await callHandoffHost(ServiceChannels.SourceServerManagement, "disconnectSource", [sourceId]);
  368. await openForm();
  369. await browser.waitUntil(
  370. async () =>
  371. (await $('[data-testid="virtual-project-device"]').getText()).includes("离线") ||
  372. (await $('[data-testid="virtual-project-device"]').getText()).includes("Offline"),
  373. );
  374. await openList();
  375. await pick.waitForDisplayed();
  376. expect(await $('[data-testid="virtual-project-directory-browser"]').isExisting()).toBe(false);
  377. expect((await directory()).entries).toHaveLength(2);
  378. await $('[data-testid="remote-project-back"]').click();
  379. await browser.keys("Escape");
  380. await writeFile(
  381. join(artifacts, "existing-project-facts.json"),
  382. JSON.stringify(
  383. {
  384. first,
  385. second,
  386. taskId,
  387. entries,
  388. task: tree.tasks.find((task) => task.taskId === taskId),
  389. unverified: ["real legacy server", "WSL", "mobile"],
  390. },
  391. null,
  392. 2,
  393. ),
  394. );
  395. });
  396. });
  397. async function createHistoryTask(
  398. target: {
  399. workspacePath: string;
  400. workspaceIdentity?: string;
  401. projectId: string;
  402. },
  403. remote = false,
  404. ) {
  405. // 空 createSession 是草稿,正式任务前置走公开历史导入,不发送模型请求。
  406. const call = remote ? callRemoteFixture : callHandoffHost;
  407. const snapshot = await call<{ session: { sessionId: string } }>(
  408. ServiceChannels.ZCodeAgent,
  409. "createSession",
  410. [
  411. {
  412. ...target,
  413. persistence: "immediate",
  414. importedHistory: {
  415. source: "claudeCode",
  416. title: "E2E_CURRENT_TASK_FIXTURE",
  417. messages: [
  418. { role: "user", content: "E2E_CURRENT_TASK_FIXTURE" },
  419. { role: "assistant", content: "Fixture ready" },
  420. ],
  421. },
  422. },
  423. ],
  424. );
  425. const taskId = snapshot.session.sessionId;
  426. await call(ServiceChannels.ZCodeTask, "resumeTask", [
  427. {
  428. taskId,
  429. workspacePath: target.workspacePath,
  430. ...(target.workspaceIdentity ? { workspaceIdentity: target.workspaceIdentity } : {}),
  431. },
  432. ]);
  433. return taskId;
  434. }
  435. let fixtureRequestId = -19300;
  436. async function callRemoteFixture<T>(
  437. channel: string,
  438. command: string,
  439. args: unknown[] = [],
  440. ): Promise<T> {
  441. const id = fixtureRequestId--;
  442. const writer = new BufferWriter();
  443. serialize(writer, [100, id, channel, command]);
  444. serialize(writer, args);
  445. const prefixes = [201, 202, 203].map((type) => {
  446. const prefix = new BufferWriter();
  447. serialize(prefix, [type, id]);
  448. return Array.from(prefix.buffer.buffer);
  449. });
  450. const reply = await browser.execute(
  451. (request, signatures) => {
  452. const port = window.__taskFixtureRemotePort;
  453. if (!port) throw new Error("Scoped task fixture port unavailable");
  454. return new Promise<number[]>((resolve) => {
  455. const receive = (event: MessageEvent) => {
  456. if (
  457. !(event.data instanceof Uint8Array) ||
  458. !signatures.some((prefix) => prefix.every((byte, index) => event.data[index] === byte))
  459. )
  460. return;
  461. port.removeEventListener("message", receive);
  462. resolve(Array.from(event.data));
  463. };
  464. port.addEventListener("message", receive);
  465. port.postMessage(Uint8Array.from(request));
  466. });
  467. },
  468. Array.from(writer.buffer.buffer),
  469. prefixes,
  470. );
  471. const reader = new BufferReader(VSBuffer.wrap(Uint8Array.from(reply)));
  472. const header = deserialize(reader) as [number, number];
  473. const body = deserialize(reader);
  474. if (header[0] !== 201) throw new Error(typeof body === "string" ? body : body.message);
  475. return body as T;
  476. }