shell-init-snapshot.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { dirname, join } from "node:path";
  4. import { describe, expect, it, vi } from "vitest";
  5. import {
  6. ShellInitSnapshotManager,
  7. buildShellInitSnapshotCreationScript,
  8. detectShellInitConfigPath,
  9. gitBashPreinstalledPathExport,
  10. supportsShellInitSnapshot,
  11. } from "../src/exec/shell-init-snapshot.js";
  12. describe("shell init snapshot", () => {
  13. it("supports only POSIX and Git Bash dialects", () => {
  14. expect(supportsShellInitSnapshot("posix")).toBe(true);
  15. expect(supportsShellInitSnapshot("git-bash")).toBe(true);
  16. expect(supportsShellInitSnapshot("cmd")).toBe(false);
  17. expect(supportsShellInitSnapshot("legacy-shell")).toBe(false);
  18. });
  19. it("detects rc file path from shell kind", () => {
  20. expect(
  21. detectShellInitConfigPath({
  22. env: { HOME: "/home/user" },
  23. shellPath: "/bin/zsh",
  24. }),
  25. ).toBe("/home/user/.zshrc");
  26. expect(
  27. detectShellInitConfigPath({
  28. env: { HOME: "/home/user" },
  29. shellPath: "/bin/bash",
  30. }),
  31. ).toBe("/home/user/.bashrc");
  32. expect(
  33. detectShellInitConfigPath({
  34. env: { HOME: "/home/user" },
  35. shellPath: "/bin/sh",
  36. }),
  37. ).toBe("/home/user/.profile");
  38. });
  39. it("detects Git Bash rc file path from USERPROFILE when HOME is unavailable", () => {
  40. expect(
  41. detectShellInitConfigPath({
  42. env: { USERPROFILE: "C:\\Users\\me" },
  43. shellPath: "C:\\Program Files\\Git\\bin\\bash.exe",
  44. }),
  45. ).toBe(join("C:\\Users\\me", ".bashrc"));
  46. });
  47. it("builds a snapshot creation script that sources config and writes exports", () => {
  48. const script = buildShellInitSnapshotCreationScript({
  49. configPath: "/home/user/.bashrc",
  50. configExists: true,
  51. shellKind: "bash",
  52. snapshotPath: "/tmp/zcode-snapshot.sh",
  53. });
  54. expect(script).toContain("SNAPSHOT_FILE='/tmp/zcode-snapshot.sh'");
  55. expect(script).toContain('source "/home/user/.bashrc" < /dev/null');
  56. expect(script).toContain('echo "# Snapshot file" >| "$SNAPSHOT_FILE"');
  57. expect(script).toContain('echo "shopt -s expand_aliases" >> "$SNAPSHOT_FILE"');
  58. expect(script).toContain("declare -F | cut -d' ' -f3 | grep -vE '^_[^_]'");
  59. expect(script).toContain("encoded_func=$(declare -f \"$func\" | base64 )");
  60. expect(script).toContain("base64 -d");
  61. expect(script).toContain('shopt -p | head -n 1000');
  62. expect(script).toContain('set -o | grep "on"');
  63. expect(script).toContain("alias | grep -v \"='winpty \"");
  64. expect(script).toContain("sed 's/^/alias -- /'");
  65. expect(script).toContain("head -n 1000");
  66. expect(script).toContain("export PATH=");
  67. });
  68. it("builds zsh snapshot creation scripts with zsh-specific exports", () => {
  69. const script = buildShellInitSnapshotCreationScript({
  70. configPath: "/home/user/.zshrc",
  71. configExists: true,
  72. shellKind: "zsh",
  73. snapshotPath: "/tmp/zcode-zsh-snapshot.sh",
  74. });
  75. expect(script).toContain("SNAPSHOT_FILE='/tmp/zcode-zsh-snapshot.sh'");
  76. expect(script).toContain('source "/home/user/.zshrc" < /dev/null');
  77. expect(script).toContain("typeset +f | grep -vE '^_[^_]'");
  78. expect(script).toContain("typeset -f \"$func\"");
  79. expect(script).toContain("setopt | sed 's/^/setopt /' | head -n 1000");
  80. expect(script).toContain("alias | grep -v \"='winpty \"");
  81. expect(script).not.toContain("declare -f");
  82. expect(script).not.toContain("shopt -s expand_aliases");
  83. });
  84. it("omits rc sourcing when the selected shell has no config file", () => {
  85. const script = buildShellInitSnapshotCreationScript({
  86. configPath: "/home/user/.bashrc",
  87. configExists: false,
  88. shellKind: "bash",
  89. snapshotPath: "/tmp/zcode-snapshot.sh",
  90. });
  91. expect(script).toContain("SNAPSHOT_FILE='/tmp/zcode-snapshot.sh'");
  92. expect(script).not.toContain('source "/home/user/.bashrc" < /dev/null');
  93. expect(script).toContain('echo "shopt -s expand_aliases" >> "$SNAPSHOT_FILE"');
  94. expect(script).not.toContain("declare -F");
  95. expect(script).not.toContain("alias |");
  96. });
  97. it("caches successful snapshot creation with snapshot-<shell>-<time>-<id> names", async () => {
  98. const rootDir = await mkdtemp(join(tmpdir(), "zcode-shell-init-snapshot-"));
  99. const execFile = vi.fn(async (_file: string, args: string[]) => {
  100. const script = args.at(-1) ?? "";
  101. const match = script.match(/SNAPSHOT_FILE='([^']+)'/u);
  102. if (!match) throw new Error("missing snapshot path");
  103. await writeFile(match[1], "alias ll='ls -l'\n");
  104. return { stdout: "", stderr: "" };
  105. });
  106. try {
  107. const manager = new ShellInitSnapshotManager({ execFile });
  108. const first = await manager.getOrCreate({
  109. env: { HOME: rootDir },
  110. rootDir,
  111. shellDialect: "posix",
  112. shellPath: "/bin/bash",
  113. });
  114. const second = await manager.getOrCreate({
  115. env: { HOME: rootDir },
  116. rootDir,
  117. shellDialect: "posix",
  118. shellPath: "/bin/bash",
  119. });
  120. expect(first).toBeDefined();
  121. if (!first) throw new Error("expected ready snapshot");
  122. expect(second).toEqual(first);
  123. expect(execFile).toHaveBeenCalledTimes(1);
  124. expect(first.path).toMatch(/\/shell-snapshots\/snapshot-bash-\d+-[a-z0-9]{6}\.sh$/u);
  125. expect(first.path).not.toContain("/session/");
  126. const cleanup = await manager.cleanup();
  127. expect(cleanup).toEqual({ deleted: 1, errors: 0 });
  128. await expect(stat(first.path)).rejects.toHaveProperty("code", "ENOENT");
  129. } finally {
  130. await rm(rootDir, { recursive: true, force: true });
  131. }
  132. });
  133. it("deduplicates concurrent snapshot creation for matching requests", async () => {
  134. const rootDir = await mkdtemp(join(tmpdir(), "zcode-shell-init-snapshot-"));
  135. let markCreationStarted: (() => void) | undefined;
  136. let releaseCreation: (() => void) | undefined;
  137. const creationStarted = new Promise<void>((resolve) => {
  138. markCreationStarted = resolve;
  139. });
  140. const creationReleased = new Promise<void>((resolve) => {
  141. releaseCreation = resolve;
  142. });
  143. const execFile = vi.fn(async (_file: string, args: string[]) => {
  144. markCreationStarted?.();
  145. await creationReleased;
  146. const script = args.at(-1) ?? "";
  147. const match = script.match(/SNAPSHOT_FILE='([^']+)'/u);
  148. if (!match) throw new Error("missing snapshot path");
  149. await writeFile(match[1], "alias ll='ls -l concurrent'\n");
  150. return { stdout: "", stderr: "" };
  151. });
  152. try {
  153. const manager = new ShellInitSnapshotManager({ execFile });
  154. const request = {
  155. env: { HOME: rootDir },
  156. rootDir,
  157. shellDialect: "posix" as const,
  158. shellPath: "/bin/bash",
  159. };
  160. const firstPromise = manager.getOrCreate(request);
  161. const secondPromise = manager.getOrCreate({ ...request });
  162. await creationStarted;
  163. expect(execFile).toHaveBeenCalledTimes(1);
  164. releaseCreation?.();
  165. const [first, second] = await Promise.all([firstPromise, secondPromise]);
  166. expect(first).toBeDefined();
  167. if (!first) throw new Error("expected ready snapshot");
  168. expect(second).toEqual(first);
  169. expect(execFile).toHaveBeenCalledTimes(1);
  170. expect(await readFile(first.path, "utf8")).toBe("alias ll='ls -l concurrent'\n");
  171. const cleanup = await manager.cleanup();
  172. expect(cleanup).toEqual({ deleted: 1, errors: 0 });
  173. await expect(stat(first.path)).rejects.toHaveProperty("code", "ENOENT");
  174. } finally {
  175. await rm(rootDir, { recursive: true, force: true });
  176. }
  177. });
  178. it("keeps bash and zsh snapshots separate for the same session", async () => {
  179. const rootDir = await mkdtemp(join(tmpdir(), "zcode-shell-init-snapshot-"));
  180. const execFile = vi.fn(async (_file: string, args: string[]) => {
  181. const script = args.at(-1) ?? "";
  182. const match = script.match(/SNAPSHOT_FILE='([^']+)'/u);
  183. if (!match) throw new Error("missing snapshot path");
  184. await writeFile(match[1], `# ${match[1].includes("zsh") ? "zsh" : "bash"}\n`);
  185. return { stdout: "", stderr: "" };
  186. });
  187. try {
  188. const manager = new ShellInitSnapshotManager({ execFile });
  189. const bash = await manager.getOrCreate({
  190. env: { HOME: rootDir },
  191. rootDir,
  192. shellDialect: "posix",
  193. shellPath: "/bin/bash",
  194. });
  195. const zsh = await manager.getOrCreate({
  196. env: { HOME: rootDir },
  197. rootDir,
  198. shellDialect: "posix",
  199. shellPath: "/bin/zsh",
  200. });
  201. expect(bash).toBeDefined();
  202. expect(zsh).toBeDefined();
  203. if (!bash || !zsh) {
  204. throw new Error("expected ready snapshots");
  205. }
  206. expect(execFile).toHaveBeenCalledTimes(2);
  207. expect(bash.path).not.toBe(zsh.path);
  208. expect(bash.path).toMatch(/\/shell-snapshots\/snapshot-bash-\d+-[a-z0-9]{6}\.sh$/u);
  209. expect(zsh.path).toMatch(/\/shell-snapshots\/snapshot-zsh-\d+-[a-z0-9]{6}\.sh$/u);
  210. expect(await readFile(bash.path, "utf8")).toBe("# bash\n");
  211. expect(await readFile(zsh.path, "utf8")).toBe("# zsh\n");
  212. const cleanup = await manager.cleanup();
  213. expect(cleanup).toEqual({ deleted: 2, errors: 0 });
  214. await expect(stat(bash.path)).rejects.toHaveProperty("code", "ENOENT");
  215. await expect(stat(zsh.path)).rejects.toHaveProperty("code", "ENOENT");
  216. } finally {
  217. await rm(rootDir, { recursive: true, force: true });
  218. }
  219. });
  220. it("creates a new random snapshot for a new manager instead of reusing cold-resume leftovers", async () => {
  221. const rootDir = await mkdtemp(join(tmpdir(), "zcode-shell-init-snapshot-"));
  222. const execFile = vi.fn(async (_file: string, args: string[]) => {
  223. const script = args.at(-1) ?? "";
  224. const match = script.match(/SNAPSHOT_FILE='([^']+)'/u);
  225. if (!match) throw new Error("missing snapshot path");
  226. await writeFile(match[1], "alias ll='ls -l fresh'\n");
  227. return { stdout: "", stderr: "" };
  228. });
  229. const nowSpy = vi
  230. .spyOn(Date, "now")
  231. .mockReturnValueOnce(1_000)
  232. .mockReturnValueOnce(2_000);
  233. try {
  234. const staleManager = new ShellInitSnapshotManager({ execFile });
  235. const stale = await staleManager.getOrCreate({
  236. env: { HOME: rootDir },
  237. rootDir,
  238. shellDialect: "posix",
  239. shellPath: "/bin/bash",
  240. });
  241. if (!stale) throw new Error("expected ready snapshot");
  242. await writeFile(stale.path, "alias ll='stale'\n");
  243. const freshManager = new ShellInitSnapshotManager({ execFile });
  244. const fresh = await freshManager.getOrCreate({
  245. env: { HOME: rootDir },
  246. rootDir,
  247. shellDialect: "posix",
  248. shellPath: "/bin/bash",
  249. });
  250. expect(fresh).toBeDefined();
  251. if (!fresh) throw new Error("expected ready snapshot");
  252. expect(fresh.path).not.toBe(stale.path);
  253. expect(execFile).toHaveBeenCalledTimes(2);
  254. expect(await readFile(fresh.path, "utf8")).toBe("alias ll='ls -l fresh'\n");
  255. } finally {
  256. nowSpy.mockRestore();
  257. await rm(rootDir, { recursive: true, force: true });
  258. }
  259. });
  260. describe("Git Bash 下预装入口目录的位置", () => {
  261. const bin = "C:\\Users\\me\\.zcode\\preinstalled-tools\\development\\bin";
  262. const loginPath =
  263. "/c/Users/me/bin:/ucrt64/bin:/usr/bin:/c/users/ME/.zcode/preinstalled-tools/development/bin:/c/Windows/system32";
  264. async function snapshotPathLine(env: NodeJS.ProcessEnv) {
  265. const rootDir = await mkdtemp(join(tmpdir(), "zcode-shell-init-snapshot-"));
  266. let script = "";
  267. const execFile = vi.fn(async (_file: string, args: string[]) => {
  268. if (args[0] === "-lc") return { stdout: `${loginPath}\n`, stderr: "" };
  269. script = args.at(-1) ?? "";
  270. const target = script.match(/SNAPSHOT_FILE='([^']+)'/u)?.[1];
  271. if (!target) throw new Error("missing snapshot path");
  272. await mkdir(dirname(target), { recursive: true });
  273. await writeFile(target, "");
  274. return { stdout: "", stderr: "" };
  275. });
  276. try {
  277. await new ShellInitSnapshotManager({ execFile }).getOrCreate({
  278. env: { HOME: rootDir, ...env },
  279. rootDir,
  280. shellDialect: "git-bash",
  281. shellPath: "C:\\Program Files\\Git\\bin\\bash.exe",
  282. });
  283. return script.match(/export PATH='[^']*'/u)?.[0];
  284. } finally {
  285. await rm(rootDir, { recursive: true, force: true });
  286. }
  287. }
  288. it("变量存在时把 Agent PATH 第一项移到最前,其余顺序不变", async () => {
  289. expect(
  290. await snapshotPathLine({
  291. PATH: `${bin};C:\\Windows\\system32`,
  292. ZCODE_PREINSTALLED_TOOLS_AVAILABLE: "1",
  293. }),
  294. ).toBe(
  295. "export PATH='/c/Users/me/.zcode/preinstalled-tools/development/bin:/c/Users/me/bin:/ucrt64/bin:/usr/bin:/c/Windows/system32'",
  296. );
  297. });
  298. it("Windows 环境变量名是 Path 时同样生效", async () => {
  299. expect(
  300. await snapshotPathLine({
  301. Path: `${bin};C:\\Windows\\system32`,
  302. ZCODE_PREINSTALLED_TOOLS_AVAILABLE: "1",
  303. }),
  304. ).toContain("export PATH='/c/Users/me/.zcode/preinstalled-tools/development/bin:/c/Users/me/bin:");
  305. });
  306. it("变量不存在时保持登录 shell 的顺序", async () => {
  307. expect(await snapshotPathLine({ PATH: `${bin};C:\\Windows\\system32` })).toBe(
  308. `export PATH='${loginPath}'`,
  309. );
  310. });
  311. it("快照创建失败时的退回命令同样把入口目录放到最前", () => {
  312. const env = { Path: `${bin};C:\\Windows\\system32`, ZCODE_PREINSTALLED_TOOLS_AVAILABLE: "1" };
  313. expect(gitBashPreinstalledPathExport(env)).toBe(
  314. "export PATH='/c/Users/me/.zcode/preinstalled-tools/development/bin':\"$PATH\"",
  315. );
  316. expect(gitBashPreinstalledPathExport({ Path: env.Path })).toBeUndefined();
  317. });
  318. });
  319. it("uses host paths in creation scripts and Git Bash paths when sourcing snapshots", async () => {
  320. const rootDir = await mkdtemp(join(tmpdir(), "zcode-shell-init-snapshot-"));
  321. const windowsLikeRoot = join(rootDir, "C:\\Users\\me\\ZCode");
  322. let creationSnapshotPath = "";
  323. const execFile = vi.fn(async (_file: string, args: string[]) => {
  324. if (args[0] === "-lc") return { stdout: "/usr/bin:/bin\n", stderr: "" };
  325. const script = args.at(-1) ?? "";
  326. const match = script.match(/SNAPSHOT_FILE='([^']+)'/u);
  327. if (!match) throw new Error("missing snapshot path");
  328. creationSnapshotPath = match[1];
  329. expect(creationSnapshotPath).toContain("C:\\Users\\me\\ZCode");
  330. await mkdir(dirname(creationSnapshotPath), { recursive: true });
  331. await writeFile(creationSnapshotPath, "alias ll='ls -l git-bash'\n");
  332. return { stdout: "", stderr: "" };
  333. });
  334. try {
  335. const manager = new ShellInitSnapshotManager({ execFile });
  336. const result = await manager.getOrCreate({
  337. env: { HOME: rootDir },
  338. rootDir: windowsLikeRoot,
  339. shellDialect: "git-bash",
  340. shellPath: "C:\\Program Files\\Git\\bin\\bash.exe",
  341. });
  342. expect(result).toBeDefined();
  343. if (!result) throw new Error("expected ready snapshot");
  344. expect(result.path).toContain("C:\\Users\\me\\ZCode");
  345. expect(result.path).toBe(creationSnapshotPath);
  346. expect(result.shellPath).toContain("C:/Users/me/ZCode");
  347. expect(result.shellPath).not.toContain("\\");
  348. expect(execFile).toHaveBeenCalledTimes(2);
  349. const cleanup = await manager.cleanup();
  350. expect(cleanup).toEqual({ deleted: 1, errors: 0 });
  351. await expect(stat(result.path)).rejects.toHaveProperty("code", "ENOENT");
  352. } finally {
  353. await rm(rootDir, { recursive: true, force: true });
  354. }
  355. });
  356. it("caches failed snapshot creation and keeps later calls failed", async () => {
  357. const rootDir = await mkdtemp(join(tmpdir(), "zcode-shell-init-snapshot-"));
  358. const execFile = vi.fn(async () => {
  359. throw new Error("shell init failed");
  360. });
  361. try {
  362. const manager = new ShellInitSnapshotManager({ execFile });
  363. const first = await manager.getOrCreate({
  364. env: { HOME: rootDir },
  365. rootDir,
  366. shellDialect: "posix",
  367. shellPath: "/bin/bash",
  368. });
  369. const second = await manager.getOrCreate({
  370. env: { HOME: rootDir },
  371. rootDir,
  372. shellDialect: "posix",
  373. shellPath: "/bin/bash",
  374. });
  375. expect(first).toBeUndefined();
  376. expect(second).toBeUndefined();
  377. expect(execFile).toHaveBeenCalledTimes(1);
  378. } finally {
  379. await rm(rootDir, { recursive: true, force: true });
  380. }
  381. });
  382. it("returns disabled for cmd and legacy shells", async () => {
  383. const manager = new ShellInitSnapshotManager();
  384. const result = await manager.getOrCreate({
  385. env: {},
  386. rootDir: "/tmp/zcode",
  387. shellDialect: "cmd",
  388. shellPath: "cmd.exe",
  389. });
  390. expect(result).toBeUndefined();
  391. });
  392. });