terminalService.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. const { spawnMock } = vi.hoisted(() => ({
  6. spawnMock: vi.fn(),
  7. }));
  8. vi.mock("node-pty", () => ({
  9. spawn: spawnMock,
  10. }));
  11. import {
  12. parseWindowsBuildNumber,
  13. createTerminalService,
  14. resolveTerminalEnv,
  15. resolveTerminalCwd,
  16. resolveTerminalShell,
  17. resolveTerminalWindowsPtyInfo,
  18. } from "../src/terminal/terminalService.js";
  19. const originalShell = process.env.SHELL;
  20. const originalHome = process.env.HOME;
  21. const originalLang = process.env.LANG;
  22. const originalLcAll = process.env.LC_ALL;
  23. const originalLcCtype = process.env.LC_CTYPE;
  24. const originalTerm = process.env.TERM;
  25. const originalColorTerm = process.env.COLORTERM;
  26. const originalCi = process.env.CI;
  27. const originalPath = process.env.PATH;
  28. const originalPathExt = process.env.PATHEXT;
  29. const originalComSpec = process.env.ComSpec;
  30. const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
  31. const tempDirs: string[] = [];
  32. function getExpectedResolvedShellPattern() {
  33. return process.platform === "win32"
  34. ? /(?:^|[\\/])(pwsh|powershell|cmd)\.exe$|^(pwsh|powershell|cmd)\.exe$/i
  35. : /^\/bin\/(zsh|bash|sh)$/;
  36. }
  37. function makeTempDir(prefix: string): string {
  38. const dir = mkdtempSync(join(tmpdir(), prefix));
  39. tempDirs.push(dir);
  40. return dir;
  41. }
  42. function prependFakeWindowsShells(commands: string[]): string {
  43. const dir = makeTempDir("zcode-terminal-shells-");
  44. for (const command of commands) {
  45. const shellPath = join(dir, command);
  46. writeFileSync(shellPath, "");
  47. chmodSync(shellPath, 0o755);
  48. }
  49. process.env.PATH = dir;
  50. process.env.PATHEXT = ".COM;.EXE;.BAT;.CMD";
  51. delete process.env.ComSpec;
  52. return dir;
  53. }
  54. function createMockPty() {
  55. return {
  56. onData: vi.fn(),
  57. onExit: vi.fn(),
  58. write: vi.fn(),
  59. resize: vi.fn(),
  60. kill: vi.fn(),
  61. };
  62. }
  63. function createTestTerminalService(settings = {}) {
  64. return createTerminalService({
  65. settingService: {
  66. get: vi.fn().mockResolvedValue({
  67. recentProjects: [],
  68. locale: "zh-CN",
  69. terminalInheritSystemProfile: true,
  70. lastWorkspaceSession: [],
  71. lastActiveTabIndex: 0,
  72. ...settings,
  73. }),
  74. update: vi.fn(),
  75. updateDataBaseDir: vi.fn(),
  76. ensureDefaultProject: vi.fn(),
  77. } as any,
  78. });
  79. }
  80. function setProcessPlatform(platform: NodeJS.Platform) {
  81. Object.defineProperty(process, "platform", { value: platform });
  82. }
  83. function restoreEnv(name: string, value: string | undefined) {
  84. if (value === undefined) {
  85. delete process.env[name];
  86. return;
  87. }
  88. process.env[name] = value;
  89. }
  90. beforeEach(() => {
  91. spawnMock.mockReset();
  92. spawnMock.mockReturnValue(createMockPty());
  93. });
  94. afterEach(() => {
  95. process.env.SHELL = originalShell;
  96. process.env.HOME = originalHome;
  97. restoreEnv("LANG", originalLang);
  98. restoreEnv("LC_ALL", originalLcAll);
  99. restoreEnv("LC_CTYPE", originalLcCtype);
  100. restoreEnv("TERM", originalTerm);
  101. restoreEnv("COLORTERM", originalColorTerm);
  102. restoreEnv("CI", originalCi);
  103. restoreEnv("PATH", originalPath);
  104. restoreEnv("PATHEXT", originalPathExt);
  105. restoreEnv("ComSpec", originalComSpec);
  106. if (originalPlatformDescriptor) {
  107. Object.defineProperty(process, "platform", originalPlatformDescriptor);
  108. }
  109. while (tempDirs.length > 0) {
  110. const dir = tempDirs.pop();
  111. if (dir) rmSync(dir, { recursive: true, force: true });
  112. }
  113. });
  114. describe("terminalService", () => {
  115. it("should fall back to a usable shell when SHELL points to a missing executable", () => {
  116. const invalidShell = join(tmpdir(), `zcode-missing-shell-${Date.now()}`);
  117. process.env.SHELL = invalidShell;
  118. const shell = resolveTerminalShell();
  119. expect(shell).not.toBe(invalidShell);
  120. expect(shell).toMatch(getExpectedResolvedShellPattern());
  121. });
  122. it("should prefer pwsh over legacy powershell on Windows", () => {
  123. setProcessPlatform("win32");
  124. prependFakeWindowsShells(["pwsh.exe", "powershell.exe", "cmd.exe"]);
  125. expect(resolveTerminalShell()).toBe("pwsh.exe");
  126. });
  127. it("should expose Windows ConPTY compatibility info only on Windows", () => {
  128. expect(parseWindowsBuildNumber("10.0.19045")).toBe(19045);
  129. expect(resolveTerminalWindowsPtyInfo("win32", "10.0.19041")).toEqual({
  130. backend: "conpty",
  131. buildNumber: 19041,
  132. });
  133. expect(resolveTerminalWindowsPtyInfo("darwin", "23.0.0")).toBeUndefined();
  134. });
  135. it("should keep the provided cwd when it still exists", () => {
  136. const cwd = makeTempDir("zcode-terminal-cwd-");
  137. expect(resolveTerminalCwd(cwd)).toBe(cwd);
  138. });
  139. it("should fall back to HOME when the provided cwd is gone", () => {
  140. const home = makeTempDir("zcode-terminal-home-");
  141. process.env.HOME = home;
  142. const cwd = resolveTerminalCwd(join(tmpdir(), `zcode-missing-cwd-${Date.now()}`));
  143. expect(cwd).toBe(home);
  144. });
  145. it("should provide a UTF-8 locale when the parent process has C locale", () => {
  146. const env = resolveTerminalEnv({
  147. PATH: "/bin",
  148. LANG: "",
  149. LC_ALL: "",
  150. LC_CTYPE: "C",
  151. TERM: "dumb",
  152. CI: "1",
  153. });
  154. if (process.platform === "darwin") {
  155. expect(env.PATH?.split(":")).toEqual(
  156. expect.arrayContaining(["/bin", "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"]),
  157. );
  158. }
  159. expect(env.LANG).toMatch(/utf-?8/i);
  160. expect(env.LC_ALL).toMatch(/utf-?8/i);
  161. expect(env.LC_CTYPE).toMatch(/utf-?8/i);
  162. expect(env.TERM).toBe("xterm-256color");
  163. expect(env.COLORTERM).toBe("truecolor");
  164. expect(env.CI).toBeUndefined();
  165. });
  166. it("should add common macOS command paths for GUI-launched terminal environments", () => {
  167. const env = resolveTerminalEnv({
  168. PATH: "/usr/bin:/bin:/usr/bin",
  169. });
  170. if (process.platform !== "darwin") {
  171. expect(env.PATH).toBe("/usr/bin:/bin:/usr/bin");
  172. return;
  173. }
  174. expect(env.PATH?.split(":")).toEqual([
  175. "/usr/bin",
  176. "/bin",
  177. "/opt/homebrew/bin",
  178. "/opt/homebrew/sbin",
  179. "/usr/local/bin",
  180. "/usr/local/sbin",
  181. "/usr/sbin",
  182. "/sbin",
  183. ]);
  184. });
  185. it("should keep interactive terminal capabilities when spawning the terminal", async () => {
  186. const home = makeTempDir("zcode-terminal-home-");
  187. process.env.HOME = home;
  188. process.env.SHELL = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
  189. process.env.TERM = "dumb";
  190. process.env.CI = "1";
  191. const service = createTestTerminalService();
  192. await service.create({ cols: 80, rows: 24, cwd: home });
  193. expect(spawnMock).toHaveBeenCalledWith(
  194. expect.any(String),
  195. [],
  196. expect.objectContaining({
  197. env: expect.objectContaining({
  198. TERM: "xterm-256color",
  199. COLORTERM: "truecolor",
  200. }),
  201. }),
  202. );
  203. expect(spawnMock.mock.calls.at(-1)?.[2]?.env?.CI).toBeUndefined();
  204. });
  205. it("should keep an inherited UTF-8 locale when spawning the terminal", async () => {
  206. const home = makeTempDir("zcode-terminal-home-");
  207. process.env.HOME = home;
  208. process.env.SHELL = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
  209. process.env.LANG = "zh_CN.UTF-8";
  210. process.env.LC_CTYPE = "C";
  211. delete process.env.LC_ALL;
  212. const service = createTestTerminalService();
  213. await service.create({ cols: 80, rows: 24, cwd: home });
  214. expect(spawnMock).toHaveBeenCalledWith(
  215. expect.any(String),
  216. [],
  217. expect.objectContaining({
  218. env: expect.objectContaining({
  219. LANG: "zh_CN.UTF-8",
  220. LC_CTYPE: "zh_CN.UTF-8",
  221. }),
  222. }),
  223. );
  224. });
  225. it("should return the resolved terminal font profile", async () => {
  226. const home = makeTempDir("zcode-terminal-home-");
  227. process.env.HOME = home;
  228. process.env.SHELL = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
  229. const service = createTestTerminalService({
  230. terminalFontFamily: "MesloLGS NF",
  231. });
  232. const result = await service.create({ cols: 80, rows: 24, cwd: home });
  233. expect(result.fontFamily).toContain("MesloLGS NF");
  234. expect(result.fontFamilySource).toBe("custom");
  235. });
  236. it("should use resolved shell and cwd before spawning the terminal", async () => {
  237. const home = makeTempDir("zcode-terminal-home-");
  238. process.env.HOME = home;
  239. process.env.SHELL = join(tmpdir(), `zcode-missing-shell-${Date.now()}`);
  240. const service = createTestTerminalService();
  241. await service.create({ cols: 80, rows: 24, cwd: join(tmpdir(), `zcode-missing-cwd-${Date.now()}`) });
  242. expect(spawnMock).toHaveBeenCalledOnce();
  243. expect(spawnMock).toHaveBeenCalledWith(
  244. expect.stringMatching(getExpectedResolvedShellPattern()),
  245. [],
  246. expect.objectContaining({
  247. name: "xterm-256color",
  248. cols: 80,
  249. rows: 24,
  250. cwd: home,
  251. }),
  252. );
  253. });
  254. it("should wrap spawn failures with shell and cwd details", async () => {
  255. const home = makeTempDir("zcode-terminal-home-");
  256. process.env.HOME = home;
  257. process.env.SHELL =
  258. process.platform === "win32" ? "/bin/sh" : "/bin/sh";
  259. spawnMock.mockImplementationOnce(() => {
  260. throw new Error("posix_spawnp failed");
  261. });
  262. const service = createTestTerminalService();
  263. const expectedShell = resolveTerminalShell().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  264. await expect(service.create({ cols: 80, rows: 24, cwd: home })).rejects.toThrow(
  265. new RegExp(`Failed to start terminal with shell '${expectedShell}' in '.*': posix_spawnp failed`),
  266. );
  267. });
  268. it("should fall back to system conpty when useConptyDll fails on Windows", async () => {
  269. setProcessPlatform("win32");
  270. prependFakeWindowsShells(["powershell.exe"]);
  271. const home = makeTempDir("zcode-terminal-home-");
  272. process.env.HOME = home;
  273. const fallbackPty = createMockPty();
  274. spawnMock
  275. .mockImplementationOnce(() => {
  276. throw new Error("Failed to get conpty.node module handle, error code: 126");
  277. })
  278. .mockReturnValueOnce(fallbackPty);
  279. const service = createTestTerminalService();
  280. await service.create({ cols: 80, rows: 24, cwd: home });
  281. expect(spawnMock).toHaveBeenCalledTimes(2);
  282. expect(spawnMock).toHaveBeenNthCalledWith(
  283. 1,
  284. "powershell.exe",
  285. [],
  286. expect.objectContaining({
  287. useConpty: true,
  288. useConptyDll: true,
  289. cwd: home,
  290. }),
  291. );
  292. expect(spawnMock).toHaveBeenNthCalledWith(
  293. 2,
  294. "powershell.exe",
  295. [],
  296. expect.objectContaining({
  297. useConpty: true,
  298. useConptyDll: false,
  299. cwd: home,
  300. }),
  301. );
  302. });
  303. it("should not fall back when Windows spawn fails for non-conpty reasons", async () => {
  304. setProcessPlatform("win32");
  305. prependFakeWindowsShells(["powershell.exe"]);
  306. const home = makeTempDir("zcode-terminal-home-");
  307. process.env.HOME = home;
  308. spawnMock.mockImplementationOnce(() => {
  309. throw new Error("powershell.exe not found");
  310. });
  311. const service = createTestTerminalService();
  312. await expect(service.create({ cols: 80, rows: 24, cwd: home })).rejects.toThrow(
  313. `Failed to start terminal with shell 'powershell.exe' in '${home}': powershell.exe not found`,
  314. );
  315. expect(spawnMock).toHaveBeenCalledOnce();
  316. });
  317. it("should kill all active terminals when disposing the service", async () => {
  318. const home = makeTempDir("zcode-terminal-home-");
  319. process.env.HOME = home;
  320. process.env.SHELL = "/bin/sh";
  321. const firstPty = createMockPty();
  322. const secondPty = createMockPty();
  323. spawnMock
  324. .mockReturnValueOnce(firstPty)
  325. .mockReturnValueOnce(secondPty);
  326. const service = createTestTerminalService() as ReturnType<typeof createTestTerminalService> & {
  327. disposeAll: () => void;
  328. };
  329. await service.create({ cols: 80, rows: 24, cwd: home });
  330. await service.create({ cols: 120, rows: 30, cwd: home });
  331. service.disposeAll();
  332. expect(firstPty.kill).toHaveBeenCalledOnce();
  333. expect(secondPty.kill).toHaveBeenCalledOnce();
  334. });
  335. });