shell-init-snapshot.test.ts 14 KB

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