conversation-session-r3-stop-remote-service.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  4. import { TID_CONFIRM_DIALOG_CONFIRM, TID_SETTINGS_BACK_BUTTON } from "@zcode/shared/test-ids";
  5. import { clearAppData, clickTestIdByDom } from "#e2e/helpers/desktop-app";
  6. import { getToastMessages } from "#e2e/helpers/conversation-session-toast";
  7. import {
  8. connectRemoteSourceFromSettings,
  9. openRemoteDevicesSettings,
  10. waitForDeviceStatus,
  11. } from "#e2e/helpers/remote-project-actions";
  12. import {
  13. connectSSHWorkspace,
  14. readHostProcesses,
  15. readSSHRuntimeConfig,
  16. runSSHCommand,
  17. waitForSSHDirectoryStep,
  18. type SSHConnectionConfig,
  19. } from "#e2e/helpers/ssh-remote-p0";
  20. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  21. const CASE_MARKER = "E2E_R3_STOP_REMOTE_SERVICE";
  22. const artifactDir = resolve(
  23. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-stop-remote-service",
  24. );
  25. // 连接管理器的在线重试档位为 2/4/8 秒;多等一段余量,覆盖完整一个自动重试周期。
  26. const AUTOMATIC_RETRY_CYCLE_MS = 2_000 + 4_000 + 8_000 + 6_000;
  27. interface RemoteDaemonSnapshot {
  28. /** 远端仍存活的 Supervisor / Core 进程数(按命令行匹配,排除探测 shell 自身)。 */
  29. alive: number;
  30. supervisorPid: number | null;
  31. corePid: number | null;
  32. state: string | null;
  33. }
  34. async function readRemoteDaemon(config: SSHConnectionConfig): Promise<RemoteDaemonSnapshot> {
  35. const result = await runSSHCommand(
  36. config,
  37. [
  38. // pgrep -f 会匹配承载模式串的 shell 自身;用 glob 括号切断字面匹配。
  39. 'n=0; for d in /proc/[0-9]*; do c=$(tr "\\0" " " < "$d/cmdline" 2>/dev/null) || continue; case "$c" in *runtime/server-cor[e].js*|*"serve --superviso"[r]*) n=$((n+1));; esac; done; echo "alive=$n"',
  40. 'echo "lock=$(cat "$HOME/.zcode/server/run/server.lock" 2>/dev/null | tr -d "\\n")"',
  41. 'echo "status=$(cat "$HOME/.zcode/server/run/status.json" 2>/dev/null | tr -d "\\n")"',
  42. ].join("; "),
  43. );
  44. const line = (key: string) =>
  45. result.stdout
  46. .split("\n")
  47. .find((value) => value.startsWith(`${key}=`))
  48. ?.slice(key.length + 1)
  49. .trim() ?? "";
  50. const parse = (value: string): Record<string, unknown> | null => {
  51. try {
  52. return value ? (JSON.parse(value) as Record<string, unknown>) : null;
  53. } catch {
  54. return null;
  55. }
  56. };
  57. const lock = parse(line("lock"));
  58. const status = parse(line("status"));
  59. return {
  60. alive: Number.parseInt(line("alive"), 10),
  61. supervisorPid: typeof lock?.pid === "number" ? lock.pid : null,
  62. corePid: typeof status?.pid === "number" ? status.pid : null,
  63. state: typeof status?.state === "string" ? status.state : null,
  64. };
  65. }
  66. /**
  67. * 远端除本次探测外仍存活的当前用户 SSH 会话数:每条 SSH 连接对应一个用户态 sshd(或 sshd-session)进程,
  68. * 探测自身是 `$PPID`。runSSHCommand 每次新建并关闭连接,不计入后续读数。
  69. */
  70. async function countOtherSSHSessions(config: SSHConnectionConfig): Promise<number> {
  71. const result = await runSSHCommand(
  72. config,
  73. 'me=$(id -u); n=0; for d in /proc/[0-9]*; do [ "${d#/proc/}" = "$PPID" ] && continue; [ "$(stat -c %u "$d" 2>/dev/null)" = "$me" ] || continue; case "$(cat "$d/comm" 2>/dev/null)" in sshd|sshd-session) n=$((n+1));; esac; done; echo "sessions=$n"',
  74. );
  75. const match = /sessions=(\d+)/u.exec(result.stdout);
  76. if (!match) throw new Error(`${CASE_MARKER}: 读取远端 SSH 会话数失败:${result.stdout}`);
  77. return Number.parseInt(match[1]!, 10);
  78. }
  79. /**
  80. * 直接在远端执行与 Host 相同的 `running-tasks --json`,作为确认弹窗任务清单段的对照证据。
  81. * Supervisor 只从 Core 心跳(10 秒一次)得知清单,Core 就绪后首个心跳之前输出 `null`。
  82. */
  83. async function readRemoteRunningTasksOutput(config: SSHConnectionConfig): Promise<string> {
  84. const result = await runSSHCommand(
  85. config,
  86. '"$HOME/.zcode/server/bin/zcode" running-tasks --json --server-root "$HOME/.zcode/server"',
  87. );
  88. return `exit=${result.code} ${result.stdout.trim()}`;
  89. }
  90. async function openStopMenuItem(sourceId: string) {
  91. await $(`[data-source-server-card="${sourceId}"] button[aria-label="更多"]`).click();
  92. const item = $('[role="menu"] [data-source-server-lifecycle-action="stop"]');
  93. await item.waitForDisplayed({ timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 缺少停止远端服务` });
  94. return item;
  95. }
  96. async function setTheme(theme: "light" | "dark"): Promise<void> {
  97. await browser.execute((color) => {
  98. (
  99. window as Window & { __testActions?: { setTheme(theme: string): void } }
  100. ).__testActions?.setTheme(color);
  101. }, theme);
  102. await browser.executeAsync((done) =>
  103. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  104. );
  105. }
  106. /** 深浅主题截图,供人工复核 destructive 菜单项与确认弹窗的可辨识度;结束后恢复浅色。 */
  107. async function captureThemeScreenshots(name: string): Promise<void> {
  108. const root = process.env.ZCODE_E2E_ARTIFACT_DIR?.trim();
  109. if (!root) return;
  110. const dir = resolve(root, "r3-stop-remote-service");
  111. await mkdir(dir, { recursive: true });
  112. for (const theme of ["light", "dark"] as const) {
  113. await setTheme(theme);
  114. await browser.saveScreenshot(resolve(dir, `${name}-${theme}.png`));
  115. }
  116. await setTheme("light");
  117. }
  118. function stopDialog() {
  119. return $('[role="dialog"][data-confirm-intent="source-server-stop"]');
  120. }
  121. async function setWindowSize(size: readonly [number, number]): Promise<void> {
  122. await browser.electron.execute((electron, [width, height]) => {
  123. electron.BrowserWindow.getAllWindows()
  124. .find((window) => !window.isDestroyed())
  125. ?.setSize(width, height);
  126. }, size);
  127. await browser.executeAsync((done) =>
  128. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  129. );
  130. }
  131. interface ConfirmOverflowProbe {
  132. overflowY: string;
  133. /** 说明区内容高于可视高度,即出现纵向滚动。 */
  134. scrollable: boolean;
  135. /** 长路径不能把说明区横向撑开。 */
  136. horizontalOverflow: boolean;
  137. /** 说明区滚动时确认按钮仍在视口内。 */
  138. footerInViewport: boolean;
  139. }
  140. /**
  141. * RDLC #05:确认弹窗在深浅主题 × 宽 / 窄窗口(最小窗口 480×640)下截图,供人工复核任务清单可读。
  142. * 真实清单通常很短,窄窗口下再向说明区追加一段合成的长清单(仅用于布局探测,截图后移除),
  143. * 断言说明区纵向滚动、长路径不横向溢出、按钮仍在视口内,并截图复核可滚动。
  144. */
  145. async function probeConfirmDialogLayouts(): Promise<ConfirmOverflowProbe> {
  146. const root = process.env.ZCODE_E2E_ARTIFACT_DIR?.trim();
  147. const dir = root ? resolve(root, "r3-stop-remote-service") : undefined;
  148. if (dir) await mkdir(dir, { recursive: true });
  149. const capture = async (name: string) => {
  150. for (const theme of ["light", "dark"] as const) {
  151. await setTheme(theme);
  152. if (dir) await browser.saveScreenshot(resolve(dir, `${name}-${theme}.png`));
  153. }
  154. };
  155. const original = await browser.electron.execute((electron) => {
  156. const size = electron.BrowserWindow.getAllWindows()
  157. .find((window) => !window.isDestroyed())
  158. ?.getSize();
  159. return size ? ([size[0]!, size[1]!] as const) : null;
  160. });
  161. if (!original) throw new Error(`${CASE_MARKER}: 读取窗口尺寸失败`);
  162. try {
  163. await capture("confirm-wide");
  164. await setWindowSize([480, 640]);
  165. await capture("confirm-narrow");
  166. const probe = await browser.execute((confirmTestId) => {
  167. const dialog = document.querySelector(
  168. '[role="dialog"][data-confirm-intent="source-server-stop"]',
  169. );
  170. const description = dialog?.querySelector<HTMLElement>('[data-slot="dialog-description"]');
  171. const confirm = dialog?.querySelector<HTMLElement>(`[data-testid="${confirmTestId}"]`);
  172. if (!description || !confirm) return null;
  173. const synthetic = document.createElement("span");
  174. synthetic.setAttribute("data-e2e-synthetic-task-list", "");
  175. synthetic.textContent = `\n${Array.from(
  176. { length: 40 },
  177. (_, index) =>
  178. `synthetic-session-${index} — /home/dev/projects/a-very-long-workspace-directory-name-without-spaces-${index}`,
  179. ).join("\n")}`;
  180. description.append(synthetic);
  181. return {
  182. overflowY: getComputedStyle(description).overflowY,
  183. scrollable: description.scrollHeight > description.clientHeight,
  184. horizontalOverflow: description.scrollWidth > description.clientWidth,
  185. footerInViewport: confirm.getBoundingClientRect().bottom <= window.innerHeight,
  186. };
  187. }, TID_CONFIRM_DIALOG_CONFIRM);
  188. if (!probe) throw new Error(`${CASE_MARKER}: 确认弹窗缺少说明区或确认按钮`);
  189. await capture("confirm-narrow-long-list");
  190. await browser.execute(() => {
  191. document.querySelector("[data-e2e-synthetic-task-list]")?.remove();
  192. });
  193. return probe;
  194. } finally {
  195. await setWindowSize(original);
  196. await setTheme("light");
  197. }
  198. }
  199. describe(`${CASE_MARKER}: 设备卡停止远端服务`, () => {
  200. after(async () => {
  201. await browser.electron.restoreAllMocks();
  202. await clearAppData();
  203. });
  204. it("R3A-BLD-10 从设备卡「更多」停止远端服务:进程退出、保持未连接且不被自动拉起,再连接可恢复", async function () {
  205. this.timeout(15 * 60_000);
  206. const config = readSSHRuntimeConfig(CASE_MARKER);
  207. await prepareV4ConversationE2E({ skipProvider: true });
  208. const hosts = await readHostProcesses();
  209. const [workspacePath] = config.workspacePaths;
  210. const facts: Record<string, unknown> = {};
  211. // 本机 runner 每次新建专用容器;基线只排除开发者自己开着的会话。
  212. const sshSessionsBaseline = await countOtherSSHSessions(config);
  213. facts.sshSessionsBaseline = sshSessionsBaseline;
  214. const project = await connectSSHWorkspace({ config, caseMarker: CASE_MARKER, workspacePath });
  215. const sourceId = parseRemoteWorkspaceIdentity(project.workspaceIdentity!)?.sourceServerId;
  216. if (!sourceId) throw new Error(`${CASE_MARKER}: 首连缺少设备身份`);
  217. const running = await readRemoteDaemon(config);
  218. expect(running.state).toBe("ready");
  219. expect(running.alive).toBeGreaterThanOrEqual(2);
  220. facts.running = running;
  221. // 在线时本机持有会话,证明下方“停止后回到基线”的读数不是空断言。
  222. const sshSessionsOnline = await countOtherSSHSessions(config);
  223. expect(sshSessionsOnline).toBeGreaterThan(sshSessionsBaseline);
  224. facts.sshSessionsOnline = sshSessionsOnline;
  225. await openRemoteDevicesSettings();
  226. await waitForDeviceStatus(sourceId, "online", CASE_MARKER);
  227. // 1. 危险确认默认聚焦取消,回车不执行:远端服务保持运行,设备仍在线。
  228. const item = await openStopMenuItem(sourceId);
  229. expect(await item.getAttribute("data-disabled")).toBeNull();
  230. expect(await item.getAttribute("data-variant")).toBe("destructive");
  231. facts.remoteRunningTasksBeforeFirstConfirm = await readRemoteRunningTasksOutput(config);
  232. await item.click();
  233. await stopDialog().waitForDisplayed({ timeout: 15_000 });
  234. // RDLC #05:先读取运行中任务再确认。说明含中断说明、任务清单段(刚启动的远端可能尚未上报清单,
  235. // 此时显示设备未提供)、其他电脑的影响,以及仅停止且启动自动重连开启(默认)时的下次启动提示。
  236. const confirmText = await stopDialog().getText();
  237. expect(confirmText).toMatch(/中断此设备上所有运行中的任务|interrupts all running tasks/u);
  238. expect(confirmText).toMatch(
  239. /此设备当前没有运行中的任务|设备未提供任务清单|No tasks are running|didn't provide a task list/u,
  240. );
  241. expect(confirmText).toMatch(/其他电脑上的 ZCode|ZCode on another computer/u);
  242. expect(confirmText).toMatch(/下次打开 ZCode 时会重新启动远端服务|next time you open ZCode/u);
  243. facts.confirmText = confirmText;
  244. const focused = await browser.execute(() => document.activeElement?.textContent ?? "");
  245. expect(["取消", "Cancel"].some((label) => focused.includes(label))).toBe(true);
  246. await browser.keys("Enter");
  247. await stopDialog().waitForDisplayed({ reverse: true, timeout: 15_000 });
  248. await waitForDeviceStatus(sourceId, "online", CASE_MARKER);
  249. expect((await readRemoteDaemon(config)).supervisorPid).toBe(running.supervisorPid);
  250. // 2. 确认停止:Supervisor 与 Core 退出,锁释放,设备显示未连接。
  251. // 先等远端上报清单(首个 Core 心跳后输出 []),再打开确认:此时任务清单段必须是“没有运行中的任务”,
  252. // 证明设备卡读到了真实清单,而不是把读取失败当作结果。
  253. let remoteRunningTasks = "";
  254. await browser.waitUntil(
  255. async () => {
  256. remoteRunningTasks = await readRemoteRunningTasksOutput(config);
  257. return remoteRunningTasks === "exit=0 []";
  258. },
  259. {
  260. timeout: 60_000,
  261. interval: 2_000,
  262. timeoutMsg: `${CASE_MARKER}: 远端未上报运行中任务清单;latest=${remoteRunningTasks}`,
  263. },
  264. );
  265. const confirmItem = await openStopMenuItem(sourceId);
  266. await captureThemeScreenshots("menu");
  267. await confirmItem.click();
  268. await stopDialog().waitForDisplayed({ timeout: 15_000 });
  269. const reportedConfirmText = await stopDialog().getText();
  270. expect(reportedConfirmText).toMatch(/此设备当前没有运行中的任务|No tasks are running/u);
  271. expect(reportedConfirmText).not.toMatch(/设备未提供任务清单|didn't provide a task list/u);
  272. facts.reportedConfirmText = reportedConfirmText;
  273. const overflowProbe = await probeConfirmDialogLayouts();
  274. expect(overflowProbe).toEqual({
  275. overflowY: "auto",
  276. scrollable: true,
  277. horizontalOverflow: false,
  278. footerInViewport: true,
  279. });
  280. facts.confirmOverflowProbe = overflowProbe;
  281. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM, { timeout: 15_000 });
  282. // Host 先断开再执行远端停止:设备卡变为未连接早于停止完成,完成以成功提示为准。
  283. await waitForDeviceStatus(sourceId, "offline", CASE_MARKER, 90_000);
  284. let toasts: string[] = [];
  285. await browser.waitUntil(
  286. async () => {
  287. toasts = await getToastMessages();
  288. return toasts.some(
  289. (message) => message.includes("已停止") || message.includes("Stopped the remote service"),
  290. );
  291. },
  292. {
  293. timeout: 60_000,
  294. timeoutMsg: `${CASE_MARKER}: 没有停止成功提示;latest=${JSON.stringify(toasts)}`,
  295. },
  296. );
  297. const stopped = await readRemoteDaemon(config);
  298. expect(stopped.alive).toBe(0);
  299. expect(stopped.supervisorPid).toBeNull();
  300. expect(stopped.state).toBe("stopped");
  301. facts.stopped = stopped;
  302. // 停止后本机不再连着设备:断开与停止命令用过的 SSH 会话都已释放,只剩基线。
  303. // sshd 退出有少许延迟,先等读数回到基线;超时后由 expect 报出最后一次读数。
  304. let sshSessionsAfterStop = -1;
  305. await browser
  306. .waitUntil(
  307. async () => {
  308. sshSessionsAfterStop = await countOtherSSHSessions(config);
  309. return sshSessionsAfterStop === sshSessionsBaseline;
  310. },
  311. { timeout: 15_000, interval: 1_000 },
  312. )
  313. .catch(() => undefined);
  314. expect(sshSessionsAfterStop).toBe(sshSessionsBaseline);
  315. facts.sshSessionsAfterStop = sshSessionsAfterStop;
  316. // 3. 等过一个自动重试周期:本机不会把远端服务重新拉起,设备仍是未连接。
  317. await browser.pause(AUTOMATIC_RETRY_CYCLE_MS);
  318. const afterRetryCycle = await readRemoteDaemon(config);
  319. expect(afterRetryCycle.alive).toBe(0);
  320. expect(afterRetryCycle.supervisorPid).toBeNull();
  321. await waitForDeviceStatus(sourceId, "offline", CASE_MARKER, 5_000);
  322. facts.afterRetryCycle = afterRetryCycle;
  323. // 4. 再点“连接”照常启动远端服务:新 Supervisor/Core 就绪,设备回到已连接。
  324. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  325. await connectRemoteSourceFromSettings(sourceId, CASE_MARKER);
  326. await waitForDeviceStatus(sourceId, "online", CASE_MARKER, 120_000);
  327. // 设置页连接留在设备管理(RDUX-27);等向导真正收起,避免迟到导航影响后续断言。
  328. expect(await waitForSSHDirectoryStep(CASE_MARKER)).toBe("closed");
  329. const restarted = await readRemoteDaemon(config);
  330. expect(restarted.state).toBe("ready");
  331. expect(restarted.alive).toBeGreaterThanOrEqual(2);
  332. expect(restarted.supervisorPid).not.toBe(running.supervisorPid);
  333. expect(restarted.corePid).not.toBe(running.corePid);
  334. facts.restarted = restarted;
  335. expect(await readHostProcesses()).toEqual(hosts);
  336. await mkdir(artifactDir, { recursive: true });
  337. await writeFile(
  338. resolve(artifactDir, "stop-remote-service.json"),
  339. JSON.stringify(facts, null, 2),
  340. );
  341. });
  342. });