Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(settings): relaunch the app after Reset app data (#2134)
void9840ed8bb175
diff --git a/CLAUDE.md b/CLAUDE.mdindex d15cdfa85..dd01a4b2e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -105,10 +105,11 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- `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+- **autoStartPolicy.js**: Electron-free launch-at-login and relaunch 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+ - `getRelaunchOptions()` and `getRelaunchWaiter()` shape the `relaunch-app` IPC that follows `cleanup-app` (Reset app data; Delete account with device erase): the relaunch drops `--hidden` and any cold-start deep link, and an AppImage or Windows portable build is started again from its on-disk file (`$APPIMAGE`, `$PORTABLE_EXECUTABLE_FILE`) by a detached waiter, since both run from a directory that disappears when the app exits. The handler in `ipcHandlers.js` only quits under `npm run dev` and, on macOS with an update Squirrel already holds, hands the restart to the updater- **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 mountdiff --git a/preload.js b/preload.jsindex 169da6cc2..434129be3 100644--- a/preload.js+++ b/preload.js@@ -521,6 +521,7 @@ contextBridge.exposeInMainWorld("electronAPI", {// Cleanup functioncleanupApp: () => ipcRenderer.invoke("cleanup-app"),+ relaunchApp: () => ipcRenderer.invoke("relaunch-app"),updateHotkey: (hotkey) => ipcRenderer.invoke("update-hotkey", hotkey),setHotkeyListeningMode: (enabled) => ipcRenderer.invoke("set-hotkey-listening-mode", enabled),getHotkeyModeInfo: (hotkey) => ipcRenderer.invoke("get-hotkey-mode-info", hotkey),diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex c718d701a..c10392be4 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -2026,7 +2026,14 @@ export default function SettingsPage({? t("settingsPage.account.deleteAccount.partialCleanupDescription"): t("settingsPage.account.deleteAccount.successDescription"),});- setTimeout(() => window.location.reload(), 1000);+ // cleanup-app leaves the database closed; only a relaunch reopens it.+ setTimeout(() => {+ if (eraseDeviceData) {+ window.electronAPI?.relaunchApp();+ } else {+ window.location.reload();+ }+ }, 1000);} catch (error) {logger.error("Account deletion failed", error, "auth");showAlertDialog({@@ -4809,9 +4816,7 @@ EOF`,"settingsPage.developer.resetAll.successDescription"),});- setTimeout(() => {- window.location.reload();- }, 1000);+ setTimeout(() => window.electronAPI?.relaunchApp(), 1000);} catch {showAlertDialog({title: t("settingsPage.developer.resetAll.failedTitle"),diff --git a/src/helpers/autoStartPolicy.js b/src/helpers/autoStartPolicy.jsindex ef52cc880..a3fa79e5d 100644--- a/src/helpers/autoStartPolicy.js+++ b/src/helpers/autoStartPolicy.js@@ -1,4 +1,4 @@-// Launch-at-login decisions, kept free of Electron so they can be unit-tested.+// Launch-at-login and relaunch decisions, kept free of Electron so they can be unit-tested.//// A login launch should come up in the tray, and Windows has no way to ask for// that (macOS' openAsHidden is macOS-only and a no-op on macOS 13+). So the login@@ -45,10 +45,61 @@ function wasLaunchedHidden({ platform, argv, loginItemSettings }) {return argv.includes(HIDDEN_LAUNCH_FLAG);}+// A relaunch must not replay how this process was launched: --hidden would put the+// restarted app in the tray, and startup would handle a cold-start deep link again+// (a sign-in link would restore the session a reset just cleared). An AppImage and+// the Windows portable build run from a directory that is gone once this process+// exits (the FUSE mount; the stub's %TEMP% unpack dir), so app.relaunch() cannot+// bring them back: getRelaunchWaiter() starts the on-disk file from outside instead.+function getRelaunchOptions({ argv, protocol, appImagePath, portableExecutablePath }) {+ const args = argv+ .slice(1)+ .filter((arg) => arg !== HIDDEN_LAUNCH_FLAG && !arg.startsWith(`${protocol}://`));+ const launcherPath = appImagePath || portableExecutablePath;+ return launcherPath ? { launcherPath, args } : { args };+}++// The portable stub deletes its unpack dir only after the app exits, so on Windows the+// waiter must outlive the stub (this process's parent), not just this process.+function getRelaunchWaiter({+ platform,+ launcherPath,+ args,+ pid,+ ppid,+ systemRoot = "C:\\Windows",+}) {+ if (platform === "win32") {+ const quote = (value) => `'${String(value).replace(/'/g, "''")}'`;+ const argumentList = args.length ? ` -ArgumentList ${args.map(quote).join(",")}` : "";+ return {+ file: `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,+ args: [+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ `Wait-Process -Id ${ppid}; Start-Process -FilePath ${quote(launcherPath)}${argumentList}`,+ ],+ };+ }+ return {+ file: "/bin/sh",+ args: [+ "-c",+ 'while kill -0 "$0"; do sleep 0.2; done; exec "$@"',+ String(pid),+ launcherPath,+ ...args,+ ],+ };+}+module.exports = {HIDDEN_LAUNCH_FLAG,getLoginItemArgs,resolveAutoStartState,needsHiddenFlagMigration,wasLaunchedHidden,+ getRelaunchOptions,+ getRelaunchWaiter,};diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 1ba2cf314..757e29570 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -80,6 +80,7 @@ const diarizationHost = (endpoint) => {};const { resolveLocalServerNeeds } = require("./localServerPolicy");const autoStart = require("./autoStart");+const { getRelaunchOptions, getRelaunchWaiter } = require("./autoStartPolicy");const HyprlandShortcutManager = require("./hyprlandShortcut");const AssemblyAiStreaming = require("./assemblyAiStreaming");const { i18nMain, changeLanguage } = require("./i18nMain");@@ -3884,6 +3885,47 @@ class IPCHandlers {return this.diarizationManager.cancelDownload();});+ // Under `npm run dev` the Vite server dies with Electron, so a relaunched dev+ // instance would have no renderer: just quit there.+ ipcMain.handle("relaunch-app", async () => {+ if (process.env.NODE_ENV === "development") return app.quit();+ // Once Squirrel.Mac holds a downloaded update it installs it on this quit regardless+ // of any flag, so the updater owns that restart instead of racing app.relaunch().+ if (this.updateManager.hasStagedUpdate()) {+ const { success } = await this.updateManager+ .installUpdate()+ .catch(() => ({ success: false }));+ if (success) return;+ }+ this.updateManager.deferInstallOnQuit();+ const { launcherPath, args } = getRelaunchOptions({+ argv: process.argv,+ protocol: this.oauthProtocol,+ appImagePath: process.env.APPIMAGE,+ portableExecutablePath: process.env.PORTABLE_EXECUTABLE_FILE,+ });+ if (launcherPath) {+ const waiter = getRelaunchWaiter({+ platform: process.platform,+ launcherPath,+ args,+ pid: process.pid,+ ppid: process.ppid,+ systemRoot: process.env.SystemRoot,+ });+ require("child_process")+ .spawn(waiter.file, waiter.args, {+ detached: true,+ stdio: "ignore",+ cwd: path.dirname(launcherPath), // never inside the directory being removed+ })+ .unref();+ } else {+ app.relaunch({ args });+ }+ app.quit();+ });+ipcMain.handle("cleanup-app", async (event) => {const fs = require("fs");const os = require("os");diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 4566f3f53..18c83f02e 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -2872,10 +2872,10 @@"removing": "جاري الإزالة...","resetAll": {"confirmText": "حذف كل شيء",- "description": "سيؤدي هذا إلى حذف جميع الإعدادات المحلية والنصوص المفرَّغة والتسجيلات الصوتية ونماذج الذكاء الاصطناعي التي تم تنزيلها واتصالات التقويم والبيانات المخزنة مؤقتًا بشكل دائم. لن تتأثر البيانات السحابية وحسابك. سيتم إعادة تحميل التطبيق بعد إعادة التعيين.",+ "description": "سيؤدي هذا إلى حذف جميع الإعدادات المحلية والنصوص المفرَّغة والتسجيلات الصوتية ونماذج الذكاء الاصطناعي التي تم تنزيلها واتصالات التقويم والبيانات المخزنة مؤقتًا بشكل دائم. لن تتأثر البيانات السحابية وحسابك. سيتم إعادة تشغيل التطبيق بعد إعادة التعيين.","failedDescription": "حدث خطأ ما. يرجى المحاولة مرة أخرى أو إعادة تثبيت التطبيق.","failedTitle": "تعذر إعادة التعيين",- "successDescription": "تمت إعادة تعيين كل شيء. سيتم إعادة تحميل التطبيق الآن.",+ "successDescription": "تمت إعادة تعيين كل شيء. سيتم إعادة تشغيل التطبيق الآن.","successTitle": "تم الانتهاء","title": "إعادة تعيين جميع بيانات التطبيق"},diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex e55f0edc6..7032784de 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2119,10 +2119,10 @@"removing": "Wird entfernt...","resetAll": {"confirmText": "Alles löschen",- "description": "Dies löscht dauerhaft alle lokalen Einstellungen, Transkriptionen, Audioaufnahmen, heruntergeladene KI-Modelle, Kalenderverbindungen und zwischengespeicherte Daten. Cloud-Daten und Ihr Konto werden nicht beeinträchtigt. Die App wird nach dem Zurücksetzen neu geladen.",+ "description": "Dies löscht dauerhaft alle lokalen Einstellungen, Transkriptionen, Audioaufnahmen, heruntergeladene KI-Modelle, Kalenderverbindungen und zwischengespeicherte Daten. Cloud-Daten und Ihr Konto werden nicht beeinträchtigt. Die App wird nach dem Zurücksetzen neu gestartet.","failedDescription": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut oder installieren Sie die App neu.","failedTitle": "Zurücksetzen fehlgeschlagen",- "successDescription": "Alles wurde zurückgesetzt. Die App wird jetzt neu geladen.",+ "successDescription": "Alles wurde zurückgesetzt. Die App wird jetzt neu gestartet.","successTitle": "Fertig","title": "Alle App-Daten zurücksetzen"},diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 998df6d32..16dd6dd2d 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2119,10 +2119,10 @@"removing": "Removing...","resetAll": {"confirmText": "Delete Everything",- "description": "This will permanently delete all local settings, transcriptions, audio recordings, downloaded AI models, calendar connections, and cached data. Cloud data and your account will not be affected. The app will reload after reset.",+ "description": "This will permanently delete all local settings, transcriptions, audio recordings, downloaded AI models, calendar connections, and cached data. Cloud data and your account will not be affected. The app will restart after reset.","failedDescription": "Something went wrong. Please try again or reinstall the app.","failedTitle": "Couldn't reset",- "successDescription": "Everything has been reset. The app will reload now.",+ "successDescription": "Everything has been reset. The app will restart now.","successTitle": "All done","title": "Reset All App Data"},diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex e6b3bb796..55cc81224 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -1879,10 +1879,10 @@"removing": "Eliminando...","resetAll": {"confirmText": "Eliminar todo",- "description": "Esta acción eliminará permanentemente todas las configuraciones locales, transcripciones, grabaciones de audio, modelos de IA descargados, conexiones de calendario y datos en caché. Los datos en la nube y tu cuenta no se verán afectados. La aplicación se recargará después del restablecimiento.",+ "description": "Esta acción eliminará permanentemente todas las configuraciones locales, transcripciones, grabaciones de audio, modelos de IA descargados, conexiones de calendario y datos en caché. Los datos en la nube y tu cuenta no se verán afectados. La app se reiniciará después del restablecimiento.","failedDescription": "Algo salió mal. Inténtalo de nuevo o reinstala la app.","failedTitle": "No se pudo restablecer",- "successDescription": "Todo ha sido restablecido. La app se recargará ahora.",+ "successDescription": "Todo ha sido restablecido. La app se reiniciará ahora.","successTitle": "Completado","title": "Restablecer todos los datos de la app"},diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 8930c778a..dec33890f 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2119,7 +2119,7 @@"removing": "Suppression...","resetAll": {"confirmText": "Tout supprimer",- "description": "Cela supprimera définitivement tous les paramètres locaux, transcriptions, enregistrements audio, modèles IA téléchargés, connexions de calendrier et données en cache. Les données cloud et votre compte ne seront pas affectés. L'application se rechargera après la réinitialisation.",+ "description": "Cela supprimera définitivement tous les paramètres locaux, transcriptions, enregistrements audio, modèles IA téléchargés, connexions de calendrier et données en cache. Les données cloud et votre compte ne seront pas affectés. L'application redémarrera après la réinitialisation.","failedDescription": "Un problème est survenu. Veuillez réessayer ou réinstaller l'application.","failedTitle": "Impossible de réinitialiser","successDescription": "Tout a été réinitialisé. L'application va redémarrer.",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex eb14d7e7e..6e63d3e99 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -1826,10 +1826,10 @@"removing": "Rimozione...","resetAll": {"confirmText": "Elimina tutto",- "description": "Questo eliminerà permanentemente tutte le impostazioni locali, trascrizioni, registrazioni audio, modelli IA scaricati, connessioni calendario e dati memorizzati nella cache. I dati cloud e il tuo account non saranno interessati. L'app si ricaricherà dopo il ripristino.",+ "description": "Questo eliminerà permanentemente tutte le impostazioni locali, trascrizioni, registrazioni audio, modelli IA scaricati, connessioni calendario e dati memorizzati nella cache. I dati cloud e il tuo account non saranno interessati. L'app si riavvierà dopo il ripristino.","failedDescription": "Qualcosa è andato storto. Riprova o reinstalla l'app.","failedTitle": "Impossibile reimpostare",- "successDescription": "Tutto è stato reimpostato. L'app si ricaricherà ora.",+ "successDescription": "Tutto è stato reimpostato. L'app si riavvierà ora.","successTitle": "Tutto fatto","title": "Reimposta tutti i dati dell'app"},diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 1f949dfa2..585169300 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -1826,10 +1826,10 @@"removing": "削除中...","resetAll": {"confirmText": "すべて削除",- "description": "すべてのローカル設定、文字起こし、音声録音、ダウンロード済みAIモデル、カレンダー接続、キャッシュデータが完全に削除されます。クラウドデータとアカウントは影響を受けません。リセット後にアプリが再読み込みされます。",+ "description": "すべてのローカル設定、文字起こし、音声録音、ダウンロード済みAIモデル、カレンダー接続、キャッシュデータが完全に削除されます。クラウドデータとアカウントは影響を受けません。リセット後にアプリが再起動します。","failedDescription": "問題が発生しました。もう一度試すか、アプリを再インストールしてください。","failedTitle": "リセットできませんでした",- "successDescription": "すべてリセットされました。アプリを再読み込みします。",+ "successDescription": "すべてリセットされました。アプリを再起動します。","successTitle": "完了しました","title": "すべてのアプリデータをリセット"},diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 6aebd03dc..a1dac61e9 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -1805,10 +1805,10 @@"removing": "Removendo...","resetAll": {"confirmText": "Excluir tudo",- "description": "Isso excluirá permanentemente todas as configurações locais, transcrições, gravações de áudio, modelos de IA baixados, conexões de calendário e dados em cache. Os dados na nuvem e sua conta não serão afetados. O aplicativo será recarregado após a redefinição.",+ "description": "Isso excluirá permanentemente todas as configurações locais, transcrições, gravações de áudio, modelos de IA baixados, conexões de calendário e dados em cache. Os dados na nuvem e sua conta não serão afetados. O app será reiniciado após a redefinição.","failedDescription": "Algo deu errado. Tente novamente ou reinstale o app.","failedTitle": "Não foi possível redefinir",- "successDescription": "Tudo foi redefinido. O app será recarregado agora.",+ "successDescription": "Tudo foi redefinido. O app será reiniciado agora.","successTitle": "Tudo pronto","title": "Redefinir todos os dados do app"},diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex bd9c1f441..31decb361 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -1830,10 +1830,10 @@"removing": "Удаление...","resetAll": {"confirmText": "Удалить всё",- "description": "Это навсегда удалит все локальные настройки, транскрипции, аудиозаписи, загруженные модели ИИ, подключения календаря и кэшированные данные. Облачные данные и ваш аккаунт не будут затронуты. Приложение перезагрузится после сброса.",+ "description": "Это навсегда удалит все локальные настройки, транскрипции, аудиозаписи, загруженные модели ИИ, подключения календаря и кэшированные данные. Облачные данные и ваш аккаунт не будут затронуты. Приложение перезапустится после сброса.","failedDescription": "Что-то пошло не так. Попробуйте ещё раз или переустановите приложение.","failedTitle": "Не удалось сбросить",- "successDescription": "Всё сброшено. Приложение сейчас перезагрузится.",+ "successDescription": "Всё сброшено. Приложение сейчас перезапустится.","successTitle": "Готово","title": "Сбросить все данные приложения"},diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 0c82d244e..d61c7a48b 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -1826,10 +1826,10 @@"removing": "正在删除...","resetAll": {"confirmText": "删除所有数据",- "description": "这将永久删除所有本地设置、转录、音频录制、下载的 AI 模型、日历连接和缓存数据。云端数据和您的账户不会受到影响。应用将在重置后重新加载。",+ "description": "这将永久删除所有本地设置、转录、音频录制、下载的 AI 模型、日历连接和缓存数据。云端数据和您的账户不会受到影响。应用将在重置后重启。","failedDescription": "出了点问题,请重试或重新安装应用。","failedTitle": "无法重置",- "successDescription": "所有数据已重置,应用将立即重新加载。",+ "successDescription": "所有数据已重置,应用将立即重启。","successTitle": "全部完成","title": "重置所有应用数据"},diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 1fe6ab2ce..0982b0b4b 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -1826,10 +1826,10 @@"removing": "移除中...","resetAll": {"confirmText": "刪除所有資料",- "description": "這將永久刪除所有本地設定、轉錄、音訊錄製、下載的 AI 模型、行事曆連線和快取資料。雲端資料和您的帳戶不會受到影響。應用程式將在重設後重新載入。",+ "description": "這將永久刪除所有本地設定、轉錄、音訊錄製、下載的 AI 模型、行事曆連線和快取資料。雲端資料和您的帳戶不會受到影響。應用程式將在重設後重新啟動。","failedDescription": "發生錯誤。請再試一次或重新安裝應用程式。","failedTitle": "無法重設",- "successDescription": "所有資料已重設。應用程式即將重新載入。",+ "successDescription": "所有資料已重設。應用程式即將重新啟動。","successTitle": "完成","title": "重設所有應用程式資料"},diff --git a/src/types/electron.ts b/src/types/electron.tsindex 06f814bff..111d7f9c3 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1981,6 +1981,7 @@ declare global {// App managementcleanupApp: () => Promise<{ success: boolean; message: string; errors?: string[] }>;+ relaunchApp: () => Promise<void>;// Update operationscheckForUpdates: () => Promise<UpdateCheckResult>;diff --git a/src/updater.js b/src/updater.jsindex 8b6305fc3..9ebcba898 100644--- a/src/updater.js+++ b/src/updater.js@@ -309,6 +309,19 @@ class UpdateManager {if (enabled) this._autoDownloadIfEnabled();}+ // NSIS and AppImage install a downloaded update from their quit handler, which would+ // replace the executable a reset relaunch starts (an AppImage even moves to a new+ // file name).+ deferInstallOnQuit() {+ autoUpdater.autoInstallOnAppQuit = false;+ }++ // On macOS a finished download is handed to Squirrel.Mac, which installs it on any+ // quit from then on; MacUpdater records that hand-off in squirrelDownloadedUpdate.+ hasStagedUpdate() {+ return process.platform === "darwin" && autoUpdater.squirrelDownloadedUpdate === true;+ }+_autoDownloadIfEnabled() {if (!this.autoUpdatesEnabled || !this.updateAvailable) return;// downloadUpdate() is a no-op while a download is in flight or complete;diff --git a/test/helpers/autoStartPolicy.test.js b/test/helpers/autoStartPolicy.test.jsindex 4cf910dae..568810236 100644--- a/test/helpers/autoStartPolicy.test.js+++ b/test/helpers/autoStartPolicy.test.js@@ -7,6 +7,8 @@ const {resolveAutoStartState,needsHiddenFlagMigration,wasLaunchedHidden,+ getRelaunchOptions,+ getRelaunchWaiter,} = require("../../src/helpers/autoStartPolicy.js");// getLoginItemSettings compares the Run value against `"exe" args` verbatim, so@@ -148,3 +150,114 @@ test("macOS detects a login launch from wasOpenedAtLogin, not from argv", () =>false);});++test("a relaunch drops the hidden-launch flag and keeps every other arg", () => {+ assert.deepEqual(+ getRelaunchOptions({+ argv: ["OpenWhispr.exe", HIDDEN_LAUNCH_FLAG, "--log-level=debug"],+ protocol: "openwhispr",+ }),+ { args: ["--log-level=debug"] }+ );+});++test("a relaunch drops the deep link that cold-started the app", () => {+ assert.deepEqual(+ getRelaunchOptions({+ argv: [+ "OpenWhispr.exe",+ "openwhispr://auth/callback?bearer_token=stale",+ "--proxy-server=http://proxy:8080",+ ],+ protocol: "openwhispr",+ }),+ { args: ["--proxy-server=http://proxy:8080"] }+ );+});++test("an AppImage relaunches from the AppImage file, not its FUSE mount", () => {+ assert.deepEqual(+ getRelaunchOptions({+ argv: ["/tmp/.mount_OpenWh/open-whispr", "--no-sandbox"],+ protocol: "openwhispr",+ appImagePath: "/home/user/OpenWhispr.AppImage",+ }),+ { launcherPath: "/home/user/OpenWhispr.AppImage", args: ["--no-sandbox"] }+ );+});++test("the Windows portable build relaunches from the portable exe, not its unpack dir", () => {+ assert.deepEqual(+ getRelaunchOptions({+ argv: ["C:\\Users\\me\\AppData\\Local\\Temp\\2abc\\OpenWhispr.exe", HIDDEN_LAUNCH_FLAG],+ protocol: "openwhispr",+ portableExecutablePath: "D:\\Tools\\OpenWhispr-1.10.0.exe",+ }),+ { launcherPath: "D:\\Tools\\OpenWhispr-1.10.0.exe", args: [] }+ );+});++test("the AppImage waiter outlives this process, then execs the file with its args", () => {+ assert.deepEqual(+ getRelaunchWaiter({+ platform: "linux",+ launcherPath: "/home/user/OpenWhispr.AppImage",+ args: ["--no-sandbox"],+ pid: 4242,+ ppid: 4200,+ }),+ {+ file: "/bin/sh",+ args: [+ "-c",+ 'while kill -0 "$0"; do sleep 0.2; done; exec "$@"',+ "4242",+ "/home/user/OpenWhispr.AppImage",+ "--no-sandbox",+ ],+ }+ );+});++test("the portable waiter waits for the stub and quotes the path for PowerShell", () => {+ assert.deepEqual(+ getRelaunchWaiter({+ platform: "win32",+ launcherPath: "D:\\Tom's Tools\\OpenWhispr.exe",+ args: ["--log-level=debug"],+ pid: 4242,+ ppid: 4200,+ systemRoot: "D:\\Win",+ }),+ {+ file: "D:\\Win\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",+ args: [+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "Wait-Process -Id 4200; Start-Process -FilePath 'D:\\Tom''s Tools\\OpenWhispr.exe' -ArgumentList '--log-level=debug'",+ ],+ }+ );+});++test("the portable waiter runs the system PowerShell and omits -ArgumentList without args", () => {+ assert.deepEqual(+ getRelaunchWaiter({+ platform: "win32",+ launcherPath: "D:\\Tools\\OpenWhispr.exe",+ args: [],+ pid: 4242,+ ppid: 4200,+ }),+ {+ file: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",+ args: [+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "Wait-Process -Id 4200; Start-Process -FilePath 'D:\\Tools\\OpenWhispr.exe'",+ ],+ }+ );+});diff --git a/test/helpers/updater.test.js b/test/helpers/updater.test.jsindex 51d91a3ac..45a4adb77 100644--- a/test/helpers/updater.test.js+++ b/test/helpers/updater.test.js@@ -144,6 +144,31 @@ test("with automatic updates off, an available update waits for the user", () =>manager.cleanup();});+test("deferInstallOnQuit clears the flag the NSIS and AppImage quit handlers read", () => {+ const autoUpdater = makeAutoUpdater();+ const manager = createUpdateManager(autoUpdater);+ assert.equal(autoUpdater.autoInstallOnAppQuit, true);++ manager.deferInstallOnQuit();+ assert.equal(autoUpdater.autoInstallOnAppQuit, false);++ manager.cleanup();+});++test("only a macOS update that Squirrel already holds counts as staged", () => {+ const autoUpdater = makeAutoUpdater();+ const manager = createUpdateManager(autoUpdater);+ assert.equal(manager.hasStagedUpdate(), false);++ autoUpdater.squirrelDownloadedUpdate = true;+ assert.equal(manager.hasStagedUpdate(), true);++ setPlatform("win32");+ assert.equal(manager.hasStagedUpdate(), false);++ manager.cleanup();+});+test("enabling automatic updates after the startup check found one starts the download", () => {const autoUpdater = makeAutoUpdater();const manager = createUpdateManager(autoUpdater);