desktopLinuxDeepLinkRegistration.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. import {
  2. chmodSync,
  3. existsSync,
  4. mkdirSync,
  5. mkdtempSync,
  6. readFileSync,
  7. rmSync,
  8. writeFileSync,
  9. } from "node:fs";
  10. import { tmpdir } from "node:os";
  11. import { dirname, join } from "node:path";
  12. import { describe, expect, it } from "vitest";
  13. type CommandCall = { command: string; args: string[] };
  14. function readPngSize(path: string): { width: number; height: number } {
  15. const png = readFileSync(path);
  16. expect(png.subarray(0, 8)).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
  17. return {
  18. width: png.readUInt32BE(16),
  19. height: png.readUInt32BE(20),
  20. };
  21. }
  22. describe("desktop Linux deep link registration helpers", () => {
  23. it("prefers the AppImage path for protocol desktop entry Exec", async () => {
  24. const { createLinuxDeepLinkDesktopEntry, resolveLinuxDeepLinkCommand } =
  25. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  26. const command = resolveLinuxDeepLinkCommand({
  27. env: { APPIMAGE: "/home/alice/Downloads/ZCode-2.8.0-linux-x64.AppImage" },
  28. executablePath: "/tmp/.mount_ZCode/zcode",
  29. });
  30. const entry = createLinuxDeepLinkDesktopEntry(command);
  31. expect(command.executablePath).toBe("/home/alice/Downloads/ZCode-2.8.0-linux-x64.AppImage");
  32. expect(entry).toContain('Exec="/home/alice/Downloads/ZCode-2.8.0-linux-x64.AppImage" %U');
  33. expect(entry).toContain("MimeType=x-scheme-handler/zcode;");
  34. });
  35. it("keeps AppImage sandbox and GPU launch switches for protocol callbacks", async () => {
  36. const { createLinuxDeepLinkDesktopEntry, resolveLinuxDeepLinkCommand } =
  37. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  38. const command = resolveLinuxDeepLinkCommand({
  39. env: { APPIMAGE: "/home/alice/Applications/ZCode.AppImage" },
  40. executablePath: "/tmp/.mount_ZCode/zcode",
  41. argv: [
  42. "/tmp/.mount_ZCode/zcode",
  43. "--no-sandbox",
  44. "--disable-gpu",
  45. "--disable-software-rasterizer",
  46. "--use-gl=swiftshader",
  47. "--remote-debugging-port=9229",
  48. "zcode://oauth/callback?code=1&state=s",
  49. "/home/alice/project",
  50. ],
  51. });
  52. const entry = createLinuxDeepLinkDesktopEntry(command);
  53. expect(command.args).toEqual([
  54. "--no-sandbox",
  55. "--disable-gpu",
  56. "--disable-software-rasterizer",
  57. "--use-gl=swiftshader",
  58. ]);
  59. expect(entry).toContain(
  60. 'Exec="/home/alice/Applications/ZCode.AppImage" "--no-sandbox" "--disable-gpu" "--disable-software-rasterizer" "--use-gl=swiftshader" %U',
  61. );
  62. expect(entry).not.toContain("remote-debugging-port");
  63. expect(entry).not.toContain("oauth/callback");
  64. expect(entry).not.toContain("/home/alice/project");
  65. });
  66. it("does not persist launch switches for non-AppImage Linux installs", async () => {
  67. const { createLinuxDeepLinkDesktopEntry, resolveLinuxDeepLinkCommand } =
  68. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  69. const command = resolveLinuxDeepLinkCommand({
  70. env: {},
  71. executablePath: "/opt/ZCode/zcode",
  72. argv: ["/opt/ZCode/zcode", "--no-sandbox", "--disable-gpu"],
  73. });
  74. const entry = createLinuxDeepLinkDesktopEntry(command);
  75. expect(command).toEqual({ executablePath: "/opt/ZCode/zcode", args: [] });
  76. expect(entry).toContain('Exec="/opt/ZCode/zcode" %U');
  77. });
  78. it("escapes desktop Exec paths before writing user-level handlers", async () => {
  79. const { createLinuxDeepLinkDesktopEntry } =
  80. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  81. const entry = createLinuxDeepLinkDesktopEntry({
  82. executablePath: '/home/alice/Downloads/ZCode "Nightly".AppImage',
  83. });
  84. expect(entry).toContain('Exec="/home/alice/Downloads/ZCode \\"Nightly\\".AppImage" %U');
  85. });
  86. it("writes the Preview product name into the shared Linux protocol handler", async () => {
  87. const { createLinuxDeepLinkDesktopEntry } =
  88. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  89. const entry = createLinuxDeepLinkDesktopEntry({
  90. executablePath: "/opt/ZCode Preview/zcode-preview",
  91. productName: "ZCode Preview",
  92. });
  93. expect(entry).toContain("Name=ZCode Preview");
  94. expect(entry).toContain("StartupWMClass=ZCode Preview");
  95. expect(entry).toContain('Exec="/opt/ZCode Preview/zcode-preview" %U');
  96. expect(entry).toContain("MimeType=x-scheme-handler/zcode;");
  97. });
  98. it("escapes AppImage callback switches before writing desktop Exec", async () => {
  99. const { createLinuxDeepLinkDesktopEntry } =
  100. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  101. const entry = createLinuxDeepLinkDesktopEntry({
  102. executablePath: "/home/alice/Downloads/ZCode.AppImage",
  103. args: ['--disable-features=UseOzonePlatform,"Quoted"'],
  104. });
  105. expect(entry).toContain(
  106. 'Exec="/home/alice/Downloads/ZCode.AppImage" "--disable-features=UseOzonePlatform,\\"Quoted\\"" %U',
  107. );
  108. });
  109. it("installs a user-level hicolor icon only for AppImage launches", async () => {
  110. const { resolveLinuxUserDataDir } =
  111. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  112. const { installLinuxAppImageDesktopIcon, shouldInstallAppImageDesktopIcon } =
  113. await import("../src/main/desktopLinuxAppImageIcon.js");
  114. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-icon-"));
  115. const iconSourcePath = join(import.meta.dirname, "..", "build", "icons", "512x512.png");
  116. const homeDir = join(tempRoot, "home");
  117. const dataDir = resolveLinuxUserDataDir({ homeDir });
  118. const commandCalls: CommandCall[] = [];
  119. try {
  120. expect(readPngSize(iconSourcePath)).toEqual({ width: 512, height: 512 });
  121. expect(
  122. shouldInstallAppImageDesktopIcon({
  123. env: { APPIMAGE: "/home/alice/Applications/ZCode.AppImage" },
  124. iconSourcePath,
  125. }),
  126. ).toBe(true);
  127. expect(shouldInstallAppImageDesktopIcon({ env: {}, iconSourcePath })).toBe(false);
  128. const result = installLinuxAppImageDesktopIcon({
  129. dataDir,
  130. iconSourcePath,
  131. logger: { info: () => undefined, warn: () => undefined },
  132. runCommand: (command, args) => {
  133. commandCalls.push({ command, args });
  134. return { status: 0, stderr: "" };
  135. },
  136. });
  137. expect(result).toEqual({
  138. iconFilePath: join(dataDir, "icons", "hicolor", "512x512", "apps", "zcode.png"),
  139. installed: true,
  140. changed: true,
  141. });
  142. expect(existsSync(result.iconFilePath)).toBe(true);
  143. expect(readPngSize(result.iconFilePath)).toEqual({ width: 512, height: 512 });
  144. expect(commandCalls).toEqual([
  145. {
  146. command: "gtk-update-icon-cache",
  147. args: ["-f", "-t", join(dataDir, "icons", "hicolor")],
  148. },
  149. ]);
  150. } finally {
  151. rmSync(tempRoot, { force: true, recursive: true });
  152. }
  153. });
  154. it("uses XDG_DATA_HOME for user-level desktop entries and icons", async () => {
  155. const { resolveLinuxUserDataDir } =
  156. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  157. expect(
  158. resolveLinuxUserDataDir({
  159. env: { XDG_DATA_HOME: "/tmp/xdg-data" },
  160. homeDir: "/home/alice",
  161. }),
  162. ).toBe("/tmp/xdg-data");
  163. expect(resolveLinuxUserDataDir({ env: { XDG_DATA_HOME: " " }, homeDir: "/home/alice" })).toBe(
  164. join("/home/alice", ".local", "share"),
  165. );
  166. });
  167. it("keeps desktop entry registration when optional AppImage icon install fails", async () => {
  168. const { registerLinuxDeepLinkProtocol } =
  169. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  170. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-registration-"));
  171. const homeDir = join(tempRoot, "home");
  172. const badIconSourcePath = join(tempRoot, "icon-source-directory");
  173. const warnings: unknown[][] = [];
  174. const commandCalls: CommandCall[] = [];
  175. try {
  176. mkdirSync(badIconSourcePath, { recursive: true });
  177. registerLinuxDeepLinkProtocol({
  178. executablePath: "/tmp/.mount_ZCode/zcode",
  179. homeDir,
  180. iconSourcePath: badIconSourcePath,
  181. env: { APPIMAGE: "/home/alice/Applications/ZCode.AppImage" },
  182. // 固定系统级目录为空,避免测试机恰好装了 ZCode 系统包时走清理分支。
  183. systemApplicationDirs: [join(tempRoot, "empty-system-applications")],
  184. logger: {
  185. info: () => undefined,
  186. warn: (...args: unknown[]) => warnings.push(args),
  187. },
  188. runCommand: (command, args) => {
  189. commandCalls.push({ command, args });
  190. return { status: 0, stderr: "" };
  191. },
  192. });
  193. const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
  194. expect(existsSync(desktopFilePath)).toBe(true);
  195. expect(readFileSync(desktopFilePath, "utf8")).toContain(
  196. 'Exec="/home/alice/Applications/ZCode.AppImage" %U',
  197. );
  198. expect(
  199. warnings.some(([message]) => message === "[deep-link] Linux AppImage 图标安装失败,已降级"),
  200. ).toBe(true);
  201. expect(commandCalls).toEqual([
  202. {
  203. command: "update-desktop-database",
  204. args: [join(homeDir, ".local", "share", "applications")],
  205. },
  206. {
  207. command: "xdg-mime",
  208. args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
  209. },
  210. ]);
  211. } finally {
  212. rmSync(tempRoot, { force: true, recursive: true });
  213. }
  214. });
  215. it("resolves system application dirs from XDG_DATA_DIRS with spec defaults", async () => {
  216. const { resolveLinuxSystemApplicationDirs } =
  217. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  218. expect(
  219. resolveLinuxSystemApplicationDirs({
  220. XDG_DATA_DIRS: " /opt/custom/share :/usr/share: ",
  221. }),
  222. ).toEqual([join("/opt/custom/share", "applications"), join("/usr/share", "applications")]);
  223. expect(resolveLinuxSystemApplicationDirs({ XDG_DATA_DIRS: "::" })).toEqual([
  224. join("/usr/local/share", "applications"),
  225. join("/usr/share", "applications"),
  226. ]);
  227. expect(resolveLinuxSystemApplicationDirs()).toEqual([
  228. join("/usr/local/share", "applications"),
  229. join("/usr/share", "applications"),
  230. ]);
  231. });
  232. it("removes the stale owned user-level entry when a system-level entry exists", async () => {
  233. const { registerLinuxDeepLinkProtocol } =
  234. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  235. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-system-entry-"));
  236. const homeDir = join(tempRoot, "home");
  237. const systemApplicationsDir = join(tempRoot, "system", "applications");
  238. const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
  239. const infos: unknown[][] = [];
  240. const commandCalls: CommandCall[] = [];
  241. try {
  242. // 模拟 rpm/deb 安装产物:/usr/share/applications/zcode.desktop。
  243. mkdirSync(systemApplicationsDir, { recursive: true });
  244. writeFileSync(
  245. join(systemApplicationsDir, "zcode.desktop"),
  246. "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
  247. "utf8",
  248. );
  249. // 模拟旧 AppImage 时代遗留的用户级条目(含归属标记 Comment 行)。
  250. mkdirSync(dirname(desktopFilePath), { recursive: true });
  251. writeFileSync(
  252. desktopFilePath,
  253. [
  254. "[Desktop Entry]",
  255. "Name=ZCode",
  256. "Comment=ZCode Desktop App",
  257. 'Exec="/home/alice/Downloads/ZCode-2.8.0-linux-x64.AppImage" %U',
  258. "MimeType=x-scheme-handler/zcode;",
  259. "",
  260. ].join("\n"),
  261. "utf8",
  262. );
  263. registerLinuxDeepLinkProtocol({
  264. executablePath: "/opt/ZCode/zcode",
  265. homeDir,
  266. env: {},
  267. systemApplicationDirs: [systemApplicationsDir],
  268. logger: {
  269. info: (...args: unknown[]) => infos.push(args),
  270. warn: () => undefined,
  271. },
  272. runCommand: (command, args) => {
  273. commandCalls.push({ command, args });
  274. return { status: 0, stderr: "" };
  275. },
  276. });
  277. // 用户级遗留条目必须被清掉,让系统级条目在 XDG 解析中生效。
  278. expect(existsSync(desktopFilePath)).toBe(false);
  279. expect(commandCalls).toEqual([
  280. {
  281. command: "update-desktop-database",
  282. args: [join(homeDir, ".local", "share", "applications")],
  283. },
  284. {
  285. command: "xdg-mime",
  286. args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
  287. },
  288. ]);
  289. expect(
  290. infos.some(([message]) => message === "[deep-link] Linux 系统级 desktop entry 已存在"),
  291. ).toBe(true);
  292. } finally {
  293. rmSync(tempRoot, { force: true, recursive: true });
  294. }
  295. });
  296. it("keeps a custom user-level entry untouched when a system-level entry exists", async () => {
  297. const { registerLinuxDeepLinkProtocol } =
  298. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  299. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-custom-entry-"));
  300. const homeDir = join(tempRoot, "home");
  301. const systemApplicationsDir = join(tempRoot, "system", "applications");
  302. const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
  303. const warnings: unknown[][] = [];
  304. try {
  305. mkdirSync(systemApplicationsDir, { recursive: true });
  306. writeFileSync(
  307. join(systemApplicationsDir, "zcode.desktop"),
  308. "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
  309. "utf8",
  310. );
  311. // 用户手写的自定义条目:没有我们的归属标记,不应被静默删除。
  312. mkdirSync(dirname(desktopFilePath), { recursive: true });
  313. const customEntry =
  314. "[Desktop Entry]\nName=ZCode\nComment=Custom wrapper\nExec=/home/alice/wrap.sh %U\n";
  315. writeFileSync(desktopFilePath, customEntry, "utf8");
  316. registerLinuxDeepLinkProtocol({
  317. executablePath: "/opt/ZCode/zcode",
  318. homeDir,
  319. env: {},
  320. systemApplicationDirs: [systemApplicationsDir],
  321. logger: {
  322. info: () => undefined,
  323. warn: (...args: unknown[]) => warnings.push(args),
  324. },
  325. runCommand: () => ({ status: 0, stderr: "" }),
  326. });
  327. expect(existsSync(desktopFilePath)).toBe(true);
  328. expect(readFileSync(desktopFilePath, "utf8")).toBe(customEntry);
  329. expect(
  330. warnings.some(
  331. ([message]) =>
  332. message === "[deep-link] Linux 用户级 zcode.desktop 非本应用写入,保留不清理",
  333. ),
  334. ).toBe(true);
  335. } finally {
  336. rmSync(tempRoot, { force: true, recursive: true });
  337. }
  338. });
  339. it("does not shadow a system-level entry for AppImage launches", async () => {
  340. const { registerLinuxDeepLinkProtocol } =
  341. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  342. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-appimage-system-"));
  343. const homeDir = join(tempRoot, "home");
  344. const systemApplicationsDir = join(tempRoot, "system", "applications");
  345. const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
  346. const iconSourcePath = join(import.meta.dirname, "..", "build", "icons", "512x512.png");
  347. const commandCalls: CommandCall[] = [];
  348. try {
  349. mkdirSync(systemApplicationsDir, { recursive: true });
  350. writeFileSync(
  351. join(systemApplicationsDir, "zcode.desktop"),
  352. "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
  353. "utf8",
  354. );
  355. registerLinuxDeepLinkProtocol({
  356. executablePath: "/tmp/.mount_ZCode/zcode",
  357. homeDir,
  358. iconSourcePath,
  359. env: { APPIMAGE: "/home/alice/Applications/ZCode.AppImage" },
  360. systemApplicationDirs: [systemApplicationsDir],
  361. logger: { info: () => undefined, warn: () => undefined },
  362. runCommand: (command, args) => {
  363. commandCalls.push({ command, args });
  364. return { status: 0, stderr: "" };
  365. },
  366. });
  367. // AppImage 不得再写用户级同名条目遮蔽系统级,也不安装用户级图标。
  368. expect(existsSync(desktopFilePath)).toBe(false);
  369. expect(
  370. existsSync(
  371. join(homeDir, ".local", "share", "icons", "hicolor", "512x512", "apps", "zcode.png"),
  372. ),
  373. ).toBe(false);
  374. expect(commandCalls).toEqual([
  375. {
  376. command: "update-desktop-database",
  377. args: [join(homeDir, ".local", "share", "applications")],
  378. },
  379. {
  380. command: "xdg-mime",
  381. args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
  382. },
  383. ]);
  384. } finally {
  385. rmSync(tempRoot, { force: true, recursive: true });
  386. }
  387. });
  388. it("still writes the user-level entry when no system-level entry exists", async () => {
  389. const { registerLinuxDeepLinkProtocol } =
  390. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  391. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-no-system-"));
  392. const homeDir = join(tempRoot, "home");
  393. const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
  394. try {
  395. registerLinuxDeepLinkProtocol({
  396. executablePath: "/opt/ZCode/zcode",
  397. homeDir,
  398. env: {},
  399. systemApplicationDirs: [join(tempRoot, "empty-system-applications")],
  400. logger: { info: () => undefined, warn: () => undefined },
  401. runCommand: () => ({ status: 0, stderr: "" }),
  402. });
  403. expect(existsSync(desktopFilePath)).toBe(true);
  404. expect(readFileSync(desktopFilePath, "utf8")).toContain('Exec="/opt/ZCode/zcode" %U');
  405. } finally {
  406. rmSync(tempRoot, { force: true, recursive: true });
  407. }
  408. });
  409. it("ignores non-regular system-level paths when probing for shadow entries", async () => {
  410. const { registerLinuxDeepLinkProtocol } =
  411. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  412. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-dir-system-"));
  413. const homeDir = join(tempRoot, "home");
  414. // 系统目录下的 zcode.desktop 是一个目录而非普通文件,不得视为有效系统条目。
  415. const systemApplicationsDir = join(tempRoot, "system", "applications");
  416. const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
  417. try {
  418. mkdirSync(join(systemApplicationsDir, "zcode.desktop"), { recursive: true });
  419. registerLinuxDeepLinkProtocol({
  420. executablePath: "/opt/ZCode/zcode",
  421. homeDir,
  422. env: {},
  423. systemApplicationDirs: [systemApplicationsDir],
  424. logger: { info: () => undefined, warn: () => undefined },
  425. runCommand: () => ({ status: 0, stderr: "" }),
  426. });
  427. // 病态路径不抑制用户级注册。
  428. expect(existsSync(desktopFilePath)).toBe(true);
  429. } finally {
  430. rmSync(tempRoot, { force: true, recursive: true });
  431. }
  432. });
  433. it("keeps an unreadable user-level entry and continues protocol registration", async () => {
  434. const { registerLinuxDeepLinkProtocol } =
  435. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  436. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-unreadable-"));
  437. const homeDir = join(tempRoot, "home");
  438. const systemApplicationsDir = join(tempRoot, "system", "applications");
  439. const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
  440. const warnings: unknown[][] = [];
  441. const commandCalls: CommandCall[] = [];
  442. try {
  443. mkdirSync(systemApplicationsDir, { recursive: true });
  444. writeFileSync(
  445. join(systemApplicationsDir, "zcode.desktop"),
  446. "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
  447. "utf8",
  448. );
  449. mkdirSync(dirname(desktopFilePath), { recursive: true });
  450. writeFileSync(desktopFilePath, "unreadable-placeholder", "utf8");
  451. // chmod 000 让 readFileSync 抛 EACCES:归属无法确认时必须保守保留。
  452. chmodSync(desktopFilePath, 0o000);
  453. registerLinuxDeepLinkProtocol({
  454. executablePath: "/opt/ZCode/zcode",
  455. homeDir,
  456. env: {},
  457. systemApplicationDirs: [systemApplicationsDir],
  458. logger: {
  459. info: () => undefined,
  460. warn: (...args: unknown[]) => warnings.push(args),
  461. },
  462. runCommand: (command, args) => {
  463. commandCalls.push({ command, args });
  464. return { status: 0, stderr: "" };
  465. },
  466. });
  467. expect(existsSync(desktopFilePath)).toBe(true);
  468. expect(
  469. warnings.some(
  470. ([message]) =>
  471. message === "[deep-link] Linux 用户级 zcode.desktop 非本应用写入,保留不清理",
  472. ),
  473. ).toBe(true);
  474. // 归属识别失败只降级,协议注册命令仍完整执行。
  475. expect(commandCalls).toEqual([
  476. {
  477. command: "update-desktop-database",
  478. args: [join(homeDir, ".local", "share", "applications")],
  479. },
  480. {
  481. command: "xdg-mime",
  482. args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
  483. },
  484. ]);
  485. } finally {
  486. chmodSync(desktopFilePath, 0o700);
  487. rmSync(tempRoot, { force: true, recursive: true });
  488. }
  489. });
  490. it("recognizes ownership markers with CRLF line endings", async () => {
  491. const { registerLinuxDeepLinkProtocol } =
  492. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  493. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-crlf-"));
  494. const homeDir = join(tempRoot, "home");
  495. const systemApplicationsDir = join(tempRoot, "system", "applications");
  496. const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
  497. const infos: unknown[][] = [];
  498. try {
  499. mkdirSync(systemApplicationsDir, { recursive: true });
  500. writeFileSync(
  501. join(systemApplicationsDir, "zcode.desktop"),
  502. "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
  503. "utf8",
  504. );
  505. // 旧版本写出的 LF 条目被 Windows 风格工具改写为 CRLF 后仍应识别为可清理。
  506. mkdirSync(dirname(desktopFilePath), { recursive: true });
  507. writeFileSync(
  508. desktopFilePath,
  509. [
  510. "[Desktop Entry]",
  511. "Name=ZCode",
  512. "Comment=ZCode Desktop App",
  513. 'Exec="/home/alice/Downloads/ZCode.AppImage" %U',
  514. "MimeType=x-scheme-handler/zcode;",
  515. "",
  516. ].join("\r\n"),
  517. "utf8",
  518. );
  519. registerLinuxDeepLinkProtocol({
  520. executablePath: "/opt/ZCode/zcode",
  521. homeDir,
  522. env: {},
  523. systemApplicationDirs: [systemApplicationsDir],
  524. logger: {
  525. info: (...args: unknown[]) => infos.push(args),
  526. warn: () => undefined,
  527. },
  528. runCommand: () => ({ status: 0, stderr: "" }),
  529. });
  530. expect(existsSync(desktopFilePath)).toBe(false);
  531. expect(
  532. infos.some(
  533. ([message]) => message === "[deep-link] 已清理遗留的用户级 zcode.desktop,恢复系统级条目",
  534. ),
  535. ).toBe(true);
  536. } finally {
  537. rmSync(tempRoot, { force: true, recursive: true });
  538. }
  539. });
  540. // Bugfix:本用例靠 chmod 0o500 去掉目录写权限让 rmSync 抛 EPERM,Windows 的 chmod
  541. // 对目录是 no-op,删除照样成功,制造不出"删除失败"场景,本地 Windows 上必挂;
  542. // 降级路径由 Linux/macOS(含 CI)继续覆盖,Windows 跳过。
  543. it.skipIf(process.platform === "win32")(
  544. "continues protocol registration when removing the stale entry fails",
  545. async () => {
  546. const { registerLinuxDeepLinkProtocol } =
  547. await import("../src/main/desktopLinuxDeepLinkRegistration.js");
  548. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-rm-fail-"));
  549. const homeDir = join(tempRoot, "home");
  550. const systemApplicationsDir = join(tempRoot, "system", "applications");
  551. const applicationsDir = join(homeDir, ".local", "share", "applications");
  552. const desktopFilePath = join(applicationsDir, "zcode.desktop");
  553. const warnings: unknown[][] = [];
  554. const commandCalls: CommandCall[] = [];
  555. try {
  556. mkdirSync(systemApplicationsDir, { recursive: true });
  557. writeFileSync(
  558. join(systemApplicationsDir, "zcode.desktop"),
  559. "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
  560. "utf8",
  561. );
  562. mkdirSync(applicationsDir, { recursive: true });
  563. writeFileSync(
  564. desktopFilePath,
  565. '[Desktop Entry]\nComment=ZCode Desktop App\nExec="/old/ZCode.AppImage" %U\n',
  566. "utf8",
  567. );
  568. // 目录去掉写权限后 rmSync 失败(EPERM):删除失败必须只降级,不得抛出或阻断注册。
  569. chmodSync(applicationsDir, 0o500);
  570. registerLinuxDeepLinkProtocol({
  571. executablePath: "/opt/ZCode/zcode",
  572. homeDir,
  573. env: {},
  574. systemApplicationDirs: [systemApplicationsDir],
  575. logger: {
  576. info: () => undefined,
  577. warn: (...args: unknown[]) => warnings.push(args),
  578. },
  579. runCommand: (command, args) => {
  580. commandCalls.push({ command, args });
  581. return { status: 0, stderr: "" };
  582. },
  583. });
  584. expect(existsSync(desktopFilePath)).toBe(true);
  585. expect(
  586. warnings.some(([message]) => message === "[deep-link] 清理遗留用户级 zcode.desktop 失败"),
  587. ).toBe(true);
  588. expect(commandCalls).toEqual([
  589. {
  590. command: "update-desktop-database",
  591. args: [applicationsDir],
  592. },
  593. {
  594. command: "xdg-mime",
  595. args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
  596. },
  597. ]);
  598. } finally {
  599. chmodSync(applicationsDir, 0o700);
  600. rmSync(tempRoot, { force: true, recursive: true });
  601. }
  602. },
  603. );
  604. });