Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(startup): make launch at login work on Windows and start hidden everywhere

Gabriel Stein449018d371dc
diff --git a/CLAUDE.md b/CLAUDE.md
index e031e4afb..a54812a9a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -95,11 +95,22 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- Converts Electron hotkey format to Qt key codes
- Only active on Linux + KDE desktop (detected via `XDG_CURRENT_DESKTOP`)
- D-Bus transport: `@homebridge/dbus-native` (pure JavaScript, no native addons)
+- **autoStart.js**: Single entry point for launch at login, used by `ipcHandlers.js` and `main.js`
+ - Dispatches to `setLoginItemSettings()` on macOS/Windows and to `linuxAutostart.js` on Linux
+ - `getAutoStartState()` returns `{ enabled, requiresApproval }`; `requiresApproval` is macOS-only and means SMAppService registered the item but the user has not allowed it under System Settings → General → Login Items yet
+ - `wasLaunchedAtLoginHidden()` decides whether this launch should go straight to the tray
+ - `syncAutoStartEntry()` runs from `initializeCoreManagers()` and repairs entries written by older builds
+ - Decision logic lives in `autoStartPolicy.js` (pure, unit-tested in `test/helpers/autoStartPolicy.test.js`)
+- **autoStartPolicy.js**: Electron-free launch-at-login decisions
+ - `HIDDEN_LAUNCH_FLAG` (`--hidden`) is how a login launch tells the app to start in the tray. Windows has no native equivalent (`openAsHidden` is macOS-only and a no-op on macOS 13+), so the flag rides on the login item's `args`; Linux puts it on the autostart entry's `Exec`; macOS uses `wasOpenedAtLogin` instead
+ - On Windows, read the state from `executableWillLaunchAtLogin`, never from `openAtLogin`: `openAtLogin` only compares the `Run` value against the current executable and args and ignores the `StartupApproved` key that Task Manager and Settings write when a user disables a startup app
+ - Reads and writes must pass identical `args`, or `openAtLogin` always reports false
- **linuxAutostart.js**: Launch-at-login on Linux via an XDG autostart entry
- `app.setLoginItemSettings()` is a no-op on Linux, so the entry is written directly to `$XDG_CONFIG_HOME/autostart/open-whispr.desktop`, matching the executable name electron-builder packages under
- `Exec` resolves from `$APPIMAGE` first: `process.execPath` is the ephemeral AppImage FUSE mount
- `isAutostartEnabled()` honors `X-GNOME-Autostart-enabled=false` and `Hidden=true`, which GNOME Tweaks and KDE's autostart editor write in place instead of deleting the file
- - `syncAutostartEntry()` runs from `initializeCoreManagers()` in `main.js` and re-points a stale `Exec` after the executable moves (renamed or auto-updated AppImage); it never re-enables an entry the user disabled, and no-ops in development
+ - `Exec` carries `--hidden` (see `autoStartPolicy.js`), and `syncAutostartEntry()` compares against the full value including that flag — comparing against the bare path would make every launch look stale
+ - `syncAutostartEntry()` runs from `autoStart.syncAutoStartEntry()` in `initializeCoreManagers()` and re-points a stale `Exec` after the executable moves (renamed or auto-updated AppImage); it never re-enables an entry the user disabled, and no-ops in development
- Unit-tested in `test/helpers/linuxAutostart.test.js`
- **ipcHandlers.js**: Centralized IPC handler registration
- **windowsKeyManager.js**: Windows Push-to-Talk support with native key listener
@@ -424,14 +435,15 @@ The app can open OS-level settings for microphone permissions, sound input selec
- `open-microphone-settings`: Opens microphone privacy settings
- `open-sound-input-settings`: Opens sound/audio input device settings
- `open-accessibility-settings`: Opens accessibility privacy settings (macOS only)
+- `open-login-items-settings`: Opens the login/startup items pane (macOS Login Items, Windows Startup Apps)
**Platform-specific URLs**:
-| Platform | Microphone Privacy | Sound Input | Accessibility |
-| -------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------- |
-| macOS | `x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone` | `x-apple.systempreferences:com.apple.preference.sound?input` | `x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility` |
-| Windows | `ms-settings:privacy-microphone` | `ms-settings:sound` | N/A |
-| Linux | Manual (no URL scheme) | Manual (e.g., pavucontrol) | N/A |
+| Platform | Microphone Privacy | Sound Input | Accessibility | Login Items |
+| -------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
+| macOS | `x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone` | `x-apple.systempreferences:com.apple.preference.sound?input` | `x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility` | `x-apple.systempreferences:com.apple.LoginItems-Settings.extension` |
+| Windows | `ms-settings:privacy-microphone` | `ms-settings:sound` | N/A | `ms-settings:startupapps` |
+| Linux | Manual (no URL scheme) | Manual (e.g., pavucontrol) | N/A | N/A (XDG autostart entry, see `linuxAutostart.js`) |
**UI Component** (`MicPermissionWarning.tsx`):
@@ -773,6 +785,7 @@ const { t } = useTranslation();
- Shows in dock with indicator dot when running (LSUIElement: false)
- whisper.cpp bundled for both arm64 and x64
- System settings accessible via `x-apple.systempreferences:` URL scheme
+- **Launch at login**: `setLoginItemSettings()`, which routes through `SMAppService` on macOS 13+. `openAsHidden` is deprecated and does nothing, so `wasOpenedAtLogin` is what sends a login launch to the tray. An item can register and still report `status: "requires-approval"` until the user allows it under System Settings → General → Login Items
**Windows**:
@@ -781,6 +794,9 @@ const { t } = useTranslation();
- Sound settings at `ms-settings:sound`
- NSIS installer for distribution
- whisper.cpp bundled for x64
+- **Launch at login**: `HKCU\...\Run` entry written by Electron, named after the AppUserModelId, carrying `--hidden` so a login launch goes to the tray
+ - Read the state from `executableWillLaunchAtLogin`; `openAtLogin` misses a startup app disabled from Task Manager or Settings
+ - `resources/nsis/installer.nsh` removes the `Run` and `StartupApproved\Run` values on uninstall (but not on update), which Electron itself never cleans up
- **Push-to-Talk**: Native key listener binary (`windows-key-listener.exe`) enables true push-to-talk
- Uses Windows Low-Level Keyboard Hook (`WH_KEYBOARD_LL`)
- Supports compound hotkeys (e.g., `Ctrl+Shift+F11`)
diff --git a/main.js b/main.js
index d190bfad3..107b017b7 100644
--- a/main.js
+++ b/main.js
@@ -266,6 +266,7 @@ const ParakeetManager = require("./src/helpers/parakeet");
const DiarizationManager = require("./src/helpers/diarization");
const TrayManager = require("./src/helpers/tray");
const dockManager = require("./src/helpers/dockManager");
+const autoStart = require("./src/helpers/autoStart");
const IPCHandlers = require("./src/helpers/ipcHandlers");
const CliBridge = require("./src/helpers/cliBridge");
const UpdateManager = require("./src/updater");
@@ -382,14 +383,13 @@ function cleanupOrphanedLinuxRestoreToken() {
} catch {}
}
-function syncLinuxAutostartEntry() {
- if (process.platform !== "linux") return;
+function syncAutoStartEntry() {
try {
- if (require("./src/helpers/linuxAutostart").syncAutostartEntry()) {
- debugLogger.info("Re-pointed the autostart entry at the current executable");
+ if (autoStart.syncAutoStartEntry()) {
+ debugLogger.info("Re-pointed the launch-at-login entry at the current executable");
}
} catch (error) {
- debugLogger.warn("Failed to sync the autostart entry", { error: error?.message });
+ debugLogger.warn("Failed to sync the launch-at-login entry", { error: error?.message });
}
}
@@ -449,7 +449,7 @@ function initializeCoreManagers() {
// doesn't pay the probe spawn. No-ops on non-Windows.
windowsLoopbackAudioManager.getCapability().catch(() => {});
cleanupOrphanedLinuxRestoreToken();
- syncLinuxAutostartEntry();
+ syncAutoStartEntry();
meetingAecManager = new MeetingAecManager();
windowManager.textEditMonitor = textEditMonitor;
windowManager.selectionManager = selectionManager;
@@ -957,9 +957,12 @@ async function startApp() {
await new Promise((resolve) => setTimeout(resolve, 500));
}
- // Create windows FIRST so the user sees UI as soon as possible
- const startMinimized = environmentManager.getStartMinimized();
- if (debugLogger) debugLogger.info("Start minimized", { enabled: startMinimized });
+ // Create windows FIRST so the user sees UI as soon as possible.
+ // A login launch goes to the tray whatever the preference says: the user asked
+ // the OS to start us, not to put a window in front of them at every login.
+ const launchedHidden = autoStart.wasLaunchedAtLoginHidden();
+ const startMinimized = environmentManager.getStartMinimized() || launchedHidden;
+ if (debugLogger) debugLogger.info("Start minimized", { enabled: startMinimized, launchedHidden });
await windowManager.createMainWindow();
if (!startMinimized) {
await windowManager.createControlPanelWindow();
diff --git a/preload.js b/preload.js
index cfbcdba89..217506caa 100644
--- a/preload.js
+++ b/preload.js
@@ -597,6 +597,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
openAccessibilitySettings: () => ipcRenderer.invoke("open-accessibility-settings"),
openSystemAudioSettings: () => ipcRenderer.invoke("open-system-audio-settings"),
openScreenRecordingSettings: () => ipcRenderer.invoke("open-screen-recording-settings"),
+ openLoginItemsSettings: () => ipcRenderer.invoke("open-login-items-settings"),
checkScreenRecordingAccess: () => ipcRenderer.invoke("check-screen-recording-access"),
requestScreenRecordingAccess: () => ipcRenderer.invoke("request-screen-recording-access"),
captureScreenContext: () => ipcRenderer.invoke("capture-screen-context"),
diff --git a/resources/nsis/installer.nsh b/resources/nsis/installer.nsh
index 4dd142001..45dadf21d 100644
--- a/resources/nsis/installer.nsh
+++ b/resources/nsis/installer.nsh
@@ -10,13 +10,33 @@
; netsh needs elevation — per-user installs skip this silently.
!define SHERPA_FIREWALL_RULE "OpenWhispr Local Transcription Server (sherpa-onnx)"
+; Electron writes the launch-at-login entry itself, so nothing in the generated
+; uninstaller knows to remove it, and Windows keeps listing a startup item that
+; points at a deleted executable. The Run value is named after the
+; AppUserModelId main.js sets, which appends the release channel for non-
+; production builds (keep in sync with BASE_WINDOWS_APP_ID and VALID_CHANNELS
+; there). Disabling an item leaves a second value behind under StartupApproved,
+; so both have to go.
+!define RUN_KEY "Software\Microsoft\Windows\CurrentVersion\Run"
+!define STARTUP_APPROVED_KEY "Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"
+
+!macro DeleteAutoStartEntry NAME
+ DeleteRegValue HKCU "${RUN_KEY}" "${NAME}"
+ DeleteRegValue HKCU "${STARTUP_APPROVED_KEY}" "${NAME}"
+!macroend
+
!macro customInstall
nsExec::ExecToLog 'netsh advfirewall firewall delete rule name="${SHERPA_FIREWALL_RULE}"'
nsExec::ExecToLog 'netsh advfirewall firewall add rule name="${SHERPA_FIREWALL_RULE}" dir=in action=block program="$INSTDIR\resources\bin\sherpa-onnx-ws-win32-x64.exe" enable=yes profile=any'
!macroend
!macro customUnInstall
+ ; Guarded by isUpdated so an in-place update does not silently turn launch at
+ ; login off for a user who had enabled it.
${ifNot} ${isUpdated}
+ !insertmacro DeleteAutoStartEntry "com.gizmolabs.openwhispr"
+ !insertmacro DeleteAutoStartEntry "com.gizmolabs.openwhispr.staging"
+ !insertmacro DeleteAutoStartEntry "com.gizmolabs.openwhispr.development"
nsExec::ExecToLog 'netsh advfirewall firewall delete rule name="${SHERPA_FIREWALL_RULE}"'
StrCpy $0 "$PROFILE\.cache\openwhispr\models"
IfFileExists "$0\*.*" 0 +3
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 0a86b0a62..c3cc39f68 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -1172,23 +1172,24 @@ export default function SettingsPage({
const platform = getCachedPlatform();
const [autoStartEnabled, setAutoStartEnabled] = useState(false);
+ const [autoStartNeedsApproval, setAutoStartNeedsApproval] = useState(false);
const [autoStartLoading, setAutoStartLoading] = useState(true);
- useEffect(() => {
- const loadAutoStart = async () => {
- if (window.electronAPI?.getAutoStartEnabled) {
- try {
- const enabled = await window.electronAPI.getAutoStartEnabled();
- setAutoStartEnabled(enabled);
- } catch (error) {
- logger.error("Failed to get auto-start status", error, "settings");
- }
- }
- setAutoStartLoading(false);
- };
- loadAutoStart();
+ const readAutoStartState = useCallback(async () => {
+ if (!window.electronAPI?.getAutoStartEnabled) return;
+ try {
+ const state = await window.electronAPI.getAutoStartEnabled();
+ setAutoStartEnabled(state.enabled);
+ setAutoStartNeedsApproval(state.requiresApproval);
+ } catch (error) {
+ logger.error("Failed to get auto-start status", error, "settings");
+ }
}, []);
+ useEffect(() => {
+ readAutoStartState().finally(() => setAutoStartLoading(false));
+ }, [readAutoStartState]);
+
useEffect(() => {
window.electronAPI?.syncNotificationPreferences?.({
notificationsEnabled,
@@ -1199,18 +1200,17 @@ export default function SettingsPage({
}, [notificationsEnabled, notifyMeetingDetection, notifyCalendarReminders, notifyUpdates]);
const handleAutoStartChange = async (enabled: boolean) => {
- if (window.electronAPI?.setAutoStartEnabled) {
- try {
- setAutoStartLoading(true);
- const result = await window.electronAPI.setAutoStartEnabled(enabled);
- if (result.success) {
- setAutoStartEnabled(enabled);
- }
- } catch (error) {
- logger.error("Failed to set auto-start", error, "settings");
- } finally {
- setAutoStartLoading(false);
- }
+ if (!window.electronAPI?.setAutoStartEnabled) return;
+ try {
+ setAutoStartLoading(true);
+ const result = await window.electronAPI.setAutoStartEnabled(enabled);
+ // Read the state back rather than assuming: on Windows the OS can have the
+ // item disabled out from under us, and on macOS it can need approval first.
+ if (result.success) await readAutoStartState();
+ } catch (error) {
+ logger.error("Failed to set auto-start", error, "settings");
+ } finally {
+ setAutoStartLoading(false);
}
};
@@ -2832,6 +2832,29 @@ export default function SettingsPage({
/>
</SettingsRow>
</SettingsPanelRow>
+ {autoStartNeedsApproval && (
+ <SettingsPanelRow>
+ <Alert
+ variant="warning"
+ className="dark:bg-amber-950/50 dark:border-amber-800 dark:text-amber-200 dark:[&>svg]:text-amber-400"
+ >
+ <AlertTriangle className="h-4 w-4" />
+ <AlertTitle>
+ {t("settingsPage.general.startup.needsApproval.title")}
+ </AlertTitle>
+ <AlertDescription className="space-y-2">
+ <p>{t("settingsPage.general.startup.needsApproval.description")}</p>
+ <Button
+ onClick={() => void window.electronAPI?.openLoginItemsSettings?.()}
+ variant="outline"
+ size="sm"
+ >
+ {t("settingsPage.general.startup.needsApproval.action")}
+ </Button>
+ </AlertDescription>
+ </Alert>
+ </SettingsPanelRow>
+ )}
<SettingsPanelRow>
<SettingsRow
label={t("settingsPage.general.startup.startMinimized")}
diff --git a/src/helpers/autoStart.js b/src/helpers/autoStart.js
new file mode 100644
index 000000000..16d9d0bbd
--- /dev/null
+++ b/src/helpers/autoStart.js
@@ -0,0 +1,78 @@
+// Single entry point for launch at login. Electron's setLoginItemSettings covers
+// macOS and Windows; Linux is handled by an XDG autostart entry (linuxAutostart).
+// Decisions live in autoStartPolicy so they can be tested without Electron.
+
+const { app } = require("electron");
+const linuxAutostart = require("./linuxAutostart");
+const {
+ getLoginItemArgs,
+ resolveAutoStartState,
+ needsHiddenFlagMigration,
+ wasLaunchedHidden,
+} = require("./autoStartPolicy");
+
+const isLinux = () => process.platform === "linux";
+
+function readLoginItemSettings() {
+ return app.getLoginItemSettings({ args: getLoginItemArgs(process.platform) });
+}
+
+function writeLoginItem(enabled) {
+ app.setLoginItemSettings({
+ openAtLogin: enabled,
+ args: getLoginItemArgs(process.platform),
+ });
+}
+
+// { enabled, requiresApproval } — requiresApproval is macOS-only and means the
+// item is registered but still waiting on the user in System Settings.
+function getAutoStartState() {
+ if (isLinux()) {
+ return { enabled: linuxAutostart.isAutostartEnabled(), requiresApproval: false };
+ }
+ return resolveAutoStartState({
+ platform: process.platform,
+ loginItemSettings: readLoginItemSettings(),
+ });
+}
+
+function setAutoStartEnabled(enabled) {
+ if (isLinux()) {
+ linuxAutostart.setAutostartEnabled(enabled);
+ return;
+ }
+ writeLoginItem(enabled);
+}
+
+function wasLaunchedAtLoginHidden() {
+ return wasLaunchedHidden({
+ platform: process.platform,
+ argv: process.argv,
+ loginItemSettings: process.platform === "darwin" ? app.getLoginItemSettings() : null,
+ });
+}
+
+// Repairs an entry that still exists but no longer starts this executable, or
+// starts it without the flag that sends it to the tray. Returns true when
+// something was rewritten, so the caller can log it.
+function syncAutoStartEntry() {
+ if (isLinux()) return linuxAutostart.syncAutostartEntry();
+
+ if (
+ !needsHiddenFlagMigration({
+ platform: process.platform,
+ loginItemSettings: readLoginItemSettings(),
+ })
+ ) {
+ return false;
+ }
+ writeLoginItem(true);
+ return true;
+}
+
+module.exports = {
+ getAutoStartState,
+ setAutoStartEnabled,
+ wasLaunchedAtLoginHidden,
+ syncAutoStartEntry,
+};
diff --git a/src/helpers/autoStartPolicy.js b/src/helpers/autoStartPolicy.js
new file mode 100644
index 000000000..8b5a0ab94
--- /dev/null
+++ b/src/helpers/autoStartPolicy.js
@@ -0,0 +1,61 @@
+// Launch-at-login decisions, kept free of Electron so they can be unit-tested.
+//
+// Windows has no equivalent of macOS' openAsHidden (which is itself a no-op on
+// macOS 13 and up), so a login item that should come up in the tray has to say so
+// with a command-line flag we read back at startup. Linux rides the same flag on
+// the autostart entry's Exec line; macOS reports it through wasOpenedAtLogin.
+
+const HIDDEN_LAUNCH_FLAG = "--hidden";
+
+// The args a Windows login item is registered with. getLoginItemSettings compares
+// the registry value against `"exe" args` verbatim, so reads have to pass exactly
+// what writes did or openAtLogin always reports false.
+function getLoginItemArgs(platform) {
+ return platform === "win32" ? [HIDDEN_LAUNCH_FLAG] : [];
+}
+
+// On Windows, openAtLogin only reports whether the Run entry matches this
+// executable and args. It ignores Explorer's StartupApproved key, which is what
+// Task Manager and Settings write when a user disables a startup app, so an app
+// the user switched off still reads as enabled. executableWillLaunchAtLogin is
+// the only field that accounts for both.
+function resolveAutoStartState({ platform, loginItemSettings }) {
+ if (platform === "win32") {
+ return {
+ enabled: !!loginItemSettings.executableWillLaunchAtLogin,
+ requiresApproval: false,
+ };
+ }
+ return {
+ enabled: !!loginItemSettings.openAtLogin,
+ // macOS 13+ routes login items through SMAppService, which can register an
+ // item and still leave it awaiting the user's approval in System Settings.
+ // Without surfacing that, the toggle just appears not to stick.
+ requiresApproval: loginItemSettings.status === "requires-approval",
+ };
+}
+
+// A login item written before this build carries no --hidden, so it no longer
+// matches what we now write and openAtLogin reads false while the stale entry
+// keeps launching the app with its window showing. Rewriting it uses the same
+// registry value name, so it re-points the entry instead of adding a second one.
+function needsHiddenFlagMigration({ platform, loginItemSettings }) {
+ if (platform !== "win32") return false;
+ return !!loginItemSettings.executableWillLaunchAtLogin && !loginItemSettings.openAtLogin;
+}
+
+// Whether this process was started by the login item rather than by the user, in
+// which case it should go straight to the tray. Checked instead of the user's
+// startMinimized preference so a login launch never overwrites it.
+function wasLaunchedHidden({ platform, argv, loginItemSettings }) {
+ if (platform === "darwin") return !!loginItemSettings?.wasOpenedAtLogin;
+ return !!argv?.includes(HIDDEN_LAUNCH_FLAG);
+}
+
+module.exports = {
+ HIDDEN_LAUNCH_FLAG,
+ getLoginItemArgs,
+ resolveAutoStartState,
+ needsHiddenFlagMigration,
+ wasLaunchedHidden,
+};
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 6c942ad75..6c6b04f9f 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -45,7 +45,7 @@ const diarizationHost = (endpoint) => {
return null;
};
const { resolveLocalServerNeeds } = require("./localServerPolicy");
-const linuxAutostart = require("./linuxAutostart");
+const autoStart = require("./autoStart");
const GnomeShortcutManager = require("./gnomeShortcut");
const HyprlandShortcutManager = require("./hyprlandShortcut");
const AssemblyAiStreaming = require("./assemblyAiStreaming");
@@ -3391,27 +3391,16 @@ class IPCHandlers {
ipcMain.handle("get-auto-start-enabled", async () => {
try {
- if (process.platform === "linux") {
- return linuxAutostart.isAutostartEnabled();
- }
- const loginSettings = app.getLoginItemSettings();
- return loginSettings.openAtLogin;
+ return autoStart.getAutoStartState();
} catch (error) {
debugLogger.error("Error getting auto-start status:", error);
- return false;
+ return { enabled: false, requiresApproval: false };
}
});
ipcMain.handle("set-auto-start-enabled", async (event, enabled) => {
try {
- if (process.platform === "linux") {
- linuxAutostart.setAutostartEnabled(enabled);
- } else {
- app.setLoginItemSettings({
- openAtLogin: enabled,
- openAsHidden: true, // Start minimized to tray
- });
- }
+ autoStart.setAutoStartEnabled(enabled);
debugLogger.debug("Auto-start setting updated", { enabled });
return { success: true };
} catch (error) {
@@ -4448,10 +4437,12 @@ class IPCHandlers {
screenRecording:
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",
calendars: "x-apple.systempreferences:com.apple.preference.security?Privacy_Calendars",
+ loginItems: "x-apple.systempreferences:com.apple.LoginItems-Settings.extension",
},
win32: {
microphone: "ms-settings:privacy-microphone",
sound: "ms-settings:sound",
+ loginItems: "ms-settings:startupapps",
},
};
@@ -4468,6 +4459,7 @@ class IPCHandlers {
accessibility: i18nMain.t("systemSettings.accessibility"),
systemAudio: i18nMain.t("systemSettings.systemAudio"),
screenRecording: i18nMain.t("systemSettings.screenRecording"),
+ loginItems: i18nMain.t("systemSettings.loginItems"),
};
return {
success: false,
@@ -4490,6 +4482,7 @@ class IPCHandlers {
ipcMain.handle("open-accessibility-settings", () => openSystemSettings("accessibility"));
ipcMain.handle("open-system-audio-settings", () => openSystemSettings("systemAudio"));
ipcMain.handle("open-screen-recording-settings", () => openSystemSettings("screenRecording"));
+ ipcMain.handle("open-login-items-settings", () => openSystemSettings("loginItems"));
ipcMain.handle("capture-screen-context", () => screenContextCapture.captureCursorDisplay());
diff --git a/src/helpers/linuxAutostart.js b/src/helpers/linuxAutostart.js
index e43891d76..50922fe1c 100644
--- a/src/helpers/linuxAutostart.js
+++ b/src/helpers/linuxAutostart.js
@@ -1,6 +1,7 @@
const fs = require("fs");
const path = require("path");
const os = require("os");
+const { HIDDEN_LAUNCH_FLAG } = require("./autoStartPolicy");
const DESKTOP_ENTRY_GROUP = "[Desktop Entry]";
@@ -86,13 +87,20 @@ function quoteExecPath(execPath) {
return `"${escaped}"`;
}
+// A session launch goes straight to the tray, so the entry carries the same flag
+// the Windows login item passes. syncAutostartEntry() compares against this, not
+// against the bare path, or every launch would look stale and rewrite the file.
+function buildExecValue(execPath) {
+ return `${quoteExecPath(execPath)} ${HIDDEN_LAUNCH_FLAG}`;
+}
+
function buildDesktopFileContents(execPath, iconName) {
return [
DESKTOP_ENTRY_GROUP,
"Type=Application",
"Name=OpenWhispr",
"Comment=Voice dictation and AI agent",
- `Exec=${quoteExecPath(execPath)}`,
+ `Exec=${buildExecValue(execPath)}`,
iconName ? `Icon=${iconName}` : null,
"Terminal=false",
"Categories=Utility;",
@@ -181,7 +189,7 @@ function syncAutostartEntry() {
const entry = readDesktopEntry();
if (!isEntryEnabled(entry)) return false;
- if (entry.Exec === quoteExecPath(resolveExecutablePath())) return false;
+ if (entry.Exec === buildExecValue(resolveExecutablePath())) return false;
writeAutostartEntry();
return true;
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 81486a288..c772955e3 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -107,7 +107,8 @@
"sound": "Bitte öffnen Sie die Sound-Einstellungen des Systems (z. B. pavucontrol).",
"accessibility": "Bedienungshilfen-Einstellungen sind auf dieser Plattform nicht verfügbar.",
"systemAudio": "Systemaudio-Einstellungen sind auf dieser Plattform nicht verfügbar.",
- "screenRecording": "Einstellungen zur Bildschirmaufnahme sind auf dieser Plattform nicht verfügbar."
+ "screenRecording": "Einstellungen zur Bildschirmaufnahme sind auf dieser Plattform nicht verfügbar.",
+ "loginItems": "Einstellungen für Anmeldeobjekte sind auf dieser Plattform nicht verfügbar."
},
"upgradePrompt": {
"paymentFailed": "Ihre Zahlung konnte nicht verarbeitet werden",
@@ -1892,11 +1893,16 @@
},
"startup": {
"launchAtLogin": "Beim Anmelden starten",
- "launchAtLoginDescription": "OpenWhispr automatisch starten, wenn Sie sich anmelden",
+ "launchAtLoginDescription": "OpenWhispr bei der Anmeldung im Hintergrund starten",
"title": "Autostart",
"description": "Steuern Sie das Verhalten von OpenWhispr beim Start",
"startMinimized": "Minimiert starten",
- "startMinimizedDescription": "Starten, ohne das Einstellungsfenster anzuzeigen"
+ "startMinimizedDescription": "Starten, ohne das Einstellungsfenster anzuzeigen",
+ "needsApproval": {
+ "title": "Bestätigung in den Systemeinstellungen erforderlich",
+ "description": "macOS hat OpenWhispr als Anmeldeobjekt registriert, wartet aber darauf, dass du es unter Anmeldeobjekte erlaubst.",
+ "action": "Anmeldeobjekte öffnen"
+ }
},
"waylandPaste": {
"title": "Wayland-Einfügen einrichten",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index afd715699..bbe0984f6 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -107,7 +107,8 @@
"sound": "Please open your system sound settings (for example, pavucontrol).",
"accessibility": "Accessibility settings are not available on this platform.",
"systemAudio": "System audio settings are not available on this platform.",
- "screenRecording": "Screen recording settings are not available on this platform."
+ "screenRecording": "Screen recording settings are not available on this platform.",
+ "loginItems": "Login item settings are not available on this platform."
},
"upgradePrompt": {
"paymentFailed": "We couldn't process your payment",
@@ -1892,11 +1893,16 @@
},
"startup": {
"launchAtLogin": "Launch at login",
- "launchAtLoginDescription": "Start OpenWhispr automatically when you log in",
+ "launchAtLoginDescription": "Start OpenWhispr in the background when you log in",
"title": "Startup",
"description": "Control how OpenWhispr behaves when it launches",
"startMinimized": "Start minimized",
- "startMinimizedDescription": "Launch without showing the control panel window"
+ "startMinimizedDescription": "Launch without showing the control panel window",
+ "needsApproval": {
+ "title": "Approval needed in System Settings",
+ "description": "macOS registered OpenWhispr as a login item but is waiting for you to allow it under Login Items.",
+ "action": "Open Login Items"
+ }
},
"waylandPaste": {
"title": "Wayland Paste Setup",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 4a0e4399d..bfd5fc376 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -107,7 +107,8 @@
"sound": "Abre la configuración de sonido del sistema (por ejemplo, pavucontrol).",
"accessibility": "La configuración de accesibilidad no está disponible en esta plataforma.",
"systemAudio": "La configuración de audio del sistema no está disponible en esta plataforma.",
- "screenRecording": "La configuración de grabación de pantalla no está disponible en esta plataforma."
+ "screenRecording": "La configuración de grabación de pantalla no está disponible en esta plataforma.",
+ "loginItems": "La configuración de elementos de inicio no está disponible en esta plataforma."
},
"upgradePrompt": {
"paymentFailed": "No pudimos procesar tu pago",
@@ -1654,11 +1655,16 @@
},
"startup": {
"launchAtLogin": "Abrir al iniciar sesión",
- "launchAtLoginDescription": "Inicia OpenWhispr automáticamente al iniciar sesión",
+ "launchAtLoginDescription": "Inicia OpenWhispr en segundo plano al iniciar sesión",
"title": "Inicio",
"description": "Controla el comportamiento de OpenWhispr al iniciar",
"startMinimized": "Iniciar minimizado",
- "startMinimizedDescription": "Iniciar sin mostrar la ventana del panel de control"
+ "startMinimizedDescription": "Iniciar sin mostrar la ventana del panel de control",
+ "needsApproval": {
+ "title": "Se necesita aprobación en Configuración del Sistema",
+ "description": "macOS registró OpenWhispr como elemento de inicio, pero espera que lo permitas en Elementos de inicio.",
+ "action": "Abrir Elementos de inicio"
+ }
},
"waylandPaste": {
"title": "Configuración de pegado en Wayland",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 070c2e92c..851d8255b 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -107,7 +107,8 @@
"sound": "Veuillez ouvrir les paramètres son du système (par exemple, pavucontrol).",
"accessibility": "Les paramètres d'accessibilité ne sont pas disponibles sur cette plateforme.",
"systemAudio": "Les paramètres audio système ne sont pas disponibles sur cette plateforme.",
- "screenRecording": "Les réglages d'enregistrement de l'écran ne sont pas disponibles sur cette plateforme."
+ "screenRecording": "Les réglages d'enregistrement de l'écran ne sont pas disponibles sur cette plateforme.",
+ "loginItems": "Les réglages des éléments d'ouverture ne sont pas disponibles sur cette plateforme."
},
"upgradePrompt": {
"paymentFailed": "Nous n'avons pas pu traiter votre paiement",
@@ -1892,11 +1893,16 @@
},
"startup": {
"launchAtLogin": "Lancer au démarrage",
- "launchAtLoginDescription": "Démarrer OpenWhispr automatiquement à la connexion",
+ "launchAtLoginDescription": "Lancer OpenWhispr en arrière-plan à l'ouverture de session",
"title": "Démarrage",
"description": "Contrôlez le comportement d'OpenWhispr au lancement",
"startMinimized": "Démarrer réduit",
- "startMinimizedDescription": "Lancer sans afficher la fenêtre du panneau de contrôle"
+ "startMinimizedDescription": "Lancer sans afficher la fenêtre du panneau de contrôle",
+ "needsApproval": {
+ "title": "Autorisation requise dans Réglages Système",
+ "description": "macOS a enregistré OpenWhispr comme élément d'ouverture, mais attend que vous l'autorisiez dans Éléments d'ouverture.",
+ "action": "Ouvrir Éléments d'ouverture"
+ }
},
"waylandPaste": {
"title": "Configuration du collage Wayland",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 52249400d..cd37cebff 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -107,7 +107,8 @@
"sound": "Apri le impostazioni audio di sistema (ad esempio, pavucontrol).",
"accessibility": "Le impostazioni di accessibilità non sono disponibili su questa piattaforma.",
"systemAudio": "Le impostazioni audio di sistema non sono disponibili su questa piattaforma.",
- "screenRecording": "Le impostazioni di registrazione dello schermo non sono disponibili su questa piattaforma."
+ "screenRecording": "Le impostazioni di registrazione dello schermo non sono disponibili su questa piattaforma.",
+ "loginItems": "Le impostazioni degli elementi di login non sono disponibili su questa piattaforma."
},
"upgradePrompt": {
"paymentFailed": "Non siamo riusciti a elaborare il pagamento",
@@ -1606,11 +1607,16 @@
},
"startup": {
"launchAtLogin": "Avvia all'accesso",
- "launchAtLoginDescription": "Avvia OpenWhispr automaticamente all'accesso",
+ "launchAtLoginDescription": "Avvia OpenWhispr in background all'accesso",
"title": "Avvio",
"description": "Controlla il comportamento di OpenWhispr all'avvio",
"startMinimized": "Avvia ridotto a icona",
- "startMinimizedDescription": "Avvia senza mostrare la finestra del pannello di controllo"
+ "startMinimizedDescription": "Avvia senza mostrare la finestra del pannello di controllo",
+ "needsApproval": {
+ "title": "Approvazione necessaria in Impostazioni di Sistema",
+ "description": "macOS ha registrato OpenWhispr come elemento di login, ma attende che tu lo consenta in Elementi login.",
+ "action": "Apri Elementi login"
+ }
},
"waylandPaste": {
"title": "Configurazione incolla su Wayland",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index ad936a25c..60c2820ab 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -107,7 +107,8 @@
"sound": "システムのサウンド設定を開いてください(例: pavucontrol)。",
"accessibility": "このプラットフォームではアクセシビリティ設定を利用できません。",
"systemAudio": "システムオーディオの設定はこのプラットフォームでは利用できません。",
- "screenRecording": "このプラットフォームでは画面収録の設定を利用できません。"
+ "screenRecording": "このプラットフォームでは画面収録の設定を利用できません。",
+ "loginItems": "ログイン項目の設定はこのプラットフォームでは利用できません。"
},
"upgradePrompt": {
"paymentFailed": "お支払いを処理できませんでした",
@@ -1606,11 +1607,16 @@
},
"startup": {
"launchAtLogin": "ログイン時に起動",
- "launchAtLoginDescription": "ログイン時に OpenWhispr を自動的に起動",
+ "launchAtLoginDescription": "ログイン時に OpenWhispr をバックグラウンドで起動します",
"title": "起動設定",
"description": "OpenWhispr の起動時の動作を制御",
"startMinimized": "最小化で起動",
- "startMinimizedDescription": "コントロールパネルウィンドウを表示せずに起動"
+ "startMinimizedDescription": "コントロールパネルウィンドウを表示せずに起動",
+ "needsApproval": {
+ "title": "システム設定での許可が必要です",
+ "description": "macOS は OpenWhispr をログイン項目として登録しましたが、「ログイン項目」での許可を待っています。",
+ "action": "ログイン項目を開く"
+ }
},
"waylandPaste": {
"title": "Wayland 貼り付け設定",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 60dbfb0d7..c9b8e111a 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -107,7 +107,8 @@
"sound": "Abra as configurações de som do sistema (por exemplo, pavucontrol).",
"accessibility": "As configurações de acessibilidade não estão disponíveis nesta plataforma.",
"systemAudio": "As configurações de áudio do sistema não estão disponíveis nesta plataforma.",
- "screenRecording": "As configurações de gravação de tela não estão disponíveis nesta plataforma."
+ "screenRecording": "As configurações de gravação de tela não estão disponíveis nesta plataforma.",
+ "loginItems": "As configurações de itens de início não estão disponíveis nesta plataforma."
},
"windows": {
"pttUnavailable": "O listener nativo de Push-to-Talk não está disponível"
@@ -1585,11 +1586,16 @@
},
"startup": {
"launchAtLogin": "Iniciar ao fazer login",
- "launchAtLoginDescription": "Iniciar o OpenWhispr automaticamente ao fazer login",
+ "launchAtLoginDescription": "Iniciar o OpenWhispr em segundo plano ao fazer login",
"title": "Inicialização",
"description": "Controle o comportamento do OpenWhispr ao iniciar",
"startMinimized": "Iniciar minimizado",
- "startMinimizedDescription": "Iniciar sem mostrar a janela do painel de controle"
+ "startMinimizedDescription": "Iniciar sem mostrar a janela do painel de controle",
+ "needsApproval": {
+ "title": "Aprovação necessária nas Configurações do Sistema",
+ "description": "O macOS registrou o OpenWhispr como item de início, mas está aguardando que você o permita em Itens de Início.",
+ "action": "Abrir Itens de Início"
+ }
},
"waylandPaste": {
"title": "Configuração de colagem no Wayland",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 31d7d4436..918c8a6eb 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -107,7 +107,8 @@
"sound": "Откройте системные настройки звука (например, pavucontrol).",
"accessibility": "Настройки универсального доступа недоступны на этой платформе.",
"systemAudio": "Настройки системного аудио недоступны на этой платформе.",
- "screenRecording": "Настройки записи экрана недоступны на этой платформе."
+ "screenRecording": "Настройки записи экрана недоступны на этой платформе.",
+ "loginItems": "Настройки объектов входа недоступны на этой платформе."
},
"upgradePrompt": {
"paymentFailed": "Не удалось обработать платёж",
@@ -1610,11 +1611,16 @@
},
"startup": {
"launchAtLogin": "Запускать при входе",
- "launchAtLoginDescription": "Автоматически запускать OpenWhispr при входе в систему",
+ "launchAtLoginDescription": "Запускать OpenWhispr в фоновом режиме при входе в систему",
"title": "Автозапуск",
"description": "Управляйте поведением OpenWhispr при запуске",
"startMinimized": "Запуск в свёрнутом виде",
- "startMinimizedDescription": "Запускать без отображения окна панели управления"
+ "startMinimizedDescription": "Запускать без отображения окна панели управления",
+ "needsApproval": {
+ "title": "Требуется подтверждение в Системных настройках",
+ "description": "macOS добавил OpenWhispr в объекты входа, но ожидает вашего разрешения в разделе «Объекты входа».",
+ "action": "Открыть объекты входа"
+ }
},
"waylandPaste": {
"title": "Настройка вставки в Wayland",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 79262265a..aa8452b61 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -107,7 +107,8 @@
"sound": "请打开系统声音设置(例如 pavucontrol)。",
"accessibility": "此平台不支持辅助功能设置。",
"systemAudio": "系统音频设置在此平台上不可用。",
- "screenRecording": "此平台不提供屏幕录制设置。"
+ "screenRecording": "此平台不提供屏幕录制设置。",
+ "loginItems": "此平台不支持登录项设置。"
},
"upgradePrompt": {
"paymentFailed": "我们无法处理你的付款",
@@ -1606,11 +1607,16 @@
},
"startup": {
"launchAtLogin": "登录时启动",
- "launchAtLoginDescription": "登录时自动启动 OpenWhispr",
+ "launchAtLoginDescription": "登录时在后台启动 OpenWhispr",
"title": "启动",
"description": "控制 OpenWhispr 启动时的行为",
"startMinimized": "启动时最小化",
- "startMinimizedDescription": "启动时不显示控制面板窗口"
+ "startMinimizedDescription": "启动时不显示控制面板窗口",
+ "needsApproval": {
+ "title": "需要在系统设置中批准",
+ "description": "macOS 已将 OpenWhispr 注册为登录项,但仍在等待你在“登录项”中允许它。",
+ "action": "打开登录项"
+ }
},
"waylandPaste": {
"title": "Wayland 粘贴设置",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 27bc6e0ef..dc7889772 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -107,7 +107,8 @@
"sound": "請開啟系統音效設定(例如 pavucontrol)。",
"accessibility": "此平台不支援輔助使用設定。",
"systemAudio": "系統音訊設定在此平台上不可用。",
- "screenRecording": "此平台不提供螢幕錄製設定。"
+ "screenRecording": "此平台不提供螢幕錄製設定。",
+ "loginItems": "此平台不支援登入項目設定。"
},
"upgradePrompt": {
"paymentFailed": "我們無法處理你的付款",
@@ -1606,11 +1607,16 @@
},
"startup": {
"launchAtLogin": "登入時啟動",
- "launchAtLoginDescription": "登入時自動啟動 OpenWhispr",
+ "launchAtLoginDescription": "登入時在背景啟動 OpenWhispr",
"title": "啟動",
"description": "控制 OpenWhispr 啟動時的行為",
"startMinimized": "啟動時最小化",
- "startMinimizedDescription": "啟動時不顯示控制面板視窗"
+ "startMinimizedDescription": "啟動時不顯示控制面板視窗",
+ "needsApproval": {
+ "title": "需要在系統設定中允許",
+ "description": "macOS 已將 OpenWhispr 註冊為登入項目,但仍在等待你在「登入項目」中允許它。",
+ "action": "開啟登入項目"
+ }
},
"waylandPaste": {
"title": "Wayland 貼上設定",
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 270e095a9..f8581785f 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1692,6 +1692,7 @@ declare global {
openAccessibilitySettings?: () => Promise<{ success: boolean; error?: string }>;
openSystemAudioSettings?: () => Promise<{ success: boolean; error?: string }>;
openScreenRecordingSettings?: () => Promise<{ success: boolean; error?: string }>;
+ openLoginItemsSettings?: () => Promise<{ success: boolean; error?: string }>;
checkScreenRecordingAccess?: () => Promise<ScreenRecordingAccessResult>;
requestScreenRecordingAccess?: () => Promise<ScreenRecordingAccessResult>;
captureScreenContext?: () => Promise<ScreenContextImage | null>;
@@ -1711,8 +1712,10 @@ declare global {
notifyStartMinimizedChanged?: (enabled: boolean) => void;
notifyPanelStartPositionChanged?: (position: string) => void;
- // Auto-start at login
- getAutoStartEnabled?: () => Promise<boolean>;
+ // Auto-start at login. requiresApproval is macOS-only: SMAppService can
+ // register the login item and still leave it awaiting approval in System
+ // Settings, which otherwise looks like a toggle that will not stick.
+ getAutoStartEnabled?: () => Promise<{ enabled: boolean; requiresApproval: boolean }>;
setAutoStartEnabled?: (enabled: boolean) => Promise<{ success: boolean; error?: string }>;
// Auth
diff --git a/test/helpers/autoStartPolicy.test.js b/test/helpers/autoStartPolicy.test.js
new file mode 100644
index 000000000..7ffbad032
--- /dev/null
+++ b/test/helpers/autoStartPolicy.test.js
@@ -0,0 +1,147 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ HIDDEN_LAUNCH_FLAG,
+ getLoginItemArgs,
+ resolveAutoStartState,
+ needsHiddenFlagMigration,
+ wasLaunchedHidden,
+} = require("../../src/helpers/autoStartPolicy.js");
+
+// getLoginItemSettings compares the Run value against `"exe" args` verbatim, so
+// reads that pass different args than writes did always report openAtLogin false.
+test("Windows login items are read and written with the same args", () => {
+ assert.deepEqual(getLoginItemArgs("win32"), [HIDDEN_LAUNCH_FLAG]);
+});
+
+test("platforms without a hidden-launch flag pass no args", () => {
+ assert.deepEqual(getLoginItemArgs("darwin"), []);
+ assert.deepEqual(getLoginItemArgs("linux"), []);
+});
+
+// The bug behind the reported "startup app not recognized": openAtLogin only
+// checks the Run entry, so an app the user switched off in Task Manager still
+// reads as enabled while never actually starting.
+test("a startup item disabled in Task Manager reads as disabled on Windows", () => {
+ const state = resolveAutoStartState({
+ platform: "win32",
+ loginItemSettings: { openAtLogin: true, executableWillLaunchAtLogin: false },
+ });
+ assert.equal(state.enabled, false);
+});
+
+test("a startup item Windows will actually launch reads as enabled", () => {
+ const state = resolveAutoStartState({
+ platform: "win32",
+ loginItemSettings: { openAtLogin: true, executableWillLaunchAtLogin: true },
+ });
+ assert.deepEqual(state, { enabled: true, requiresApproval: false });
+});
+
+// An entry written by an older build carries no --hidden, so it no longer matches
+// what we write now even though it is still there and still launching the app.
+test("Windows re-enables through executableWillLaunchAtLogin when only the args differ", () => {
+ const state = resolveAutoStartState({
+ platform: "win32",
+ loginItemSettings: { openAtLogin: false, executableWillLaunchAtLogin: true },
+ });
+ assert.equal(state.enabled, true);
+});
+
+test("macOS reports an item awaiting approval as enabled but unapproved", () => {
+ const state = resolveAutoStartState({
+ platform: "darwin",
+ loginItemSettings: { openAtLogin: true, status: "requires-approval" },
+ });
+ assert.deepEqual(state, { enabled: true, requiresApproval: true });
+});
+
+test("macOS reports an approved item without prompting for approval", () => {
+ const state = resolveAutoStartState({
+ platform: "darwin",
+ loginItemSettings: { openAtLogin: true, status: "enabled" },
+ });
+ assert.deepEqual(state, { enabled: true, requiresApproval: false });
+});
+
+test("a disabled macOS item is neither enabled nor awaiting approval", () => {
+ const state = resolveAutoStartState({
+ platform: "darwin",
+ loginItemSettings: { openAtLogin: false, status: "not-registered" },
+ });
+ assert.deepEqual(state, { enabled: false, requiresApproval: false });
+});
+
+test("an entry written before the hidden flag is migrated", () => {
+ assert.equal(
+ needsHiddenFlagMigration({
+ platform: "win32",
+ loginItemSettings: { openAtLogin: false, executableWillLaunchAtLogin: true },
+ }),
+ true
+ );
+});
+
+test("an entry already carrying the hidden flag is left alone", () => {
+ assert.equal(
+ needsHiddenFlagMigration({
+ platform: "win32",
+ loginItemSettings: { openAtLogin: true, executableWillLaunchAtLogin: true },
+ }),
+ false
+ );
+});
+
+// Migrating here would recreate an entry the user deliberately removed.
+test("launch at login that is simply off is not mistaken for a stale entry", () => {
+ assert.equal(
+ needsHiddenFlagMigration({
+ platform: "win32",
+ loginItemSettings: { openAtLogin: false, executableWillLaunchAtLogin: false },
+ }),
+ false
+ );
+});
+
+test("migration is Windows-only", () => {
+ assert.equal(
+ needsHiddenFlagMigration({
+ platform: "darwin",
+ loginItemSettings: { openAtLogin: false, executableWillLaunchAtLogin: true },
+ }),
+ false
+ );
+});
+
+test("Windows and Linux detect a login launch from the flag on argv", () => {
+ for (const platform of ["win32", "linux"]) {
+ assert.equal(
+ wasLaunchedHidden({ platform, argv: ["OpenWhispr.exe", HIDDEN_LAUNCH_FLAG] }),
+ true,
+ platform
+ );
+ assert.equal(wasLaunchedHidden({ platform, argv: ["OpenWhispr.exe"] }), false, platform);
+ }
+});
+
+// openAsHidden and wasOpenedAsHidden are no-ops on macOS 13+, so wasOpenedAtLogin
+// is the only signal left that the session, not the user, started us.
+test("macOS detects a login launch from wasOpenedAtLogin, not from argv", () => {
+ assert.equal(
+ wasLaunchedHidden({
+ platform: "darwin",
+ argv: ["OpenWhispr"],
+ loginItemSettings: { wasOpenedAtLogin: true },
+ }),
+ true
+ );
+ assert.equal(
+ wasLaunchedHidden({
+ platform: "darwin",
+ argv: ["OpenWhispr", HIDDEN_LAUNCH_FLAG],
+ loginItemSettings: { wasOpenedAtLogin: false },
+ }),
+ false
+ );
+});
diff --git a/test/helpers/linuxAutostart.test.js b/test/helpers/linuxAutostart.test.js
index 37ee5ade2..5fcef2e86 100644
--- a/test/helpers/linuxAutostart.test.js
+++ b/test/helpers/linuxAutostart.test.js
@@ -64,12 +64,45 @@ test(
const { buildDesktopFileContents } = await load();
const contents = buildDesktopFileContents("/a/b/OpenWhispr.AppImage", "open-whispr");
- assert.match(contents, /^Exec="\/a\/b\/OpenWhispr\.AppImage"$/m);
+ assert.match(contents, /^Exec="\/a\/b\/OpenWhispr\.AppImage" --hidden$/m);
assert.match(contents, /^Icon=open-whispr$/m);
assert.match(contents, /^X-GNOME-Autostart-enabled=true$/m);
})
);
+// The flag has to be part of what syncAutostartEntry() compares against, or an
+// up-to-date entry looks stale and gets rewritten on every single launch.
+test(
+ "an entry already carrying the hidden flag is not rewritten on startup",
+ withTmpXdgDirs(async () => {
+ const { setAutostartEnabled, syncAutostartEntry, getDesktopFilePath } = await load();
+
+ process.env.APPIMAGE = "/apps/OpenWhispr.AppImage";
+ setAutostartEnabled(true);
+ assert.match(fs.readFileSync(getDesktopFilePath(), "utf8"), /^Exec=.* --hidden$/m);
+
+ assert.equal(syncAutostartEntry(), false);
+ })
+);
+
+// Entries written before the flag existed still launch the app, just with its
+// window showing, so startup has to re-point them.
+test(
+ "an entry written before the hidden flag is re-pointed on startup",
+ withTmpXdgDirs(async () => {
+ const { syncAutostartEntry, getDesktopFilePath } = await load();
+
+ process.env.APPIMAGE = "/apps/OpenWhispr.AppImage";
+ writeEntry(
+ getDesktopFilePath(),
+ '[Desktop Entry]\nType=Application\nExec="/apps/OpenWhispr.AppImage"\n'
+ );
+
+ assert.equal(syncAutostartEntry(), true);
+ assert.match(fs.readFileSync(getDesktopFilePath(), "utf8"), /^Exec=.* --hidden$/m);
+ })
+);
+
test(
"desktop file omits the Icon line rather than writing a broken reference",
withTmpXdgDirs(async () => {
@@ -88,7 +121,10 @@ test(
const { buildDesktopFileContents } = await load();
const contents = buildDesktopFileContents('/home/o"neill/$HOME/`app`\\v/OpenWhispr', null);
- assert.match(contents, /^Exec="\/home\/o\\"neill\/\\\$HOME\/\\`app\\`\\\\\\\\v\/OpenWhispr"$/m);
+ assert.match(
+ contents,
+ /^Exec="\/home\/o\\"neill\/\\\$HOME\/\\`app\\`\\\\\\\\v\/OpenWhispr" --hidden$/m
+ );
})
);
@@ -211,7 +247,7 @@ test(
assert.equal(syncAutostartEntry(), true);
const contents = fs.readFileSync(getDesktopFilePath(), "utf8");
- assert.match(contents, /^Exec="\/new\/path\/OpenWhispr-1\.9\.0\.AppImage"$/m);
+ assert.match(contents, /^Exec="\/new\/path\/OpenWhispr-1\.9\.0\.AppImage" --hidden$/m);
})
);
@@ -269,6 +305,6 @@ test(
assert.equal(syncAutostartEntry(), false);
const contents = fs.readFileSync(getDesktopFilePath(), "utf8");
- assert.match(contents, /^Exec="\/installed\/OpenWhispr\.AppImage"$/m);
+ assert.match(contents, /^Exec="\/installed\/OpenWhispr\.AppImage" --hidden$/m);
})
);