conversation-session-remote-command-authority-race.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import { execFile } from "node:child_process";
  2. import { randomBytes } from "node:crypto";
  3. import { mkdir, writeFile } from "node:fs/promises";
  4. import { resolve } from "node:path";
  5. import { promisify } from "node:util";
  6. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  7. import {
  8. TID_SETTINGS_PAGE,
  9. TID_SETTINGS_SECTION_NAV,
  10. TID_TASK_SETTINGS_BUTTON,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. clearAppData,
  15. clickTestIdByDom,
  16. DEFAULT_WORKSPACE,
  17. waitForTestIdByDom,
  18. } from "#e2e/helpers/desktop-app";
  19. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  20. import {
  21. execInRemoteContainer,
  22. readRemoteDockerContainer,
  23. writeRemoteContainerFile,
  24. } from "#e2e/helpers/remote-docker-target";
  25. import { clickOpenScopeMenuOption } from "#e2e/helpers/settings-scope-menu";
  26. import {
  27. connectSSHWorkspace,
  28. readSSHRuntimeConfig,
  29. runSSHCommand,
  30. } from "#e2e/helpers/ssh-remote-p0";
  31. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  32. const run = promisify(execFile);
  33. const MARKER = "E2E_COMMAND_AUTHORITY_RACE";
  34. const COMMAND_DIR = "/home/dev/.zcode/commands";
  35. const FIFO = `${COMMAND_DIR}/pending-a.md`;
  36. const FIFO_KEEPER = "/home/dev/.zcode/e2e-command-fifo.pid";
  37. const CONFIG = "/home/dev/.zcode/cli/config.json";
  38. const A_MARKER = "AUTHORITY_A_ONLY";
  39. const B_MARKER = "AUTHORITY_B_ONLY";
  40. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR!, "command-authority-race");
  41. async function selectUserScope(sourceId: string): Promise<void> {
  42. const key = `source-user:${sourceId}`;
  43. await browser.waitUntil(
  44. () =>
  45. browser.execute(() => {
  46. if (document.querySelector('[role="menuitemradio"]')) return true;
  47. const trigger = [
  48. ...document.querySelectorAll<HTMLElement>('[data-plugin-scope-trigger="true"]'),
  49. ].find((element) => element.getClientRects().length > 0);
  50. trigger?.dispatchEvent(
  51. new PointerEvent("pointerdown", { bubbles: true, button: 0, pointerType: "mouse" }),
  52. );
  53. return false;
  54. }),
  55. { timeout: 15_000 },
  56. );
  57. await clickOpenScopeMenuOption(key);
  58. await browser.waitUntil(
  59. () =>
  60. browser.execute(
  61. (expected) =>
  62. [...document.querySelectorAll<HTMLElement>('[data-plugin-scope-trigger="true"]')].some(
  63. (element) =>
  64. element.getClientRects().length > 0 && element.dataset.pluginScopeKey === expected,
  65. ),
  66. key,
  67. ),
  68. {
  69. timeout: 15_000,
  70. timeoutMsg: `Scope 没有切换到 ${key}`,
  71. },
  72. );
  73. }
  74. async function readConfig(container: string): Promise<string> {
  75. return (
  76. await execInRemoteContainer(container, [
  77. "sh",
  78. "-c",
  79. 'if [ -f "$1" ]; then cat "$1"; else printf "{}"; fi',
  80. "sh",
  81. CONFIG,
  82. ])
  83. ).stdout;
  84. }
  85. async function fifoHasReader(container: string): Promise<boolean> {
  86. const result = await execInRemoteContainer(container, [
  87. "sh",
  88. "-c",
  89. 'pid=$(sed -nE \'s/.*"pid": *([0-9]+).*/\\1/p\' "$HOME/.zcode/server/run/status.json" | head -n1); for file in /proc/"$pid"/fd/*; do if [ "$(readlink "$file" 2>/dev/null)" = "$1" ]; then printf yes; break; fi; done',
  90. "sh",
  91. FIFO,
  92. ]);
  93. return result.stdout.trim() === "yes";
  94. }
  95. async function startFifoKeeper(container: string): Promise<void> {
  96. const release = JSON.parse(
  97. (await execInRemoteContainer(container, ["cat", "/home/dev/.zcode/server/current.json"]))
  98. .stdout,
  99. );
  100. // 保留写端使 Core 的 open 能完成而 read 继续等待;因此可从 Core fd 证明请求确实在途。
  101. const script =
  102. 'const fs=require("node:fs/promises"),{constants}=require("node:fs");(async()=>{const file=await fs.open(process.argv[1],constants.O_RDWR|constants.O_NONBLOCK);const timer=setInterval(()=>{},1000);process.once("SIGUSR1",()=>{void(async()=>{await file.write("---\\ndescription: AUTHORITY_A_PENDING\\n---\\nA command\\n");await file.close();const temporary=process.argv[1]+".released";await fs.writeFile(temporary,"---\\ndescription: AUTHORITY_A_PENDING\\n---\\nA command\\n");await fs.rename(temporary,process.argv[1]);await fs.rm(process.argv[2],{force:true});clearInterval(timer);})().catch(error=>{console.error(error);process.exit(1);});});await fs.writeFile(process.argv[2],String(process.pid));})().catch(error=>{console.error(error);process.exit(1);});';
  103. await run("docker", [
  104. "exec",
  105. "--detach",
  106. "--user",
  107. "dev",
  108. container,
  109. `${release.releaseDir}/runtime/node`,
  110. "-e",
  111. script,
  112. FIFO,
  113. FIFO_KEEPER,
  114. ]);
  115. await browser.waitUntil(
  116. async () =>
  117. (
  118. await execInRemoteContainer(container, [
  119. "sh",
  120. "-c",
  121. 'test -s "$1" && printf ready',
  122. "sh",
  123. FIFO_KEEPER,
  124. ]).catch(() => ({ stdout: "" }))
  125. ).stdout === "ready",
  126. { timeout: 15_000 },
  127. );
  128. }
  129. async function releaseFifo(container: string): Promise<void> {
  130. await execInRemoteContainer(container, [
  131. "sh",
  132. "-c",
  133. 'if [ -s "$1" ]; then kill -USR1 "$(cat "$1")"; fi',
  134. "sh",
  135. FIFO_KEEPER,
  136. ]);
  137. }
  138. describe("DSYNC-15-06:两个相同 home 远端的命令读取与写入隔离", () => {
  139. let secondContainer: string | undefined;
  140. let firstContainer: string | undefined;
  141. const facts: Record<string, unknown> = {};
  142. after(async () => {
  143. if (firstContainer) await releaseFifo(firstContainer).catch(() => undefined);
  144. if (secondContainer) await run("docker", ["rm", "-f", secondContainer]);
  145. await mkdir(artifactDir, { recursive: true });
  146. await writeFile(resolve(artifactDir, "facts.json"), JSON.stringify(facts, null, 2));
  147. await clearAppData();
  148. });
  149. it("A 读取挂起时 B 独立加载,A 迟到不覆盖 B,B 的开关只写 B", async function () {
  150. this.timeout(15 * 60_000);
  151. firstContainer = readRemoteDockerContainer(MARKER);
  152. const configA = readSSHRuntimeConfig(MARKER);
  153. secondContainer = `zcode-command-authority-${randomBytes(6).toString("hex")}`;
  154. facts.fixtureContainers = { first: firstContainer, second: secondContainer };
  155. await mkdir(artifactDir, { recursive: true });
  156. await writeFile(resolve(artifactDir, "facts.json"), JSON.stringify(facts, null, 2));
  157. await run("docker", [
  158. "run",
  159. "-d",
  160. "--name",
  161. secondContainer,
  162. "--label",
  163. "zcode.e2e.run=r3-server",
  164. "--label",
  165. "zcode.e2e.runner=local-docker",
  166. "-p",
  167. "127.0.0.1::22",
  168. "zcode-remote-ssh:test",
  169. ]);
  170. // 两个临时目标共用 runner 生成的口令,确保其现有日志脱敏覆盖第二条真实 SSH 线路。
  171. const password = configA.password;
  172. await execInRemoteContainer(secondContainer, ["chpasswd"], {
  173. user: "0",
  174. input: `dev:${password}\n`,
  175. });
  176. await execInRemoteContainer(secondContainer, ["mkdir", "-p", configA.workspacePaths[0]]);
  177. const port = Number(
  178. (await run("docker", ["port", secondContainer, "22"])).stdout.trim().split(":").at(-1),
  179. );
  180. const configB = { host: "127.0.0.1", port, username: "dev", password };
  181. await browser.waitUntil(
  182. async () => {
  183. try {
  184. return (await runSSHCommand(configB, "true")).code === 0;
  185. } catch {
  186. return false;
  187. }
  188. },
  189. { timeout: 30_000, timeoutMsg: "第二个 SSH fixture 未就绪" },
  190. );
  191. await prepareV4ConversationE2E({ skipProvider: true });
  192. const a = await connectSSHWorkspace({
  193. caseMarker: MARKER,
  194. config: configA,
  195. workspacePath: configA.workspacePaths[0],
  196. });
  197. const b = await connectSSHWorkspace({
  198. caseMarker: MARKER,
  199. config: configB,
  200. workspacePath: configA.workspacePaths[0],
  201. });
  202. const sourceA = parseRemoteWorkspaceIdentity(a.workspaceIdentity!)?.sourceServerId;
  203. const sourceB = parseRemoteWorkspaceIdentity(b.workspaceIdentity!)?.sourceServerId;
  204. expect(sourceA).toBeTruthy();
  205. expect(sourceB).toBeTruthy();
  206. expect(sourceA).not.toBe(sourceB);
  207. facts.sources = { sourceA, sourceB, home: "/home/dev" };
  208. await writeRemoteContainerFile(
  209. firstContainer,
  210. `${COMMAND_DIR}/authority-a.md`,
  211. `---\ndescription: ${A_MARKER}\n---\nA only\n`,
  212. );
  213. await writeRemoteContainerFile(
  214. secondContainer,
  215. `${COMMAND_DIR}/authority-b.md`,
  216. `---\ndescription: ${B_MARKER}\n---\nB only\n`,
  217. );
  218. await execInRemoteContainer(firstContainer, ["mkfifo", FIFO]);
  219. await startFifoKeeper(firstContainer);
  220. const beforeA = await readConfig(firstContainer);
  221. const beforeB = await readConfig(secondContainer);
  222. // 从本机 Scope 进入,避免先加载 B 后由缓存掩盖同 home 的在途请求串用。
  223. await startDraftFromProject(DEFAULT_WORKSPACE);
  224. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  225. await waitForTestIdByDom(TID_SETTINGS_PAGE);
  226. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "commands"));
  227. await selectUserScope(sourceA!);
  228. await browser.waitUntil(() => fifoHasReader(firstContainer!), {
  229. timeout: 30_000,
  230. timeoutMsg: "A 的命令读取未进入真实 FIFO 阻塞点",
  231. });
  232. facts.aReadBlocked = true;
  233. await selectUserScope(sourceB!);
  234. await browser.waitUntil(
  235. async () => (await browser.execute(() => document.body.innerText)).includes(B_MARKER),
  236. {
  237. timeout: 30_000,
  238. timeoutMsg: "B 的用户命令未显示,需核对独立读取结果与 Scope 过滤",
  239. },
  240. );
  241. expect(await browser.execute(() => document.body.innerText)).not.toContain(A_MARKER);
  242. await browser.saveScreenshot(resolve(artifactDir, "b-loaded-while-a-blocked.png"));
  243. await releaseFifo(firstContainer);
  244. await browser.waitUntil(async () => !(await fifoHasReader(firstContainer!)), {
  245. timeout: 15_000,
  246. });
  247. expect(await browser.execute(() => document.body.innerText)).toContain(B_MARKER);
  248. expect(await browser.execute(() => document.body.innerText)).not.toContain(A_MARKER);
  249. const row = $(`//p[normalize-space(text())="${B_MARKER}"]/ancestor::div[@role="button"][1]`);
  250. const toggle = row.$('[role="switch"]');
  251. await toggle.waitForClickable();
  252. await toggle.click();
  253. await browser.waitUntil(async () => (await toggle.getAttribute("aria-checked")) === "false", {
  254. timeout: 15_000,
  255. });
  256. await browser.waitUntil(async () => (await readConfig(secondContainer!)) !== beforeB, {
  257. timeout: 15_000,
  258. });
  259. expect(await readConfig(firstContainer)).toBe(beforeA);
  260. expect(await browser.execute(() => document.body.innerText)).toContain(B_MARKER);
  261. expect(await browser.execute(() => document.body.innerText)).not.toContain(A_MARKER);
  262. facts.onlyBChanged = true;
  263. await browser.saveScreenshot(resolve(artifactDir, "b-toggle-isolated.png"));
  264. const validConfigB = await readConfig(secondContainer);
  265. const corruptConfigB = '{"incomplete":';
  266. await writeRemoteContainerFile(secondContainer, CONFIG, corruptConfigB);
  267. try {
  268. await toggle.click();
  269. await browser.waitUntil(
  270. async () =>
  271. (await browser.execute(() => document.body.innerText)).includes("not valid JSON"),
  272. {
  273. timeout: 15_000,
  274. timeoutMsg: "损坏配置写入未明确报错",
  275. },
  276. );
  277. expect(await readConfig(secondContainer)).toBe(corruptConfigB);
  278. expect(await readConfig(firstContainer)).toBe(beforeA);
  279. facts.corruptConfigPreserved = true;
  280. await browser.saveScreenshot(resolve(artifactDir, "corrupt-config-write-rejected.png"));
  281. } finally {
  282. await writeRemoteContainerFile(secondContainer, CONFIG, validConfigB);
  283. }
  284. });
  285. });