openInEditor.test.ts 16 KB

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