Преглед изворни кода

build(desktop): Windows-only 精简——移除 mac/linux 打包配置与专属资产

- electron-builder.config.js:删除 mac/dmg/linux/deb/rpm/pacman 段、mac 签名常量与
  pacman 依赖表、linux hicolor 图标资源分支
- bundle.mjs:打包目标仅支持 win,默认 x64;移除 mac/linux 别名与产物扩展名映射
- audit-bundle-size.mjs:体积预算仅保留 .exe
- 删除 mac 专属资产(entitlements*.plist、dmg 背景、icns 图标)与 linux 512x512 图标
- main/index.ts:deep link 图标统一回退通用 iconPath(原 Linux 专用资产已删)
- 删除 Linux deep link 注册测试(desktopLinuxDeepLinkRegistration.test.ts)

验证:typecheck/lint 通过;desktop 打包相关单测与裁剪前基线一致(原有
Windows 环境性失败不变,无新增失败)
wubinggen пре 1 месец
родитељ
комит
d83e150da4

BIN
packages/desktop/build/dmg_background.png


BIN
packages/desktop/build/dmg_background@2x.png


+ 0 - 10
packages/desktop/build/entitlements.helper.plist

@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-  <key>com.apple.security.cs.allow-jit</key>
-  <true/>
-  <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
-  <true/>
-</dict>
-</plist>

+ 0 - 12
packages/desktop/build/entitlements.mac.inherit.plist

@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-  <key>com.apple.security.cs.allow-jit</key>
-  <true/>
-  <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
-  <true/>
-  <key>com.apple.security.cs.disable-library-validation</key>
-  <true/>
-</dict>
-</plist>

+ 0 - 14
packages/desktop/build/entitlements.mac.plist

@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-  <key>com.apple.security.cs.allow-jit</key>
-  <true/>
-  <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
-  <true/>
-  <key>com.apple.security.cs.disable-library-validation</key>
-  <true/>
-  <key>com.apple.security.cs.allow-dyld-environment-variables</key>
-  <true/>
-</dict>
-</plist>

BIN
packages/desktop/build/icon.icns


BIN
packages/desktop/build/icon_installer.icns


BIN
packages/desktop/build/icons/512x512.png


+ 2 - 129
packages/desktop/electron-builder.config.js

@@ -58,11 +58,6 @@ const nativeSearchReleasePlan = resolveNativeSearchReleasePlan({
   platform: targetPlatform.os,
   arch: targetPlatform.arch,
 });
-const rawMacSigningIdentity = process.env.APPLE_SIGNING_IDENTITY || process.env.CSC_NAME;
-const macSigningIdentity =
-  rawMacSigningIdentity?.replace(/^Developer ID Application:\s*/, "") ?? null;
-const shouldEnableMacSigning =
-  process.env.ZCODE_ENABLE_MAC_SIGN === "1" && Boolean(macSigningIdentity);
 const workspaceRoot = resolve(import.meta.dirname, "../..");
 const desktopPackageRoot = import.meta.dirname;
 // Computer Use Helper(macOS .app、Windows runtime)只随真实 producer 打包;开源占位包下跳过随包资源与校验。
@@ -148,19 +143,6 @@ const REQUIRED_ASAR_RUNTIME_MODULES = [
   // 自动更新链路直接崩。ms 是叶子包,显式注入即可让 debug 在 app.asar 内稳定解析。
   "ms",
 ];
-// pacman 依赖必须使用 Arch 官方仓库中的包名。electron-builder 的历史默认集合包含
-// 已移除的 libappindicator-gtk3/http-parser,且缺少 Electron 实际需要的运行库;显式
-// 维护最小运行时闭包,避免 pacman -U 无法解析依赖或启动时才暴露缺库。
-const PACMAN_RUNTIME_DEPENDENCIES = [
-  "gtk3",
-  "nss",
-  "libxss",
-  "libxtst",
-  "libnotify",
-  "alsa-lib",
-  "mesa",
-  "xdg-utils",
-];
 
 const WINDOWS_INSTALL_MANIFEST_NAME = ".zcode-install-manifest";
 
@@ -220,18 +202,6 @@ const commandStdoutMaxBuffer = 64 * 1024 * 1024;
 // 产物后缀只标记后端环境(_TEST);身份靠 productName 区分,生产后端的 Preview 包没有后缀。
 const desktopArtifactEnvSuffix = resolveDesktopArtifactSuffix(process.env);
 
-// Preview 是内部签名测试包。CI 明确打开 macOS 签名时若没有身份,必须在生成未签名包前失败,
-// 避免“产物存在”被误认为已经走完和生产版相同的签名链路。
-if (
-  desktopProductIdentity.flavor === "preview" &&
-  process.env.ZCODE_ENABLE_MAC_SIGN === "1" &&
-  !macSigningIdentity
-) {
-  throw new Error(
-    "ZCode Preview macOS packaging requires APPLE_SIGNING_IDENTITY or CSC_NAME when ZCODE_ENABLE_MAC_SIGN=1",
-  );
-}
-
 const PACKAGING_PRUNE_PATTERNS = [
   "!**/*.map",
   "!**/*.pdb",
@@ -766,15 +736,6 @@ export default {
       from: "build/icon.png",
       to: "icon.png",
     },
-    ...(targetPlatform.os === "linux"
-      ? [
-          {
-            // AppImage 用户级 hicolor 图标安装使用真实 512x512 资源,避免目录标称尺寸和 PNG IHDR 不一致。
-            from: "build/icons/512x512.png",
-            to: "icon_512x512.png",
-          },
-        ]
-      : []),
     {
       // Windows 独立图标:开发态和打包态都统一走同一套任务栏/窗口图标资源。
       from: "build/icon_windows.png",
@@ -841,43 +802,7 @@ export default {
       schemes: ["zcode"],
     },
   ],
-  mac: {
-    target: ["dmg", "zip"],
-    category: "public.app-category.developer-tools",
-    artifactName: buildDesktopArtifactName("mac"),
-    extendInfo: {
-      NSAppleEventsUsageDescription: `${desktopProductIdentity.productName} needs Apple Events access to coordinate local automation workflows with user-approved desktop apps.`,
-      // 缺失该 key 时 macOS 会静默拒绝 CoreBluetooth 枚举,内置浏览器 Web Bluetooth
-      // 的设备选择器列表恒为空(实测 Chrome 有蓝牙隐私权限则正常)。
-      NSBluetoothAlwaysUsageDescription: `${desktopProductIdentity.productName} needs Bluetooth access to list nearby devices when a website you open in the embedded browser requests one.`,
-    },
-    // 预签名脚本走的是原生 codesign,要求完整的 "Developer ID Application: ..." 身份串;
-    // 但 electron-builder 的 mac.identity 在 26.x 下会拒绝带此前缀的名字。
-    // 这里仅对 electron-builder 侧做前缀归一化,避免本地预签名和最终 .app 签名互相打架。
-    // z-code 之前只有本地未签名打包配置,CI 即使注入了证书变量,
-    // electron-builder 也不会自动切到 hardened runtime / entitlement 这套发布参数。
-    // 这里显式收拢到环境开关,保证本地开发不被签名配置绑死,CI 发布时再按需打开。
-    identity: shouldEnableMacSigning ? macSigningIdentity : null,
-    // macOS 产物采用“build 阶段签名 + 独立公证阶段”的两段式流水线。
-    // 如果这里不显式关闭 electron-builder 内置 notarize,它会在 build 阶段读取 Apple 凭据后直接尝试公证,
-    // 并强制要求 APPLE_APP_SPECIFIC_PASSWORD,导致 build 还没产出 DMG 就提前失败。
-    notarize: false,
-    hardenedRuntime: shouldEnableMacSigning,
-    gatekeeperAssess: false,
-    entitlements: "build/entitlements.mac.plist",
-    entitlementsInherit: "build/entitlements.mac.inherit.plist",
-    // runtime 可执行文件已在打包前的独立预签名阶段完成签名,
-    // electron-builder 在签主 app 时若继续深度扫描这些目录,会显著拉长 macOS codesign 时长。
-    // 这里按“任意前缀 + Contents/Resources”匹配绝对路径,避免 ^Contents/... 在 CI 中无法命中。
-    // 命中后可跳过已预签名目录的重复签名/遍历,同时保留主 app 与框架签名。
-    // CUA Helper 在独立 job 中已完成 Developer ID 签名和 notarization staple;
-    // electron-builder 若再次签名嵌套 Helper 会改变 CDHash,使最终用户包中的 staple 失效。
-    signIgnore: [
-      "[/\\\\]Contents[/\\\\]Resources[/\\\\]cua-helper([/\\\\]|$)",
-      "[/\\\\]Contents[/\\\\]Resources[/\\\\]glm([/\\\\]|$)",
-      "[/\\\\]Contents[/\\\\]Resources[/\\\\]tools([/\\\\]|$)",
-    ],
-  },
+  /* Windows-only 精简:原 macOS 打包段(dmg/zip、codesign/notarize/entitlements)已整体移除。 */
   win: {
     target: ["nsis"],
     artifactName: buildDesktopArtifactName("win"),
@@ -894,59 +819,7 @@ export default {
         }
       : {}),
   },
-  linux: {
-    target: ["AppImage", "deb", "rpm", "pacman"],
-    artifactName: buildDesktopArtifactName("linux"),
-    // desktop 包名是 scoped package(@zcode/desktop),electron-builder 默认会把
-    // Linux executable/Icon 推成 @zcodedesktop。部分桌面环境无法按这个 icon name 命中
-    // hicolor 图标,最终回退成系统齿轮。这里固定成稳定的小写名称,让 Icon=zcode
-    // 与 /usr/share/icons/hicolor/*/apps/zcode.png 保持一致。
-    executableName: desktopProductIdentity.linuxExecutableName,
-    category: "Development",
-    maintainer: "ZCode <dev@zcode.z.ai>",
-  },
-  deb: {
-    // 生产版与 Preview 必须是两个 dpkg package;只改可执行名仍会让安装器把另一版本当成升级替换。
-    packageName: desktopProductIdentity.linuxPackageName,
-  },
-  pacman: {
-    // 与 deb/rpm 保持相同的 flavor 隔离,避免 Preview/Production 被 pacman 当作同一包覆盖。
-    packageName: desktopProductIdentity.linuxPackageName,
-    // 显式列出 Arch 官方仓库可解析的 Electron 运行时依赖,替换 electron-builder
-    // 陈旧默认集合,避免安装阶段因已移除包名直接失败。
-    depends: PACMAN_RUNTIME_DEPENDENCIES,
-    // Electron Builder 默认把 pacman target 命名为 .pacman;Arch 原生包的标准扩展名是 .pkg.tar.zst。
-    artifactName: buildDesktopArtifactName("linux", "pkg.tar.zst"),
-  },
-  rpm: {
-    // 与 deb 同一约束:生产版与 Preview 必须是两个独立 rpm 包,否则 dnf 会把另一 flavor 当成升级替换。
-    // rpm 面向 RHEL 8+(glibc 2.28)分发;整包 glibc 下限由 node-pty prebuild 与 bfs/ugrep 抬到 2.28,
-    // Electron 41 主二进制只引用到 2.25,不会更高。fpm 产 rpm 需要构建机提供 rpmbuild 与 xz。
-    packageName: desktopProductIdentity.linuxPackageName,
-    // electron-builder 的 rpm 默认 Requires(gtk3/nss/libXtst 等)不包含 Electron ELF 实际
-    // DT_NEEDED 的 mesa-libgbm 与 alsa-lib;rockylinux:8 最小化容器实测装完后启动报
-    // libgbm.so.1 缺失。这里用 fpm 追加 -d(在默认 Requires 之后累积),不能用 depends——
-    // depends 会整组替换默认 Requires 集。
-    fpm: ["-d", "mesa-libgbm", "-d", "alsa-lib"],
-  },
-  dmg: {
-    // 当前安装包携带的运行时资源(尤其 agent node_modules)体积已超过默认 DMG 估算值。
-    // 之前依赖自动容量时,生成的 DMG 挂载卷只有约 1.9Gi,复制 .app 过程中会因为空间耗尽
-    // 丢失 Electron Framework 主二进制,安装后启动直接报 DYLD Library missing。
-    // 显式放大 DMG 容量,避免拷贝截断导致的“Framework 目录存在但核心文件缺失”。
-    size: "3200m",
-    // 使用自定义安装背景图。
-    background: "build/dmg_background.png",
-    // 安装盘图标统一使用安装专用素材,避免复用应用图标导致安装识别度不足。
-    icon: "build/icon_installer.icns",
-    contents: [
-      // 实验性调整:为隐藏资源文件显式指定图标坐标,尽量把它们移到角落区域。
-      { x: 640, y: 56, type: "file", path: ".background.tiff" },
-      { x: 640, y: 56, type: "file", path: ".VolumeIcon.icns" },
-      { x: 130, y: 220 },
-      { x: 410, y: 220, type: "link", path: "/Applications" },
-    ],
-  },
+  /* Windows-only 精简:原 Linux 打包段(AppImage/deb/rpm/pacman)与 dmg 段已整体移除。 */
   nsis: {
     oneClick: false,
     allowToChangeInstallationDirectory: true,

+ 1 - 4
packages/desktop/scripts/audit-bundle-size.mjs

@@ -21,11 +21,8 @@ if (!artifactPath) {
 const absoluteArtifactPath = resolve(artifactPath);
 const limitsMb = {
   default: 500,
-  ".dmg": 500,
-  ".zip": 500,
+  // Windows-only 精简:仅保留 .exe(NSIS 安装包)产物预算。
   ".exe": 500,
-  ".appimage": 500,
-  ".deb": 500,
 };
 
 function formatMiB(bytes) {

+ 9 - 38
packages/desktop/scripts/bundle.mjs

@@ -39,21 +39,17 @@ const runtimeModuleLookupRoots = [
   resolve(workspaceRoot, "node_modules", ".pnpm", "node_modules"),
 ];
 const pnpmCommand = "pnpm";
-const DEFAULT_TARGET_OS = "mac";
-const DEFAULT_TARGET_ARCH = "arm64";
+// Windows-only 精简:打包目标只支持 win,默认 x64。
+const DEFAULT_TARGET_OS = "win";
+const DEFAULT_TARGET_ARCH = "x64";
 const desktopDistDir = process.env.ZCODE_DESKTOP_DIST_DIR || "dist";
 const desktopDistRoot = resolve(desktopRoot, desktopDistDir);
 const desktopProductIdentity = resolveDesktopProductIdentity(process.env);
 
 const osAliasMap = new Map([
-  ["mac", "mac"],
-  ["macos", "mac"],
-  ["darwin", "mac"],
-  ["osx", "mac"],
   ["win", "win"],
   ["windows", "win"],
   ["win32", "win"],
-  ["linux", "linux"],
 ]);
 
 const archAliasMap = new Map([
@@ -65,9 +61,7 @@ const archAliasMap = new Map([
 ]);
 
 const osBuilderFlagMap = {
-  mac: "--mac",
   win: "--win",
-  linux: "--linux",
 };
 
 const archBuilderFlagMap = {
@@ -76,9 +70,7 @@ const archBuilderFlagMap = {
 };
 
 const artifactExtensionsByOs = {
-  mac: [".dmg", ".zip"],
   win: [".exe"],
-  linux: [".AppImage", ".deb", ".rpm", ".pkg.tar.zst"],
 };
 const artifactArchHintsByArch = {
   x64: ["x64", "x86_64", "amd64"],
@@ -253,12 +245,12 @@ function printHelp() {
 
 用法:
   pnpm bundle:desktop
-  pnpm bundle:desktop -- --os mac --arch x64
-  pnpm bundle:desktop -- linux arm64
+  pnpm bundle:desktop -- --os win --arch x64
+  pnpm bundle:desktop -- win arm64
 
 参数:
-  --os, -o <mac|win|linux>     目标操作系统,默认 mac
-  --arch, -a <x64|arm64>       目标 CPU 架构,默认 arm64
+  --os, -o <win>                目标操作系统(Windows-only 精简,仅支持 win),默认 win
+  --arch, -a <x64|arm64>       目标 CPU 架构,默认 x64
   --skip-prepare               跳过 prepare:runtime-assets
   --skip-build                 跳过 pnpm build
   --dry-run                    只打印最终命令,不执行打包
@@ -608,18 +600,7 @@ async function runElectronBuilderWithRetry(args, envPatch) {
 }
 
 function resolveAppAsarPath(os, arch) {
-  if (os === "mac") {
-    return resolve(
-      desktopRoot,
-      desktopDistDir,
-      arch === "arm64" ? "mac-arm64" : "mac",
-      `${desktopProductIdentity.productName}.app`,
-      "Contents",
-      "Resources",
-      "app.asar",
-    );
-  }
-
+  // Windows-only 精简:仅保留 win 产物路径(mac/linux 分支已移除)。
   if (os === "win") {
     return resolve(
       desktopRoot,
@@ -630,16 +611,6 @@ function resolveAppAsarPath(os, arch) {
     );
   }
 
-  if (os === "linux") {
-    return resolve(
-      desktopRoot,
-      desktopDistDir,
-      arch === "arm64" ? "linux-arm64-unpacked" : "linux-unpacked",
-      "resources",
-      "app.asar",
-    );
-  }
-
   throw new Error(`不支持的目标操作系统: ${os}`);
 }
 
@@ -661,7 +632,7 @@ function verifyPackagedRuntimeDependencies(os, arch) {
   );
   const asarEntries = asarEntriesWithPackState.map((entry) => entry.path);
 
-  const targetPlatformKey = `${os === "mac" ? "darwin" : os === "win" ? "win32" : os}-${arch}`;
+  const targetPlatformKey = `win32-${arch}`;
   const nativePackageViolations = findDesktopNativePackageViolations(
     asarEntriesWithPackState,
     targetPlatformKey,

+ 4 - 7
packages/desktop/src/main/index.ts

@@ -311,12 +311,9 @@ const iconPath =
     : app.isPackaged
       ? join(process.resourcesPath, "icon.png")
       : join(import.meta.dirname, "../../build/icon.png");
-const linuxDesktopIntegrationIconPath =
-  process.platform === "linux"
-    ? app.isPackaged
-      ? join(process.resourcesPath, "icon_512x512.png")
-      : join(import.meta.dirname, "../../build/icons/512x512.png")
-    : iconPath;
+// Windows-only 精简:原 Linux 桌面集成专用图标(build/icons/512x512.png)已随
+// Linux 打包段移除;deep link 的 iconPath 参数仅在 Linux 分支消费,统一回退通用图标。
+const deepLinkIconPath = iconPath;
 let currentApplicationLocale: Locale = DEFAULT_LOCALE;
 let closeToTrayOnWindows = true;
 // CR-01:托盘实例创建结果(模块级,关窗分支读取)。DBus 能力探测通过不等于 Electron
@@ -2017,7 +2014,7 @@ function createWindowInstance(startupBootstrap: StartupWindowBootstrap = {}) {
   return win;
 }
 
-registerDeepLinkProtocol(logger, { iconPath: linuxDesktopIntegrationIconPath });
+registerDeepLinkProtocol(logger, { iconPath: deepLinkIconPath });
 app.on("open-url", (event, url) => {
   event.preventDefault();
   const workspacePath = extractOpenWorkspacePathFromDeepLinkUrl(url);

+ 0 - 666
packages/desktop/test/desktopLinuxDeepLinkRegistration.test.ts

@@ -1,666 +0,0 @@
-import {
-  chmodSync,
-  existsSync,
-  mkdirSync,
-  mkdtempSync,
-  readFileSync,
-  rmSync,
-  writeFileSync,
-} from "node:fs";
-import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
-import { describe, expect, it } from "vitest";
-
-type CommandCall = { command: string; args: string[] };
-
-function readPngSize(path: string): { width: number; height: number } {
-  const png = readFileSync(path);
-  expect(png.subarray(0, 8)).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
-  return {
-    width: png.readUInt32BE(16),
-    height: png.readUInt32BE(20),
-  };
-}
-
-describe("desktop Linux deep link registration helpers", () => {
-  it("prefers the AppImage path for protocol desktop entry Exec", async () => {
-    const { createLinuxDeepLinkDesktopEntry, resolveLinuxDeepLinkCommand } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-
-    const command = resolveLinuxDeepLinkCommand({
-      env: { APPIMAGE: "/home/alice/Downloads/ZCode-2.8.0-linux-x64.AppImage" },
-      executablePath: "/tmp/.mount_ZCode/zcode",
-    });
-    const entry = createLinuxDeepLinkDesktopEntry(command);
-
-    expect(command.executablePath).toBe("/home/alice/Downloads/ZCode-2.8.0-linux-x64.AppImage");
-    expect(entry).toContain('Exec="/home/alice/Downloads/ZCode-2.8.0-linux-x64.AppImage" %U');
-    expect(entry).toContain("MimeType=x-scheme-handler/zcode;");
-  });
-
-  it("keeps AppImage sandbox and GPU launch switches for protocol callbacks", async () => {
-    const { createLinuxDeepLinkDesktopEntry, resolveLinuxDeepLinkCommand } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-
-    const command = resolveLinuxDeepLinkCommand({
-      env: { APPIMAGE: "/home/alice/Applications/ZCode.AppImage" },
-      executablePath: "/tmp/.mount_ZCode/zcode",
-      argv: [
-        "/tmp/.mount_ZCode/zcode",
-        "--no-sandbox",
-        "--disable-gpu",
-        "--disable-software-rasterizer",
-        "--use-gl=swiftshader",
-        "--remote-debugging-port=9229",
-        "zcode://oauth/callback?code=1&state=s",
-        "/home/alice/project",
-      ],
-    });
-    const entry = createLinuxDeepLinkDesktopEntry(command);
-
-    expect(command.args).toEqual([
-      "--no-sandbox",
-      "--disable-gpu",
-      "--disable-software-rasterizer",
-      "--use-gl=swiftshader",
-    ]);
-    expect(entry).toContain(
-      'Exec="/home/alice/Applications/ZCode.AppImage" "--no-sandbox" "--disable-gpu" "--disable-software-rasterizer" "--use-gl=swiftshader" %U',
-    );
-    expect(entry).not.toContain("remote-debugging-port");
-    expect(entry).not.toContain("oauth/callback");
-    expect(entry).not.toContain("/home/alice/project");
-  });
-
-  it("does not persist launch switches for non-AppImage Linux installs", async () => {
-    const { createLinuxDeepLinkDesktopEntry, resolveLinuxDeepLinkCommand } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-
-    const command = resolveLinuxDeepLinkCommand({
-      env: {},
-      executablePath: "/opt/ZCode/zcode",
-      argv: ["/opt/ZCode/zcode", "--no-sandbox", "--disable-gpu"],
-    });
-    const entry = createLinuxDeepLinkDesktopEntry(command);
-
-    expect(command).toEqual({ executablePath: "/opt/ZCode/zcode", args: [] });
-    expect(entry).toContain('Exec="/opt/ZCode/zcode" %U');
-  });
-
-  it("escapes desktop Exec paths before writing user-level handlers", async () => {
-    const { createLinuxDeepLinkDesktopEntry } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-
-    const entry = createLinuxDeepLinkDesktopEntry({
-      executablePath: '/home/alice/Downloads/ZCode "Nightly".AppImage',
-    });
-
-    expect(entry).toContain('Exec="/home/alice/Downloads/ZCode \\"Nightly\\".AppImage" %U');
-  });
-
-  it("writes the Preview product name into the shared Linux protocol handler", async () => {
-    const { createLinuxDeepLinkDesktopEntry } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-
-    const entry = createLinuxDeepLinkDesktopEntry({
-      executablePath: "/opt/ZCode Preview/zcode-preview",
-      productName: "ZCode Preview",
-    });
-
-    expect(entry).toContain("Name=ZCode Preview");
-    expect(entry).toContain("StartupWMClass=ZCode Preview");
-    expect(entry).toContain('Exec="/opt/ZCode Preview/zcode-preview" %U');
-    expect(entry).toContain("MimeType=x-scheme-handler/zcode;");
-  });
-
-  it("escapes AppImage callback switches before writing desktop Exec", async () => {
-    const { createLinuxDeepLinkDesktopEntry } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-
-    const entry = createLinuxDeepLinkDesktopEntry({
-      executablePath: "/home/alice/Downloads/ZCode.AppImage",
-      args: ['--disable-features=UseOzonePlatform,"Quoted"'],
-    });
-
-    expect(entry).toContain(
-      'Exec="/home/alice/Downloads/ZCode.AppImage" "--disable-features=UseOzonePlatform,\\"Quoted\\"" %U',
-    );
-  });
-
-  it("installs a user-level hicolor icon only for AppImage launches", async () => {
-    const { resolveLinuxUserDataDir } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const { installLinuxAppImageDesktopIcon, shouldInstallAppImageDesktopIcon } =
-      await import("../src/main/desktopLinuxAppImageIcon.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-icon-"));
-    const iconSourcePath = join(import.meta.dirname, "..", "build", "icons", "512x512.png");
-    const homeDir = join(tempRoot, "home");
-    const dataDir = resolveLinuxUserDataDir({ homeDir });
-    const commandCalls: CommandCall[] = [];
-
-    try {
-      expect(readPngSize(iconSourcePath)).toEqual({ width: 512, height: 512 });
-
-      expect(
-        shouldInstallAppImageDesktopIcon({
-          env: { APPIMAGE: "/home/alice/Applications/ZCode.AppImage" },
-          iconSourcePath,
-        }),
-      ).toBe(true);
-      expect(shouldInstallAppImageDesktopIcon({ env: {}, iconSourcePath })).toBe(false);
-
-      const result = installLinuxAppImageDesktopIcon({
-        dataDir,
-        iconSourcePath,
-        logger: { info: () => undefined, warn: () => undefined },
-        runCommand: (command, args) => {
-          commandCalls.push({ command, args });
-          return { status: 0, stderr: "" };
-        },
-      });
-
-      expect(result).toEqual({
-        iconFilePath: join(dataDir, "icons", "hicolor", "512x512", "apps", "zcode.png"),
-        installed: true,
-        changed: true,
-      });
-      expect(existsSync(result.iconFilePath)).toBe(true);
-      expect(readPngSize(result.iconFilePath)).toEqual({ width: 512, height: 512 });
-      expect(commandCalls).toEqual([
-        {
-          command: "gtk-update-icon-cache",
-          args: ["-f", "-t", join(dataDir, "icons", "hicolor")],
-        },
-      ]);
-    } finally {
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  it("uses XDG_DATA_HOME for user-level desktop entries and icons", async () => {
-    const { resolveLinuxUserDataDir } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-
-    expect(
-      resolveLinuxUserDataDir({
-        env: { XDG_DATA_HOME: "/tmp/xdg-data" },
-        homeDir: "/home/alice",
-      }),
-    ).toBe("/tmp/xdg-data");
-    expect(resolveLinuxUserDataDir({ env: { XDG_DATA_HOME: " " }, homeDir: "/home/alice" })).toBe(
-      join("/home/alice", ".local", "share"),
-    );
-  });
-
-  it("keeps desktop entry registration when optional AppImage icon install fails", async () => {
-    const { registerLinuxDeepLinkProtocol } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-registration-"));
-    const homeDir = join(tempRoot, "home");
-    const badIconSourcePath = join(tempRoot, "icon-source-directory");
-    const warnings: unknown[][] = [];
-    const commandCalls: CommandCall[] = [];
-
-    try {
-      mkdirSync(badIconSourcePath, { recursive: true });
-      registerLinuxDeepLinkProtocol({
-        executablePath: "/tmp/.mount_ZCode/zcode",
-        homeDir,
-        iconSourcePath: badIconSourcePath,
-        env: { APPIMAGE: "/home/alice/Applications/ZCode.AppImage" },
-        // 固定系统级目录为空,避免测试机恰好装了 ZCode 系统包时走清理分支。
-        systemApplicationDirs: [join(tempRoot, "empty-system-applications")],
-        logger: {
-          info: () => undefined,
-          warn: (...args: unknown[]) => warnings.push(args),
-        },
-        runCommand: (command, args) => {
-          commandCalls.push({ command, args });
-          return { status: 0, stderr: "" };
-        },
-      });
-
-      const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
-      expect(existsSync(desktopFilePath)).toBe(true);
-      expect(readFileSync(desktopFilePath, "utf8")).toContain(
-        'Exec="/home/alice/Applications/ZCode.AppImage" %U',
-      );
-      expect(
-        warnings.some(([message]) => message === "[deep-link] Linux AppImage 图标安装失败,已降级"),
-      ).toBe(true);
-      expect(commandCalls).toEqual([
-        {
-          command: "update-desktop-database",
-          args: [join(homeDir, ".local", "share", "applications")],
-        },
-        {
-          command: "xdg-mime",
-          args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
-        },
-      ]);
-    } finally {
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  it("resolves system application dirs from XDG_DATA_DIRS with spec defaults", async () => {
-    const { resolveLinuxSystemApplicationDirs } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-
-    expect(
-      resolveLinuxSystemApplicationDirs({
-        XDG_DATA_DIRS: " /opt/custom/share :/usr/share: ",
-      }),
-    ).toEqual([join("/opt/custom/share", "applications"), join("/usr/share", "applications")]);
-    expect(resolveLinuxSystemApplicationDirs({ XDG_DATA_DIRS: "::" })).toEqual([
-      join("/usr/local/share", "applications"),
-      join("/usr/share", "applications"),
-    ]);
-    expect(resolveLinuxSystemApplicationDirs()).toEqual([
-      join("/usr/local/share", "applications"),
-      join("/usr/share", "applications"),
-    ]);
-  });
-
-  it("removes the stale owned user-level entry when a system-level entry exists", async () => {
-    const { registerLinuxDeepLinkProtocol } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-system-entry-"));
-    const homeDir = join(tempRoot, "home");
-    const systemApplicationsDir = join(tempRoot, "system", "applications");
-    const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
-    const infos: unknown[][] = [];
-    const commandCalls: CommandCall[] = [];
-
-    try {
-      // 模拟 rpm/deb 安装产物:/usr/share/applications/zcode.desktop。
-      mkdirSync(systemApplicationsDir, { recursive: true });
-      writeFileSync(
-        join(systemApplicationsDir, "zcode.desktop"),
-        "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
-        "utf8",
-      );
-      // 模拟旧 AppImage 时代遗留的用户级条目(含归属标记 Comment 行)。
-      mkdirSync(dirname(desktopFilePath), { recursive: true });
-      writeFileSync(
-        desktopFilePath,
-        [
-          "[Desktop Entry]",
-          "Name=ZCode",
-          "Comment=ZCode Desktop App",
-          'Exec="/home/alice/Downloads/ZCode-2.8.0-linux-x64.AppImage" %U',
-          "MimeType=x-scheme-handler/zcode;",
-          "",
-        ].join("\n"),
-        "utf8",
-      );
-
-      registerLinuxDeepLinkProtocol({
-        executablePath: "/opt/ZCode/zcode",
-        homeDir,
-        env: {},
-        systemApplicationDirs: [systemApplicationsDir],
-        logger: {
-          info: (...args: unknown[]) => infos.push(args),
-          warn: () => undefined,
-        },
-        runCommand: (command, args) => {
-          commandCalls.push({ command, args });
-          return { status: 0, stderr: "" };
-        },
-      });
-
-      // 用户级遗留条目必须被清掉,让系统级条目在 XDG 解析中生效。
-      expect(existsSync(desktopFilePath)).toBe(false);
-      expect(commandCalls).toEqual([
-        {
-          command: "update-desktop-database",
-          args: [join(homeDir, ".local", "share", "applications")],
-        },
-        {
-          command: "xdg-mime",
-          args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
-        },
-      ]);
-      expect(
-        infos.some(([message]) => message === "[deep-link] Linux 系统级 desktop entry 已存在"),
-      ).toBe(true);
-    } finally {
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  it("keeps a custom user-level entry untouched when a system-level entry exists", async () => {
-    const { registerLinuxDeepLinkProtocol } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-custom-entry-"));
-    const homeDir = join(tempRoot, "home");
-    const systemApplicationsDir = join(tempRoot, "system", "applications");
-    const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
-    const warnings: unknown[][] = [];
-
-    try {
-      mkdirSync(systemApplicationsDir, { recursive: true });
-      writeFileSync(
-        join(systemApplicationsDir, "zcode.desktop"),
-        "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
-        "utf8",
-      );
-      // 用户手写的自定义条目:没有我们的归属标记,不应被静默删除。
-      mkdirSync(dirname(desktopFilePath), { recursive: true });
-      const customEntry =
-        "[Desktop Entry]\nName=ZCode\nComment=Custom wrapper\nExec=/home/alice/wrap.sh %U\n";
-      writeFileSync(desktopFilePath, customEntry, "utf8");
-
-      registerLinuxDeepLinkProtocol({
-        executablePath: "/opt/ZCode/zcode",
-        homeDir,
-        env: {},
-        systemApplicationDirs: [systemApplicationsDir],
-        logger: {
-          info: () => undefined,
-          warn: (...args: unknown[]) => warnings.push(args),
-        },
-        runCommand: () => ({ status: 0, stderr: "" }),
-      });
-
-      expect(existsSync(desktopFilePath)).toBe(true);
-      expect(readFileSync(desktopFilePath, "utf8")).toBe(customEntry);
-      expect(
-        warnings.some(
-          ([message]) =>
-            message === "[deep-link] Linux 用户级 zcode.desktop 非本应用写入,保留不清理",
-        ),
-      ).toBe(true);
-    } finally {
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  it("does not shadow a system-level entry for AppImage launches", async () => {
-    const { registerLinuxDeepLinkProtocol } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-appimage-system-"));
-    const homeDir = join(tempRoot, "home");
-    const systemApplicationsDir = join(tempRoot, "system", "applications");
-    const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
-    const iconSourcePath = join(import.meta.dirname, "..", "build", "icons", "512x512.png");
-    const commandCalls: CommandCall[] = [];
-
-    try {
-      mkdirSync(systemApplicationsDir, { recursive: true });
-      writeFileSync(
-        join(systemApplicationsDir, "zcode.desktop"),
-        "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
-        "utf8",
-      );
-
-      registerLinuxDeepLinkProtocol({
-        executablePath: "/tmp/.mount_ZCode/zcode",
-        homeDir,
-        iconSourcePath,
-        env: { APPIMAGE: "/home/alice/Applications/ZCode.AppImage" },
-        systemApplicationDirs: [systemApplicationsDir],
-        logger: { info: () => undefined, warn: () => undefined },
-        runCommand: (command, args) => {
-          commandCalls.push({ command, args });
-          return { status: 0, stderr: "" };
-        },
-      });
-
-      // AppImage 不得再写用户级同名条目遮蔽系统级,也不安装用户级图标。
-      expect(existsSync(desktopFilePath)).toBe(false);
-      expect(
-        existsSync(
-          join(homeDir, ".local", "share", "icons", "hicolor", "512x512", "apps", "zcode.png"),
-        ),
-      ).toBe(false);
-      expect(commandCalls).toEqual([
-        {
-          command: "update-desktop-database",
-          args: [join(homeDir, ".local", "share", "applications")],
-        },
-        {
-          command: "xdg-mime",
-          args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
-        },
-      ]);
-    } finally {
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  it("still writes the user-level entry when no system-level entry exists", async () => {
-    const { registerLinuxDeepLinkProtocol } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-no-system-"));
-    const homeDir = join(tempRoot, "home");
-    const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
-
-    try {
-      registerLinuxDeepLinkProtocol({
-        executablePath: "/opt/ZCode/zcode",
-        homeDir,
-        env: {},
-        systemApplicationDirs: [join(tempRoot, "empty-system-applications")],
-        logger: { info: () => undefined, warn: () => undefined },
-        runCommand: () => ({ status: 0, stderr: "" }),
-      });
-
-      expect(existsSync(desktopFilePath)).toBe(true);
-      expect(readFileSync(desktopFilePath, "utf8")).toContain('Exec="/opt/ZCode/zcode" %U');
-    } finally {
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  it("ignores non-regular system-level paths when probing for shadow entries", async () => {
-    const { registerLinuxDeepLinkProtocol } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-dir-system-"));
-    const homeDir = join(tempRoot, "home");
-    // 系统目录下的 zcode.desktop 是一个目录而非普通文件,不得视为有效系统条目。
-    const systemApplicationsDir = join(tempRoot, "system", "applications");
-    const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
-
-    try {
-      mkdirSync(join(systemApplicationsDir, "zcode.desktop"), { recursive: true });
-      registerLinuxDeepLinkProtocol({
-        executablePath: "/opt/ZCode/zcode",
-        homeDir,
-        env: {},
-        systemApplicationDirs: [systemApplicationsDir],
-        logger: { info: () => undefined, warn: () => undefined },
-        runCommand: () => ({ status: 0, stderr: "" }),
-      });
-
-      // 病态路径不抑制用户级注册。
-      expect(existsSync(desktopFilePath)).toBe(true);
-    } finally {
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  it("keeps an unreadable user-level entry and continues protocol registration", async () => {
-    const { registerLinuxDeepLinkProtocol } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-unreadable-"));
-    const homeDir = join(tempRoot, "home");
-    const systemApplicationsDir = join(tempRoot, "system", "applications");
-    const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
-    const warnings: unknown[][] = [];
-    const commandCalls: CommandCall[] = [];
-
-    try {
-      mkdirSync(systemApplicationsDir, { recursive: true });
-      writeFileSync(
-        join(systemApplicationsDir, "zcode.desktop"),
-        "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
-        "utf8",
-      );
-      mkdirSync(dirname(desktopFilePath), { recursive: true });
-      writeFileSync(desktopFilePath, "unreadable-placeholder", "utf8");
-      // chmod 000 让 readFileSync 抛 EACCES:归属无法确认时必须保守保留。
-      chmodSync(desktopFilePath, 0o000);
-
-      registerLinuxDeepLinkProtocol({
-        executablePath: "/opt/ZCode/zcode",
-        homeDir,
-        env: {},
-        systemApplicationDirs: [systemApplicationsDir],
-        logger: {
-          info: () => undefined,
-          warn: (...args: unknown[]) => warnings.push(args),
-        },
-        runCommand: (command, args) => {
-          commandCalls.push({ command, args });
-          return { status: 0, stderr: "" };
-        },
-      });
-
-      expect(existsSync(desktopFilePath)).toBe(true);
-      expect(
-        warnings.some(
-          ([message]) =>
-            message === "[deep-link] Linux 用户级 zcode.desktop 非本应用写入,保留不清理",
-        ),
-      ).toBe(true);
-      // 归属识别失败只降级,协议注册命令仍完整执行。
-      expect(commandCalls).toEqual([
-        {
-          command: "update-desktop-database",
-          args: [join(homeDir, ".local", "share", "applications")],
-        },
-        {
-          command: "xdg-mime",
-          args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
-        },
-      ]);
-    } finally {
-      chmodSync(desktopFilePath, 0o700);
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  it("recognizes ownership markers with CRLF line endings", async () => {
-    const { registerLinuxDeepLinkProtocol } =
-      await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-    const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-crlf-"));
-    const homeDir = join(tempRoot, "home");
-    const systemApplicationsDir = join(tempRoot, "system", "applications");
-    const desktopFilePath = join(homeDir, ".local", "share", "applications", "zcode.desktop");
-    const infos: unknown[][] = [];
-
-    try {
-      mkdirSync(systemApplicationsDir, { recursive: true });
-      writeFileSync(
-        join(systemApplicationsDir, "zcode.desktop"),
-        "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
-        "utf8",
-      );
-      // 旧版本写出的 LF 条目被 Windows 风格工具改写为 CRLF 后仍应识别为可清理。
-      mkdirSync(dirname(desktopFilePath), { recursive: true });
-      writeFileSync(
-        desktopFilePath,
-        [
-          "[Desktop Entry]",
-          "Name=ZCode",
-          "Comment=ZCode Desktop App",
-          'Exec="/home/alice/Downloads/ZCode.AppImage" %U',
-          "MimeType=x-scheme-handler/zcode;",
-          "",
-        ].join("\r\n"),
-        "utf8",
-      );
-
-      registerLinuxDeepLinkProtocol({
-        executablePath: "/opt/ZCode/zcode",
-        homeDir,
-        env: {},
-        systemApplicationDirs: [systemApplicationsDir],
-        logger: {
-          info: (...args: unknown[]) => infos.push(args),
-          warn: () => undefined,
-        },
-        runCommand: () => ({ status: 0, stderr: "" }),
-      });
-
-      expect(existsSync(desktopFilePath)).toBe(false);
-      expect(
-        infos.some(
-          ([message]) => message === "[deep-link] 已清理遗留的用户级 zcode.desktop,恢复系统级条目",
-        ),
-      ).toBe(true);
-    } finally {
-      rmSync(tempRoot, { force: true, recursive: true });
-    }
-  });
-
-  // Bugfix:本用例靠 chmod 0o500 去掉目录写权限让 rmSync 抛 EPERM,Windows 的 chmod
-  // 对目录是 no-op,删除照样成功,制造不出"删除失败"场景,本地 Windows 上必挂;
-  // 降级路径由 Linux/macOS(含 CI)继续覆盖,Windows 跳过。
-  it.skipIf(process.platform === "win32")(
-    "continues protocol registration when removing the stale entry fails",
-    async () => {
-      const { registerLinuxDeepLinkProtocol } =
-        await import("../src/main/desktopLinuxDeepLinkRegistration.js");
-      const tempRoot = mkdtempSync(join(tmpdir(), "zcode-linux-rm-fail-"));
-      const homeDir = join(tempRoot, "home");
-      const systemApplicationsDir = join(tempRoot, "system", "applications");
-      const applicationsDir = join(homeDir, ".local", "share", "applications");
-      const desktopFilePath = join(applicationsDir, "zcode.desktop");
-      const warnings: unknown[][] = [];
-      const commandCalls: CommandCall[] = [];
-
-      try {
-        mkdirSync(systemApplicationsDir, { recursive: true });
-        writeFileSync(
-          join(systemApplicationsDir, "zcode.desktop"),
-          "[Desktop Entry]\nName=ZCode\nExec=/opt/ZCode/zcode %U\n",
-          "utf8",
-        );
-        mkdirSync(applicationsDir, { recursive: true });
-        writeFileSync(
-          desktopFilePath,
-          '[Desktop Entry]\nComment=ZCode Desktop App\nExec="/old/ZCode.AppImage" %U\n',
-          "utf8",
-        );
-        // 目录去掉写权限后 rmSync 失败(EPERM):删除失败必须只降级,不得抛出或阻断注册。
-        chmodSync(applicationsDir, 0o500);
-
-        registerLinuxDeepLinkProtocol({
-          executablePath: "/opt/ZCode/zcode",
-          homeDir,
-          env: {},
-          systemApplicationDirs: [systemApplicationsDir],
-          logger: {
-            info: () => undefined,
-            warn: (...args: unknown[]) => warnings.push(args),
-          },
-          runCommand: (command, args) => {
-            commandCalls.push({ command, args });
-            return { status: 0, stderr: "" };
-          },
-        });
-
-        expect(existsSync(desktopFilePath)).toBe(true);
-        expect(
-          warnings.some(([message]) => message === "[deep-link] 清理遗留用户级 zcode.desktop 失败"),
-        ).toBe(true);
-        expect(commandCalls).toEqual([
-          {
-            command: "update-desktop-database",
-            args: [applicationsDir],
-          },
-          {
-            command: "xdg-mime",
-            args: ["default", "zcode.desktop", "x-scheme-handler/zcode"],
-          },
-        ]);
-      } finally {
-        chmodSync(applicationsDir, 0o700);
-        rmSync(tempRoot, { force: true, recursive: true });
-      }
-    },
-  );
-});