conversation-session-remote-project-handoff.test.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import {
  4. appSettingsSchema,
  5. ServiceChannels,
  6. type SourceServerManagementSnapshot,
  7. } from "@zcode/shared";
  8. import type { RemoteProjectDirectory } from "@zcode/services";
  9. import { clearAppData, readSettings, seedSettings } from "#e2e/helpers/desktop-app";
  10. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  11. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  12. import { waitForRendererAfterColdRestart } from "#e2e/helpers/ssh-remote-lifecycle";
  13. import {
  14. connectSSHWorkspace,
  15. readSingleSSHWorkspaceRuntimeConfig,
  16. readRemoteTabSnapshot,
  17. fillSSHPasswordSettings,
  18. clickLastEnabledSSHDialogButton,
  19. } from "#e2e/helpers/ssh-remote-p0";
  20. import { requestRemoteProjectConnection } from "#e2e/helpers/remote-project-actions";
  21. import {
  22. installHandoffRpcProbe,
  23. callHandoffHost,
  24. holdProjectBind,
  25. waitForHeldProjectBind,
  26. releaseProjectBind,
  27. restoreHandoffProbes,
  28. } from "#e2e/helpers/remote-project-handoff-probe";
  29. const MARKER = "E2E_REMOTE_PROJECT_HANDOFF";
  30. const artifactDir = resolve(
  31. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/remote-project-handoff",
  32. );
  33. const management = <T>(command: string, args: unknown[] = []) =>
  34. callHandoffHost<T>(ServiceChannels.SourceServerManagement, command, args);
  35. const directory = () =>
  36. callHandoffHost<RemoteProjectDirectory>(ServiceChannels.RemoteProjects, "readDirectory");
  37. // 真实 SSH/Host/Root;bind 返回屏障只控制时序,不伪造连接或导航结果。
  38. describe(`${MARKER}: 默认线路与原项目完成有效性`, () => {
  39. after(async () => {
  40. await mkdir(artifactDir, { recursive: true });
  41. await browser.saveScreenshot(resolve(artifactDir, "handoff-final.png"));
  42. await restoreHandoffProbes();
  43. await browser.electron.restoreAllMocks();
  44. await clearAppData();
  45. });
  46. it("RPN-06 默认线路不被备用失败替换,绑定期间移除入口不提交历史或导航", async function () {
  47. this.timeout(20 * 60_000);
  48. const config = readSingleSSHWorkspaceRuntimeConfig(MARKER);
  49. if (!["localhost", "127.0.0.1"].includes(config.host))
  50. throw new Error("用例仅使用本机隔离 SSH 目标");
  51. await prepareV4ConversationE2E({ skipProvider: true });
  52. const initial = await readSettings();
  53. const connected = await connectSSHWorkspace({
  54. caseMarker: MARKER,
  55. config,
  56. workspacePath: config.workspacePath,
  57. });
  58. const identity = connected.workspaceIdentity!;
  59. const settings = await readSettings();
  60. const source = settings.sourceServers!.find((item) =>
  61. identity.startsWith(`remote:server:${item.sourceServerId}:`),
  62. )!;
  63. const primary = settings.connectionProfiles!.find(
  64. (item) => item.profileId === source.preferredProfileId,
  65. )!;
  66. if (primary.target.kind !== "ssh" || !primary.target.passwordCredentialKey)
  67. throw new Error("缺少已保存 SSH 密码线路");
  68. const alternate = {
  69. ...primary,
  70. profileId: "e568a489-c0a8-4620-a22e-b0f39aa00923",
  71. displayName: "failed-alternate",
  72. target: { ...primary.target, port: 1 },
  73. };
  74. await reloadElectronSessionPreservingBrowserProfile(browser, {
  75. afterElectronProcessExit: async () => {
  76. await seedSettings(
  77. appSettingsSchema.parse({
  78. ...settings,
  79. remoteStartupAutoReconnectEnabled: false,
  80. connectionProfiles: [...settings.connectionProfiles!, alternate],
  81. lastWorkspaceSession: initial.lastWorkspaceSession,
  82. lastActiveWorkspace: initial.lastActiveWorkspace,
  83. }),
  84. );
  85. },
  86. });
  87. await waitForRendererAfterColdRestart(MARKER);
  88. await installHandoffRpcProbe();
  89. expect((await readRemoteTabSnapshot(identity)).workspacePath).toBeNull();
  90. await expect(management("connectProfile", [alternate.profileId])).rejects.toThrow();
  91. const failed = await management<SourceServerManagementSnapshot>("getSnapshot");
  92. expect(failed.states.find((state) => state.profileId === alternate.profileId)?.state).toBe(
  93. "failed",
  94. );
  95. await requestRemoteProjectConnection(identity, MARKER);
  96. await browser.waitUntil(
  97. async () =>
  98. (await management<SourceServerManagementSnapshot>("getSnapshot")).states.some(
  99. (state) => state.profileId === primary.profileId && state.state === "online",
  100. ),
  101. {
  102. timeout: 120_000,
  103. timeoutMsg: "项目连接没有尝试默认线路",
  104. },
  105. );
  106. expect(await $('[data-testid="ssh-dialog"]').isDisplayed()).toBe(false);
  107. expect((await readRemoteTabSnapshot(identity)).workspacePath).toBeNull();
  108. await management("disconnectSource", [source.sourceServerId]);
  109. await callHandoffHost(ServiceChannels.Credential, "delete", [
  110. primary.target.passwordCredentialKey,
  111. ]);
  112. const retained = (await directory()).entries.find(
  113. (entry) => entry.hostId === `remote:server:${source.sourceServerId}`,
  114. )!;
  115. const historyBefore = (await readSettings()).lastWorkspaceSession;
  116. await holdProjectBind(config.workspacePath);
  117. await requestRemoteProjectConnection(identity, MARKER);
  118. await $('[data-testid="ssh-error"]').waitForDisplayed();
  119. const back = $('[data-testid="ssh-dialog"]').$(
  120. './/button[normalize-space(.)="返回配置" or normalize-space(.)="Back to configuration"]',
  121. );
  122. await back.click();
  123. await fillSSHPasswordSettings(config);
  124. await clickLastEnabledSSHDialogButton(MARKER);
  125. await waitForHeldProjectBind();
  126. await callHandoffHost(ServiceChannels.RemoteProjects, "removeEntry", [retained.id]);
  127. await releaseProjectBind();
  128. await browser.waitUntil(
  129. async () => {
  130. const text = await $('[data-testid="ssh-dialog"]')
  131. .getText()
  132. .catch(() => "");
  133. return /已取消|Cancelled|Canceled/i.test(text);
  134. },
  135. { timeout: 30_000, timeoutMsg: "已移除项目的完成意图没有取消" },
  136. );
  137. expect((await readRemoteTabSnapshot(identity)).workspacePath).toBeNull();
  138. // 成员目录驱动兼容历史投影;移除入口应删除远端行,本地历史仍保持原值。
  139. const historyAfter = (await readSettings()).lastWorkspaceSession ?? [];
  140. expect(historyAfter.filter((entry) => entry.kind === "remote")).toEqual([]);
  141. expect(historyAfter.filter((entry) => entry.kind === "local")).toEqual(
  142. historyBefore?.filter((entry) => entry.kind === "local") ?? [],
  143. );
  144. expect((await directory()).entries.some((entry) => entry.id === retained.id)).toBe(false);
  145. expect(await $('[data-testid="ssh-success"]').isDisplayed()).toBe(false);
  146. await mkdir(artifactDir, { recursive: true });
  147. await writeFile(
  148. resolve(artifactDir, "handoff.json"),
  149. JSON.stringify(
  150. {
  151. identity,
  152. primaryProfileId: primary.profileId,
  153. alternateProfileId: alternate.profileId,
  154. removedEntryId: retained.id,
  155. state: "cancelled",
  156. removedHistoryAbsent: true,
  157. },
  158. null,
  159. 2,
  160. ),
  161. );
  162. });
  163. });