conversation-session-r3-daemon-service-fallback.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  4. import {
  5. disconnectRemoteSource,
  6. reconnectRemoteProject,
  7. } from "#e2e/helpers/remote-project-actions";
  8. import { clearAppData } from "#e2e/helpers/desktop-app";
  9. import {
  10. execInRemoteContainer,
  11. readRemoteDockerContainer,
  12. } from "#e2e/helpers/remote-docker-target";
  13. import { readRemoteCoreIdentity } from "#e2e/helpers/ssh-remote-lifecycle";
  14. import {
  15. clickLastEnabledSSHDialogButton,
  16. fillSSHPasswordSettings,
  17. openSSHRemoteDialog,
  18. readHostProcesses,
  19. readSSHRuntimeConfig,
  20. runSSHCommand,
  21. selectSSHRemoteDirectory,
  22. waitForRemoteTab,
  23. waitForSSHDirectoryStep,
  24. type SSHConnectionConfig,
  25. } from "#e2e/helpers/ssh-remote-p0";
  26. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  27. import { selectTaskOrganizeMode } from "#e2e/helpers/workspace-agent-warmup";
  28. // R3A-BLD-08:带常驻 user manager 的 SSH 目标(run-local-docker.mjs --systemd)。
  29. // stale-group / private-tmp 复现 manager 读不到 server root 时 systemd 装载失败,连接必须回退
  30. // detached fallback 并在连接日志带原因;registered 是正常环境回归。
  31. const CASE_MARKER = "E2E_R3_DAEMON_SERVICE_FALLBACK";
  32. type ServiceCase = "stale-group" | "private-tmp" | "registered";
  33. const SUBCASE = (process.env.R3_DAEMON_SERVICE_CASE ?? "") as ServiceCase;
  34. const artifactDir = resolve(
  35. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-daemon-service-fallback",
  36. );
  37. const ACCESS_GROUP = "zcode-e2e-svc";
  38. const RESTRICTED_ROOT = "/srv/zcode-e2e-svc";
  39. const PRIVATE_TMP_ROOT = "/tmp/zcode-e2e-private";
  40. const SERVER_BIN = '"$HOME/.zcode/server/bin/zcode"';
  41. const SERVER_ROOT = '"$HOME/.zcode/server"';
  42. const FALLBACK_LOG = "Source Server started in detached fallback mode for this remote environment";
  43. const REGISTERED_LOG = "Source Server registered with the remote OS user service manager";
  44. const REUSE_LOG = "Reusing running Source Server";
  45. type ConnectionLog = { message: string; level: string };
  46. /** 连接日志带 `[source-server:<phase>] ` 前缀,按正文匹配。 */
  47. function findLog(logs: ConnectionLog[], text: string): ConnectionLog | undefined {
  48. return logs.find((entry) => entry.message.includes(text));
  49. }
  50. async function rootShell(container: string, script: string): Promise<string> {
  51. return (await execInRemoteContainer(container, ["sh", "-c", script], { user: "0" })).stdout;
  52. }
  53. async function readManager(container: string): Promise<{ pid: number; groups: string[] }> {
  54. const output = await rootShell(
  55. container,
  56. "pid=$(systemctl show -p MainPID --value user@1000.service); echo $pid; grep '^Groups:' /proc/$pid/status",
  57. );
  58. const [pidText = "", groupsLine = ""] = output.trim().split("\n");
  59. return {
  60. pid: Number.parseInt(pidText, 10),
  61. groups: groupsLine
  62. .replace(/^Groups:\s*/u, "")
  63. .split(/\s+/u)
  64. .filter(Boolean),
  65. };
  66. }
  67. /** 读当前 server root 的 unit 状态;unit 名取 descriptor 文件名,与注册时 start 的名字一致。 */
  68. async function readUnitState(config: SSHConnectionConfig): Promise<Record<string, string>> {
  69. const result = await runSSHCommand(
  70. config,
  71. `unit=$(basename "$(ls ${SERVER_ROOT}/service/com.zhipu.zcode.server.*.service | head -n1)"); ` +
  72. 'echo "Unit=$unit"; systemctl --user show "$unit" -p LoadState -p ActiveState; ' +
  73. 'echo "Enabled=$(systemctl --user is-enabled "$unit" 2>&1)"',
  74. );
  75. return Object.fromEntries(
  76. result.stdout
  77. .trim()
  78. .split("\n")
  79. .map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]),
  80. );
  81. }
  82. async function readStatusFile(config: SSHConnectionConfig): Promise<Record<string, unknown>> {
  83. const result = await runSSHCommand(config, `cat ${SERVER_ROOT}/run/status.json`);
  84. expect(result.code).toBe(0);
  85. return JSON.parse(result.stdout) as Record<string, unknown>;
  86. }
  87. async function readConnectionLogs(): Promise<ConnectionLog[]> {
  88. return browser.execute(
  89. () =>
  90. (window as Window & { __serviceFallbackLogs?: ConnectionLog[] }).__serviceFallbackLogs ?? [],
  91. );
  92. }
  93. /** 按 E-SVC fixture 造出 manager 读不到 server root 的现场,并验证前提成立,避免空跑通过。 */
  94. async function prepareRemoteFixture(container: string, facts: Record<string, unknown>) {
  95. expect((await rootShell(container, "systemctl is-active user@1000.service")).trim()).toBe(
  96. "active",
  97. );
  98. if (SUBCASE === "stale-group") {
  99. // manager 开机常驻(linger),之后才把 dev 加进目录访问组:新 SSH 会话有该组,manager 没有。
  100. await rootShell(
  101. container,
  102. `set -e; groupadd ${ACCESS_GROUP}; install -d -o root -g ${ACCESS_GROUP} -m 0750 ${RESTRICTED_ROOT}; ` +
  103. `install -d -o dev -g dev -m 0700 ${RESTRICTED_ROOT}/.zcode; ` +
  104. `ln -sfn ${RESTRICTED_ROOT}/.zcode /home/dev/.zcode; chown -h dev:dev /home/dev/.zcode; ` +
  105. `usermod -aG ${ACCESS_GROUP} dev`,
  106. );
  107. const gid = (await rootShell(container, `getent group ${ACCESS_GROUP} | cut -d: -f3`)).trim();
  108. const manager = await readManager(container);
  109. expect(manager.groups).not.toContain(gid);
  110. facts.accessGid = gid;
  111. facts.managerBefore = manager;
  112. return gid;
  113. }
  114. if (SUBCASE === "private-tmp") {
  115. // manager 使用私有 /tmp,~/.zcode 指向宿主 /tmp:SSH 会话可写,manager 的挂载视图里不存在。
  116. await rootShell(
  117. container,
  118. "set -e; mkdir -p /etc/systemd/system/user@1000.service.d; " +
  119. "printf '[Service]\\nPrivateTmp=yes\\n' > /etc/systemd/system/user@1000.service.d/zcode-e2e-private-tmp.conf; " +
  120. "systemctl daemon-reload; systemctl restart user@1000.service; " +
  121. `install -d -o dev -g dev -m 0700 ${PRIVATE_TMP_ROOT}/.zcode; ` +
  122. `ln -sfn ${PRIVATE_TMP_ROOT}/.zcode /home/dev/.zcode; chown -h dev:dev /home/dev/.zcode`,
  123. );
  124. const manager = await readManager(container);
  125. const hidden = await rootShell(
  126. container,
  127. `test -d ${PRIVATE_TMP_ROOT}/.zcode && echo host-visible; ` +
  128. `nsenter -t ${manager.pid} -m test -e ${PRIVATE_TMP_ROOT} && echo manager-visible || echo manager-hidden`,
  129. );
  130. expect(hidden.trim().split("\n")).toEqual(["host-visible", "manager-hidden"]);
  131. facts.managerBefore = manager;
  132. }
  133. return undefined;
  134. }
  135. async function connectFirstProject(config: ReturnType<typeof readSSHRuntimeConfig>) {
  136. await openSSHRemoteDialog(CASE_MARKER);
  137. await fillSSHPasswordSettings(config);
  138. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  139. expect(await waitForSSHDirectoryStep(CASE_MARKER)).toBe("directory");
  140. await selectSSHRemoteDirectory(config.workspacePaths[0], CASE_MARKER);
  141. return waitForRemoteTab({ caseMarker: CASE_MARKER, expectedPath: config.workspacePaths[0] });
  142. }
  143. describe(`${CASE_MARKER}: systemd 注册装载失败时回退 detached fallback(${SUBCASE})`, () => {
  144. after(async () => {
  145. await browser.electron.restoreAllMocks();
  146. await clearAppData();
  147. });
  148. it(`R3A-BLD-08 ${SUBCASE}`, async function () {
  149. this.timeout(30 * 60_000);
  150. if (!["stale-group", "private-tmp", "registered"].includes(SUBCASE)) {
  151. throw new Error(
  152. `${CASE_MARKER}: R3_DAEMON_SERVICE_CASE 必须为 stale-group|private-tmp|registered`,
  153. );
  154. }
  155. const config = readSSHRuntimeConfig(CASE_MARKER);
  156. const container = readRemoteDockerContainer(CASE_MARKER);
  157. const facts: Record<string, unknown> = { subcase: SUBCASE };
  158. const accessGid = await prepareRemoteFixture(container, facts);
  159. await prepareV4ConversationE2E({ skipProvider: true });
  160. await browser.execute(() => {
  161. const state = window as Window & {
  162. __serviceFallbackLogs?: ConnectionLog[];
  163. zcode?: {
  164. onRemoteConnectionLog: (callback: (entry: ConnectionLog) => void) => () => void;
  165. };
  166. };
  167. state.__serviceFallbackLogs = [];
  168. if (!state.zcode) throw new Error("Missing desktop platform");
  169. state.zcode.onRemoteConnectionLog(({ message, level }) =>
  170. state.__serviceFallbackLogs!.push({ message, level }),
  171. );
  172. });
  173. const initialHosts = await readHostProcesses();
  174. expect(initialHosts).toHaveLength(1);
  175. try {
  176. const project = await connectFirstProject(config);
  177. const identity = project.workspaceIdentity!;
  178. const core0 = await readRemoteCoreIdentity(config, CASE_MARKER);
  179. const status0 = await readStatusFile(config);
  180. const unit0 = await readUnitState(config);
  181. const firstLogs = await readConnectionLogs();
  182. Object.assign(facts, { core0, status0, unit0, firstLogs });
  183. expect(core0.state).toBe("ready");
  184. if (SUBCASE === "registered") {
  185. // 正常环境回归:探测与注册都成功,由 OS user service 托管。
  186. expect(status0.serviceRegistered).toBe(true);
  187. expect(unit0).toMatchObject({ LoadState: "loaded", ActiveState: "active" });
  188. expect(findLog(firstLogs, REGISTERED_LOG)).toBeDefined();
  189. expect(findLog(firstLogs, FALLBACK_LOG)).toBeUndefined();
  190. expect(await readHostProcesses()).toEqual(initialHosts);
  191. return;
  192. }
  193. // 1. 装载失败回退:连接成功、fallback 未注册;原因只进本次输出和连接日志,不写 status.json。
  194. expect(status0.serviceRegistered).toBe(false);
  195. expect(status0).not.toHaveProperty("serviceFallbackReason");
  196. // 装载阶段失败时没有启动任何 unit。
  197. expect(unit0).toMatchObject({ LoadState: "not-found", ActiveState: "inactive" });
  198. const fallbackLog = findLog(firstLogs, `${FALLBACK_LOG} (`);
  199. expect(fallbackLog?.message).toContain("Failed to register service com.zhipu.zcode.server.");
  200. expect(fallbackLog?.message).toContain(
  201. SUBCASE === "stale-group"
  202. ? "Failed to enable unit: Access denied"
  203. : "Failed to enable unit: Unit file",
  204. );
  205. // 2. 设备断开后重连:probe 看到存活的 fallback,直接复用,Supervisor/Core 都不换。
  206. const sourceId = parseRemoteWorkspaceIdentity(identity)?.sourceServerId;
  207. expect(sourceId).toBeTruthy();
  208. await selectTaskOrganizeMode(["项目", "Project"]);
  209. await disconnectRemoteSource(sourceId!, CASE_MARKER, { workspaceIdentities: [identity] });
  210. const logCountBeforeReconnect = (await readConnectionLogs()).length;
  211. await reconnectRemoteProject(identity, CASE_MARKER);
  212. const reconnectLogs = (await readConnectionLogs()).slice(logCountBeforeReconnect);
  213. const core1 = await readRemoteCoreIdentity(config, CASE_MARKER);
  214. Object.assign(facts, { core1, reconnectLogs });
  215. expect(core1).toMatchObject({
  216. pid: core0.pid,
  217. supervisorPid: core0.supervisorPid,
  218. startTicks: core0.startTicks,
  219. });
  220. expect(findLog(reconnectLogs, REUSE_LOG)).toBeDefined();
  221. expect(findLog(reconnectLogs, FALLBACK_LOG)).toBeUndefined();
  222. // 3. 服务管理器仍可用时直接执行 serve --daemon:存活的 fallback 一律复用,不停止、不再注册。
  223. const serve = await runSSHCommand(
  224. config,
  225. `${SERVER_BIN} serve --daemon --json --server-root ${SERVER_ROOT}`,
  226. );
  227. facts.directServe = serve;
  228. expect(serve.code).toBe(0);
  229. const served = JSON.parse(serve.stdout.trim().split("\n").at(-1) ?? "{}") as Record<
  230. string,
  231. unknown
  232. >;
  233. expect(served).toMatchObject({ state: "ready", pid: core0.pid, serviceRegistered: false });
  234. expect(served).not.toHaveProperty("serviceFallbackReason");
  235. expect(await readRemoteCoreIdentity(config, CASE_MARKER)).toMatchObject({
  236. pid: core0.pid,
  237. supervisorPid: core0.supervisorPid,
  238. });
  239. if (SUBCASE === "stale-group") {
  240. // 4. 自愈:刷新 manager 组列表并停止 daemon,下一次冷启动自动改用 OS user service。
  241. await rootShell(container, "systemctl restart user@1000.service");
  242. const managerAfter = await readManager(container);
  243. expect(managerAfter.groups).toContain(accessGid);
  244. facts.managerAfter = managerAfter;
  245. await disconnectRemoteSource(sourceId!, CASE_MARKER, { workspaceIdentities: [identity] });
  246. const stopped = await runSSHCommand(
  247. config,
  248. `${SERVER_BIN} stop --wait --json --server-root ${SERVER_ROOT}`,
  249. );
  250. expect(stopped.code).toBe(0);
  251. const logCountBeforeHeal = (await readConnectionLogs()).length;
  252. await reconnectRemoteProject(identity, CASE_MARKER);
  253. const healLogs = (await readConnectionLogs()).slice(logCountBeforeHeal);
  254. const core2 = await readRemoteCoreIdentity(config, CASE_MARKER);
  255. const status2 = await readStatusFile(config);
  256. const unit2 = await readUnitState(config);
  257. Object.assign(facts, { healLogs, core2, status2, unit2 });
  258. expect(core2.pid).not.toBe(core0.pid);
  259. expect(core2.supervisorPid).not.toBe(core0.supervisorPid);
  260. expect(status2.serviceRegistered).toBe(true);
  261. expect(unit2).toMatchObject({ LoadState: "loaded", ActiveState: "active" });
  262. expect(findLog(healLogs, REGISTERED_LOG)).toBeDefined();
  263. }
  264. expect(await readHostProcesses()).toEqual(initialHosts);
  265. } finally {
  266. await mkdir(artifactDir, { recursive: true });
  267. await writeFile(
  268. resolve(artifactDir, `daemon-service-fallback-${SUBCASE}.json`),
  269. JSON.stringify(facts, null, 2),
  270. );
  271. }
  272. });
  273. });