conversation-session-remote-server-root-replaced-ssh.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { readFileSync } from "node:fs";
  3. import { resolve } from "node:path";
  4. import { readLastConnectRemoteError } from "#e2e/helpers/connect-remote-error-log";
  5. import { clearAppData } from "#e2e/helpers/desktop-app";
  6. import {
  7. execInRemoteContainer,
  8. readRemoteDockerContainer,
  9. } from "#e2e/helpers/remote-docker-target";
  10. import {
  11. installRemoteServerArchive,
  12. isRemotePidAlive,
  13. readRemoteDaemonFiles,
  14. type RemoteAccount,
  15. } from "#e2e/helpers/remote-restart-stale-daemon";
  16. import {
  17. clickLastEnabledSSHDialogButton,
  18. fillSSHPasswordSettings,
  19. openSSHRemoteDialog,
  20. readSSHRuntimeConfig,
  21. waitForSSHDirectoryStep,
  22. } from "#e2e/helpers/ssh-remote-p0";
  23. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  24. // A4(ZCT-2112854001415753728)的真实 SSH 验证(本机 Docker runner --systemd):daemon 以 OS 用户服务运行时
  25. // 删除 ~/.zcode/server 再重装。旧 Supervisor 的锁、control socket 与 ingress-token 随旧目录消失;
  26. // 它不能再把 ready 与旧端口写进新 root。连接必须拉起新的 Supervisor 并读到 token,不能报 `cat: …ingress-token`。
  27. const MARKER = "E2E_REMOTE_SERVER_ROOT_REPLACED_SSH";
  28. const DEV: RemoteAccount = { user: "dev", home: "/home/dev" };
  29. const SERVER_ROOT = '"$HOME/.zcode/server"';
  30. const SERVER_BIN = '"$HOME/.zcode/server/bin/zcode"';
  31. // Core heartbeat 周期是 10 秒;等 1.5 个周期,旧实现此时已把旧快照写进新 root。
  32. const AFTER_HEARTBEAT_MS = 15_000;
  33. const desktopRoot = process.cwd();
  34. const artifactDir = resolve(
  35. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/remote-server-root-replaced-ssh",
  36. );
  37. /** 以 dev 身份执行,带 user manager 的 bus,等同于 SSH 会话里的 systemctl --user。 */
  38. async function devShell(container: string, script: string): Promise<string> {
  39. return (
  40. await execInRemoteContainer(
  41. container,
  42. ["env", `HOME=${DEV.home}`, "XDG_RUNTIME_DIR=/run/user/1000", "sh", "-c", script],
  43. { user: DEV.user },
  44. )
  45. ).stdout;
  46. }
  47. /** 当前 server root 的 unit 状态;unit 名与注册时相同(按 root 路径哈希,重装后不变)。 */
  48. async function readUnit(container: string): Promise<Record<string, string>> {
  49. const output = await devShell(
  50. container,
  51. "systemctl --user show 'com.zhipu.zcode.server.*.service' -p Id -p ActiveState -p MainPID -p NRestarts",
  52. );
  53. return Object.fromEntries(
  54. output
  55. .trim()
  56. .split("\n")
  57. .filter((line) => line.includes("="))
  58. .map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]),
  59. );
  60. }
  61. async function readRunEntries(container: string): Promise<string[]> {
  62. return (await devShell(container, `ls -A ${SERVER_ROOT}/run 2>/dev/null || true`))
  63. .trim()
  64. .split("\n")
  65. .filter(Boolean)
  66. .sort();
  67. }
  68. describe(`${MARKER}: server root 被删除并重装后重连`, () => {
  69. const facts: Record<string, unknown> = {};
  70. after(async () => {
  71. await mkdir(artifactDir, { recursive: true });
  72. await writeFile(
  73. resolve(artifactDir, "server-root-replaced-ssh.json"),
  74. JSON.stringify(facts, null, 2),
  75. );
  76. await browser.electron.restoreAllMocks();
  77. await clearAppData();
  78. });
  79. it("A4 OS 服务运行中删除并重装 server root:旧 Supervisor 退出,连接拉起新实例并上线", async function () {
  80. this.timeout(15 * 60_000);
  81. const config = readSSHRuntimeConfig(MARKER);
  82. const container = readRemoteDockerContainer(MARKER);
  83. const appVersion = (
  84. JSON.parse(readFileSync(resolve(desktopRoot, "../../package.json"), "utf8")) as {
  85. version: string;
  86. }
  87. ).version;
  88. await prepareV4ConversationE2E({ skipProvider: true });
  89. // 前提:E-SVC 目标,daemon 由 OS 用户服务持有,否则场景退化成 detached。
  90. await installRemoteServerArchive(container, DEV, { desktopRoot, appVersion });
  91. const served = JSON.parse(
  92. (
  93. await devShell(
  94. container,
  95. `${SERVER_BIN} serve --daemon --server-root ${SERVER_ROOT} --json`,
  96. )
  97. )
  98. .trim()
  99. .split("\n")
  100. .at(-1) ?? "{}",
  101. ) as Record<string, unknown>;
  102. const before = await readRemoteDaemonFiles(container, DEV);
  103. const unitBefore = await readUnit(container);
  104. facts.before = { served, files: before, unit: unitBefore };
  105. expect(served).toMatchObject({ state: "ready", serviceRegistered: true });
  106. expect(unitBefore.ActiveState).toBe("active");
  107. const oldSupervisorPid = Number(unitBefore.MainPID);
  108. const oldCorePid = before.status?.pid as number;
  109. expect(oldSupervisorPid).toBeGreaterThan(0);
  110. expect(await isRemotePidAlive(container, DEV, oldCorePid)).toBe(true);
  111. // 触发:daemon 运行中删除 server root,再按同一 archive 重装(重装会建出空的 run/),不启动 daemon。
  112. await devShell(container, `rm -rf ${SERVER_ROOT}`);
  113. await installRemoteServerArchive(container, DEV, { desktopRoot, appVersion });
  114. await new Promise<void>((done) => setTimeout(done, AFTER_HEARTBEAT_MS));
  115. const replaced = {
  116. runEntries: await readRunEntries(container),
  117. files: await readRemoteDaemonFiles(container, DEV),
  118. unit: await readUnit(container),
  119. oldSupervisorAlive: await isRemotePidAlive(container, DEV, oldSupervisorPid),
  120. oldCoreAlive: await isRemotePidAlive(container, DEV, oldCorePid),
  121. };
  122. facts.replaced = replaced;
  123. await openSSHRemoteDialog(MARKER);
  124. await fillSSHPasswordSettings(config);
  125. await clickLastEnabledSSHDialogButton(MARKER);
  126. let connectError: unknown;
  127. try {
  128. facts.flow = await waitForSSHDirectoryStep(MARKER);
  129. } catch (error) {
  130. connectError = error;
  131. facts.connectError = error instanceof Error ? error.message : String(error);
  132. facts.rawError = await readLastConnectRemoteError();
  133. }
  134. const afterConnect = {
  135. runEntries: await readRunEntries(container),
  136. files: await readRemoteDaemonFiles(container, DEV),
  137. unit: await readUnit(container),
  138. tokenReadable: (
  139. await devShell(container, `test -s ${SERVER_ROOT}/run/ingress-token && echo yes || echo no`)
  140. ).trim(),
  141. };
  142. facts.afterConnect = afterConnect;
  143. if (connectError) throw connectError;
  144. expect(facts.flow).toBe("directory");
  145. // 失去 server root 的旧 Supervisor 与旧 Core 已退出,没有把旧快照写进新 root。
  146. expect(replaced.oldSupervisorAlive).toBe(false);
  147. expect(replaced.oldCoreAlive).toBe(false);
  148. expect(replaced.files.status?.pid ?? null).not.toBe(oldCorePid);
  149. // 连接拉起的是新的 OS service 实例:锁、token、快照属于同一个新 daemon。
  150. expect(afterConnect.unit.ActiveState).toBe("active");
  151. expect(Number(afterConnect.unit.MainPID)).not.toBe(oldSupervisorPid);
  152. expect(afterConnect.files.lock?.pid).toBe(Number(afterConnect.unit.MainPID));
  153. expect(afterConnect.files.status).toMatchObject({ state: "ready", serviceRegistered: true });
  154. expect(afterConnect.files.status?.pid).not.toBe(oldCorePid);
  155. expect(await isRemotePidAlive(container, DEV, afterConnect.files.status?.pid as number)).toBe(
  156. true,
  157. );
  158. expect(afterConnect.tokenReadable).toBe("yes");
  159. });
  160. });