conversation-session-r3-shared-waiters.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { DatabaseSync } from "node:sqlite";
  2. import { selectTaskOrganizeMode } from "#e2e/helpers/workspace-agent-warmup";
  3. import { createStallableTcpProxy as createStallableProxy } from "#e2e/helpers/ssh-stallable-proxy";
  4. import {
  5. disconnectRemoteSource,
  6. requestRemoteProjectConnection,
  7. } from "#e2e/helpers/remote-project-actions";
  8. import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  9. import { join, resolve } from "node:path";
  10. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  11. import { TID_SETTINGS_BACK_BUTTON } from "@zcode/shared/test-ids";
  12. import {
  13. clearAppData,
  14. clickTestIdByDom,
  15. getE2EAppDataPaths,
  16. readSettings,
  17. } from "#e2e/helpers/desktop-app";
  18. import { removeRemoteProjectEntry } from "#e2e/helpers/ssh-remote-lifecycle";
  19. import {
  20. connectSSHWorkspace,
  21. openSSHRemoteDialog,
  22. fillSSHPasswordSettings,
  23. clickLastEnabledSSHDialogButton,
  24. openSSHSourceDirectory,
  25. readHostProcesses,
  26. readRemoteTabSnapshot,
  27. readSSHRuntimeConfig,
  28. runSSHCommand,
  29. selectSSHRemoteDirectory,
  30. waitForRemoteTab,
  31. waitForSSHDirectoryStep,
  32. type SSHConnectionConfig,
  33. } from "#e2e/helpers/ssh-remote-p0";
  34. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  35. const CASE_MARKER = "E2E_R3_SHARED_WAITERS";
  36. const artifactDir = resolve(
  37. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-shared-waiters",
  38. );
  39. async function readHostConnectRequests(): Promise<Set<string>> {
  40. const directory = process.env.ZCODE_E2E_RUNTIME_LOG_DIR;
  41. if (!directory) throw new Error(`${CASE_MARKER}: 缺少本 worker 的日志目录`);
  42. const files = (await readdir(directory)).filter((name) => name.endsWith(".log"));
  43. const ids = new Set<string>();
  44. for (const content of await Promise.all(
  45. files.map((name) => readFile(join(directory, name), "utf8")),
  46. )) {
  47. for (const line of content.split("\n").slice(0, -1)) {
  48. const match = /connecting window-scoped remote source, requestId=([^,\s]+), target=.+$/u.exec(
  49. line,
  50. );
  51. if (match) ids.add(match[1]!);
  52. }
  53. }
  54. return ids;
  55. }
  56. describe(`${CASE_MARKER}: 同一 target 的多个等待者与连接中项目入口移除`, () => {
  57. let proxy: Awaited<ReturnType<typeof createStallableProxy>> | null = null;
  58. const facts: Record<string, unknown> = {};
  59. after(async () => {
  60. await mkdir(artifactDir, { recursive: true });
  61. await writeFile(resolve(artifactDir, "shared-waiters.json"), JSON.stringify(facts, null, 2));
  62. await proxy?.close().catch(() => undefined);
  63. proxy = null;
  64. await browser.electron.restoreAllMocks();
  65. await clearAppData();
  66. });
  67. it("R3A-CON-04 取消向导等待者不取消原项目连接;连接中移除 B 入口后不复活,A 正常上线", async function () {
  68. this.timeout(30 * 60_000);
  69. const direct = readSSHRuntimeConfig(CASE_MARKER);
  70. proxy = await createStallableProxy(direct);
  71. const proxied: SSHConnectionConfig = {
  72. host: direct.host,
  73. password: direct.password,
  74. port: proxy.port,
  75. username: direct.username,
  76. };
  77. const [workspaceA, workspaceB] = direct.workspacePaths;
  78. await prepareV4ConversationE2E({ skipProvider: true });
  79. const initialHosts = await readHostProcesses();
  80. // 在线:项目 a、项目 b 共享一个 Source 连接(同一 target)。
  81. const tabA = await connectSSHWorkspace({
  82. caseMarker: CASE_MARKER,
  83. config: proxied,
  84. workspacePath: workspaceA,
  85. });
  86. const sourceId = parseRemoteWorkspaceIdentity(tabA.workspaceIdentity!)?.sourceServerId ?? "";
  87. await openSSHSourceDirectory(proxied, CASE_MARKER);
  88. await waitForSSHDirectoryStep(CASE_MARKER);
  89. await selectSSHRemoteDirectory(workspaceB, CASE_MARKER);
  90. const tabB = await waitForRemoteTab({
  91. caseMarker: CASE_MARKER,
  92. expectedPath: workspaceB,
  93. timeoutMs: 120_000,
  94. });
  95. expect(parseRemoteWorkspaceIdentity(tabB.workspaceIdentity!)?.sourceServerId).toBe(sourceId);
  96. const projectAId = await $(
  97. `[data-project-workspace-identity="${tabA.workspaceIdentity}"]`,
  98. ).getAttribute("data-project-id");
  99. const projectBId = await $(
  100. `[data-project-workspace-identity="${tabB.workspaceIdentity}"]`,
  101. ).getAttribute("data-project-id");
  102. if (!projectAId || !projectBId) throw new Error(`${CASE_MARKER}: 缺少项目身份`);
  103. const entryPresent = (projectId: string) => {
  104. // node:sqlite 只有同步连接;只读提交后的 membership,不把导航缓存当作项目入口的权威。
  105. const db = new DatabaseSync(join(getE2EAppDataPaths().appDataDir, "tasks-index.sqlite"), {
  106. readOnly: true,
  107. });
  108. try {
  109. return Boolean(
  110. db
  111. .prepare("SELECT 1 FROM remote_project_entries WHERE host_id=? AND remote_project_id=?")
  112. .get(`remote:server:${sourceId}`, projectId),
  113. );
  114. } finally {
  115. db.close();
  116. }
  117. };
  118. expect(entryPresent(projectBId)).toBe(true);
  119. facts.online = {
  120. a: tabA.remoteSessionId,
  121. b: tabB.remoteSessionId,
  122. sharedSession: tabA.remoteSessionId === tabB.remoteSessionId,
  123. accepted: proxy.acceptedCount(),
  124. };
  125. // 显式断开 → 新连接停摆 → 点击重连:a/b 两个 workspace 成为同一 target 的等待者。
  126. await selectTaskOrganizeMode(["项目", "Project"]);
  127. await disconnectRemoteSource(sourceId!, CASE_MARKER, {
  128. workspaceIdentities: [tabA.workspaceIdentity!, tabB.workspaceIdentity!],
  129. });
  130. proxy.setStall(true);
  131. const acceptedBeforeReconnect = proxy.acceptedCount();
  132. await requestRemoteProjectConnection(tabA.workspaceIdentity!, CASE_MARKER);
  133. await browser.waitUntil(() => Promise.resolve(proxy!.pendingCount() > 0), {
  134. timeout: 30_000,
  135. timeoutMsg: `${CASE_MARKER}: 重连没有产生停摆的 TCP 连接`,
  136. });
  137. await browser.waitUntil(
  138. async () =>
  139. (await $(`[data-project-workspace-identity="${tabA.workspaceIdentity}"]`).getAttribute(
  140. "data-connection-state",
  141. )) === "connecting",
  142. { timeout: 15_000 },
  143. );
  144. facts.waiting = {
  145. status: "connecting",
  146. pendingConnections: proxy.pendingCount(),
  147. acceptedSinceReconnect: proxy.acceptedCount() - acceptedBeforeReconnect,
  148. };
  149. // 新项目的连接动作属于 Source;独立设置向导提供可取消的第二个真实等待者。
  150. const requestsBeforeWizard = await readHostConnectRequests();
  151. // helper 默认从项目表单进入;本例需要独立设置等待者,否则取消后没有设置返回按钮。
  152. await openSSHRemoteDialog(CASE_MARKER, { entry: "settings" });
  153. await $('[data-testid="settings-page"]').waitForDisplayed();
  154. await fillSSHPasswordSettings(proxied);
  155. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  156. // 该 Host 日志紧接着同步登记 logical waiter;取消 IPC 只能在本次 handler 让出后处理。
  157. // 等待请求已到达 Host,避免只取消尚未提交的前端表单而误称覆盖了共享等待者。
  158. await browser.waitUntil(
  159. async () => {
  160. const requests = await readHostConnectRequests();
  161. return [...requests].some((id) => !requestsBeforeWizard.has(id));
  162. },
  163. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 第二个等待者没有到达 Host` },
  164. );
  165. await browser.waitUntil(
  166. () =>
  167. browser.execute(() => {
  168. const button = [
  169. ...document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  170. ].find(
  171. (item) =>
  172. ["取消连接", "Cancel connection"].includes(item.innerText.trim()) && !item.disabled,
  173. );
  174. button?.click();
  175. return Boolean(button);
  176. }),
  177. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 第二个向导等待者没有取消入口` },
  178. );
  179. await browser.waitUntil(
  180. () =>
  181. browser.execute(() => {
  182. const dialog = document.querySelector('[data-testid="ssh-dialog"]');
  183. return !dialog || /已取消|Cancelled/u.test(dialog.textContent ?? "");
  184. }),
  185. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 向导取消没有收口` },
  186. );
  187. if (await $('[data-testid="ssh-dialog"]').isExisting()) {
  188. await $('[data-testid="ssh-dialog"]')
  189. .$('.//button[normalize-space(.)="关闭" or normalize-space(.)="Close"]')
  190. .click();
  191. await $('[data-testid="ssh-dialog"]').waitForExist({ reverse: true });
  192. }
  193. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  194. expect(proxy.pendingCount()).toBe(1);
  195. facts.cancelledWizardDidNotCancelProject = true;
  196. // 当前合同仅移除本机 membership。不能再用 tab-store user-close 回退偷偷关闭运行态。
  197. await removeRemoteProjectEntry(workspaceB, CASE_MARKER);
  198. const bEntryGone = !(await $(
  199. `[data-project-workspace-identity="${tabB.workspaceIdentity}"]`,
  200. ).isExisting());
  201. facts.closedBVia = "sidebar-entry-removal";
  202. const afterClose = await browser.execute((key) => {
  203. const row = document.querySelector<HTMLElement>(`[data-project-workspace-identity="${key}"]`);
  204. return row?.dataset.connectionState ?? null;
  205. }, tabA.workspaceIdentity!);
  206. const entriesAfterClose = (await readSettings()).lastWorkspaceSession ?? [];
  207. const bTabGone = !(await readRemoteTabSnapshot(tabB.workspaceIdentity!)).workspaceIdentity;
  208. facts.afterCloseB = {
  209. sourceStatus: afterClose,
  210. pendingConnections: proxy.pendingCount(),
  211. aEntryPresent: entryPresent(projectAId),
  212. bEntryPresent: entryPresent(projectBId),
  213. bRemovedFromSettings: !entriesAfterClose.some(
  214. (entry) => entry.kind === "remote" && entry.workspacePath === workspaceB,
  215. ),
  216. bEntryGone,
  217. bTabGone,
  218. };
  219. expect(facts.afterCloseB).toMatchObject({
  220. aEntryPresent: true,
  221. bEntryPresent: false,
  222. bEntryGone: true,
  223. });
  224. expect(proxy.pendingCount()).toBeGreaterThan(0);
  225. // 代理必须保留 SSH banner;释放原等待者就应恢复,不能再靠一次手动重试掩盖取消或握手失败。
  226. const released = proxy.release();
  227. proxy.setStall(false);
  228. facts.released = released;
  229. expect(released).toBeGreaterThan(0);
  230. const restored = await waitForRemoteTab({
  231. caseMarker: CASE_MARKER,
  232. expectedIdentity: tabA.workspaceIdentity!,
  233. expectedPath: workspaceA,
  234. requireActive: false,
  235. timeoutMs: 60_000,
  236. });
  237. const sessionA = restored.remoteSessionId;
  238. facts.cameOnlineAfterRelease = true;
  239. expect(sessionA).not.toBe(tabA.remoteSessionId);
  240. await browser.pause(5_000);
  241. const finalEntries = (await readSettings()).lastWorkspaceSession ?? [];
  242. const finalB = await readRemoteTabSnapshot(tabB.workspaceIdentity!);
  243. facts.final = {
  244. sessionA,
  245. regenerated: sessionA !== tabA.remoteSessionId,
  246. bTabPresent: Boolean(finalB?.workspaceIdentity),
  247. bEntryPresent: entryPresent(projectBId),
  248. bNavigationEntryPresent: finalEntries.some(
  249. (entry) => entry.kind === "remote" && entry.workspacePath === workspaceB,
  250. ),
  251. accepted: proxy.acceptedCount(),
  252. };
  253. expect(
  254. await $(`[data-project-workspace-identity="${tabB.workspaceIdentity}"]`).isExisting(),
  255. ).toBe(false);
  256. expect(proxy.acceptedCount() - acceptedBeforeReconnect).toBe(1);
  257. expect(entryPresent(projectAId)).toBe(true);
  258. expect(entryPresent(projectBId)).toBe(false);
  259. expect(await readHostProcesses()).toEqual(initialHosts);
  260. // agent spawnArgs 恒为 "app-server --stdio"(3.12+ release 优先 glm 原生二进制,
  261. // 旧 dev 态才是 node zcode.cjs);按 args 匹配与实现形态无关。
  262. const remoteAgents = await runSSHCommand(
  263. direct,
  264. `for d in /proc/[0-9]*; do c=$(tr "\\0" " " < "$d/cmdline" 2>/dev/null) || continue; case "$c" in *"app-server --stdi"[o]*) echo "$(readlink $d/cwd)";; esac; done`,
  265. );
  266. facts.remoteAgentCwds = remoteAgents.stdout.trim().split("\n").filter(Boolean);
  267. });
  268. });