openInEditor.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
  3. import { join } from "node:path";
  4. import { tmpdir } from "node:os";
  5. const {
  6. accessMock,
  7. execFileMock,
  8. listWSLDistrosMock,
  9. openPathMock,
  10. showItemInFolderMock,
  11. loggerWarnMock,
  12. } =
  13. vi.hoisted(() => ({
  14. accessMock: vi.fn(),
  15. execFileMock: vi.fn(),
  16. listWSLDistrosMock: vi.fn(),
  17. openPathMock: vi.fn(),
  18. showItemInFolderMock: vi.fn(),
  19. loggerWarnMock: vi.fn(),
  20. }));
  21. vi.mock("node:child_process", () => ({
  22. execFile: execFileMock,
  23. }));
  24. vi.mock("node:fs/promises", () => ({
  25. access: accessMock,
  26. }));
  27. vi.mock("electron", () => ({
  28. shell: {
  29. openPath: openPathMock,
  30. showItemInFolder: showItemInFolderMock,
  31. },
  32. }));
  33. vi.mock("@zcode/server/remote/wsl-detect.js", () => ({
  34. listWSLDistros: listWSLDistrosMock,
  35. }));
  36. vi.mock("../src/main/editors.js", () => ({
  37. getEditorDefsForCurrentPlatform: () => [
  38. {
  39. id: "explorer",
  40. name: "资源管理器",
  41. appPath: "C:/Windows/explorer.exe",
  42. command: null,
  43. },
  44. {
  45. id: "vscode",
  46. name: "VS Code",
  47. appPath: "C:/Users/demo/AppData/Local/Programs/Microsoft VS Code/Code.exe",
  48. command: "code",
  49. },
  50. {
  51. id: "qspace",
  52. name: "QSpace",
  53. appPath: "/Applications/QSpace.app",
  54. command: null,
  55. },
  56. {
  57. id: "qspace-pro",
  58. name: "QSpace Pro",
  59. appPath: "/Applications/QSpace Pro.app",
  60. command: null,
  61. },
  62. ],
  63. resolveEditorDefAppPath: (def: { appPath: string }) => def.appPath,
  64. }));
  65. vi.mock("../src/main/logger.js", () => ({
  66. logger: {
  67. warn: loggerWarnMock,
  68. },
  69. }));
  70. import { openInEditor } from "../src/main/openInEditor.js";
  71. const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
  72. function setProcessPlatform(platform: NodeJS.Platform) {
  73. Object.defineProperty(process, "platform", { value: platform });
  74. }
  75. describe("openInEditor", () => {
  76. let tempDir: string;
  77. beforeEach(() => {
  78. tempDir = mkdtempSync(join(tmpdir(), "zcode-open-in-editor-"));
  79. accessMock.mockReset();
  80. accessMock.mockResolvedValue(undefined);
  81. execFileMock.mockReset();
  82. listWSLDistrosMock.mockReset();
  83. openPathMock.mockReset();
  84. showItemInFolderMock.mockReset();
  85. loggerWarnMock.mockReset();
  86. listWSLDistrosMock.mockResolvedValue([{ name: "Ubuntu", isDefault: true }]);
  87. openPathMock.mockResolvedValue("");
  88. });
  89. afterEach(() => {
  90. rmSync(tempDir, { recursive: true, force: true });
  91. if (originalPlatformDescriptor) {
  92. Object.defineProperty(process, "platform", originalPlatformDescriptor);
  93. }
  94. });
  95. it("Windows 目录路径应直接走 shell.openPath,避免 explorer fallback 双开", async () => {
  96. const result = await openInEditor("explorer", tempDir);
  97. expect(result).toEqual({ success: true });
  98. expect(execFileMock).not.toHaveBeenCalled();
  99. expect(openPathMock).toHaveBeenCalledTimes(1);
  100. expect(openPathMock).toHaveBeenCalledWith(tempDir);
  101. });
  102. it("Windows 本地文件只调用一次 shell 定位,不启动 Explorer 子进程", async () => {
  103. setProcessPlatform("win32");
  104. const filePath = join(tempDir, "生成 文件.html");
  105. writeFileSync(filePath, "<html></html>");
  106. // 回归:旧实现即使 Explorer 已打开窗口,非零退出码仍会触发第二次定位。
  107. execFileMock.mockImplementation(
  108. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  109. callback(Object.assign(new Error("Command failed: explorer.exe"), { code: 1 }));
  110. },
  111. );
  112. const result = await openInEditor("explorer", filePath);
  113. expect(result).toEqual({ success: true });
  114. expect(execFileMock).not.toHaveBeenCalled();
  115. expect(showItemInFolderMock).toHaveBeenCalledExactlyOnceWith(filePath);
  116. expect(openPathMock).not.toHaveBeenCalled();
  117. });
  118. it("Windows CLI 命令不可用时应回退到编辑器 exe 打开目录", async () => {
  119. setProcessPlatform("win32");
  120. execFileMock.mockImplementation(
  121. (file: string, _args: string[], callback: (error: Error | null) => void) => {
  122. callback(file === "code" ? new Error("missing code cli") : null);
  123. },
  124. );
  125. const result = await openInEditor("vscode", tempDir);
  126. expect(result).toEqual({ success: true });
  127. expect(execFileMock).toHaveBeenNthCalledWith(1, "code", [tempDir], expect.any(Function));
  128. expect(execFileMock).toHaveBeenNthCalledWith(
  129. 2,
  130. "C:/Users/demo/AppData/Local/Programs/Microsoft VS Code/Code.exe",
  131. [tempDir],
  132. expect.any(Function),
  133. );
  134. });
  135. it("SSH 远程工作区用 VS Code 打开时应走 Remote-SSH folder URI", async () => {
  136. execFileMock.mockImplementation(
  137. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  138. callback(null);
  139. },
  140. );
  141. const result = await openInEditor("vscode", "/root/demo-project", {
  142. remoteTarget: {
  143. kind: "ssh",
  144. host: "jumpserver.example.com",
  145. port: 2222,
  146. username: "asset01@root@192.168.100.166",
  147. sshConfigAlias: "zcode",
  148. },
  149. });
  150. expect(result).toEqual({ success: true });
  151. expect(execFileMock).toHaveBeenCalledWith(
  152. "code",
  153. ["--folder-uri", "vscode-remote://ssh-remote+zcode/root/demo-project"],
  154. expect.any(Function),
  155. );
  156. });
  157. it("SSH 远程文件用 VS Code 打开时应走 Remote-SSH file URI", async () => {
  158. execFileMock.mockImplementation(
  159. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  160. callback(null);
  161. },
  162. );
  163. const result = await openInEditor("vscode", "/root/demo-project/src/index.ts", {
  164. pathKind: "file",
  165. remoteTarget: {
  166. kind: "ssh",
  167. host: "jumpserver.example.com",
  168. port: 2222,
  169. username: "root",
  170. sshConfigAlias: "zcode",
  171. },
  172. });
  173. expect(result).toEqual({ success: true });
  174. expect(execFileMock).toHaveBeenCalledWith(
  175. "code",
  176. ["--file-uri", "vscode-remote://ssh-remote+zcode/root/demo-project/src/index.ts"],
  177. expect.any(Function),
  178. );
  179. });
  180. it("SSH 远程工作区没有 alias 时应编码 VS Code Remote-SSH authority", async () => {
  181. execFileMock.mockImplementation(
  182. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  183. callback(null);
  184. },
  185. );
  186. const result = await openInEditor("vscode", "/root/demo-project", {
  187. remoteTarget: {
  188. kind: "ssh",
  189. host: "192.168.100.166",
  190. port: 2222,
  191. username: "asset01@root",
  192. },
  193. });
  194. expect(result).toEqual({ success: true });
  195. expect(execFileMock).toHaveBeenCalledWith(
  196. "code",
  197. [
  198. "--folder-uri",
  199. "vscode-remote://ssh-remote+asset01%40root%40192.168.100.166%3A2222/root/demo-project",
  200. ],
  201. expect.any(Function),
  202. );
  203. });
  204. it("WSL 远程工作区用 VS Code 打开时应走 Remote-WSL folder URI", async () => {
  205. execFileMock.mockImplementation(
  206. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  207. callback(null);
  208. },
  209. );
  210. const result = await openInEditor("vscode", "/home/demo/My Repo", {
  211. remoteTarget: {
  212. kind: "wsl",
  213. distro: "Ubuntu 22.04",
  214. },
  215. });
  216. expect(result).toEqual({ success: true });
  217. expect(execFileMock).toHaveBeenCalledWith(
  218. "code",
  219. [
  220. "--folder-uri",
  221. "vscode-remote://wsl+Ubuntu%2022.04/home/demo/My%20Repo",
  222. ],
  223. expect.any(Function),
  224. );
  225. });
  226. it("WSL 远程文件用 VS Code 打开时应走 Remote-WSL file URI", async () => {
  227. execFileMock.mockImplementation(
  228. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  229. callback(null);
  230. },
  231. );
  232. const result = await openInEditor("vscode", "/home/demo/My Repo/src/index.ts", {
  233. pathKind: "file",
  234. remoteTarget: {
  235. kind: "wsl",
  236. distro: "Ubuntu 22.04",
  237. },
  238. });
  239. expect(result).toEqual({ success: true });
  240. expect(execFileMock).toHaveBeenCalledWith(
  241. "code",
  242. [
  243. "--file-uri",
  244. "vscode-remote://wsl+Ubuntu%2022.04/home/demo/My%20Repo/src/index.ts",
  245. ],
  246. expect.any(Function),
  247. );
  248. });
  249. it("WSL 远程工作区缺少 distro 时应使用默认 distro 打开 VS Code", async () => {
  250. execFileMock.mockImplementation(
  251. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  252. callback(null);
  253. },
  254. );
  255. const result = await openInEditor("vscode", "/home/demo/repo", {
  256. remoteTarget: {
  257. kind: "wsl",
  258. },
  259. });
  260. expect(result).toEqual({ success: true });
  261. expect(listWSLDistrosMock).toHaveBeenCalledTimes(1);
  262. expect(execFileMock).toHaveBeenCalledWith(
  263. "code",
  264. ["--folder-uri", "vscode-remote://wsl+Ubuntu/home/demo/repo"],
  265. expect.any(Function),
  266. );
  267. expect(openPathMock).not.toHaveBeenCalled();
  268. });
  269. it("WSL 远程工作区缺少 distro 且检测失败时不应裸传 Linux 路径给 VS Code", async () => {
  270. listWSLDistrosMock.mockRejectedValueOnce(new Error("wsl unavailable"));
  271. const result = await openInEditor("vscode", "/home/demo/repo", {
  272. remoteTarget: {
  273. kind: "wsl",
  274. },
  275. });
  276. expect(result).toEqual({
  277. success: false,
  278. error: "missing WSL distro for VS Code Remote-WSL",
  279. });
  280. expect(listWSLDistrosMock).toHaveBeenCalledTimes(1);
  281. expect(execFileMock).not.toHaveBeenCalled();
  282. expect(openPathMock).not.toHaveBeenCalled();
  283. expect(loggerWarnMock).toHaveBeenCalledWith(
  284. "[editors] 解析默认 WSL distro 失败",
  285. { error: "wsl unavailable" },
  286. );
  287. });
  288. it("WSL 远程工作区用资源管理器打开时应通过 explorer.exe 打开 wsl.localhost UNC", async () => {
  289. execFileMock.mockImplementation(
  290. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  291. callback(null);
  292. },
  293. );
  294. const result = await openInEditor("explorer", "/home/demo/My Repo", {
  295. remoteTarget: {
  296. kind: "wsl",
  297. distro: "Ubuntu",
  298. },
  299. });
  300. expect(result).toEqual({ success: true });
  301. expect(execFileMock).toHaveBeenCalledTimes(1);
  302. expect(execFileMock).toHaveBeenCalledWith(
  303. "C:/Windows/explorer.exe",
  304. ["\\\\wsl.localhost\\Ubuntu\\home\\demo\\My Repo"],
  305. expect.any(Function),
  306. );
  307. expect(openPathMock).not.toHaveBeenCalled();
  308. });
  309. it("WSL 远程文件用资源管理器定位时应选择对应 UNC 文件", async () => {
  310. execFileMock.mockImplementation(
  311. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  312. callback(null);
  313. },
  314. );
  315. const result = await openInEditor("explorer", "/home/demo/src/index.ts", {
  316. pathKind: "file",
  317. remoteTarget: {
  318. kind: "wsl",
  319. distro: "Ubuntu",
  320. },
  321. });
  322. expect(result).toEqual({ success: true });
  323. expect(execFileMock).toHaveBeenCalledWith(
  324. "C:/Windows/explorer.exe",
  325. ["/select,", "\\\\wsl.localhost\\Ubuntu\\home\\demo\\src\\index.ts"],
  326. expect.any(Function),
  327. );
  328. });
  329. it("WSL Explorer 已委托打开但返回数字退出码时仍应视为成功", async () => {
  330. setProcessPlatform("win32");
  331. const command =
  332. '"C:/Windows/explorer.exe" /select, "\\\\wsl.localhost\\Ubuntu\\home\\demo\\src\\index.ts"';
  333. execFileMock.mockImplementation(
  334. (
  335. _file: string,
  336. _args: string[],
  337. callback: (error: Error | null) => void,
  338. ) => {
  339. callback(
  340. Object.assign(new Error(`Command failed: ${command}`), {
  341. code: 1,
  342. killed: false,
  343. signal: null,
  344. cmd: command,
  345. stderr: "",
  346. }),
  347. );
  348. },
  349. );
  350. const result = await openInEditor("explorer", "/home/demo/src/index.ts", {
  351. pathKind: "file",
  352. remoteTarget: {
  353. kind: "wsl",
  354. distro: "Ubuntu",
  355. },
  356. });
  357. expect(result).toEqual({ success: true });
  358. expect(execFileMock).toHaveBeenCalledTimes(1);
  359. expect(loggerWarnMock).not.toHaveBeenCalled();
  360. });
  361. it("WSL Explorer 数字退出码包含路径错误时应继续尝试 wsl$", async () => {
  362. setProcessPlatform("win32");
  363. accessMock.mockRejectedValueOnce(new Error("network path not found"));
  364. execFileMock.mockImplementation(
  365. (_file: string, args: string[], callback: (error: Error | null) => void) => {
  366. const candidate = args.at(-1) ?? "";
  367. if (candidate.startsWith("\\\\wsl.localhost")) {
  368. const command = `"C:/Windows/explorer.exe" "${candidate}"`;
  369. callback(
  370. Object.assign(new Error(`Command failed: ${command}`), {
  371. code: 1,
  372. killed: false,
  373. signal: null,
  374. cmd: command,
  375. stderr: "",
  376. }),
  377. );
  378. return;
  379. }
  380. callback(null);
  381. },
  382. );
  383. const result = await openInEditor("explorer", "/workspace/demo", {
  384. pathKind: "directory",
  385. remoteTarget: {
  386. kind: "wsl",
  387. distro: "Ubuntu",
  388. },
  389. });
  390. expect(result).toEqual({ success: true });
  391. expect(accessMock).toHaveBeenCalledWith(
  392. "\\\\wsl.localhost\\Ubuntu\\workspace\\demo",
  393. );
  394. expect(execFileMock).toHaveBeenCalledTimes(2);
  395. expect(execFileMock).toHaveBeenNthCalledWith(
  396. 2,
  397. "C:/Windows/explorer.exe",
  398. ["\\\\wsl$\\Ubuntu\\workspace\\demo"],
  399. expect.any(Function),
  400. );
  401. });
  402. it("WSL 远程工作区资源管理器应在 wsl.localhost 失败后回退到 wsl$ UNC", async () => {
  403. execFileMock.mockImplementation(
  404. (_file: string, args: string[], callback: (error: Error | null) => void) => {
  405. callback(
  406. args[0]?.startsWith("\\\\wsl.localhost")
  407. ? new Error("cannot open wsl.localhost")
  408. : null,
  409. );
  410. },
  411. );
  412. const result = await openInEditor("explorer", "/workspace/demo", {
  413. remoteTarget: {
  414. kind: "wsl",
  415. distro: "Ubuntu",
  416. },
  417. });
  418. expect(result).toEqual({ success: true });
  419. expect(execFileMock).toHaveBeenNthCalledWith(
  420. 1,
  421. "C:/Windows/explorer.exe",
  422. ["\\\\wsl.localhost\\Ubuntu\\workspace\\demo"],
  423. expect.any(Function),
  424. );
  425. expect(execFileMock).toHaveBeenNthCalledWith(
  426. 2,
  427. "C:/Windows/explorer.exe",
  428. ["\\\\wsl$\\Ubuntu\\workspace\\demo"],
  429. expect.any(Function),
  430. );
  431. expect(openPathMock).not.toHaveBeenCalled();
  432. });
  433. it("WSL 远程工作区资源管理器两个 UNC 候选都失败时应返回错误并记录日志", async () => {
  434. execFileMock.mockImplementation(
  435. (_file: string, args: string[], callback: (error: Error | null) => void) => {
  436. callback(new Error(`cannot open ${args[0] ?? "unknown"}`));
  437. },
  438. );
  439. const result = await openInEditor("explorer", "/workspace/demo", {
  440. remoteTarget: {
  441. kind: "wsl",
  442. distro: "Ubuntu",
  443. },
  444. });
  445. expect(result).toEqual({
  446. success: false,
  447. error: "cannot open \\\\wsl$\\Ubuntu\\workspace\\demo",
  448. });
  449. expect(execFileMock).toHaveBeenCalledTimes(2);
  450. expect(execFileMock).toHaveBeenNthCalledWith(
  451. 1,
  452. "C:/Windows/explorer.exe",
  453. ["\\\\wsl.localhost\\Ubuntu\\workspace\\demo"],
  454. expect.any(Function),
  455. );
  456. expect(execFileMock).toHaveBeenNthCalledWith(
  457. 2,
  458. "C:/Windows/explorer.exe",
  459. ["\\\\wsl$\\Ubuntu\\workspace\\demo"],
  460. expect.any(Function),
  461. );
  462. expect(openPathMock).not.toHaveBeenCalled();
  463. expect(loggerWarnMock).toHaveBeenCalledWith(
  464. "[editors] 打开 WSL 工作区资源管理器失败",
  465. {
  466. path: "/workspace/demo",
  467. candidates: [
  468. "\\\\wsl.localhost\\Ubuntu\\workspace\\demo",
  469. "\\\\wsl$\\Ubuntu\\workspace\\demo",
  470. ],
  471. error: "cannot open \\\\wsl$\\Ubuntu\\workspace\\demo",
  472. },
  473. );
  474. });
  475. it("macOS QSpace 应通过 app bundle 打开目录", async () => {
  476. setProcessPlatform("darwin");
  477. execFileMock.mockImplementation(
  478. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  479. callback(null);
  480. },
  481. );
  482. const result = await openInEditor("qspace", tempDir);
  483. expect(result).toEqual({ success: true });
  484. expect(execFileMock).toHaveBeenCalledTimes(1);
  485. expect(execFileMock).toHaveBeenCalledWith(
  486. "open",
  487. ["-a", "/Applications/QSpace.app", tempDir],
  488. expect.any(Function),
  489. );
  490. });
  491. it("macOS QSpace Pro 应通过 app bundle 打开目录", async () => {
  492. setProcessPlatform("darwin");
  493. execFileMock.mockImplementation(
  494. (_file: string, _args: string[], callback: (error: Error | null) => void) => {
  495. callback(null);
  496. },
  497. );
  498. const result = await openInEditor("qspace-pro", tempDir);
  499. expect(result).toEqual({ success: true });
  500. expect(execFileMock).toHaveBeenCalledTimes(1);
  501. expect(execFileMock).toHaveBeenCalledWith(
  502. "open",
  503. ["-a", "/Applications/QSpace Pro.app", tempDir],
  504. expect.any(Function),
  505. );
  506. });
  507. });