Files
Netcatty/electron/autoLaunch.cjs
T
axe006andClaude Sonnet 5 ee47c9e15c fix(auto-launch): 修复隐藏启动托盘保活、macOS 检测与跨平台支持
针对 PR #3238 的 4 条 Codex review 意见逐一修复:

- 隐藏启动时新增 pinTrayForHiddenLaunch/releaseHiddenLaunchTrayPin
  机制:托盘在窗口首次显示前始终保持存在,不再被渲染进程挂载时
  下发的 close-to-tray=false 提前销毁,避免开机自启+关闭托盘最小化
  组合下出现无窗口无托盘的僵尸进程。窗口首次 show 后自动释放钉住,
  交还给用户的正常 close-to-tray 偏好。
- wasLaunchedHidden 补充 macOS 检测:--hidden 启动参数只在 Windows
  生效(openAsHidden 是 macOS 专属设置,不会体现在 argv 里),macOS
  上改为读取 app.getLoginItemSettings().wasOpenedAsHidden。
- isAutoLaunchSupported 收紧为仅 macOS/Windows:Linux 打包(AppImage/
  deb/rpm/pacman)没有对应的系统登录项钩子,setLoginItemSettings 在
  该平台上静默失效,之前会误报"支持"。
- 新增 resolveEffectiveLoginState:Windows 上以
  executableWillLaunchAtLogin(考虑任务管理器"启动应用"里被禁用的
  情况)作为真实生效状态,而非只看 openAtLogin(仅反映注册表项
  是否存在)。

新增/更新单测覆盖以上全部场景,共 149 项相关测试通过。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-01 18:35:21 +08:00

114 lines
4.3 KiB
JavaScript

/**
* Auto Launch - Registers Netcatty to start at system login, hidden to the
* tray. Thin wrapper around Electron's app.setLoginItemSettings/
* getLoginItemSettings so main.cjs and the settings IPC handlers share one
* source of truth.
*
* Development runs (`electron .`) are unsupported: process.execPath points
* at the transient electron.exe, so a login item registered there would
* break (or silently do nothing) after the dev process exits.
*
* Platform support is further limited to macOS and Windows: Electron's
* login-item API is a no-op on Linux, which ships as AppImage/deb/rpm/pacman
* with no first-party autostart hook, so reporting it as supported there
* would show an enabled toggle that does nothing.
*/
const HIDDEN_LAUNCH_ARG = "--hidden";
function isAutoLaunchSupported({ defaultApp = process.defaultApp, platform = process.platform } = {}) {
if (defaultApp) return false;
return platform === "darwin" || platform === "win32";
}
/**
* Resolve the OS's effective auto-launch state, not just whether a
* registration exists. Windows can retain the run-key entry while the user
* disables it via Task Manager's Startup Apps UI; Electron surfaces that as
* executableWillLaunchAtLogin, distinct from openAtLogin (registration only).
*/
function resolveEffectiveLoginState(settings, platform) {
if (platform === "win32" && typeof settings?.executableWillLaunchAtLogin === "boolean") {
return settings.executableWillLaunchAtLogin;
}
return Boolean(settings?.openAtLogin);
}
function getAutoLaunchEnabled({ app, defaultApp = process.defaultApp, platform = process.platform } = {}) {
if (!isAutoLaunchSupported({ defaultApp, platform })) {
return { enabled: false, supported: false };
}
try {
const settings = app.getLoginItemSettings();
return { enabled: resolveEffectiveLoginState(settings, platform), supported: true };
} catch (err) {
console.warn("[AutoLaunch] Failed to read login item settings:", err?.message || err);
return { enabled: false, supported: true };
}
}
function setAutoLaunchEnabled(enabled, {
app,
execPath = process.execPath,
defaultApp = process.defaultApp,
platform = process.platform,
} = {}) {
if (!isAutoLaunchSupported({ defaultApp, platform })) {
return { success: false, enabled: false, supported: false };
}
const wantEnabled = Boolean(enabled);
try {
app.setLoginItemSettings({
openAtLogin: wantEnabled,
// openAsHidden only applies on macOS App Store builds; Windows relies
// on the --hidden arg below, which main.cjs checks on cold start.
openAsHidden: wantEnabled,
path: execPath,
args: wantEnabled ? [HIDDEN_LAUNCH_ARG] : [],
});
const settings = app.getLoginItemSettings();
return { success: true, enabled: resolveEffectiveLoginState(settings, platform), supported: true };
} catch (err) {
console.warn("[AutoLaunch] Failed to update login item settings:", err?.message || err);
return { success: false, enabled: getAutoLaunchEnabled({ app, defaultApp, platform }).enabled, supported: true };
}
}
/**
* True when this process was launched by the OS login item (cold start
* only). Windows relies on the --hidden arg (openAsHidden is a macOS-only
* setting); macOS never puts args from setLoginItemSettings() into argv for
* a login launch, so it must be detected via
* getLoginItemSettings().wasOpenedAsHidden instead.
*/
function wasLaunchedHidden({ argv = process.argv, app, platform = process.platform } = {}) {
if (Array.isArray(argv) && argv.includes(HIDDEN_LAUNCH_ARG)) return true;
if (platform !== "darwin" || typeof app?.getLoginItemSettings !== "function") return false;
try {
return Boolean(app.getLoginItemSettings().wasOpenedAsHidden);
} catch (err) {
console.warn("[AutoLaunch] Failed to read macOS hidden login-item state:", err?.message || err);
return false;
}
}
function registerHandlers(ipcMain, { app, platform = process.platform }) {
ipcMain.handle("netcatty:autoLaunch:get", async () => {
return getAutoLaunchEnabled({ app, platform });
});
ipcMain.handle("netcatty:autoLaunch:set", async (_event, { enabled }) => {
return setAutoLaunchEnabled(enabled, { app, platform });
});
}
module.exports = {
HIDDEN_LAUNCH_ARG,
isAutoLaunchSupported,
resolveEffectiveLoginState,
getAutoLaunchEnabled,
setAutoLaunchEnabled,
wasLaunchedHidden,
registerHandlers,
};