terminalService.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. } as any,
  77. });
  78. }
  79. function setProcessPlatform(platform: NodeJS.Platform) {
  80. Object.defineProperty(process, "platform", { value: platform });
  81. }
  82. function restoreEnv(name: string, value: string | undefined) {
  83. if (value === undefined) {
  84. delete process.env[name];
  85. return;
  86. }
  87. process.env[name] = value;
  88. }
  89. beforeEach(() => {
  90. spawnMock.mockReset();
  91. spawnMock.mockReturnValue(createMockPty());
  92. });
  93. afterEach(() => {
  94. process.env.SHELL = originalShell;
  95. process.env.HOME = originalHome;
  96. restoreEnv("LANG", originalLang);
  97. restoreEnv("LC_ALL", originalLcAll);
  98. restoreEnv("LC_CTYPE", originalLcCtype);
  99. restoreEnv("TERM", originalTerm);
  100. restoreEnv("COLORTERM", originalColorTerm);
  101. restoreEnv("CI", originalCi);
  102. restoreEnv("PATH", originalPath);
  103. restoreEnv("PATHEXT", originalPathExt);
  104. restoreEnv("ComSpec", originalComSpec);
  105. if (originalPlatformDescriptor) {
  106. Object.defineProperty(process, "platform", originalPlatformDescriptor);
  107. }
  108. while (tempDirs.length > 0) {
  109. const dir = tempDirs.pop();
  110. if (dir) rmSync(dir, { recursive: true, force: true });
  111. }
  112. });
  113. describe("terminalService", () => {
  114. it("should fall back to a usable shell when SHELL points to a missing executable", () => {
  115. const invalidShell = join(tmpdir(), `zcode-missing-shell-${Date.now()}`);
  116. process.env.SHELL = invalidShell;
  117. const shell = resolveTerminalShell();
  118. expect(shell).not.toBe(invalidShell);
  119. expect(shell).toMatch(getExpectedResolvedShellPattern());
  120. });
  121. it("should prefer pwsh over legacy powershell on Windows", () => {
  122. setProcessPlatform("win32");
  123. prependFakeWindowsShells(["pwsh.exe", "powershell.exe", "cmd.exe"]);
  124. expect(resolveTerminalShell()).toBe("pwsh.exe");
  125. });
  126. it("should expose Windows ConPTY compatibility info only on Windows", () => {
  127. expect(parseWindowsBuildNumber("10.0.19045")).toBe(19045);
  128. expect(resolveTerminalWindowsPtyInfo("win32", "10.0.19041")).toEqual({
  129. backend: "conpty",
  130. buildNumber: 19041,
  131. });
  132. expect(resolveTerminalWindowsPtyInfo("darwin", "23.0.0")).toBeUndefined();
  133. });
  134. it("should keep the provided cwd when it still exists", () => {
  135. const cwd = makeTempDir("zcode-terminal-cwd-");
  136. expect(resolveTerminalCwd(cwd)).toBe(cwd);
  137. });
  138. it("should fall back to HOME when the provided cwd is gone", () => {
  139. const home = makeTempDir("zcode-terminal-home-");
  140. process.env.HOME = home;
  141. const cwd = resolveTerminalCwd(join(tmpdir(), `zcode-missing-cwd-${Date.now()}`));
  142. expect(cwd).toBe(home);
  143. });
  144. it("should provide a UTF-8 locale when the parent process has C locale", () => {
  145. const env = resolveTerminalEnv({
  146. PATH: "/bin",
  147. LANG: "",
  148. LC_ALL: "",
  149. LC_CTYPE: "C",
  150. TERM: "dumb",
  151. CI: "1",
  152. });
  153. if (process.platform === "darwin") {
  154. expect(env.PATH?.split(":")).toEqual(
  155. expect.arrayContaining(["/bin", "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"]),
  156. );
  157. }
  158. expect(env.LANG).toMatch(/utf-?8/i);
  159. expect(env.LC_ALL).toMatch(/utf-?8/i);
  160. expect(env.LC_CTYPE).toMatch(/utf-?8/i);
  161. expect(env.TERM).toBe("xterm-256color");
  162. expect(env.COLORTERM).toBe("truecolor");
  163. expect(env.CI).toBeUndefined();
  164. });
  165. it("should add common macOS command paths for GUI-launched terminal environments", () => {
  166. const env = resolveTerminalEnv({
  167. PATH: "/usr/bin:/bin:/usr/bin",
  168. });
  169. if (process.platform !== "darwin") {
  170. expect(env.PATH).toBe("/usr/bin:/bin:/usr/bin");
  171. return;
  172. }
  173. expect(env.PATH?.split(":")).toEqual([
  174. "/usr/bin",
  175. "/bin",
  176. "/opt/homebrew/bin",
  177. "/opt/homebrew/sbin",
  178. "/usr/local/bin",
  179. "/usr/local/sbin",
  180. "/usr/sbin",
  181. "/sbin",
  182. ]);
  183. });
  184. it("should keep interactive terminal capabilities when spawning the terminal", async () => {
  185. const home = makeTempDir("zcode-terminal-home-");
  186. process.env.HOME = home;
  187. process.env.SHELL = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
  188. process.env.TERM = "dumb";
  189. process.env.CI = "1";
  190. const service = createTestTerminalService();
  191. await service.create({ cols: 80, rows: 24, cwd: home });
  192. expect(spawnMock).toHaveBeenCalledWith(
  193. expect.any(String),
  194. [],
  195. expect.objectContaining({
  196. env: expect.objectContaining({
  197. TERM: "xterm-256color",
  198. COLORTERM: "truecolor",
  199. }),
  200. }),
  201. );
  202. expect(spawnMock.mock.calls.at(-1)?.[2]?.env?.CI).toBeUndefined();
  203. });
  204. it("should keep an inherited UTF-8 locale when spawning the terminal", async () => {
  205. const home = makeTempDir("zcode-terminal-home-");
  206. process.env.HOME = home;
  207. process.env.SHELL = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
  208. process.env.LANG = "zh_CN.UTF-8";
  209. process.env.LC_CTYPE = "C";
  210. delete process.env.LC_ALL;
  211. const service = createTestTerminalService();
  212. await service.create({ cols: 80, rows: 24, cwd: home });
  213. expect(spawnMock).toHaveBeenCalledWith(
  214. expect.any(String),
  215. [],
  216. expect.objectContaining({
  217. env: expect.objectContaining({
  218. LANG: "zh_CN.UTF-8",
  219. LC_CTYPE: "zh_CN.UTF-8",
  220. }),
  221. }),
  222. );
  223. });
  224. it("should return the resolved terminal font profile", async () => {
  225. const home = makeTempDir("zcode-terminal-home-");
  226. process.env.HOME = home;
  227. process.env.SHELL = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
  228. const service = createTestTerminalService({
  229. terminalFontFamily: "MesloLGS NF",
  230. });
  231. const result = await service.create({ cols: 80, rows: 24, cwd: home });
  232. expect(result.fontFamily).toContain("MesloLGS NF");
  233. expect(result.fontFamilySource).toBe("custom");
  234. });
  235. it("should use resolved shell and cwd before spawning the terminal", async () => {
  236. const home = makeTempDir("zcode-terminal-home-");
  237. process.env.HOME = home;
  238. process.env.SHELL = join(tmpdir(), `zcode-missing-shell-${Date.now()}`);
  239. const service = createTestTerminalService();
  240. await service.create({
  241. cols: 80,
  242. rows: 24,
  243. cwd: join(tmpdir(), `zcode-missing-cwd-${Date.now()}`),
  244. });
  245. expect(spawnMock).toHaveBeenCalledOnce();
  246. expect(spawnMock).toHaveBeenCalledWith(
  247. expect.stringMatching(getExpectedResolvedShellPattern()),
  248. [],
  249. expect.objectContaining({
  250. name: "xterm-256color",
  251. cols: 80,
  252. rows: 24,
  253. cwd: home,
  254. }),
  255. );
  256. });
  257. it("should wrap spawn failures with shell and cwd details", async () => {
  258. const home = makeTempDir("zcode-terminal-home-");
  259. process.env.HOME = home;
  260. process.env.SHELL = process.platform === "win32" ? "/bin/sh" : "/bin/sh";
  261. spawnMock.mockImplementationOnce(() => {
  262. throw new Error("posix_spawnp failed");
  263. });
  264. const service = createTestTerminalService();
  265. const expectedShell = resolveTerminalShell().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  266. await expect(service.create({ cols: 80, rows: 24, cwd: home })).rejects.toThrow(
  267. new RegExp(
  268. `Failed to start terminal with shell '${expectedShell}' in '.*': posix_spawnp failed`,
  269. ),
  270. );
  271. });
  272. it("should fall back to system conpty when useConptyDll fails on Windows", async () => {
  273. setProcessPlatform("win32");
  274. prependFakeWindowsShells(["powershell.exe"]);
  275. const home = makeTempDir("zcode-terminal-home-");
  276. process.env.HOME = home;
  277. const fallbackPty = createMockPty();
  278. spawnMock
  279. .mockImplementationOnce(() => {
  280. throw new Error("Failed to get conpty.node module handle, error code: 126");
  281. })
  282. .mockReturnValueOnce(fallbackPty);
  283. const service = createTestTerminalService();
  284. await service.create({ cols: 80, rows: 24, cwd: home });
  285. expect(spawnMock).toHaveBeenCalledTimes(2);
  286. expect(spawnMock).toHaveBeenNthCalledWith(
  287. 1,
  288. "powershell.exe",
  289. [],
  290. expect.objectContaining({
  291. useConpty: true,
  292. useConptyDll: true,
  293. cwd: home,
  294. }),
  295. );
  296. expect(spawnMock).toHaveBeenNthCalledWith(
  297. 2,
  298. "powershell.exe",
  299. [],
  300. expect.objectContaining({
  301. useConpty: true,
  302. useConptyDll: false,
  303. cwd: home,
  304. }),
  305. );
  306. });
  307. it("should not fall back when Windows spawn fails for non-conpty reasons", async () => {
  308. setProcessPlatform("win32");
  309. prependFakeWindowsShells(["powershell.exe"]);
  310. const home = makeTempDir("zcode-terminal-home-");
  311. process.env.HOME = home;
  312. spawnMock.mockImplementationOnce(() => {
  313. throw new Error("powershell.exe not found");
  314. });
  315. const service = createTestTerminalService();
  316. await expect(service.create({ cols: 80, rows: 24, cwd: home })).rejects.toThrow(
  317. `Failed to start terminal with shell 'powershell.exe' in '${home}': powershell.exe not found`,
  318. );
  319. expect(spawnMock).toHaveBeenCalledOnce();
  320. });
  321. describe("early output buffering", () => {
  322. async function createTerminalWithPty() {
  323. const home = makeTempDir("zcode-terminal-home-");
  324. process.env.HOME = home;
  325. process.env.SHELL = "/bin/sh";
  326. const pty = createMockPty();
  327. spawnMock.mockReturnValueOnce(pty);
  328. const service = createTestTerminalService();
  329. const { id } = await service.create({ cols: 80, rows: 24, cwd: home });
  330. const emitPtyData = pty.onData.mock.calls[0]?.[0] as ((data: string) => void) | undefined;
  331. if (!emitPtyData) throw new Error("pty.onData was not wired");
  332. return { emitPtyData, id, service };
  333. }
  334. it("should replay output emitted before the first onDynamicData listener, then stream live", async () => {
  335. // R3 远端终端 bash 提示符在 spawn 后约 10ms 就到达,而 renderer 要等 create() 返回后才能订阅;
  336. // 订阅前的输出必须保留并按序回放,否则用户看到的是空白终端。
  337. const { emitPtyData, id, service } = await createTerminalWithPty();
  338. emitPtyData("banner\r\n");
  339. emitPtyData("dev@host:~$ ");
  340. const received: string[] = [];
  341. service.onDynamicData(id)((data) => received.push(data));
  342. emitPtyData("live");
  343. expect(received).toEqual(["banner\r\n", "dev@host:~$ ", "live"]);
  344. });
  345. it("should retain output while no listener is attached and replay it to the next listener", async () => {
  346. const { emitPtyData, id, service } = await createTerminalWithPty();
  347. const first: string[] = [];
  348. const subscription = service.onDynamicData(id)((data) => first.push(data));
  349. emitPtyData("a");
  350. subscription.dispose();
  351. emitPtyData("b");
  352. const second: string[] = [];
  353. service.onDynamicData(id)((data) => second.push(data));
  354. emitPtyData("c");
  355. expect(first).toEqual(["a"]);
  356. expect(second).toEqual(["b", "c"]);
  357. });
  358. it("should drop the oldest buffered output once the early buffer exceeds its bound", async () => {
  359. const { emitPtyData, id, service } = await createTerminalWithPty();
  360. const chunk = "x".repeat(600_000);
  361. emitPtyData(chunk);
  362. emitPtyData("y".repeat(600_000));
  363. emitPtyData("tail");
  364. const received: string[] = [];
  365. service.onDynamicData(id)((data) => received.push(data));
  366. expect(received).not.toContain(chunk);
  367. expect(received.at(-1)).toBe("tail");
  368. expect(received.join("").length).toBeLessThanOrEqual(1_048_576);
  369. });
  370. });
  371. it("should kill all active terminals when disposing the service", async () => {
  372. const home = makeTempDir("zcode-terminal-home-");
  373. process.env.HOME = home;
  374. process.env.SHELL = "/bin/sh";
  375. const firstPty = createMockPty();
  376. const secondPty = createMockPty();
  377. spawnMock.mockReturnValueOnce(firstPty).mockReturnValueOnce(secondPty);
  378. const service = createTestTerminalService() as ReturnType<typeof createTestTerminalService> & {
  379. disposeAll: () => void;
  380. };
  381. await service.create({ cols: 80, rows: 24, cwd: home });
  382. await service.create({ cols: 120, rows: 30, cwd: home });
  383. service.disposeAll();
  384. expect(firstPty.kill).toHaveBeenCalledOnce();
  385. expect(secondPty.kill).toHaveBeenCalledOnce();
  386. });
  387. });