Skip to content

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

feat(onboarding): Add compact macOS permission overlay (#2294)

Chad Piha0c232a3eaa30
diff --git a/.github/workflows/build-and-notarize.yml b/.github/workflows/build-and-notarize.yml
index bf9677e37..0af122b95 100644
--- a/.github/workflows/build-and-notarize.yml
+++ b/.github/workflows/build-and-notarize.yml
@@ -419,7 +419,7 @@ jobs:
- name: Verify packaged macOS native binaries
run: |
APP_PATH=$(ls -d dist/mac*/OpenWhispr.app | head -n1)
- for bin in macos-audio-tap macos-globe-listener macos-fast-paste macos-mic-listener macos-text-monitor macos-media-remote; do
+ for bin in macos-audio-tap macos-globe-listener macos-fast-paste macos-mic-listener macos-calendar-listener macos-text-monitor macos-window-bounds macos-media-remote; do
test -x "$APP_PATH/Contents/Resources/bin/$bin" || { echo "Missing in bundle: $bin"; exit 1; }
done
test -x "$APP_PATH/Contents/Resources/bin/MediaRemoteAdapter.framework/Versions/A/MediaRemoteAdapter" || { echo "Missing in bundle: MediaRemoteAdapter.framework"; exit 1; }
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 7bfe1cd6c..44fc34765 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -394,7 +394,7 @@ jobs:
- name: Verify packaged macOS native binaries
run: |
APP_PATH=$(ls -d dist/mac*/OpenWhispr.app | head -n1)
- for bin in macos-audio-tap macos-globe-listener macos-fast-paste macos-mic-listener macos-text-monitor macos-media-remote; do
+ for bin in macos-audio-tap macos-globe-listener macos-fast-paste macos-mic-listener macos-calendar-listener macos-text-monitor macos-window-bounds macos-media-remote; do
test -x "$APP_PATH/Contents/Resources/bin/$bin" || { echo "Missing in bundle: $bin"; exit 1; }
done
node scripts/verify-macos-parakeet.js "$APP_PATH"
diff --git a/CLAUDE.md b/CLAUDE.md
index 7f5981d71..e392723e5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -53,6 +53,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- **windows-system-audio-helper.c**: C source for WASAPI process-loopback system audio capture (meeting transcription). Excludes OpenWhispr's own process tree, so it hears every app on every output device. Requires Windows 10 2004+; falls back to Chromium display-media loopback when unavailable. Mid-session, the helper emits a `capture_silent` warning when its own stream is silent while a render endpoint is metering output, checked every second for the whole session because Windows keeps some apps' streams out of process loopback (Teams call audio, #1265). Main then starts renderer loopback beside the helper, and `meetingSystemAudioHandover.js` gives loopback the system channel only after it hears audio the helper misses, so a false alarm never drops a working capture. Outputs 24 kHz mono s16le PCM on stdout, line-delimited JSON events on stderr (same protocol as linux-system-audio-helper)
- **macos-mic-listener.swift**: Swift source for the CoreAudio process-object microphone listener (event-driven mic detection); falls back to aggregate device activity and retries PID monitoring from its heartbeat
- **globe-listener.swift**: Swift source for macOS Globe/Fn key detection
+- **macos-window-bounds.swift**: Swift source for the System Settings window reporter used by the onboarding permission guide. Prints the dialog's bounds, whether a sheet or authorization prompt is in front, which app owns the front window (`settings` / `self` / `other`, attributed by process because window owner names are localized) and whether System Settings is running. CoreGraphics window list only, so it needs neither Accessibility nor Screen Recording
- **bin/**: Directory for compiled native binaries (whisper-cpp, nircmd, key/mic listeners)
### Helper Modules (src/helpers/)
@@ -186,6 +187,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- Token handling shared by the OAuth connectors (`boundLogin.js`): reads, the reconnect flag, saving a refreshed token and one refresh at a time, only ever for the login an action is bound to. Gmail's and Linear's clients share one timed POST and its body helpers (`providerHttp.js`); GitHub's uses the body helpers
- Logins: one encrypted file per OpenWhispr account and connector under `userData/connectors/` (atomic writes, `0o700`, `connectorCredentials.js`). Every write names the account and the generation it started from, so an OAuth round trip, refresh or disconnect that outlives a reconnect or account switch writes nothing. Bindings carry `ownerAccountId`; receipts carry `account_id`. Signed out → every connector action is refused (`signed_out`). Pending actions also expire in main (`sweepExpired`, every minute)
- **postMigrationDetector.js**: Detects users returning from the pre-Gizmo bundle ID via a `.bundle-migrated` sentinel in userData; consumed by `ipcHandlers.js` to drive the `PostMigrationOnboarding` modal
+- **permissionGuideManager.js**: macOS onboarding permission overlay — a frameless always-on-top window anchored to the bottom of the System Settings window (placement in `permissionGuidePlacement.js`, pure), polled one read at a time via `settingsWindowState.js` (exec of `macos-window-bounds`). Steps aside for authorization prompts, other apps and a dialog on another Space; closes when the dialog closes; never subscribes to the control panel's `hide` (occlusion fires it), so `hideControlPanelToTray()` closes it explicitly. Renderer side: `permissionGuideController.ts` (pure state machine, unit-tested) + `usePermissionGuide.ts`
- **templatePrompts.js**: Pure compiler from a note template or action to the system prompt the model receives (see Note Templates and Actions). Shared by `actionProcessingStore.ts`, the note chat, and the live canary's note probe
### React Components (src/components/)
@@ -311,6 +313,7 @@ Offline semantic search that finds notes by meaning, not just keywords. Used by
- **sync-nucleo-icons.js**: Regenerates `src/components/icons/` from `nucleo-map.json` using the local Nucleo install (`~/.nucleo/skills`); only the icons the app uses are vendored
- **build-globe-listener.js**: Compiles macOS Globe key listener from Swift source
- **build-macos-mic-listener.js**: Compiles macOS mic listener from Swift source
+- **build-macos-window-bounds.js**: Compiles the System Settings window reporter from Swift source
- **build-windows-key-listener.js**: Compiles Windows key listener (for local development)
- **run-electron.js**: Development script to launch Electron with proper environment
- **lib/download-utils.js**: Shared utilities for downloading and extracting files
diff --git a/electron-builder.json b/electron-builder.json
index 1c742b198..1afda8d8a 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -121,6 +121,7 @@
"macos-mic-listener",
"macos-calendar-listener",
"macos-text-monitor",
+ "macos-window-bounds",
"macos-media-remote",
"MediaRemoteAdapter.framework/**",
"linux-fast-paste",
diff --git a/main.js b/main.js
index 730e17a6d..1758196eb 100644
--- a/main.js
+++ b/main.js
@@ -298,6 +298,7 @@ const WindowsKeyManager = require("./src/helpers/windowsKeyManager");
const LinuxKeyManager = require("./src/helpers/linuxKeyManager");
const TextEditMonitor = require("./src/helpers/textEditMonitor");
const SelectionManager = require("./src/helpers/selectionManager");
+const { PermissionGuideManager } = require("./src/helpers/permissionGuideManager");
const WhisperCudaManager = require("./src/helpers/whisperCudaManager");
const WhisperVulkanManager = require("./src/helpers/whisperVulkanManager");
const { migrateLegacyBinDir, detectOrphanedGpuPacks } = require("./src/helpers/gpuBinaryManager");
@@ -607,6 +608,7 @@ function initializeCoreManagers() {
windowManager.selectionManager = selectionManager;
windowManager.windowsKeyManager = windowsKeyManager;
windowManager.linuxKeyManager = linuxKeyManager;
+ windowManager.permissionGuide = new PermissionGuideManager(windowManager);
if (process.platform === "linux") {
windowManager.hotkeyManager.nativeListenerProbe = () => linuxKeyManager.checkAvailability();
} else if (process.platform === "win32") {
diff --git a/package.json b/package.json
index b6b45af2e..950a392c2 100644
--- a/package.json
+++ b/package.json
@@ -21,7 +21,8 @@
"compile:mic-listener": "node scripts/build-macos-mic-listener.js",
"compile:calendar-listener": "node scripts/build-macos-calendar-listener.js",
"compile:audio-tap": "node scripts/build-macos-audio-tap.js",
- "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:linuxkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:linux-system-audio && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mediaremote-adapter && npm run compile:mic-listener && npm run compile:calendar-listener && npm run compile:audio-tap",
+ "compile:window-bounds": "node scripts/build-macos-window-bounds.js",
+ "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:linuxkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:linux-system-audio && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mediaremote-adapter && npm run compile:mic-listener && npm run compile:calendar-listener && npm run compile:audio-tap && npm run compile:window-bounds",
"prestart": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model",
"start": "electron .",
"dev": "concurrently -k -r \"npm:dev:renderer\" \"npm:dev:main\"",
diff --git a/preload.js b/preload.js
index 43e6fa723..73f3b0152 100644
--- a/preload.js
+++ b/preload.js
@@ -65,6 +65,19 @@ const registerListener = (channel, handlerFactory) => {
contextBridge.exposeInMainWorld("electronAPI", {
setOnboardingWindowMode: (mode) => ipcRenderer.invoke("onboarding-set-window-mode", mode),
setOnboardingActive: (active) => ipcRenderer.invoke("onboarding-set-active", active),
+ openPermissionGuide: (state) => ipcRenderer.invoke("permission-guide-open", state),
+ closePermissionGuide: () => ipcRenderer.invoke("permission-guide-close"),
+ getPermissionGuideState: () => ipcRenderer.invoke("permission-guide-state"),
+ permissionGuideAction: (action) => ipcRenderer.send("permission-guide-action", action),
+ startPermissionGuideDrag: (target) => ipcRenderer.send("permission-guide-drag", target),
+ onPermissionGuideState: registerListener(
+ "permission-guide-state-changed",
+ (callback) => (_event, state) => callback(state)
+ ),
+ onPermissionGuideAction: registerListener(
+ "permission-guide-action",
+ (callback) => (_event, action) => callback(action)
+ ),
markMacAccessibilityFeaturesReady: (expectedAccountScope) =>
expectedAccountScope
? ipcRenderer.send("mac-accessibility-features-ready", expectedAccountScope)
@@ -733,6 +746,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
getSystemDefaultMicrophone: (options) =>
ipcRenderer.invoke("get-system-default-microphone", options),
checkSystemAudioAccess: () => ipcRenderer.invoke("check-system-audio-access"),
+ verifySystemAudioAccess: () => ipcRenderer.invoke("permission-guide-verify-system-audio"),
requestSystemAudioAccess: () => ipcRenderer.invoke("request-system-audio-access"),
openMicrophoneSettings: () => ipcRenderer.invoke("open-microphone-settings"),
openSoundInputSettings: () => ipcRenderer.invoke("open-sound-input-settings"),
diff --git a/resources/macos-window-bounds.swift b/resources/macos-window-bounds.swift
new file mode 100644
index 000000000..05ce31ffa
--- /dev/null
+++ b/resources/macos-window-bounds.swift
@@ -0,0 +1,121 @@
+/**
+ * macOS System Settings Window Reporter
+ *
+ * Prints, as JSON, the on-screen bounds of the System Settings window, whether
+ * a prompt is sitting in front of it, and which app owns the front window:
+ *
+ * {"settings":{"x":232,"y":232,"width":723,"height":804},"authPrompt":false,
+ * "frontmost":"settings","settingsRunning":true}
+ *
+ * The onboarding permission guide anchors itself to that window, dismisses
+ * itself when the window closes, and gets out of the way while macOS asks for a
+ * password, the user switches to another app, or the dialog sits on another
+ * Space (settingsRunning without a window on screen). Uses the CoreGraphics window
+ * list, which reports window owners and bounds without the Accessibility or
+ * Screen Recording permissions — the guide runs while those are still being
+ * granted, so anything requiring them would be circular.
+ *
+ * Windows are attributed by owner process, never by owner name: the name is the
+ * localized bundle name ("Systemeinstellungen" on a German Mac). The first
+ * argument is the caller's own pid, so its windows report as "self".
+ *
+ * Compile: swiftc -O macos-window-bounds.swift -o macos-window-bounds
+ */
+
+import AppKit
+import CoreGraphics
+import Foundation
+
+// Ventura renamed System Preferences to System Settings; the bundle identifier
+// is the one thing that stayed the same across the releases the app supports.
+let settingsBundleId = "com.apple.systempreferences"
+// Authorization can also be drawn by a separate process depending on the macOS
+// release, so those owners count as a prompt wherever they appear.
+let authOwners: Set<String> = ["SecurityAgent", "loginwindow", "UserNotificationCenter"]
+// Smaller than this and a window is a shadow or helper surface, not a dialog.
+let minimumDialogSide: CGFloat = 100
+// Dialogs live at the normal and modal-panel levels. The lock screen's shield
+// windows sit far above them and must not read as a prompt.
+let maximumDialogLayer = 8
+
+let selfPid: pid_t = CommandLine.arguments.dropFirst().first.flatMap { Int32($0) } ?? 0
+
+struct Window {
+ let ownerPid: pid_t
+ let owner: String
+ let layer: Int
+ let x: CGFloat
+ let y: CGFloat
+ let width: CGFloat
+ let height: CGFloat
+
+ var area: CGFloat { width * height }
+ var isDialogSized: Bool { width >= minimumDialogSide && height >= minimumDialogSide }
+ var isDialogLayer: Bool { layer >= 0 && layer <= maximumDialogLayer }
+}
+
+// Front to back, which is what makes "in front of the settings window" decidable.
+let windows: [Window] = (
+ CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
+ as? [[String: Any]] ?? []
+).compactMap { entry in
+ guard let bounds = entry[kCGWindowBounds as String] as? [String: Any],
+ let x = bounds["X"] as? CGFloat,
+ let y = bounds["Y"] as? CGFloat,
+ let width = bounds["Width"] as? CGFloat,
+ let height = bounds["Height"] as? CGFloat,
+ [x, y, width, height].allSatisfy({ $0.isFinite })
+ else { return nil }
+ return Window(
+ ownerPid: entry[kCGWindowOwnerPID as String] as? pid_t ?? 0,
+ owner: entry[kCGWindowOwnerName as String] as? String ?? "",
+ layer: entry[kCGWindowLayer as String] as? Int ?? -1,
+ x: x, y: y, width: width, height: height)
+}
+
+func isSettingsProcess(_ pid: pid_t) -> Bool {
+ NSRunningApplication(processIdentifier: pid)?.bundleIdentifier == settingsBundleId
+}
+
+let settingsRunning = !NSRunningApplication.runningApplications(withBundleIdentifier: settingsBundleId)
+ .isEmpty
+
+// Layer 0 is the normal window layer, skipping the panels and popovers System
+// Settings keeps above its window.
+let settingsWindows = windows.enumerated().filter { _, window in
+ window.layer == 0 && window.isDialogSized && isSettingsProcess(window.ownerPid)
+}
+
+// The largest one is the settings window itself. Picking the frontmost instead
+// anchors the overlay to whatever sheet is open — including the password prompt.
+let main = settingsWindows.max { $0.element.area < $1.element.area }
+
+// Anything System Settings puts in front of its own window is a sheet the user
+// has to deal with first, and the password prompt is one of those.
+let sheetInFront = main.map { mainWindow in
+ settingsWindows.contains { index, _ in index < mainWindow.offset }
+} ?? false
+
+let separateAuthWindow = windows.contains {
+ authOwners.contains($0.owner) && $0.isDialogSized && $0.isDialogLayer
+}
+
+var settings = "null"
+if let window = main?.element {
+ settings =
+ "{\"x\":\(Int(window.x)),\"y\":\(Int(window.y)),\"width\":\(Int(window.width)),\"height\":\(Int(window.height))}"
+}
+
+// The list is front to back, so the first normal window belongs to whichever app
+// the user is actually looking at. The overlay hides when that is neither the
+// dialog nor the app itself.
+let frontmost = windows.first { $0.layer == 0 && $0.isDialogSized }.map { window -> String in
+ if isSettingsProcess(window.ownerPid) { return "\"settings\"" }
+ if selfPid != 0 && window.ownerPid == selfPid { return "\"self\"" }
+ return "\"other\""
+}
+
+print(
+ "{\"settings\":\(settings),\"authPrompt\":\(sheetInFront || separateAuthWindow),"
+ + "\"frontmost\":\(frontmost ?? "null"),\"settingsRunning\":\(settingsRunning)}"
+)
diff --git a/scripts/build-macos-window-bounds.js b/scripts/build-macos-window-bounds.js
new file mode 100644
index 000000000..fcd65660d
--- /dev/null
+++ b/scripts/build-macos-window-bounds.js
@@ -0,0 +1,9 @@
+#!/usr/bin/env node
+
+const { buildMacosSwiftBinary } = require("./lib/build-macos-swift-binary");
+
+buildMacosSwiftBinary({
+ label: "window-bounds",
+ sourceName: "macos-window-bounds.swift",
+ binaryName: "macos-window-bounds",
+});
diff --git a/src/AppRouter.jsx b/src/AppRouter.jsx
index 23cd1173c..fd35995be 100644
--- a/src/AppRouter.jsx
+++ b/src/AppRouter.jsx
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import App from "./App.jsx";
import AgentDictationPillOverlay from "./components/dictation/AgentDictationPillOverlay.tsx";
import MeetingNotificationOverlay from "./components/MeetingNotificationOverlay.tsx";
+import { PermissionGuideOverlay } from "./components/onboarding/PermissionGuideOverlay";
import ReauthenticationScreen from "./components/ReauthenticationScreen.tsx";
import BackgroundModelDownloadTray from "./components/onboarding/BackgroundModelDownloadTray.tsx";
import { LEGACY_ONBOARDING_STEP_KEY, ONBOARDING_SESSION_KEY } from "./components/onboarding/flow";
@@ -28,6 +29,8 @@ export default function AppRouter() {
useTheme();
const params = window.location.search;
+ if (params.includes("permission-guide=true")) return <PermissionGuideOverlay />;
+
if (params.includes("meeting-notification=true")) {
return <MeetingNotificationOverlay />;
}
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index 867fbed6d..583bca2c2 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -64,6 +64,11 @@ import {
type OnboardingStepId,
} from "./onboarding/flow";
import { useOnboardingSession } from "./onboarding/useOnboardingSession";
+import { usePermissionGuide } from "./onboarding/usePermissionGuide";
+import {
+ requestMicrophoneForGuide,
+ type GuidePermission,
+} from "./onboarding/permissionGuideController";
import { clearPendingLocalModels, hasPendingLocalModels } from "./onboarding/pendingLocalModels";
import { resolveAssistantDemoScenario } from "./onboarding/assistantDemoScenario";
import { ActivationModeSelector } from "./ui/ActivationModeSelector";
@@ -107,6 +112,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
setSetupMode,
setSelfHostedRequested,
setScreenContextRequested,
+ setPermissionGuide,
clearSession,
} = useOnboardingSession();
@@ -199,9 +205,10 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
);
const systemAudio = useSystemAudioPermission();
const {
- isMacOS,
granted: screenRecordingGranted,
needsRelaunch: screenRecordingNeedsRelaunch,
+ loaded: screenRecordingLoaded,
+ check: checkScreenRecording,
request: requestScreenRecordingAccess,
} = useScreenRecordingPermission();
const {
@@ -281,23 +288,19 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
// macOS grants Screen Recording in System Settings, outside the app; the
// permission hook re-checks on mount and window focus. When the grant lands,
- // complete the opt-in the Enable click started. On macOS the grant serves
- // only this feature, so one that already exists (a reset wipes the setting
- // but not the permission) counts as the opt-in too; Windows is permissionless
- // and keeps its explicit Enable.
+ // complete the opt-in the Enable click started. A system grant alone must
+ // not enable Screen Context without the user's explicit opt-in.
useEffect(() => {
if (!screenRecordingGranted || !agentAllowed || !screenContextAllowed) return;
- if (screenContextRequested || (isMacOS && !settingsStore.voiceAgentScreenContext)) {
+ if (screenContextRequested) {
applyScreenContext();
}
}, [
agentAllowed,
applyScreenContext,
- isMacOS,
screenContextAllowed,
screenContextRequested,
screenRecordingGranted,
- settingsStore.voiceAgentScreenContext,
]);
const requiredModels = useRequiredLocalModels();
@@ -345,6 +348,86 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
macAccessibilityChecksEnabled: shouldInitializeMacAccessibilityFeatures(currentStepId),
}
);
+ const openSettings =
+ (open: () => Promise<{ success: boolean; error?: string }>) => async (): Promise<void> => {
+ const result = await open();
+ if (!result.success) throw new Error(result.error);
+ };
+ const openMicrophoneSettings = openSettings(window.electronAPI.openMicrophoneSettings);
+ const openAccessibilitySettings = openSettings(window.electronAPI.openAccessibilitySettings);
+ const guideRows: GuidePermission[] = [
+ {
+ id: "microphone",
+ request: async () => {
+ const result = await requestMicrophoneForGuide({
+ requestAccess: window.electronAPI.requestMicrophoneAccess,
+ checkAccess: window.electronAPI.checkMicrophoneAccess,
+ openSettings: openMicrophoneSettings,
+ });
+ permissions.setMicPermissionGranted(result.granted);
+ },
+ check: async () => {
+ const result = await window.electronAPI.checkMicrophoneAccess();
+ permissions.setMicPermissionGranted(result.granted);
+ return result;
+ },
+ openSettings: openMicrophoneSettings,
+ },
+ {
+ id: "accessibility",
+ request: openAccessibilitySettings,
+ check: async () => {
+ const granted = await window.electronAPI.checkAccessibilityPermission(true);
+ permissions.setAccessibilityPermissionGranted(granted);
+ return { granted };
+ },
+ openSettings: openAccessibilitySettings,
+ },
+ ];
+ if (systemAudio.mode === "native")
+ guideRows.push({
+ id: "system-audio",
+ request: systemAudio.request,
+ check: async () => {
+ await systemAudio.check();
+ return window.electronAPI.checkSystemAudioAccess();
+ },
+ verify: async () => {
+ const result = await window.electronAPI.verifySystemAudioAccess();
+ await systemAudio.check();
+ return result;
+ },
+ openSettings: openSettings(window.electronAPI.openSystemAudioSettings),
+ });
+ if (agentAllowed && screenContextAllowed)
+ guideRows.push({
+ id: "screen-context",
+ request: async () => {
+ setScreenContextRequested(true);
+ return requestScreenRecordingAccess();
+ },
+ onGranted: applyScreenContext,
+ check: async () => {
+ const result = await window.electronAPI.checkScreenRecordingAccess();
+ await checkScreenRecording();
+ return result;
+ },
+ openSettings: openSettings(window.electronAPI.openScreenRecordingSettings),
+ });
+ const guideReady = platform === "darwin" && systemAudio.loaded && screenRecordingLoaded;
+ const permissionGuide = usePermissionGuide({
+ enabled: currentStepId === "permissions" && guideReady,
+ progress: session.permissionGuide,
+ save: setPermissionGuide,
+ // Dismissing the guide withdraws the Screen Context opt-in; enabling
+ // another permission while it is still pending does not.
+ dismissed: () => setScreenContextRequested(false),
+ rows: guideRows,
+ });
+
+ useEffect(() => {
+ if (currentStepId !== "permissions" && session.permissionGuide) setPermissionGuide(null);
+ }, [currentStepId, session.permissionGuide, setPermissionGuide]);
const updateCurrentByokDraft = useCallback(
(state: OnboardingByokDraft) => {
if (currentStepId !== "byok-dictation" && currentStepId !== "byok-assistant") return;
@@ -871,6 +954,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
return (
<CompactPermissionsStep
permissions={permissions}
+ guide={{ ...permissionGuide, ready: guideReady }}
systemAudio={systemAudio}
screenContext={
agentAllowed && screenContextAllowed
diff --git a/src/components/onboarding/CompactPermissionsStep.tsx b/src/components/onboarding/CompactPermissionsStep.tsx
index 2d454f2ac..b5d61fc2c 100644
--- a/src/components/onboarding/CompactPermissionsStep.tsx
+++ b/src/components/onboarding/CompactPermissionsStep.tsx
@@ -11,6 +11,7 @@ import accessibilityIcon from "@/assets/onboarding-permission-accessibility.webp
import systemAudioIcon from "@/assets/onboarding-permission-system-audio.webp";
import type { UsePermissionsReturn } from "../../hooks/usePermissions";
import type { SystemAudioAccessResult } from "../../types/electron";
+import type { PermissionGuideId } from "../../types/permissionGuide";
import { canManageSystemAudioInApp } from "../../utils/systemAudioAccess";
import { getPlatform } from "../../utils/platform";
import { areRequiredPermissionsMet } from "../../utils/permissions";
@@ -20,6 +21,11 @@ import PasteToolsInfo from "../ui/PasteToolsInfo";
import { CompactOnboardingFrame } from "./OnboardingShell";
interface CompactPermissionsStepProps {
+ guide?: {
+ start: (permission: PermissionGuideId) => Promise<void>;
+ ready: boolean;
+ error: boolean;
+ };
permissions: UsePermissionsReturn;
systemAudio: Pick<SystemAudioAccessResult, "granted" | "mode" | "supportsOnboardingGrant"> & {
request: () => Promise<boolean>;
@@ -35,8 +41,6 @@ interface CompactPermissionsStepProps {
onContinue: () => void;
}
-type PermissionRowId = "microphone" | "accessibility" | "system-audio" | "screen-context";
-
interface PermissionRowProps {
title: string;
description: string;
@@ -118,6 +122,7 @@ function PermissionRow({
}
export default function CompactPermissionsStep({
+ guide,
permissions,
systemAudio,
screenContext,
@@ -125,7 +130,7 @@ export default function CompactPermissionsStep({
onContinue,
}: CompactPermissionsStepProps) {
const { t } = useTranslation();
- const [busyPermission, setBusyPermission] = useState<PermissionRowId | null>(null);
+ const [busyPermission, setBusyPermission] = useState<PermissionGuideId | null>(null);
const platform = getPlatform();
const canRequestSystemAudio = canManageSystemAudioInApp(systemAudio);
const requiredGranted = areRequiredPermissionsMet(permissions.micPermissionGranted);
@@ -143,10 +148,11 @@ export default function CompactPermissionsStep({
permissions.pasteToolsInfo !== null &&
needsLinuxPasteToolGuidance(permissions.pasteToolsInfo);
- const request = async (id: PermissionRowId, action: () => Promise<unknown>) => {
+ const request = async (id: PermissionGuideId, action: () => Promise<unknown>) => {
setBusyPermission(id);
try {
- await action();
+ if (guide?.ready && !guide.error) await guide.start(id);
+ else await action();
} finally {
setBusyPermission(null);
}
diff --git a/src/components/onboarding/PermissionGuideOverlay.tsx b/src/components/onboarding/PermissionGuideOverlay.tsx
new file mode 100644
index 000000000..0b2398ee2
--- /dev/null
+++ b/src/components/onboarding/PermissionGuideOverlay.tsx
@@ -0,0 +1,165 @@
+import { useEffect, useState, type CSSProperties, type ReactElement } from "react";
+import { useTranslation } from "react-i18next";
+import { ChevronLeft } from "../icons";
+import type { PermissionGuideAction, PermissionGuideState } from "../../types/permissionGuide";
+
+interface CardProps {
+ state: PermissionGuideState;
+ onAction: (action: PermissionGuideAction["action"]) => void;
+ onDrag: () => void;
+}
+
+export function PermissionGuideCard({ state, onAction, onDrag }: CardProps): ReactElement {
+ const { t } = useTranslation();
+ const instructions = {
+ microphone: t("onboarding.permissionGuide.microphone"),
+ accessibility: t("onboarding.permissionGuide.accessibility"),
+ "system-audio": t("onboarding.permissionGuide.systemAudio"),
+ "screen-context": t("onboarding.permissionGuide.screenContext"),
+ };
+ // A failed check shows its recovery actions in place of the drag tile; either
+ // action clears the error and brings the tile back.
+ const dragStep =
+ !state.granted &&
+ !state.error &&
+ (state.permission === "accessibility" || state.permission === "screen-context");
+ const interactive = { WebkitAppRegion: "no-drag" } as CSSProperties;
+ const button =
+ "rounded-full px-3 py-1.5 text-xs font-medium hover:bg-[var(--onboarding-surface-tertiary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--onboarding-accent)] disabled:opacity-50";
+
+ return (
+ <section
+ className="permission-settings-overlay onboarding-canvas flex h-screen items-center gap-3 overflow-y-auto rounded-2xl border border-[var(--onboarding-control-border)] bg-[var(--onboarding-surface)] px-4 py-3 text-[var(--onboarding-text-primary)]"
+ style={{ WebkitAppRegion: "drag" } as CSSProperties}
+ aria-label={t("onboarding.permissionGuide.label")}
+ >
+ <button
+ type="button"
+ className={`${button} shrink-0 p-2! bg-[var(--onboarding-surface-tertiary)]`}
+ style={interactive}
+ onClick={() => onAction("close")}
+ aria-label={t("onboarding.permissionGuide.return")}
+ >
+ <ChevronLeft className="size-4 rtl:rotate-180" />
+ </button>
+ <div className="min-w-0 flex-1">
+ <p className="flex items-center gap-2 text-sm leading-5" aria-live="polite">
+ {dragStep && (
+ <span
+ aria-hidden="true"
+ className="text-3xl leading-none text-[var(--onboarding-accent)]"
+ >
+ ↑
+ </span>
+ )}
+ <span>
+ {state.needsRelaunch
+ ? t("onboarding.permissionGuide.restartRequired")
+ : instructions[state.permission]}
+ </span>
+ </p>
+ {dragStep && (
+ <div
+ draggable={Boolean(state.canDrag)}
+ onDragStart={(event) => {
+ event.preventDefault();
+ if (state.canDrag) onDrag();
+ }}
+ style={interactive}
+ aria-disabled={!state.canDrag}
+ className={`mt-2 flex items-center gap-2.5 rounded-lg border border-[var(--onboarding-control-border)] px-3 py-2 ${state.canDrag ? "cursor-grab active:cursor-grabbing" : "opacity-60"}`}
+ >
+ {state.appIcon && (
+ <img
+ src={state.appIcon}
+ alt=""
+ aria-hidden="true"
+ width={28}
+ height={28}
+ decoding="async"
+ draggable={false}
+ className="size-7"
+ />
+ )}
+ <span className="text-sm font-medium">OpenWhispr</span>
+ <span className="ms-auto text-[11px] text-[var(--onboarding-text-secondary)]">
+ {t("onboarding.permissionGuide.missingApp")}
+ </span>
+ </div>
+ )}
+ {state.error && (
+ <p role="alert" className="mt-1 text-xs text-warning">
+ {t("onboarding.permissionGuide.failed")}
+ </p>
+ )}
+ </div>
+ {(state.permission === "system-audio" || state.needsRelaunch || state.error) && (
+ <div className="flex shrink-0 items-center gap-2" style={interactive}>
+ {state.error && (
+ <button
+ type="button"
+ className={button}
+ disabled={state.busy}
+ onClick={() => onAction("settings")}
+ >
+ {t("onboarding.permissionGuide.settings")}
+ </button>
+ )}
+ <button
+ type="button"
+ className={`${button} bg-[var(--onboarding-accent)] text-white`}
+ disabled={state.busy}
+ onClick={() => onAction(state.needsRelaunch ? "restart" : "check")}
+ >
+ {state.busy
+ ? t("common.loading")
+ : state.needsRelaunch
+ ? t("onboarding.permissionGuide.restart")
+ : t("onboarding.permissionGuide.check")}
+ </button>
+ </div>
+ )}
+ </section>
+ );
+}
+
+export function PermissionGuideOverlay(): ReactElement | null {
+ const [state, setState] = useState<PermissionGuideState | null>(null);
+ useEffect(() => {
+ let disposed = false;
+ let received = false;
+ const unsubscribe = window.electronAPI.onPermissionGuideState?.((next) => {
+ received = true;
+ setState(next);
+ });
+ void window.electronAPI.getPermissionGuideState?.().then((initial) => {
+ if (!disposed && !received && initial) setState(initial);
+ });
+ return () => {
+ disposed = true;
+ unsubscribe?.();
+ };
+ }, []);
+
+ const sessionId = state?.sessionId;
+ const permission = state?.permission;
+ useEffect(() => {
+ if (!sessionId || !permission) return;
+ const keydown = (event: KeyboardEvent): void => {
+ if (event.key === "Escape")
+ window.electronAPI.permissionGuideAction?.({ sessionId, permission, action: "close" });
+ };
+ window.addEventListener("keydown", keydown);
+ return () => window.removeEventListener("keydown", keydown);
+ }, [sessionId, permission]);
+
+ if (!state) return null;
+ const target = { sessionId: state.sessionId, permission: state.permission };
+ return (
+ <PermissionGuideCard
+ state={state}
+ onAction={(action) => window.electronAPI.permissionGuideAction?.({ ...target, action })}
+ onDrag={() => window.electronAPI.startPermissionGuideDrag?.(target)}
+ />
+ );
+}
diff --git a/src/components/onboarding/flow.ts b/src/components/onboarding/flow.ts
index 95a1466d8..528ea1e58 100644
--- a/src/components/onboarding/flow.ts
+++ b/src/components/onboarding/flow.ts
@@ -1,5 +1,6 @@
import { SIGN_IN_PROMPTED_AT_KEY } from "../../utils/requestSignIn";
import { PENDING_LOCAL_MODELS_KEY } from "./pendingLocalModels";
+import type { PermissionGuideId } from "../../types/permissionGuide";
export const ONBOARDING_SESSION_KEY = "onboardingSessionV2";
export const LEGACY_ONBOARDING_STEP_KEY = "onboardingCurrentStep";
@@ -89,6 +90,7 @@ export interface OnboardingSession {
* dropped with the session at finalization.
*/
screenContextRequested: boolean;
+ permissionGuide: PermissionGuideId | null;
resume: OnboardingResumeState;
}
@@ -205,6 +207,7 @@ export function createOnboardingSession(): OnboardingSession {
setupMode: null,
selfHostedRequested: false,
screenContextRequested: false,
+ permissionGuide: null,
resume: createOnboardingResumeState(),
};
}
@@ -292,6 +295,13 @@ export function isOnboardingStepId(value: unknown): value is OnboardingStepId {
return typeof value === "string" && KNOWN_STEPS.has(value as OnboardingStepId);
}
+function isPermissionGuideId(value: unknown): value is PermissionGuideId {
+ return (
+ typeof value === "string" &&
+ ["microphone", "accessibility", "system-audio", "screen-context"].includes(value)
+ );
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
@@ -440,6 +450,7 @@ export function parseOnboardingSession(value: string | null): OnboardingSession
setupMode,
selfHostedRequested: parsed.selfHostedRequested ?? false,
screenContextRequested: parsed.screenContextRequested ?? false,
+ permissionGuide: isPermissionGuideId(parsed.permissionGuide) ? parsed.permissionGuide : null,
resume: parseOnboardingResumeState(parsed.resume, parsed.currentStepId),
};
} catch {
diff --git a/src/components/onboarding/permissionGuideController.ts b/src/components/onboarding/permissionGuideController.ts
new file mode 100644
index 000000000..15e73f9f4
--- /dev/null
+++ b/src/components/onboarding/permissionGuideController.ts
@@ -0,0 +1,211 @@
+import type {
+ PermissionGuideAction,
+ PermissionGuideId,
+ PermissionGuideState,
+} from "../../types/permissionGuide";
+
+export interface GuideAccess {
+ granted: boolean;
+ needsRelaunch?: boolean;
+}
+
+export interface GuidePermission {
+ id: PermissionGuideId;
+ request: () => Promise<unknown>;
+ check: () => Promise<GuideAccess>;
+ verify?: () => Promise<GuideAccess>;
+ openSettings: () => Promise<unknown>;
+ onGranted?: () => void;
+}
+
+interface ControllerOptions {
+ sessionId: string;
+ rows: () => GuidePermission[];
+ save: (progress: PermissionGuideId | null) => void;
+ publish: (state: PermissionGuideState) => Promise<boolean>;
+ // The helper could not be opened for a request that is still live; a false
+ // publish for a superseded request is expected and not reported.
+ unavailable: () => void;
+ dismissed: () => void;
+ close: () => void;
+ restart: () => Promise<unknown>;
+}
+
+interface MicrophoneAccess {
+ requestAccess: () => Promise<unknown>;
+ checkAccess: () => Promise<{ granted: boolean; status: string }>;
+ openSettings: () => Promise<unknown>;
+}
+
+// The native prompt is the request. Settings only helps after a denial: until
+// the user has answered a prompt the Privacy pane does not list the app, and
+// the in-app alert that getUserMedia raises would stack under the overlay.
+export async function requestMicrophoneForGuide(
+ access: MicrophoneAccess
+): Promise<{ granted: boolean; status: string }> {
+ await access.requestAccess();
+ const result = await access.checkAccess();
+ if (result.status === "denied") await access.openSettings();
+ return result;
+}
+
+export function createPermissionGuideController(options: ControllerOptions): {
+ start: (requested?: PermissionGuideId, saved?: PermissionGuideId) => Promise<void>;
+ act: (action: PermissionGuideAction) => Promise<void>;
+ refresh: () => Promise<void>;
+ reconcile: () => Promise<void>;
+ dispose: () => void;
+} {
+ let current: PermissionGuideId | null = null;
+ let busy = false;
+ let checking = false;
+ let error = false;
+ let revision = 0;
+ let access: GuideAccess = { granted: false };
+
+ const row = (): GuidePermission | undefined => options.rows().find((item) => item.id === current);
+ const close = (): void => {
+ revision++;
+ current = null;
+ busy = false;
+ options.save(null);
+ options.close();
+ };
+ const valid = (expected: number): boolean => revision === expected && !!row();
+
+ const publish = async (): Promise<void> => {
+ if (!current || !row()) return;
+ if (access.granted && !access.needsRelaunch) {
+ close();
+ return;
+ }
+ const expected = revision;
+ const opened = await options.publish({
+ sessionId: options.sessionId,
+ permission: current,
+ granted: access.granted,
+ needsRelaunch: access.needsRelaunch ?? false,
+ busy,
+ error,
+ });
+ if (!opened && valid(expected)) {
+ close();
+ options.unavailable();
+ }
+ };
+
+ const accept = (result: GuideAccess, expected: number): void => {
+ if (!valid(expected)) return;
+ const consented = access.granted;
+ access = result;
+ // Apply feature consent once, on the grant, and only while this explicit
+ // request is still active and eligible: a grant that needs a relaunch keeps
+ // the helper open, so later checks report granted again.
+ if (result.granted && !consented) row()?.onGranted?.();
+ };
+
+ const reconcile = async (): Promise<void> => {
+ if (current && !row()) close();
+ };
+
+ const refresh = async (): Promise<void> => {
+ await reconcile();
+ const permission = row();
+ if (!permission || busy || checking || current === "system-audio") return;
+ const expected = revision;
+ checking = true;
+ try {
+ const before = access;
+ accept(await permission.check(), expected);
+ if (!valid(expected)) return;
+ // Only a change is published: a publish racing a close from main would
+ // reopen the overlay the user just dismissed.
+ if (access.granted !== before.granted || !!access.needsRelaunch !== !!before.needsRelaunch)
+ await publish();
+ } catch {
+ if (valid(expected)) {
+ error = true;
+ await publish();
+ }
+ } finally {
+ checking = false;
+ }
+ };
+
+ const start = async (requested?: PermissionGuideId, saved?: PermissionGuideId): Promise<void> => {
+ if (busy) return;
+ const permission = options.rows().find((item) => item.id === (saved ?? requested));
+ if (!permission) {
+ if (saved) close();
+ return;
+ }
+ if (current) options.close();
+ current = permission.id;
+ access = { granted: false };
+ busy = true;
+ error = false;
+ const expected = ++revision;
+ // Save before the native request; macOS can restart the app while applying access.
+ options.save(current);
+ try {
+ // The onboarding Enable button is the consent action. Never put a helper in front
+ // of a native prompt or require a second click before opening System Settings.
+ if (!saved) await permission.request();
+ if (!valid(expected)) return;
+ accept(await row()!.check(), expected);
+ // A resume only has to recognize a grant that landed before a relaunch;
+ // without one there is no System Settings window to anchor a helper to.
+ if (saved && !access.granted && valid(expected)) close();
+ } catch {
+ if (valid(expected)) error = true;
+ } finally {
+ if (valid(expected)) {
+ busy = false;
+ await publish();
+ }
+ }
+ };
+
+ const act = async (message: PermissionGuideAction): Promise<void> => {
+ if (!current || message.sessionId !== options.sessionId || message.permission !== current)
+ return;
+ if (message.action === "close") {
+ options.dismissed();
+ close();
+ return;
+ }
+ const permission = row();
+ if (!permission || busy) return;
+ if (message.action === "restart" && !access.needsRelaunch) return;
+ if (message.action === "check" && current !== "system-audio" && !error) return;
+ busy = true;
+ error = false;
+ const expected = ++revision;
+ try {
+ await publish();
+ if (!valid(expected)) return;
+ if (message.action === "restart") await options.restart();
+ else if (message.action === "settings") await permission.openSettings();
+ else accept(await (permission.verify ?? permission.check)(), expected);
+ } catch {
+ if (valid(expected)) error = true;
+ } finally {
+ if (valid(expected)) {
+ busy = false;
+ await publish();
+ }
+ }
+ };
+
+ return {
+ start,
+ act,
+ refresh,
+ reconcile,
+ dispose: (): void => {
+ revision++;
+ current = null;
+ busy = false;
+ },
+ };
+}
diff --git a/src/components/onboarding/useOnboardingSession.ts b/src/components/onboarding/useOnboardingSession.ts
index c1fca3da1..b28ebde14 100644
--- a/src/components/onboarding/useOnboardingSession.ts
+++ b/src/components/onboarding/useOnboardingSession.ts
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useState } from "react";
+import type { PermissionGuideId } from "../../types/permissionGuide";
import {
LEGACY_ONBOARDING_STEP_KEY,
ONBOARDING_SESSION_KEY,
@@ -78,6 +79,10 @@ export function useOnboardingSession() {
setSession((current) => ({ ...current, screenContextRequested }));
}, []);
+ const setPermissionGuide = useCallback((permissionGuide: PermissionGuideId | null) => {
+ setSession((current) => ({ ...current, permissionGuide }));
+ }, []);
+
const clearSession = useCallback(() => {
localStorage.removeItem(ONBOARDING_SESSION_KEY);
localStorage.removeItem(LEGACY_ONBOARDING_STEP_KEY);
@@ -92,6 +97,7 @@ export function useOnboardingSession() {
setSetupMode,
setSelfHostedRequested,
setScreenContextRequested,
+ setPermissionGuide,
clearSession,
};
}
diff --git a/src/components/onboarding/usePermissionGuide.ts b/src/components/onboarding/usePermissionGuide.ts
new file mode 100644
index 000000000..59c4a7f11
--- /dev/null
+++ b/src/components/onboarding/usePermissionGuide.ts
@@ -0,0 +1,75 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { PermissionGuideId } from "../../types/permissionGuide";
+import { createPermissionGuideController, type GuidePermission } from "./permissionGuideController";
+
+interface Options {
+ enabled: boolean;
+ progress: PermissionGuideId | null;
+ save: (progress: PermissionGuideId | null) => void;
+ dismissed: () => void;
+ rows: GuidePermission[];
+}
+
+export function usePermissionGuide(options: Options): {
+ start: (permission: PermissionGuideId) => Promise<void>;
+ error: boolean;
+} {
+ const latest = useRef(options);
+ latest.current = options;
+ const controller = useRef<ReturnType<typeof createPermissionGuideController> | null>(null);
+ const [error, setError] = useState(false);
+ const eligibility = options.rows.map((row) => row.id).join(",");
+
+ useEffect(() => {
+ if (!options.enabled) return;
+ const api = window.electronAPI;
+ const guide = createPermissionGuideController({
+ sessionId: crypto.randomUUID(),
+ rows: () => latest.current.rows,
+ save: (progress) => latest.current.save(progress),
+ publish: async (state) => {
+ try {
+ return (await api.openPermissionGuide?.(state)) ?? false;
+ } catch {
+ return false;
+ }
+ },
+ unavailable: () => setError(true),
+ dismissed: () => latest.current.dismissed(),
+ close: () => {
+ void api.closePermissionGuide?.().catch(() => {});
+ },
+ restart: api.relaunchApp,
+ });
+ controller.current = guide;
+ const unsubscribe = api.onPermissionGuideAction?.((action) => {
+ void guide.act(action);
+ });
+ const refresh = (): void => {
+ void guide.refresh();
+ };
+ // Re-checked often enough that the overlay disappears as soon as the user
+ // grants the permission — dragging the app into the list enables it, and a
+ // slower loop reads as the overlay ignoring what you just did.
+ const timer = window.setInterval(refresh, 750);
+ window.addEventListener("focus", refresh);
+ if (latest.current.progress) void guide.start(undefined, latest.current.progress);
+ return () => {
+ controller.current = null;
+ guide.dispose();
+ unsubscribe?.();
+ clearInterval(timer);
+ window.removeEventListener("focus", refresh);
+ void api.closePermissionGuide?.().catch(() => {});
+ };
+ }, [options.enabled]);
+
+ useEffect(() => {
+ void controller.current?.reconcile();
+ }, [eligibility]);
+
+ const start = useCallback(async (permission: PermissionGuideId): Promise<void> => {
+ await controller.current?.start(permission);
+ }, []);
+ return { start, error };
+}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 27ab76f0b..155f53d95 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -1342,6 +1342,22 @@ class IPCHandlers {
this.windowManager.setOnboardingWindowMode(mode)
);
+ ipcMain.handle("permission-guide-open", (event, state) =>
+ this.windowManager.permissionGuide.open(event, state)
+ );
+ ipcMain.handle("permission-guide-close", (event) =>
+ this.windowManager.permissionGuide.closeFromOwner(event)
+ );
+ ipcMain.handle("permission-guide-state", (event) =>
+ this.windowManager.permissionGuide.stateFor(event)
+ );
+ ipcMain.on("permission-guide-action", (event, action) =>
+ this.windowManager.permissionGuide.handleAction(event, action)
+ );
+ ipcMain.on("permission-guide-drag", (event, target) =>
+ this.windowManager.permissionGuide.startDrag(event, target)
+ );
+
// WindowManager owns every teardown path for a demo (id-matched end,
// onboarding-set-active(false), control panel closed); without this hook a
// renderer crash mid-demo would leave the session set and broadcast every
@@ -5934,6 +5950,12 @@ class IPCHandlers {
ipcMain.handle("check-system-audio-access", () => getSystemAudioAccess());
+ ipcMain.handle("permission-guide-verify-system-audio", async () => {
+ if (!this.audioTapManager?.isSupported()) return buildSystemAudioAccess();
+ const result = await this.audioTapManager.requestAccess();
+ return buildSystemAudioAccess({ ...result, mode: "native", strategy: "native" });
+ });
+
ipcMain.handle("request-system-audio-access", async () => {
if (process.platform === "win32") {
return getWindowsSystemAudioAccess();
diff --git a/src/helpers/permissionGuideManager.js b/src/helpers/permissionGuideManager.js
new file mode 100644
index 000000000..1308c7869
--- /dev/null
+++ b/src/helpers/permissionGuideManager.js
@@ -0,0 +1,356 @@
+const { app, BrowserWindow, nativeImage, screen } = require("electron");
+const path = require("path");
+const DevServerManager = require("./devServerManager");
+const debugLogger = require("./debugLogger");
+const { computeGuideBounds } = require("./permissionGuidePlacement");
+const {
+ isSettingsWindowStateAvailable,
+ readSettingsWindowState,
+} = require("./settingsWindowState");
+
+const PERMISSIONS = new Set(["microphone", "accessibility", "system-audio", "screen-context"]);
+const ACTIONS = new Set(["check", "settings", "close", "restart"]);
+const GUIDE_SIZE = { width: 560, height: 124 };
+const POLL_MS = 500;
+// System Settings takes a moment to put its window up after the Enable click.
+// Showing before then is what made the overlay appear low and then jump.
+const SETTINGS_WAIT_ATTEMPTS = 6;
+
+function validState(state) {
+ return (
+ state &&
+ typeof state.sessionId === "string" &&
+ state.sessionId.length > 0 &&
+ state.sessionId.length <= 128 &&
+ PERMISSIONS.has(state.permission) &&
+ ["granted", "needsRelaunch", "busy", "error"].every((key) => typeof state[key] === "boolean")
+ );
+}
+
+function fromWindow(event, window) {
+ return (
+ window &&
+ !window.isDestroyed() &&
+ event.sender === window.webContents &&
+ event.senderFrame === window.webContents.mainFrame
+ );
+}
+
+class PermissionGuideManager {
+ constructor(windowManager, { wait } = {}) {
+ this.windowManager = windowManager;
+ this.window = null;
+ this.owner = null;
+ // The owner's contents, held separately: once a BrowserWindow has closed,
+ // reading its webContents throws, and the listeners still have to come off.
+ this.ownerContents = null;
+ this.state = null;
+ this.bundlePath = null;
+ this.icon = null;
+ this.wait = wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
+ this.sawSettings = false;
+ this.steppedAside = false;
+ this.pollTimer = null;
+ // The onboarding document that owns this guide is gone: closed, crashed, or
+ // navigated away (log out reloads it, the OAuth refresh loads a new URL).
+ // Not wired to hide: on macOS that fires on occlusion too, and isVisible()
+ // folds occlusion in as well, so neither can tell a covered window from one
+ // sent to the tray. hideControlPanelToTray() closes the guide explicitly.
+ this.ownerGone = () => this.close(false, true);
+ this.ownerNavigated = (navigation) => {
+ if (navigation.isMainFrame && !navigation.isSameDocument) this.ownerGone();
+ };
+ }
+
+ // Not restoring focus: the renderer closes on a grant, and the user may
+ // still be in System Settings for the next permission.
+ closeFromOwner(event) {
+ if (!this.isOwner(event)) return false;
+ this.close();
+ return true;
+ }
+
+ stateFor(event) {
+ return fromWindow(event, this.window) ? this.snapshot() : null;
+ }
+
+ handleAction(event, action) {
+ if (!fromWindow(event, this.window) || !this.matches(action) || !ACTIONS.has(action.action))
+ return;
+ // Closing is done here, not echoed back through the owner: the owner may
+ // no longer be listening, and the guide must never outlive its controls.
+ if (action.action === "close") this.close(true, true);
+ else this.sendAction(action.action);
+ }
+
+ startDrag(event, target) {
+ if (!fromWindow(event, this.window) || !this.matches(target) || !this.snapshot().canDrag)
+ return;
+ try {
+ event.sender.startDrag({ file: this.bundlePath, icon: this.icon });
+ } catch (error) {
+ debugLogger.warn("Permission guide drag failed", { error: error.message });
+ }
+ }
+
+ isOwner(event) {
+ return (
+ process.platform === "darwin" &&
+ this.windowManager._onboardingActive &&
+ fromWindow(event, this.windowManager.controlPanelWindow)
+ );
+ }
+
+ matches(target) {
+ return (
+ target &&
+ this.state &&
+ target.sessionId === this.state.sessionId &&
+ target.permission === this.state.permission
+ );
+ }
+
+ snapshot() {
+ if (!this.state) return null;
+ return {
+ ...this.state,
+ canDrag:
+ !!this.bundlePath &&
+ !this.state.busy &&
+ !this.state.granted &&
+ ["accessibility", "screen-context"].includes(this.state.permission),
+ appIcon: this.icon?.toDataURL(),
+ };
+ }
+
+ setState(state) {
+ // Only forward presentation fields; filesystem paths and app identity belong to main.
+ this.state = Object.fromEntries(
+ ["sessionId", "permission", "granted", "needsRelaunch", "busy", "error"].map((key) => [
+ key,
+ state[key],
+ ])
+ );
+ if (this.window && !this.window.isDestroyed()) {
+ this.window.webContents.send("permission-guide-state-changed", this.snapshot());
+ }
+ }
+
+ workAreaFor(rect) {
+ return screen.getDisplayMatching(rect).workArea;
+ }
+
+ // Anchored inside the System Settings window, falling back to the bottom of
+ // the display while that window has not appeared.
+ applyBounds(window, settings) {
+ // Keyed off the dialog, not the onboarding window: System Settings can open
+ // on a different display, and clamping to the onboarding window's screen
+ // strands the overlay away from the dialog it belongs to.
+ const bounds = computeGuideBounds({
+ settingsBounds: settings,
+ workArea: this.workAreaFor(settings ?? this.owner.getBounds()),
+ size: GUIDE_SIZE,
+ });
+ const current = window.getBounds();
+ if (current.x !== bounds.x || current.y !== bounds.y) window.setBounds(bounds);
+ }
+
+ async waitForSettings(window) {
+ let state = await readSettingsWindowState();
+ for (let attempt = 0; attempt < SETTINGS_WAIT_ATTEMPTS && !state?.settings; attempt++) {
+ await this.wait(POLL_MS);
+ if (this.window !== window || window.isDestroyed()) return null;
+ state = await readSettingsWindowState();
+ }
+ return state;
+ }
+
+ // One tick of the overlay's relationship with the settings window: follow it,
+ // step aside for an authorization prompt, and close with it.
+ async poll() {
+ const window = this.window;
+ if (!window || window.isDestroyed()) return;
+
+ const state = await readSettingsWindowState();
+ // A failed read is unknown, not closed: acting on it would dismiss the
+ // overlay over a transient hiccup.
+ if (!state || this.window !== window || window.isDestroyed()) return;
+
+ if (state.settings) {
+ this.sawSettings = true;
+ this.applyBounds(window, state.settings);
+ } else if (this.sawSettings && !state.settingsRunning) {
+ this.close(true, true);
+ return;
+ }
+
+ const aside = this.shouldStepAside(state);
+ if (aside === this.steppedAside) return;
+ this.steppedAside = aside;
+ if (aside) window.hide();
+ else window.showInactive();
+ }
+
+ // The overlay belongs to the settings dialog: it steps aside for an
+ // authorization prompt, for any other app the user brings to the front, and
+ // while the dialog is on another Space.
+ shouldStepAside(state) {
+ return (
+ state.authPrompt || state.frontmost === "other" || (!state.settings && state.settingsRunning)
+ );
+ }
+
+ // One read at a time: an interval would keep firing while a slow helper is
+ // still running, and two reads in flight can answer out of order.
+ startPolling() {
+ this.stopPolling();
+ const window = this.window;
+ const tick = async () => {
+ await this.poll();
+ if (this.window === window) this.pollTimer = setTimeout(tick, POLL_MS);
+ };
+ this.pollTimer = setTimeout(tick, POLL_MS);
+ }
+
+ stopPolling() {
+ if (this.pollTimer === null) return;
+ clearTimeout(this.pollTimer);
+ this.pollTimer = null;
+ }
+
+ sendAction(action) {
+ if (this.state && this.ownerContents && !this.ownerContents.isDestroyed()) {
+ this.ownerContents.send("permission-guide-action", {
+ sessionId: this.state.sessionId,
+ permission: this.state.permission,
+ action,
+ });
+ }
+ }
+
+ async open(event, state) {
+ if (!this.isOwner(event) || !validState(state)) return false;
+ // Without the helper the overlay could neither follow the dialog nor close
+ // with it; refusing lets Enable fall back to the plain Settings flow.
+ if (!isSettingsWindowStateAvailable()) return false;
+ if (this.window && !this.window.isDestroyed() && state.sessionId === this.state?.sessionId) {
+ this.setState(state);
+ return true;
+ }
+ this.close();
+ const owner = this.windowManager.controlPanelWindow;
+ this.owner = owner;
+ this.ownerContents = owner.webContents;
+ const window = new BrowserWindow({
+ // Created at the fallback spot with no await between here and the
+ // this.window assignment below, so a second publish takes the early
+ // return above instead of tearing this window down. The anchored bounds
+ // are applied further down, while the window is still hidden.
+ ...computeGuideBounds({
+ settingsBounds: null,
+ workArea: this.workAreaFor(owner.getBounds()),
+ size: GUIDE_SIZE,
+ }),
+ frame: false,
+ transparent: true,
+ backgroundColor: "#00000000",
+ show: false,
+ alwaysOnTop: true,
+ skipTaskbar: true,
+ resizable: false,
+ minimizable: false,
+ maximizable: false,
+ fullscreenable: false,
+ focusable: true,
+ acceptFirstMouse: true,
+ hasShadow: true,
+ webPreferences: {
+ preload: path.join(__dirname, "../../preload.js"),
+ nodeIntegration: false,
+ contextIsolation: true,
+ sandbox: true,
+ },
+ });
+ // System Settings may be on another Space; without this the overlay can be
+ // ordered onto the Space being left and stay invisible there.
+ window.setVisibleOnAllWorkspaces(true, {
+ visibleOnFullScreen: true,
+ skipTransformProcessType: true,
+ });
+ this.window = window;
+ this.setState(state);
+ owner.on("closed", this.ownerGone);
+ this.ownerContents.on("render-process-gone", this.ownerGone);
+ this.ownerContents.on("did-start-navigation", this.ownerNavigated);
+ window.on("closed", () => {
+ if (this.window === window) this.close(false, true);
+ });
+ window.webContents.on("render-process-gone", () => {
+ if (this.window === window) this.close(true, true);
+ });
+ window.webContents.on("will-navigate", (navigation) => navigation.preventDefault());
+ window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
+
+ try {
+ // Anchored before the load, so the overlay is already in place by the time
+ // showInactive() below makes it visible.
+ const settingsState = await this.waitForSettings(window);
+ if (this.window !== window || window.isDestroyed()) return false;
+ if (settingsState?.settings) this.sawSettings = true;
+ this.applyBounds(window, settingsState?.settings ?? null);
+
+ if (app.isPackaged) {
+ this.bundlePath = path.resolve(app.getPath("exe"), "../../..");
+ // The PNG, not icon.icns: nativeImage cannot read .icns. Downscaled
+ // because the snapshot carries it as a data URL on every state publish.
+ this.icon = nativeImage
+ .createFromPath(path.join(process.resourcesPath, "src", "assets", "icon.png"))
+ .resize({ width: 64, height: 64 });
+ }
+ if (process.env.NODE_ENV === "development") {
+ await window.loadURL(`${DevServerManager.DEV_SERVER_URL}?permission-guide=true`);
+ } else {
+ const file = DevServerManager.getAppFilePath(false);
+ await window.loadFile(file.path, { query: { ...file.query, "permission-guide": "true" } });
+ }
+ if (this.window !== window || window.isDestroyed()) return false;
+ window.webContents.send("permission-guide-state-changed", this.snapshot());
+ this.steppedAside = Boolean(settingsState && this.shouldStepAside(settingsState));
+ if (!this.steppedAside) window.showInactive();
+ this.startPolling();
+ return true;
+ } catch (error) {
+ debugLogger.error("Could not open permission guide", { error: error.message });
+ if (this.window === window) this.close();
+ return false;
+ }
+ }
+
+ close(restore = false, notify = false) {
+ const window = this.window;
+ const owner = this.owner;
+ const ownerContents = this.ownerContents;
+ this.stopPolling();
+ if (notify) this.sendAction("close");
+ this.window = null;
+ this.state = null;
+ this.owner = null;
+ this.ownerContents = null;
+ this.bundlePath = null;
+ this.icon = null;
+ this.sawSettings = false;
+ this.steppedAside = false;
+ if (owner) owner.removeListener("closed", this.ownerGone);
+ if (ownerContents) {
+ ownerContents.removeListener("render-process-gone", this.ownerGone);
+ ownerContents.removeListener("did-start-navigation", this.ownerNavigated);
+ }
+ if (window && !window.isDestroyed()) window.close();
+ if (restore && owner && !owner.isDestroyed()) {
+ owner.show();
+ owner.focus();
+ }
+ }
+}
+
+exports.PermissionGuideManager = PermissionGuideManager;
diff --git a/src/helpers/permissionGuidePlacement.js b/src/helpers/permissionGuidePlacement.js
new file mode 100644
index 000000000..29080791d
--- /dev/null
+++ b/src/helpers/permissionGuidePlacement.js
@@ -0,0 +1,35 @@
+// Placement for the permission guide overlay. Kept free of Electron so the
+// geometry can be unit-tested: the manager supplies the work area, the size and
+// the System Settings window bounds (null when it is closed or unreadable).
+
+// The overlay sits inside the System Settings window, this far above its bottom
+// edge; SCREEN_MARGIN is the gutter it keeps from the bottom of the screen when
+// it falls back or when the inset spot would land off screen.
+const BOTTOM_INSET = 20;
+const SCREEN_MARGIN = 24;
+
+function clamp(value, min, max) {
+ return Math.min(Math.max(value, min), Math.max(min, max));
+}
+
+function computeGuideBounds({ settingsBounds, workArea, size }) {
+ const width = Math.min(size.width, workArea.width);
+ const height = Math.min(size.height, workArea.height);
+ const lowestTop = workArea.y + workArea.height - height - SCREEN_MARGIN;
+
+ const anchor = settingsBounds
+ ? {
+ x: settingsBounds.x + (settingsBounds.width - width) / 2,
+ y: settingsBounds.y + settingsBounds.height - height - BOTTOM_INSET,
+ }
+ : { x: workArea.x + (workArea.width - width) / 2, y: lowestTop };
+
+ return {
+ x: Math.round(clamp(anchor.x, workArea.x, workArea.x + workArea.width - width)),
+ y: Math.round(clamp(anchor.y, workArea.y, lowestTop)),
+ width,
+ height,
+ };
+}
+
+module.exports = { computeGuideBounds, BOTTOM_INSET, SCREEN_MARGIN };
diff --git a/src/helpers/settingsWindowState.js b/src/helpers/settingsWindowState.js
new file mode 100644
index 000000000..1b804391c
--- /dev/null
+++ b/src/helpers/settingsWindowState.js
@@ -0,0 +1,47 @@
+const { execFile } = require("child_process");
+const { resolveBundledBinary } = require("./binaryResolver");
+
+// The guide polls this while the overlay is open, so a hung helper must never
+// hold it up: the query is cheap enough that a short timeout is plenty.
+const TIMEOUT_MS = 400;
+
+// Resolved once: the resolver logs every lookup, and the guide polls twice a
+// second for as long as the overlay is open.
+let binaryPath;
+function helperBinary() {
+ if (binaryPath === undefined) {
+ binaryPath =
+ process.platform === "darwin"
+ ? resolveBundledBinary("macos-window-bounds", "permission-guide")
+ : null;
+ }
+ return binaryPath;
+}
+
+function isSettingsWindowStateAvailable() {
+ return helperBinary() !== null;
+}
+
+// { settings: bounds | null, authPrompt, frontmost, settingsRunning }, or null
+// when the state could not be read at all. null means unknown, never "closed":
+// dismissing the overlay on a transient read failure would strand the user
+// mid-permission. settingsRunning tells a dialog on another Space (no window
+// on screen, app still running) from one that was closed.
+function readSettingsWindowState() {
+ const binary = helperBinary();
+ if (!binary) return Promise.resolve(null);
+
+ return new Promise((resolve) => {
+ execFile(binary, [String(process.pid)], { timeout: TIMEOUT_MS }, (error, stdout) => {
+ if (error) return resolve(null);
+
+ try {
+ resolve(JSON.parse(String(stdout)));
+ } catch {
+ resolve(null);
+ }
+ });
+ });
+}
+
+module.exports = { readSettingsWindowState, isSettingsWindowStateAvailable };
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index 34c95a7ef..4c663ca4b 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -1588,6 +1588,7 @@ class WindowManager {
setOnboardingActive(active) {
const nextActive = active === true;
+ if (!nextActive) this.permissionGuide?.close();
if (nextActive === this._onboardingActive) {
if (nextActive) this._hideNormalAppSurfaces();
return true;
@@ -1785,6 +1786,9 @@ class WindowManager {
// A demo left running when the panel hides would keep swallowing normal
// dictations (paste suppressed, transcripts rerouted to the demo session).
this.endOnboardingDemo();
+ // The guide cannot watch the panel's hide event (occlusion fires it too),
+ // so the one real hide path tells it.
+ this.permissionGuide?.close(false, true);
this.controlPanelWindow.hide();
dockManager.setControlPanelVisible(false);
}
diff --git a/src/hooks/useScreenRecordingPermission.ts b/src/hooks/useScreenRecordingPermission.ts
index 9438ab864..fbaaca141 100644
--- a/src/hooks/useScreenRecordingPermission.ts
+++ b/src/hooks/useScreenRecordingPermission.ts
@@ -52,6 +52,8 @@ export function useScreenRecordingPermission() {
granted: access?.granted ?? false,
supported: access?.supported ?? true,
needsRelaunch: access?.needsRelaunch ?? false,
+ loaded: access !== null,
+ check,
request,
isMacOS,
};
diff --git a/src/hooks/useSystemAudioPermission.ts b/src/hooks/useSystemAudioPermission.ts
index 6646216b1..b332e75ec 100644
--- a/src/hooks/useSystemAudioPermission.ts
+++ b/src/hooks/useSystemAudioPermission.ts
@@ -84,6 +84,7 @@ export function useSystemAudioPermission() {
const portalVersion = access?.portalVersion ?? null;
return {
+ loaded: access !== null,
granted,
status,
mode,
diff --git a/src/index.css b/src/index.css
index 3063e2512..a10f0e6b2 100644
--- a/src/index.css
+++ b/src/index.css
@@ -241,7 +241,9 @@
is cleared here rather than filled. The compact frame owns the complete
480x576 surface, including its rounded corners. */
body:has(.onboarding-canvas.compact),
- body:has(.onboarding-canvas.compact) #root {
+ body:has(.onboarding-canvas.compact) #root,
+ body:has(.permission-settings-overlay),
+ body:has(.permission-settings-overlay) #root {
background: transparent;
}
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index f285925f6..09eddf37a 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -2911,6 +2911,20 @@
"title": "لم يكتمل التنزيل",
"description": "تحقق من اتصالك والمساحة الخالية على القرص، ثم أعد المحاولة. إذا استمر الفشل، فاتصل بالمسؤول."
}
+ },
+ "permissionGuide": {
+ "label": "دليل الأذونات",
+ "return": "العودة إلى الإعداد",
+ "missingApp": "أو اختر التطبيق عبر +",
+ "failed": "تعذر التحقق من الوصول.",
+ "microphone": "فعّل OpenWhispr ضمن الميكروفون.",
+ "accessibility": "اسحب OpenWhispr إلى تسهيلات الاستخدام، ثم فعّله.",
+ "systemAudio": "فعّل OpenWhispr ضمن تسجيل صوت النظام فقط.",
+ "screenContext": "اسحب OpenWhispr إلى تسجيل الشاشة وصوت النظام، ثم فعّله.",
+ "settings": "فتح الإعدادات",
+ "check": "التحقق مجددًا",
+ "restart": "إعادة التشغيل",
+ "restartRequired": "أعد تشغيل OpenWhispr لتطبيق الوصول إلى الشاشة."
}
},
"settingsPage": {
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 77860ff04..2da5a0510 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -579,6 +579,20 @@
"title": "Ein Download wurde nicht abgeschlossen",
"description": "Prüfen Sie Ihre Verbindung und den freien Speicherplatz und versuchen Sie es erneut. Wenn der Fehler weiterhin auftritt, wenden Sie sich an Ihren Administrator."
}
+ },
+ "permissionGuide": {
+ "label": "Berechtigungsassistent",
+ "return": "Zurück zur Einrichtung",
+ "missingApp": "Oder wähle die App über +",
+ "failed": "Zugriff konnte nicht geprüft werden.",
+ "microphone": "Aktiviere OpenWhispr unter Mikrofon.",
+ "accessibility": "Ziehe OpenWhispr in Bedienungshilfen und aktiviere es.",
+ "systemAudio": "Aktiviere OpenWhispr unter „Nur Systemaudioaufnahme“.",
+ "screenContext": "Ziehe OpenWhispr in „Bildschirm- & Systemaudioaufnahme“ und aktiviere es.",
+ "settings": "Einstellungen",
+ "check": "Erneut prüfen",
+ "restart": "App neu starten",
+ "restartRequired": "Starte OpenWhispr für den Bildschirmzugriff neu."
}
},
"streaming": {
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index b560c3c7f..a82b5130b 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -579,6 +579,20 @@
"title": "A download didn't finish",
"description": "Check your connection and free disk space, then retry. If it keeps failing, contact your administrator."
}
+ },
+ "permissionGuide": {
+ "label": "Permission guide",
+ "return": "Return to onboarding",
+ "missingApp": "Or use + to select the app",
+ "failed": "Could not check access.",
+ "microphone": "Turn on OpenWhispr in Microphone.",
+ "accessibility": "Drag OpenWhispr into Accessibility, then turn it on.",
+ "systemAudio": "Turn on OpenWhispr under System Audio Recording Only.",
+ "screenContext": "Drag OpenWhispr into Screen & System Audio Recording, then turn it on.",
+ "settings": "Open Settings",
+ "check": "Check again",
+ "restart": "Restart OpenWhispr",
+ "restartRequired": "Restart OpenWhispr to apply screen access."
}
},
"streaming": {
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 153cf9f38..e83989eb0 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -579,6 +579,20 @@
"title": "Una descarga no se completó",
"description": "Comprueba tu conexión y el espacio libre en disco, y vuelve a intentarlo. Si sigue fallando, contacta a tu administrador."
}
+ },
+ "permissionGuide": {
+ "label": "Guía de permisos",
+ "return": "Volver a la configuración",
+ "missingApp": "O selecciona la app con +",
+ "failed": "No se pudo comprobar el acceso.",
+ "microphone": "Activa OpenWhispr en Micrófono.",
+ "accessibility": "Arrastra OpenWhispr a Accesibilidad y actívalo.",
+ "systemAudio": "Activa OpenWhispr en Solo grabación de audio del sistema.",
+ "screenContext": "Arrastra OpenWhispr a Grabación de pantalla y audio del sistema y actívalo.",
+ "settings": "Abrir Ajustes",
+ "check": "Comprobar de nuevo",
+ "restart": "Reiniciar app",
+ "restartRequired": "Reinicia OpenWhispr para aplicar el acceso a la pantalla."
}
},
"streaming": {
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 204bee777..1f92a5825 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -579,6 +579,20 @@
"title": "Un téléchargement ne s'est pas terminé",
"description": "Vérifiez votre connexion et l'espace disque disponible, puis réessayez. Si le problème persiste, contactez votre administrateur."
}
+ },
+ "permissionGuide": {
+ "label": "Guide des autorisations",
+ "return": "Revenir à la configuration",
+ "missingApp": "Ou sélectionnez l’app avec +",
+ "failed": "Impossible de vérifier l’accès.",
+ "microphone": "Activez OpenWhispr dans Microphone.",
+ "accessibility": "Glissez OpenWhispr dans Accessibilité, puis activez-le.",
+ "systemAudio": "Activez OpenWhispr sous Enregistrement audio du système uniquement.",
+ "screenContext": "Glissez OpenWhispr dans Enregistrement de l’écran et de l’audio système, puis activez-le.",
+ "settings": "Réglages",
+ "check": "Vérifier",
+ "restart": "Relancer l’app",
+ "restartRequired": "Redémarrez OpenWhispr pour appliquer l’accès à l’écran."
}
},
"streaming": {
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 16618f0b8..6f165e170 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -579,6 +579,20 @@
"title": "Un download non è stato completato",
"description": "Controlla la connessione e lo spazio libero su disco, poi riprova. Se continua a fallire, contatta il tuo amministratore."
}
+ },
+ "permissionGuide": {
+ "label": "Guida ai permessi",
+ "return": "Torna alla configurazione",
+ "missingApp": "Oppure seleziona l’app con +",
+ "failed": "Impossibile verificare l’accesso.",
+ "microphone": "Attiva OpenWhispr in Microfono.",
+ "accessibility": "Trascina OpenWhispr in Accessibilità e attivalo.",
+ "systemAudio": "Attiva OpenWhispr in Solo registrazione audio di sistema.",
+ "screenContext": "Trascina OpenWhispr in Registrazione schermo e audio di sistema e attivalo.",
+ "settings": "Impostazioni",
+ "check": "Ricontrolla",
+ "restart": "Riavvia l’app",
+ "restartRequired": "Riavvia OpenWhispr per applicare l’accesso allo schermo."
}
},
"streaming": {
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 5d661aeb3..31b1fe0a5 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -579,6 +579,20 @@
"title": "ダウンロードが完了しませんでした",
"description": "接続とディスクの空き容量を確認して、再試行してください。それでも失敗する場合は、管理者にお問い合わせください。"
}
+ },
+ "permissionGuide": {
+ "label": "権限ガイド",
+ "return": "初期設定に戻る",
+ "missingApp": "または+でアプリを選択",
+ "failed": "アクセスを確認できませんでした。",
+ "microphone": "「マイク」でOpenWhisprをオンにしてください。",
+ "accessibility": "OpenWhisprを「アクセシビリティ」にドラッグしてオンにしてください。",
+ "systemAudio": "「システムオーディオの録音のみ」でOpenWhisprをオンにしてください。",
+ "screenContext": "OpenWhisprを「画面収録とシステムオーディオ録音」にドラッグしてオンにしてください。",
+ "settings": "設定を開く",
+ "check": "再確認",
+ "restart": "アプリを再起動",
+ "restartRequired": "画面アクセスを適用するにはOpenWhisprを再起動してください。"
}
},
"streaming": {
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 693ec6f51..f6fc8bee8 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -558,6 +558,20 @@
"title": "Um download não foi concluído",
"description": "Verifique sua conexão e o espaço livre em disco e tente novamente. Se continuar falhando, entre em contato com seu administrador."
}
+ },
+ "permissionGuide": {
+ "label": "Guia de permissões",
+ "return": "Voltar à configuração",
+ "missingApp": "Ou selecione o app com +",
+ "failed": "Não foi possível verificar o acesso.",
+ "microphone": "Ative o OpenWhispr em Microfone.",
+ "accessibility": "Arraste o OpenWhispr para Acessibilidade e ative-o.",
+ "systemAudio": "Ative o OpenWhispr em Apenas gravação de áudio do sistema.",
+ "screenContext": "Arraste o OpenWhispr para Gravação de tela e áudio do sistema e ative-o.",
+ "settings": "Abrir Ajustes",
+ "check": "Verificar novamente",
+ "restart": "Reiniciar app",
+ "restartRequired": "Reinicie o OpenWhispr para aplicar o acesso à tela."
}
},
"streaming": {
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 3a34ae4f8..310d2ea1d 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -579,6 +579,20 @@
"title": "Загрузка не завершилась",
"description": "Проверьте подключение и свободное место на диске, затем повторите попытку. Если ошибка повторяется, обратитесь к администратору."
}
+ },
+ "permissionGuide": {
+ "label": "Помощник по разрешениям",
+ "return": "Вернуться к настройке",
+ "missingApp": "Или выберите приложение через +",
+ "failed": "Не удалось проверить доступ.",
+ "microphone": "Включите OpenWhispr в разделе «Микрофон».",
+ "accessibility": "Перетащите OpenWhispr в «Универсальный доступ» и включите его.",
+ "systemAudio": "Включите OpenWhispr в разделе «Только запись системного аудио».",
+ "screenContext": "Перетащите OpenWhispr в «Запись экрана и системного аудио» и включите его.",
+ "settings": "Настройки",
+ "check": "Проверить снова",
+ "restart": "Перезапустить",
+ "restartRequired": "Перезапустите OpenWhispr, чтобы применить доступ к экрану."
}
},
"streaming": {
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 18c7aee25..a7a2390cf 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -579,6 +579,20 @@
"title": "有一项下载未完成",
"description": "请检查网络连接和磁盘剩余空间,然后重试。如果仍然失败,请联系您的管理员。"
}
+ },
+ "permissionGuide": {
+ "label": "权限引导",
+ "return": "返回初始设置",
+ "missingApp": "或通过 + 选择应用",
+ "failed": "无法检查访问权限。",
+ "microphone": "在“麦克风”中打开 OpenWhispr。",
+ "accessibility": "将 OpenWhispr 拖入“辅助功能”,然后打开开关。",
+ "systemAudio": "在“仅系统音频录制”中打开 OpenWhispr。",
+ "screenContext": "将 OpenWhispr 拖入“屏幕与系统音频录制”,然后打开开关。",
+ "settings": "打开设置",
+ "check": "重新检查",
+ "restart": "重启 OpenWhispr",
+ "restartRequired": "重新启动 OpenWhispr 以应用屏幕访问权限。"
}
},
"streaming": {
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index e9889f086..da601d41d 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -579,6 +579,20 @@
"title": "有一項下載未完成",
"description": "請檢查網路連線與磁碟剩餘空間,然後重試。如果仍然失敗,請聯絡您的管理員。"
}
+ },
+ "permissionGuide": {
+ "label": "權限引導",
+ "return": "返回初始設定",
+ "missingApp": "或透過 + 選取 App",
+ "failed": "無法檢查存取權限。",
+ "microphone": "在「麥克風」中開啟 OpenWhispr。",
+ "accessibility": "將 OpenWhispr 拖入「輔助使用」,然後開啟開關。",
+ "systemAudio": "在「僅系統音訊錄製」中開啟 OpenWhispr。",
+ "screenContext": "將 OpenWhispr 拖入「螢幕與系統音訊錄製」,然後開啟開關。",
+ "settings": "開啟設定",
+ "check": "重新檢查",
+ "restart": "重新啟動",
+ "restartRequired": "重新啟動 OpenWhispr 以套用螢幕存取權限。"
}
},
"streaming": {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 3cbac4807..42565b0d3 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1,4 +1,5 @@
import type { ModelDefinition } from "../models/ModelRegistry";
+import type { PermissionGuideState, PermissionGuideAction } from "./permissionGuide";
import type { TinfoilCatalogModel } from "../models/tinfoilModels";
import type { UsageResponse } from "../lib/usageStore";
import type { OrgPolicy } from "./policy";
@@ -1152,6 +1153,16 @@ declare global {
// Basic window operations
setOnboardingWindowMode?: (mode: "compact" | "expanded" | "restore") => Promise<boolean>;
setOnboardingActive?: (active: boolean) => Promise<boolean>;
+ openPermissionGuide?: (state: PermissionGuideState) => Promise<boolean>;
+ closePermissionGuide?: () => Promise<boolean>;
+ getPermissionGuideState?: () => Promise<PermissionGuideState | null>;
+ permissionGuideAction?: (action: PermissionGuideAction) => void;
+ startPermissionGuideDrag?: (
+ target: Pick<PermissionGuideState, "sessionId" | "permission">
+ ) => void;
+ onPermissionGuideState?: (callback: (state: PermissionGuideState) => void) => () => void;
+ onPermissionGuideAction?: (callback: (action: PermissionGuideAction) => void) => () => void;
+ verifySystemAudioAccess?: () => Promise<SystemAudioAccessResult>;
beginOnboardingDemo?: (session: { id: string; kind: OnboardingDemoKind }) => Promise<boolean>;
endOnboardingDemo?: (id: string) => Promise<boolean>;
stopOnboardingDemo?: (id: string) => Promise<boolean>;
diff --git a/src/types/permissionGuide.ts b/src/types/permissionGuide.ts
new file mode 100644
index 000000000..89eb51456
--- /dev/null
+++ b/src/types/permissionGuide.ts
@@ -0,0 +1,18 @@
+export type PermissionGuideId = "microphone" | "accessibility" | "system-audio" | "screen-context";
+
+export interface PermissionGuideState {
+ sessionId: string;
+ permission: PermissionGuideId;
+ granted: boolean;
+ needsRelaunch: boolean;
+ busy: boolean;
+ error: boolean;
+ canDrag?: boolean;
+ appIcon?: string;
+}
+
+export interface PermissionGuideAction {
+ sessionId: string;
+ permission: PermissionGuideId;
+ action: "check" | "settings" | "close" | "restart";
+}
diff --git a/test/components/permissionGuide.test.js b/test/components/permissionGuide.test.js
new file mode 100644
index 000000000..0433e0f92
--- /dev/null
+++ b/test/components/permissionGuide.test.js
@@ -0,0 +1,15 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+
+test("saved sessions default to no helper and preserve explicit pending permission", async () => {
+ const { createOnboardingSession, parseOnboardingSession } =
+ await import("../../src/components/onboarding/flow.ts");
+ const session = createOnboardingSession();
+ assert.equal(session.permissionGuide, null);
+ delete session.permissionGuide;
+ const parse = (permissionGuide) =>
+ parseOnboardingSession(JSON.stringify({ ...session, permissionGuide })).permissionGuide;
+ assert.equal(parse(undefined), null);
+ assert.equal(parse("screen-context"), "screen-context");
+ assert.equal(parse("files"), null);
+});
diff --git a/test/components/permissionGuideController.test.js b/test/components/permissionGuideController.test.js
new file mode 100644
index 000000000..39a7f2f31
--- /dev/null
+++ b/test/components/permissionGuideController.test.js
@@ -0,0 +1,378 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+
+async function fixture(permission = "accessibility") {
+ const { createPermissionGuideController } =
+ await import("../../src/components/onboarding/permissionGuideController.ts");
+ const calls = [],
+ states = [],
+ saves = [];
+ let finish;
+ let granted = false;
+ let closed = 0;
+ let unavailable = 0;
+ let dismissed = 0;
+ let publishResult = async () => true;
+ const rows = [
+ {
+ id: permission,
+ granted: false,
+ request: () => {
+ assert.equal(saves.at(-1), permission);
+ calls.push("request");
+ return new Promise((resolve) => {
+ finish = resolve;
+ });
+ },
+ check: async () => {
+ calls.push("check");
+ return { granted };
+ },
+ verify: async () => {
+ calls.push("verify");
+ return { granted };
+ },
+ openSettings: async () => {
+ calls.push("settings");
+ },
+ },
+ ];
+ const controller = createPermissionGuideController({
+ sessionId: "test",
+ rows: () => rows,
+ save: (value) => saves.push(value),
+ publish: async (state) => {
+ states.push(state);
+ return publishResult();
+ },
+ unavailable: () => {
+ unavailable++;
+ },
+ dismissed: () => {
+ dismissed++;
+ },
+ close: () => {
+ closed++;
+ },
+ restart: async () => {
+ calls.push("restart");
+ },
+ });
+ return {
+ controller,
+ calls,
+ states,
+ saves,
+ rows,
+ finish: () => finish(),
+ grant: () => {
+ granted = true;
+ },
+ closed: () => closed,
+ unavailable: () => unavailable,
+ dismissed: () => dismissed,
+ failPublish: (result) => {
+ publishResult = result;
+ },
+ };
+}
+
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+
+test("one Enable click requests access immediately, before showing the Settings helper", async () => {
+ const setup = await fixture();
+ const pending = setup.controller.start("accessibility");
+ await tick();
+ assert.deepEqual(setup.calls, ["request"]);
+ assert.equal(setup.states.length, 0);
+ setup.finish();
+ await pending;
+ assert.equal(setup.states.at(-1).permission, "accessibility");
+ assert.deepEqual(setup.calls, ["request", "check"]);
+});
+
+test("the helper stays out of the native microphone prompt and never appears after Allow", async () => {
+ const setup = await fixture("microphone");
+ const pending = setup.controller.start("microphone");
+ await tick();
+ assert.equal(setup.states.length, 0);
+ setup.grant();
+ setup.finish();
+ await pending;
+ assert.equal(setup.states.length, 0);
+ assert.equal(setup.saves.at(-1), null);
+});
+
+test("denied microphone access shows only the Settings recovery helper", async () => {
+ const setup = await fixture("microphone");
+ const pending = setup.controller.start("microphone");
+ setup.finish();
+ await pending;
+ assert.equal(setup.states.at(-1).permission, "microphone");
+});
+
+test("permission recognition dismisses the overlay without moving to another permission", async () => {
+ const setup = await fixture();
+ const pending = setup.controller.start("accessibility");
+ setup.finish();
+ await pending;
+ setup.rows.push({ ...setup.rows[0], id: "system-audio" });
+ setup.grant();
+ await setup.controller.refresh();
+ assert.equal(setup.saves.at(-1), null);
+ assert.equal(setup.calls.filter((call) => call === "request").length, 1);
+});
+
+test("resuming saved intent after the grant landed applies consent without a native request", async () => {
+ // The relaunch that Screen Recording asks for happens after the grant, so
+ // resume only has to recognize it and complete the opt-in.
+ const setup = await fixture("screen-context");
+ setup.rows[0].onGranted = () => setup.calls.push("consent");
+ setup.grant();
+ await setup.controller.start(undefined, "screen-context");
+ assert.deepEqual(setup.calls, ["check", "consent"]);
+ assert.equal(setup.states.length, 0);
+ assert.equal(setup.saves.at(-1), null);
+});
+
+test("resuming saved intent that was never granted clears it instead of opening a helper", async () => {
+ // Quitting mid-guide and relaunching later must not float a "drag OpenWhispr
+ // into Accessibility" card over a desktop with no System Settings window.
+ const setup = await fixture();
+ await setup.controller.start(undefined, "accessibility");
+ assert.deepEqual(setup.calls, ["check"]);
+ assert.equal(setup.states.length, 0);
+ assert.equal(setup.saves.at(-1), null);
+ assert.equal(setup.closed(), 1);
+ assert.equal(setup.dismissed(), 0);
+});
+
+test("screen consent is applied once, not on every refresh while a restart is pending", async () => {
+ // Granted-but-needs-relaunch keeps the helper open, so refresh keeps
+ // checking; each check must not re-run the opt-in (store write, IPC, session).
+ const setup = await fixture("screen-context");
+ setup.rows[0].onGranted = () => setup.calls.push("consent");
+ setup.rows[0].check = async () => ({ granted: true, needsRelaunch: true });
+ const pending = setup.controller.start("screen-context");
+ setup.finish();
+ await pending;
+ await setup.controller.refresh();
+ await setup.controller.refresh();
+ assert.equal(setup.calls.filter((call) => call === "consent").length, 1);
+ assert.equal(setup.states.at(-1).needsRelaunch, true);
+});
+
+test("a helper that cannot open is reported unavailable and the request ends", async () => {
+ const setup = await fixture();
+ setup.failPublish(async () => false);
+ const pending = setup.controller.start("accessibility");
+ setup.finish();
+ await pending;
+ assert.equal(setup.unavailable(), 1);
+ assert.equal(setup.saves.at(-1), null);
+});
+
+test("dismissing any permission's guide is reported, an overlay that cannot open or a grant is not", async () => {
+ // A dismissal withdraws a pending Screen Context opt-in even while the guide
+ // shows another permission; a failed open or a grant must leave it in place.
+ const setup = await fixture();
+ setup.failPublish(async () => false);
+ const unavailable = setup.controller.start("accessibility");
+ setup.finish();
+ await unavailable;
+ assert.equal(setup.unavailable(), 1);
+ assert.equal(setup.dismissed(), 0);
+
+ setup.failPublish(async () => true);
+ const dismissed = setup.controller.start("accessibility");
+ setup.finish();
+ await dismissed;
+ await setup.controller.act({ sessionId: "test", permission: "accessibility", action: "close" });
+ assert.equal(setup.dismissed(), 1);
+
+ const granted = setup.controller.start("accessibility");
+ setup.finish();
+ await granted;
+ setup.grant();
+ await setup.controller.refresh();
+ assert.equal(setup.saves.at(-1), null);
+ assert.equal(setup.dismissed(), 1);
+});
+
+test("a refresh publishes only a change, so it cannot reopen an overlay main just closed", async () => {
+ const setup = await fixture();
+ const pending = setup.controller.start("accessibility");
+ setup.finish();
+ await pending;
+ const published = setup.states.length;
+ await setup.controller.refresh();
+ await setup.controller.refresh();
+ assert.equal(setup.states.length, published);
+
+ const check = setup.rows[0].check;
+ setup.rows[0].check = async () => {
+ throw new Error("check failed");
+ };
+ await setup.controller.refresh();
+ assert.equal(setup.states.at(-1).error, true);
+
+ setup.rows[0].check = check;
+ setup.grant();
+ await setup.controller.refresh();
+ assert.equal(setup.saves.at(-1), null);
+});
+
+test("a helper open superseded by a newer request is not reported unavailable", async () => {
+ // The main process answers false to an open it tore down for a later one; the
+ // renderer must not read that as the guide being broken.
+ const setup = await fixture();
+ let resolveFirst;
+ setup.failPublish(() => new Promise((resolve) => (resolveFirst = resolve)));
+ const first = setup.controller.start("accessibility");
+ setup.finish();
+ await tick();
+ await setup.controller.act({ sessionId: "test", permission: "accessibility", action: "close" });
+ resolveFirst(false);
+ await first;
+ assert.equal(setup.unavailable(), 0);
+});
+
+test("duplicate clicks and late results cannot revive a dismissed helper", async () => {
+ const setup = await fixture();
+ const pending = setup.controller.start("accessibility");
+ await setup.controller.start("accessibility");
+ assert.deepEqual(setup.calls, ["request"]);
+ await setup.controller.act({ sessionId: "old", permission: "accessibility", action: "close" });
+ assert.equal(setup.closed(), 0);
+ await setup.controller.act({ sessionId: "test", permission: "accessibility", action: "close" });
+ setup.finish();
+ await pending;
+ assert.equal(setup.states.length, 0);
+ assert.equal(setup.saves.at(-1), null);
+});
+
+test("policy removal cancels an in-flight request instead of advancing to another permission", async () => {
+ const setup = await fixture();
+ const pending = setup.controller.start("accessibility");
+ setup.rows.length = 0;
+ await setup.controller.reconcile();
+ setup.finish();
+ await pending;
+ assert.equal(setup.states.length, 0);
+ assert.deepEqual(setup.calls, ["request"]);
+});
+
+test("System Audio checks only on demand, without reopening Settings or recording loops", async () => {
+ const setup = await fixture("system-audio");
+ const pending = setup.controller.start("system-audio");
+ setup.finish();
+ await pending;
+ setup.calls.length = 0;
+ await setup.controller.refresh();
+ assert.deepEqual(setup.calls, []);
+ setup.grant();
+ await setup.controller.act({ sessionId: "test", permission: "system-audio", action: "check" });
+ assert.deepEqual(setup.calls, ["verify"]);
+ assert.equal(setup.saves.at(-1), null);
+});
+
+test("a screen grant that requires restart retains the compact restart controls", async () => {
+ const setup = await fixture("screen-context");
+ setup.rows[0].check = async () => ({ granted: true, needsRelaunch: true });
+ const pending = setup.controller.start("screen-context");
+ setup.finish();
+ await pending;
+ assert.equal(setup.states.at(-1).needsRelaunch, true);
+ await setup.controller.act({
+ sessionId: "test",
+ permission: "screen-context",
+ action: "restart",
+ });
+ assert.ok(setup.calls.includes("restart"));
+});
+
+test("Settings launch failures expose a retry and never restart the native request", async () => {
+ const setup = await fixture();
+ setup.rows[0].request = async () => {
+ throw new Error("Settings unavailable");
+ };
+ await setup.controller.start("accessibility");
+ assert.equal(setup.states.at(-1).error, true);
+ await setup.controller.refresh();
+ assert.equal(setup.states.at(-1).error, true);
+ await setup.controller.act({
+ sessionId: "test",
+ permission: "accessibility",
+ action: "settings",
+ });
+ assert.deepEqual(setup.calls, ["check", "settings"]);
+ assert.equal(setup.states.at(-1).error, false);
+});
+
+test("screen consent is not applied by a stale result after cancellation", async () => {
+ const setup = await fixture("screen-context");
+ setup.rows[0].onGranted = () => setup.calls.push("consent");
+ let finishCheck;
+ setup.rows[0].check = () =>
+ new Promise((resolve) => {
+ finishCheck = resolve;
+ });
+ const pending = setup.controller.start("screen-context");
+ setup.finish();
+ await tick();
+ await setup.controller.act({ sessionId: "test", permission: "screen-context", action: "close" });
+ finishCheck({ granted: true });
+ await pending;
+ assert.ok(!setup.calls.includes("consent"));
+});
+
+test("Check again is only an action for permissions that cannot be recognized automatically", async () => {
+ const setup = await fixture();
+ const pending = setup.controller.start("accessibility");
+ setup.finish();
+ await pending;
+ setup.calls.length = 0;
+ await setup.controller.act({ sessionId: "test", permission: "accessibility", action: "check" });
+ assert.deepEqual(setup.calls, []);
+});
+
+test("a check from a cancelled request cannot report the next request as granted", async () => {
+ const setup = await fixture();
+ let finishStaleCheck;
+ setup.rows[0].check = () =>
+ new Promise((resolve) => {
+ finishStaleCheck = resolve;
+ });
+ const stale = setup.controller.start("accessibility");
+ setup.finish();
+ await tick();
+ await setup.controller.act({ sessionId: "test", permission: "accessibility", action: "close" });
+ setup.rows[0].check = async () => ({ granted: false });
+ const fresh = setup.controller.start("accessibility");
+ setup.finish();
+ await fresh;
+ finishStaleCheck({ granted: true });
+ await stale;
+ await setup.controller.refresh();
+ assert.equal(setup.states.at(-1).granted, false);
+ assert.notEqual(setup.saves.at(-1), null);
+});
+
+test("the microphone request prompts natively and opens Settings only for a denial", async () => {
+ const { requestMicrophoneForGuide } =
+ await import("../../src/components/onboarding/permissionGuideController.ts");
+ const run = async (status) => {
+ const calls = [];
+ await requestMicrophoneForGuide({
+ requestAccess: async () => calls.push("prompt"),
+ checkAccess: async () => ({ granted: status === "granted", status }),
+ openSettings: async () => calls.push("settings"),
+ });
+ return calls;
+ };
+ assert.deepEqual(await run("granted"), ["prompt"]);
+ assert.deepEqual(await run("denied"), ["prompt", "settings"]);
+ // Not determined after the prompt (dismissed, or no prompt possible): the
+ // Privacy pane does not list the app yet, so Settings would only confuse.
+ assert.deepEqual(await run("not-determined"), ["prompt"]);
+});
diff --git a/test/components/permissionGuideOverlay.test.js b/test/components/permissionGuideOverlay.test.js
new file mode 100644
index 000000000..b592bf6ba
--- /dev/null
+++ b/test/components/permissionGuideOverlay.test.js
@@ -0,0 +1,47 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+const React = require("react");
+const { renderToStaticMarkup } = require("react-dom/server");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+test("guide exposes native drag only for supported steps and keeps a keyboard alternative", async (t) => {
+ installBrowserGlobals(t, { window: { electronAPI: {} } });
+ const server = await createRendererServer(t, {
+ cachePrefix: "permission-guide-overlay-",
+ noExternal: ["react-i18next"],
+ mockModules: {
+ "react-i18next": `export function useTranslation() { return { t: (key) => key }; }`,
+ },
+ });
+ const { PermissionGuideCard } = await server.ssrLoadModule(
+ "/components/onboarding/PermissionGuideOverlay.tsx"
+ );
+ const state = {
+ sessionId: "guide",
+ permission: "accessibility",
+ granted: false,
+ needsRelaunch: false,
+ busy: false,
+ error: false,
+ canDrag: true,
+ };
+ const render = (overrides) =>
+ renderToStaticMarkup(
+ React.createElement(PermissionGuideCard, {
+ state: { ...state, ...overrides },
+ onAction() {},
+ onDrag() {},
+ })
+ );
+ const drag = render({});
+ assert.match(drag, /draggable="true"/);
+ assert.match(drag, /onboarding.permissionGuide.missingApp/);
+ const microphone = render({ permission: "microphone", canDrag: false });
+ assert.doesNotMatch(microphone, /draggable="true"/);
+ const restart = render({ permission: "screen-context", granted: true, needsRelaunch: true });
+ assert.match(restart, /onboarding.permissionGuide.restart/);
+ assert.match(restart, /onboarding.permissionGuide.return/);
+ const cachedAudio = render({ permission: "system-audio", granted: true });
+ assert.match(cachedAudio, /onboarding.permissionGuide.check/);
+ assert.match(drag, /aria-label="onboarding.permissionGuide.label"/);
+});
diff --git a/test/helpers/permissionGuideManager.test.js b/test/helpers/permissionGuideManager.test.js
new file mode 100644
index 000000000..f055c6a46
--- /dev/null
+++ b/test/helpers/permissionGuideManager.test.js
@@ -0,0 +1,652 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+const fs = require("node:fs");
+const path = require("node:path");
+const vm = require("node:vm");
+const { EventEmitter } = require("node:events");
+
+const noSettings = () => ({ settings: null, authPrompt: false });
+
+function fixture({
+ platform = "darwin",
+ packaged = true,
+ deferredLoad = false,
+ settingsState = noSettings,
+ available = true,
+} = {}) {
+ const windows = [];
+ const timers = { timeouts: [] };
+ let finishLoad;
+ class Window extends EventEmitter {
+ constructor(options) {
+ super();
+ this.options = options;
+ if (typeof options.x === "number") {
+ this.bounds = { x: options.x, y: options.y, width: options.width, height: options.height };
+ }
+ this.webContents = new EventEmitter();
+ this.webContents.sent = [];
+ this.webContents.send = (...args) => this.webContents.sent.push(args);
+ this.webContents.isDestroyed = () => this.destroyed;
+ this.webContents.mainFrame = {};
+ this.webContents.startDrag = (item) => {
+ this.dragged = item;
+ };
+ this.webContents.setWindowOpenHandler = () => {};
+ windows.push(this);
+ }
+ isDestroyed() {
+ return !!this.destroyed;
+ }
+ getBounds() {
+ return this.bounds ?? { x: 100, y: 100, width: 600, height: 700 };
+ }
+ setBounds(bounds) {
+ this.bounds = bounds;
+ }
+ close() {
+ this.destroyed = true;
+ this.emit("closed");
+ }
+ showInactive() {
+ this.shown = true;
+ this.hidden = false;
+ this.boundsAtShow = this.getBounds();
+ }
+ hide() {
+ this.hidden = true;
+ }
+ isVisible() {
+ return !!this.shown && !this.hidden;
+ }
+ show() {
+ this.shown = true;
+ }
+ focus() {
+ this.focused = true;
+ }
+ loadFile() {
+ return deferredLoad
+ ? new Promise((resolve) => {
+ finishLoad = resolve;
+ })
+ : Promise.resolve();
+ }
+ loadURL() {
+ return this.loadFile();
+ }
+ setVisibleOnAllWorkspaces() {}
+ }
+ const owner = new Window({});
+ const windowManager = { controlPanelWindow: owner, _onboardingActive: true };
+ const exports = {};
+ vm.runInNewContext(
+ fs.readFileSync(path.join(__dirname, "../../src/helpers/permissionGuideManager.js"), "utf8"),
+ {
+ module: { exports },
+ exports,
+ __dirname: path.join(__dirname, "../../src/helpers"),
+ process: {
+ platform,
+ env: {},
+ execPath: "/Applications/OpenWhispr.app/Contents/MacOS/OpenWhispr",
+ resourcesPath: "/Applications/OpenWhispr.app/Contents/Resources",
+ },
+ // The vm context has no globals of its own; the guide schedules its polls.
+ setTimeout: (callback) => {
+ timers.timeouts.push(callback);
+ return timers.timeouts.length;
+ },
+ clearTimeout: () => {},
+ require: (name) => {
+ if (name === "electron")
+ return {
+ BrowserWindow: Window,
+ app: {
+ isPackaged: packaged,
+ getPath: () => "/Applications/OpenWhispr.app/Contents/MacOS/OpenWhispr",
+ },
+ nativeImage: {
+ createFromPath: () => {
+ const image = {
+ toDataURL: () => "data:image/png;base64,bundled",
+ resize: () => image,
+ };
+ return image;
+ },
+ },
+ screen: {
+ // Two displays stacked vertically, like a laptop with an external
+ // screen below it: the work area depends on which one the given
+ // rectangle falls on.
+ getDisplayMatching: (rect) =>
+ rect && rect.y >= 900
+ ? { workArea: { x: 0, y: 900, width: 2560, height: 1440 } }
+ : { workArea: { x: 0, y: 0, width: 1440, height: 900 } },
+ },
+ };
+ if (name === "./devServerManager")
+ return { getAppFilePath: () => ({ path: "/app/index.html", query: {} }) };
+ if (name === "./debugLogger") return { warn() {}, error() {}, info() {}, debug() {} };
+ // The real geometry, so the manager is tested against the placement the
+ // app actually ships; only the OS window query is stubbed.
+ if (name === "./permissionGuidePlacement")
+ return require("../../src/helpers/permissionGuidePlacement.js");
+ if (name === "./settingsWindowState")
+ return {
+ readSettingsWindowState: async () => settingsState(),
+ isSettingsWindowStateAvailable: () => available,
+ };
+ return require(name);
+ },
+ }
+ );
+ // The real waiter paces the "wait for the settings window" loop; tests drive
+ // the same number of attempts without the wall-clock delay.
+ const manager = new exports.PermissionGuideManager(windowManager, { wait: async () => {} });
+ const event = (win) => ({ sender: win.webContents, senderFrame: win.webContents.mainFrame });
+ return {
+ manager,
+ windows,
+ owner,
+ windowManager,
+ event,
+ timers,
+ finish: () => finishLoad?.(),
+ };
+}
+
+const state = {
+ sessionId: "guide-1",
+ permission: "accessibility",
+ granted: false,
+ needsRelaunch: false,
+ busy: false,
+ error: false,
+};
+
+const openGuide = async (setup) => {
+ assert.equal(await setup.manager.open(setup.event(setup.owner), state), true);
+ return setup.windows[setup.windows.length - 1];
+};
+
+const anchored = { x: 232, y: 232, width: 723, height: 504 };
+
+test("waits for the System Settings window before showing the overlay", async () => {
+ // System Settings needs a moment to put its window up after the Enable click;
+ // showing before then is what made the overlay jump into place afterwards.
+ let reads = 0;
+ const setup = fixture({
+ settingsState: () => {
+ reads += 1;
+ return reads < 3
+ ? { settings: null, authPrompt: false }
+ : { settings: anchored, authPrompt: false };
+ },
+ });
+
+ const guide = await openGuide(setup);
+
+ assert.equal(guide.boundsAtShow.y, 592);
+});
+
+test("anchors to the settings window on whichever display it opens on", async () => {
+ // The onboarding window stays on the laptop screen, so taking the work area
+ // from it clamps the overlay back onto that display and away from the dialog.
+ const external = { x: 300, y: 1200, width: 723, height: 504 };
+ const setup = fixture({ settingsState: () => ({ settings: external, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+
+ assert.equal(guide.boundsAtShow.x, 382);
+ assert.equal(guide.boundsAtShow.y, 1560);
+});
+
+test("closes the overlay once the System Settings window is closed", async () => {
+ let settingsOpen = true;
+ const setup = fixture({
+ settingsState: () => ({
+ settings: settingsOpen ? anchored : null,
+ authPrompt: false,
+ }),
+ });
+
+ const guide = await openGuide(setup);
+ settingsOpen = false;
+ await setup.manager.poll();
+
+ assert.ok(guide.isDestroyed(), "overlay closes with the dialog it belongs to");
+});
+
+test("gets out of the way while macOS asks for a password", async () => {
+ let authPrompt = false;
+ const setup = fixture({
+ settingsState: () => ({ settings: anchored, authPrompt }),
+ });
+
+ const guide = await openGuide(setup);
+ authPrompt = true;
+ await setup.manager.poll();
+ assert.equal(guide.isVisible(), false, "hidden while the password sheet is up");
+
+ authPrompt = false;
+ await setup.manager.poll();
+ assert.equal(guide.isVisible(), true, "back once the sheet is dismissed");
+});
+
+test("hides while another app covers the settings window", async () => {
+ // The overlay belongs to the dialog: floating above an unrelated app the user
+ // switched to is just clutter.
+ let frontmost = "settings";
+ const setup = fixture({
+ settingsState: () => ({ settings: anchored, authPrompt: false, frontmost }),
+ });
+
+ const guide = await openGuide(setup);
+ frontmost = "other";
+ await setup.manager.poll();
+ assert.equal(guide.isVisible(), false, "hidden when the user switches apps");
+
+ frontmost = "settings";
+ await setup.manager.poll();
+ assert.equal(guide.isVisible(), true, "back when settings returns to the front");
+});
+
+test("stays put while the user is dragging from the overlay itself", async () => {
+ const setup = fixture({
+ settingsState: () => ({ settings: anchored, authPrompt: false, frontmost: "self" }),
+ });
+
+ const guide = await openGuide(setup);
+ await setup.manager.poll();
+
+ assert.equal(guide.isVisible(), true);
+});
+
+test("the onboarding window's hide event never tears the overlay down", async () => {
+ // macOS fires hide on occlusion, and isVisible() folds occlusion in too, so
+ // neither can tell a covered window from one sent to the tray (the same trap
+ // documented for the Dock icon). The tray path closes the guide explicitly.
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ setup.owner.emit("hide");
+
+ assert.equal(guide.isDestroyed(), false);
+ assert.equal(setup.owner.listenerCount("hide"), 0);
+});
+
+test("a navigation of the onboarding document closes the guide while the window is visible", async () => {
+ // Log out reloads the document and the OAuth refresh loads a new URL; the
+ // controller that owned this guide is gone either way.
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ setup.owner.shown = true;
+ setup.owner.webContents.emit("did-start-navigation", {
+ isMainFrame: true,
+ isSameDocument: false,
+ });
+
+ assert.ok(guide.isDestroyed());
+});
+
+test("a same-document navigation leaves the guide alone", async () => {
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ setup.owner.webContents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: true });
+
+ assert.equal(guide.isDestroyed(), false);
+});
+
+test("a renderer crash closes the guide while the window is visible", async () => {
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ setup.owner.shown = true;
+ setup.owner.webContents.emit("render-process-gone", { reason: "crashed" });
+
+ assert.ok(guide.isDestroyed());
+});
+
+test("the owner closing after its contents are destroyed still closes the guide", async () => {
+ // Once a BrowserWindow has emitted closed, reading its webContents throws
+ // "Object has been destroyed"; a throw here would leak the always-on-top
+ // guide window with nothing left to close it.
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ Object.defineProperty(setup.owner, "webContents", {
+ get() {
+ throw new TypeError("Object has been destroyed");
+ },
+ });
+ setup.owner.destroyed = true;
+ setup.owner.emit("closed");
+
+ assert.ok(guide.isDestroyed());
+});
+
+test("the overlay's own close button closes the guide without waiting for the owner", async () => {
+ // The owner may have navigated away or crashed and no longer listen; the
+ // guide must never depend on an echo to take itself down.
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ setup.manager.handleAction(setup.event(guide), { ...state, action: "close" });
+
+ assert.ok(guide.isDestroyed());
+ assert.equal(setup.owner.webContents.sent.at(-1)[1].action, "close");
+ assert.equal(setup.owner.focused, true);
+});
+
+test("a state that cannot be read leaves the overlay alone", async () => {
+ // A failed read is unknown, not "settings closed": closing here would strand
+ // the user mid-permission over a transient hiccup.
+ let readable = true;
+ const setup = fixture({
+ settingsState: () => (readable ? { settings: anchored, authPrompt: false } : null),
+ });
+
+ const guide = await openGuide(setup);
+ readable = false;
+ await setup.manager.poll();
+
+ assert.equal(guide.isDestroyed(), false);
+});
+
+test("two publishes racing the first open leave exactly one overlay on screen", async () => {
+ // start() and the 2s refresh tick routinely publish together. Both calls carry
+ // the same session, so the second must join the first rather than tearing its
+ // window down — a false return here latches guide.error in the renderer and
+ // drops every later Enable click to the settings-only fallback.
+ const setup = fixture({
+ settingsState: () => ({
+ settings: { x: 232, y: 232, width: 723, height: 504 },
+ authPrompt: false,
+ }),
+ });
+
+ const [first, second] = await Promise.all([
+ setup.manager.open(setup.event(setup.owner), state),
+ setup.manager.open(setup.event(setup.owner), state),
+ ]);
+
+ assert.equal(first, true);
+ assert.equal(second, true);
+ assert.equal(setup.windows.length, 2, "owner window plus exactly one guide window");
+ assert.ok(setup.windows[1].shown);
+});
+
+test("the overlay opens anchored inside the System Settings window, without moving", async () => {
+ const setup = fixture({
+ settingsState: () => ({
+ settings: { x: 232, y: 232, width: 723, height: 504 },
+ authPrompt: false,
+ }),
+ });
+
+ const guide = await openGuide(setup);
+
+ // Asserted at show time: the overlay must already be anchored when it first
+ // becomes visible, rather than sliding there afterwards.
+ assert.equal(guide.boundsAtShow.x, 314);
+ assert.equal(guide.boundsAtShow.y, 592);
+});
+
+test("the overlay falls back to the bottom of the display when settings is closed", async () => {
+ const setup = fixture();
+
+ const guide = await openGuide(setup);
+
+ assert.equal(guide.options.x, 440);
+ assert.equal(guide.options.y, 752);
+});
+
+test("the overlay follows the settings window when the user moves it", async () => {
+ const settingsBounds = { x: 232, y: 232, width: 723, height: 504 };
+ const setup = fixture({ settingsState: () => ({ settings: settingsBounds, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ settingsBounds.y = 100;
+ await setup.manager.poll();
+
+ assert.equal(guide.getBounds().y, 460);
+});
+
+test("only the onboarding owner can open a guide, and unsupported platforms do nothing", async () => {
+ const setup = fixture();
+ assert.equal(await setup.manager.open({ sender: {} }, state), false);
+ assert.equal(
+ await setup.manager.open(setup.event(setup.owner), {
+ ...state,
+ permission: "files",
+ }),
+ false
+ );
+ assert.equal(
+ await setup.manager.open({ ...setup.event(setup.owner), senderFrame: {} }, state),
+ false
+ );
+ const other = fixture({ platform: "win32" });
+ assert.equal(await other.manager.open(other.event(other.owner), state), false);
+ assert.equal(other.windows.length, 1);
+});
+
+test("actions reject stale steps and drag only the packaged application", async () => {
+ const setup = fixture();
+ assert.equal(await setup.manager.open(setup.event(setup.owner), state), true);
+ const helper = setup.windows[1];
+ setup.manager.handleAction(setup.event(helper), {
+ ...state,
+ permission: "microphone",
+ action: "settings",
+ });
+ assert.equal(setup.owner.webContents.sent.length, 0);
+ setup.manager.handleAction(setup.event(helper), {
+ ...state,
+ action: "settings",
+ });
+ assert.equal(setup.owner.webContents.sent[0][1].action, "settings");
+ setup.manager.startDrag(setup.event(helper), {
+ ...state,
+ path: "/private/secret",
+ });
+ assert.equal(helper.dragged.file, "/Applications/OpenWhispr.app");
+ assert.ok(helper.shown);
+});
+
+test("development guides disable dragging and owner teardown closes the helper", async () => {
+ const setup = fixture({ packaged: false });
+ await setup.manager.open(setup.event(setup.owner), state);
+ const helper = setup.windows[1];
+ const snapshot = setup.manager.stateFor(setup.event(helper));
+ assert.equal(snapshot.canDrag, false);
+ setup.manager.startDrag(setup.event(helper), state);
+ assert.equal(helper.dragged, undefined);
+ setup.owner.close();
+ assert.equal(helper.isDestroyed(), true);
+ assert.equal(setup.owner.listenerCount("closed"), 0);
+});
+
+test("a helper closed while loading never reappears", async () => {
+ const setup = fixture({ deferredLoad: true });
+ const opening = setup.manager.open(setup.event(setup.owner), state);
+ await new Promise((resolve) => setImmediate(resolve));
+ setup.manager.close();
+ setup.finish();
+ assert.equal(await opening, false);
+ assert.equal(setup.windows[1].shown, undefined);
+});
+
+test("a guide that fails to open reports it only through its return value", async () => {
+ // A close action would read as the user dismissing the guide, withdrawing
+ // the Screen Context opt-in and skipping the renderer's fallback. The
+ // throwing read stands in for any failure on the open path, such as a load.
+ const setup = fixture({
+ settingsState: () => {
+ throw new Error("helper failed");
+ },
+ });
+
+ assert.equal(await setup.manager.open(setup.event(setup.owner), state), false);
+ assert.equal(setup.windows[1].isDestroyed(), true);
+ assert.deepEqual(setup.owner.webContents.sent, []);
+});
+
+test("helper falls back to a compact bottom overlay without stealing Settings focus", async () => {
+ const setup = fixture();
+ await setup.manager.open(setup.event(setup.owner), state);
+ const helper = setup.windows[1];
+ assert.equal(helper.options.width, 560);
+ assert.equal(helper.options.height, 124);
+ assert.equal(helper.options.alwaysOnTop, true);
+ assert.equal(helper.focused, undefined);
+ assert.ok(helper.options.y + helper.options.height <= 900);
+});
+
+test("System Settings on another Space hides the overlay rather than closing it", async () => {
+ // The window list is per Space, so swiping away or minimizing the dialog
+ // reads as "no window" while the app is still running. Closing (and pulling
+ // focus back to onboarding) would yank the user out of what they were doing.
+ let onScreen = true;
+ const setup = fixture({
+ settingsState: () => ({
+ settings: onScreen ? anchored : null,
+ authPrompt: false,
+ settingsRunning: true,
+ }),
+ });
+
+ const guide = await openGuide(setup);
+ onScreen = false;
+ await setup.manager.poll();
+ await setup.manager.poll();
+ await setup.manager.poll();
+ assert.equal(guide.isDestroyed(), false);
+ assert.equal(guide.isVisible(), false, "hidden while the dialog is off screen");
+
+ onScreen = true;
+ await setup.manager.poll();
+ assert.equal(guide.isVisible(), true, "back with the dialog");
+});
+
+test("opens hidden while System Settings is on another Space", async () => {
+ const setup = fixture({
+ settingsState: () => ({ settings: null, authPrompt: false, settingsRunning: true }),
+ });
+
+ const guide = await openGuide(setup);
+
+ assert.equal(guide.isVisible(), false);
+});
+
+test("polls one read at a time, scheduling the next only after the last one answers", async () => {
+ // An interval keeps firing while a slow helper is still running, leaving two
+ // reads in flight that can answer out of order.
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ await openGuide(setup);
+
+ assert.equal(setup.timers.timeouts.length, 1);
+ await setup.timers.timeouts[0]();
+ assert.equal(setup.timers.timeouts.length, 2);
+});
+
+test("a poll still reading when the guide reopens does not start a second chain", async () => {
+ let pending = null;
+ const setup = fixture({
+ settingsState: () => pending ?? { settings: anchored, authPrompt: false },
+ });
+
+ await openGuide(setup);
+ let answer;
+ pending = new Promise((resolve) => (answer = resolve));
+ const stale = setup.timers.timeouts[0]();
+ pending = null;
+ setup.manager.close();
+ await openGuide(setup);
+ answer({ settings: anchored, authPrompt: false });
+ await stale;
+
+ assert.equal(setup.timers.timeouts.length, 2, "only the reopened guide keeps polling");
+});
+
+test("a missing helper binary refuses to open so Enable falls back to the plain flow", async () => {
+ const setup = fixture({ available: false });
+
+ assert.equal(await setup.manager.open(setup.event(setup.owner), state), false);
+ assert.equal(setup.windows.length, 1);
+});
+
+test("a close from the onboarding renderer does not pull focus back to it", async () => {
+ // The renderer closes on a grant; the user may still be in System Settings
+ // for the next permission. Only the dialog going away restores onboarding.
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ assert.equal(await setup.manager.closeFromOwner(setup.event(setup.owner)), true);
+
+ assert.ok(guide.isDestroyed());
+ assert.equal(setup.owner.focused, undefined);
+});
+
+test("System Settings going away restores the onboarding window", async () => {
+ let settingsOpen = true;
+ const setup = fixture({
+ settingsState: () => ({ settings: settingsOpen ? anchored : null, authPrompt: false }),
+ });
+
+ await openGuide(setup);
+ settingsOpen = false;
+ await setup.manager.poll();
+
+ assert.equal(setup.owner.focused, true);
+});
+
+test("the guide is only for an onboarding that is still active", async () => {
+ const setup = fixture();
+ setup.windowManager._onboardingActive = false;
+
+ assert.equal(await setup.manager.open(setup.event(setup.owner), state), false);
+ assert.equal(setup.windows.length, 1);
+});
+
+test("dragging is disabled while a check is in flight", async () => {
+ const setup = fixture({ settingsState: () => ({ settings: anchored, authPrompt: false }) });
+
+ const guide = await openGuide(setup);
+ await setup.manager.open(setup.event(setup.owner), {
+ ...state,
+ busy: true,
+ });
+ setup.manager.startDrag(setup.event(guide), state);
+
+ assert.equal(setup.manager.snapshot().canDrag, false);
+ assert.equal(guide.dragged, undefined);
+});
+
+test("a guide closed while waiting for the settings window never positions or shows", async () => {
+ let reads = 0;
+ const setup = fixture({
+ settingsState: () => {
+ reads += 1;
+ if (reads === 2) setup.manager.close();
+ return { settings: reads >= 2 ? anchored : null, authPrompt: false };
+ },
+ });
+
+ const opening = setup.manager.open(setup.event(setup.owner), state);
+
+ assert.equal(await opening, false);
+ const guide = setup.windows[1];
+ assert.ok(guide.isDestroyed());
+ assert.equal(guide.shown, undefined);
+ assert.deepEqual(guide.bounds, {
+ x: guide.options.x,
+ y: guide.options.y,
+ width: guide.options.width,
+ height: guide.options.height,
+ });
+});
diff --git a/test/helpers/permissionGuidePlacement.test.js b/test/helpers/permissionGuidePlacement.test.js
new file mode 100644
index 000000000..857a178b9
--- /dev/null
+++ b/test/helpers/permissionGuidePlacement.test.js
@@ -0,0 +1,79 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/helpers/permissionGuidePlacement.js");
+
+const workArea = { x: 0, y: 0, width: 1512, height: 944 };
+const size = { width: 560, height: 124 };
+
+test("the overlay sits inside the bottom edge of the System Settings window", async () => {
+ const { computeGuideBounds } = await load();
+
+ const bounds = computeGuideBounds({
+ settingsBounds: { x: 232, y: 232, width: 723, height: 504 },
+ workArea,
+ size,
+ });
+
+ assert.equal(bounds.x, 314);
+ assert.equal(bounds.y, 592);
+ assert.equal(bounds.width, 560);
+ assert.equal(bounds.height, 124);
+});
+
+test("without a System Settings window it falls back to the bottom of the display", async () => {
+ const { computeGuideBounds } = await load();
+
+ const bounds = computeGuideBounds({ settingsBounds: null, workArea, size });
+
+ assert.equal(bounds.x, 476);
+ assert.equal(bounds.y, 796);
+});
+
+test("a tall System Settings window cannot push the overlay off screen", async () => {
+ const { computeGuideBounds } = await load();
+
+ // The real window measured during onboarding: 723x804 at y 232 ends at 1036,
+ // past the bottom of a 944pt work area, so the inset spot is off screen too.
+ const bounds = computeGuideBounds({
+ settingsBounds: { x: 232, y: 232, width: 723, height: 804 },
+ workArea,
+ size,
+ });
+
+ assert.equal(bounds.y, 796);
+ assert.ok(bounds.y + bounds.height <= workArea.y + workArea.height);
+});
+
+test("a System Settings window near a screen edge keeps the overlay fully visible", async () => {
+ const { computeGuideBounds } = await load();
+
+ const bounds = computeGuideBounds({
+ settingsBounds: { x: 1300, y: 100, width: 700, height: 400 },
+ workArea,
+ size,
+ });
+
+ assert.ok(bounds.x >= workArea.x);
+ assert.ok(bounds.x + bounds.width <= workArea.x + workArea.width);
+});
+
+test("placement is relative to the display the window is on, not the primary one", async () => {
+ const { computeGuideBounds } = await load();
+ const external = { x: -2560, y: -200, width: 2560, height: 1440 };
+
+ const bounds = computeGuideBounds({ settingsBounds: null, workArea: external, size });
+
+ assert.equal(bounds.x, -1560);
+ assert.equal(bounds.y, 1092);
+});
+
+test("an overlay wider than the display is trimmed to fit", async () => {
+ const { computeGuideBounds } = await load();
+ const narrow = { x: 0, y: 0, width: 400, height: 500 };
+
+ const bounds = computeGuideBounds({ settingsBounds: null, workArea: narrow, size });
+
+ assert.equal(bounds.width, 400);
+ assert.equal(bounds.x, 0);
+});
diff --git a/test/helpers/preloadOnboardingBridge.test.js b/test/helpers/preloadOnboardingBridge.test.js
index 271d00043..c96083640 100644
--- a/test/helpers/preloadOnboardingBridge.test.js
+++ b/test/helpers/preloadOnboardingBridge.test.js
@@ -41,6 +41,34 @@ function loadPreloadApi() {
return { api: exposedApi, invocations, listeners, sends };
}
+test("permission guide bridge uses narrow channels and strips IPC events", async () => {
+ const { api, invocations, listeners, sends } = loadPreloadApi();
+ const state = { sessionId: "guide-1", permission: "accessibility" };
+ await api.openPermissionGuide(state);
+ await api.getPermissionGuideState();
+ await api.closePermissionGuide();
+ const action = { ...state, action: "check" };
+ api.permissionGuideAction(action);
+ api.startPermissionGuideDrag(state);
+ assert.deepEqual(invocations, [
+ ["permission-guide-open", state],
+ ["permission-guide-state"],
+ ["permission-guide-close"],
+ ]);
+ assert.deepEqual(sends, [
+ ["permission-guide-action", action],
+ ["permission-guide-drag", state],
+ ]);
+ let received;
+ const stop = api.onPermissionGuideState((payload) => {
+ received = payload;
+ });
+ listeners.get("permission-guide-state-changed")({ sender: "native" }, state);
+ assert.equal(received, state);
+ stop();
+ assert.equal(listeners.has("permission-guide-state-changed"), false);
+});
+
test("onboarding demo bridge invokes only its allowlisted channels", async () => {
const { api, invocations } = loadPreloadApi();
const session = { id: "demo-7", kind: "dictation" };
diff --git a/test/helpers/settingsWindowState.test.js b/test/helpers/settingsWindowState.test.js
new file mode 100644
index 000000000..0582d9405
--- /dev/null
+++ b/test/helpers/settingsWindowState.test.js
@@ -0,0 +1,135 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+const fs = require("node:fs");
+const path = require("node:path");
+const vm = require("node:vm");
+
+function load({ platform = "darwin", binary = "/bin/macos-window-bounds", execFile } = {}) {
+ const calls = [];
+ const resolves = [];
+ const module = { exports: {} };
+ vm.runInNewContext(
+ fs.readFileSync(path.join(__dirname, "../../src/helpers/settingsWindowState.js"), "utf8"),
+ {
+ module,
+ exports: module.exports,
+ process: { platform, pid: 4242 },
+ require: (name) => {
+ if (name === "child_process")
+ return {
+ execFile: (command, args, options, callback) => {
+ calls.push({ command, args, options });
+ execFile(callback);
+ },
+ };
+ if (name === "./binaryResolver")
+ return {
+ resolveBundledBinary: () => {
+ resolves.push(binary);
+ return binary;
+ },
+ };
+ return require(name);
+ },
+ }
+ );
+ return { ...module.exports, calls, resolves };
+}
+
+const succeed = (stdout) => (callback) => callback(null, stdout, "");
+const report = (value) => succeed(JSON.stringify(value));
+
+test("reads the System Settings window bounds", async () => {
+ const { readSettingsWindowState } = load({
+ execFile: report({ settings: { x: 232, y: 232, width: 723, height: 804 }, authPrompt: false }),
+ });
+
+ const state = await readSettingsWindowState();
+
+ assert.deepEqual({ ...state.settings }, { x: 232, y: 232, width: 723, height: 804 });
+ assert.equal(state.authPrompt, false);
+});
+
+test("unreadable output is reported as unknown, not as a closed window", async () => {
+ // A parse failure must not read as "settings closed", which would close the
+ // overlay out from under the user.
+ const { readSettingsWindowState } = load({ execFile: succeed("not json\n") });
+
+ assert.equal(await readSettingsWindowState(), null);
+});
+
+test("a helper that cannot run is unknown rather than closed", async () => {
+ const { readSettingsWindowState } = load({
+ execFile: (callback) => callback(Object.assign(new Error("boom"), { code: 1 }), "", ""),
+ });
+
+ assert.equal(await readSettingsWindowState(), null);
+});
+
+test("never blocks the guide: the helper runs under a timeout", async () => {
+ const { readSettingsWindowState, calls } = load({
+ execFile: report({ settings: null, authPrompt: false }),
+ });
+
+ await readSettingsWindowState();
+
+ assert.ok(calls[0].options.timeout > 0);
+});
+
+test("is macOS only, and never spawns anything elsewhere", async () => {
+ const { readSettingsWindowState, calls } = load({
+ platform: "win32",
+ execFile: report({ settings: null, authPrompt: false }),
+ });
+
+ assert.equal(await readSettingsWindowState(), null);
+ assert.equal(calls.length, 0);
+});
+
+test("reports nothing when the helper binary is missing from the bundle", async () => {
+ const { readSettingsWindowState, calls } = load({
+ binary: null,
+ execFile: report({ settings: null, authPrompt: false }),
+ });
+
+ assert.equal(await readSettingsWindowState(), null);
+ assert.equal(calls.length, 0);
+});
+
+test("hands the helper the app's own pid so it can tell self from other apps", async () => {
+ // Window owner names are localized ("Systemeinstellungen" on a German Mac), so
+ // the helper classifies by process instead; it needs to know which one we are.
+ const { readSettingsWindowState, calls } = load({
+ execFile: report({ settings: null, authPrompt: false, frontmost: "self" }),
+ });
+
+ await readSettingsWindowState();
+
+ // The args array is built inside the vm context, so compare contents only.
+ assert.deepEqual([...calls[0].args], ["4242"]);
+});
+
+test("resolves the helper binary once, not on every poll", async () => {
+ // The resolver logs each lookup; at two polls a second that is 120 log lines
+ // a minute for the whole time the overlay is open.
+ const { readSettingsWindowState, resolves } = load({
+ execFile: report({ settings: null, authPrompt: false }),
+ });
+
+ await readSettingsWindowState();
+ await readSettingsWindowState();
+
+ assert.equal(resolves.length, 1);
+});
+
+test("reports whether the helper is available so the guide can fall back up front", () => {
+ assert.equal(load({ execFile: report({}) }).isSettingsWindowStateAvailable(), true);
+ assert.equal(
+ load({ binary: null, execFile: report({}) }).isSettingsWindowStateAvailable(),
+ false
+ );
+ assert.equal(
+ load({ platform: "win32", execFile: report({}) }).isSettingsWindowStateAvailable(),
+ false
+ );
+});
diff --git a/test/helpers/windowManagerPermissionGuide.test.js b/test/helpers/windowManagerPermissionGuide.test.js
new file mode 100644
index 000000000..2283bdc8f
--- /dev/null
+++ b/test/helpers/windowManagerPermissionGuide.test.js
@@ -0,0 +1,52 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+// WindowManager pulls in electron + sibling managers at require time; only the
+// tray-hide path is exercised here.
+const originalLoad = Module._load;
+Module._load = function loadWindowManagerWithStubs(request, parent, isMain) {
+ if (request === "electron")
+ return {
+ app: { on: () => undefined },
+ screen: { on: () => undefined },
+ BrowserWindow: class {},
+ Menu: {},
+ nativeImage: {},
+ systemPreferences: {},
+ };
+ if (request === "./debugLogger")
+ return { debug() {}, info() {}, warn() {}, error() {}, log() {} };
+ if (request === "./hotkeyManager") return class {};
+ if (request === "./dragManager") return class {};
+ if (request === "./menuManager") return {};
+ if (request === "./devServerManager") return {};
+ if (request === "./dockManager") return { setControlPanelVisible() {} };
+ if (request === "./i18nMain") return { i18nMain: { t: (key) => key } };
+ if (request === "./windowConfig")
+ return {
+ MAIN_WINDOW_CONFIG: {},
+ CONTROL_PANEL_CONFIG: {},
+ NOTIFICATION_WINDOW_CONFIG: {},
+ WINDOW_SIZES: { BASE: { width: 96, height: 96 } },
+ ONBOARDING_WINDOW_SIZES: { COMPACT: {}, EXPANDED: {} },
+ WindowPositionUtil: {},
+ };
+ return originalLoad.call(this, request, parent, isMain);
+};
+const WindowManager = require("../../src/helpers/windowManager");
+Module._load = originalLoad;
+
+test("sending the control panel to the tray closes the permission guide explicitly", () => {
+ // The guide cannot subscribe to the panel's hide event (occlusion fires it
+ // too), so the one real hide path has to tell it.
+ const manager = new WindowManager();
+ const closes = [];
+ manager.permissionGuide = { close: (...args) => closes.push(args) };
+ manager.controlPanelWindow = { isDestroyed: () => false, hide: () => undefined };
+ manager.hideControlPanelToTray();
+ assert.deepEqual(
+ closes.map(([, notify]) => notify),
+ [true]
+ );
+});
diff --git a/test/hooks/usePermissionGuide.test.js b/test/hooks/usePermissionGuide.test.js
new file mode 100644
index 000000000..1b451d39c
--- /dev/null
+++ b/test/hooks/usePermissionGuide.test.js
@@ -0,0 +1,76 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+
+test("a helper open superseded by the next Enable click does not disable the guide", async (t) => {
+ // Main answers false to an open it tore down for a newer session. Latching
+ // guide.error on that would drop every later Enable click to the legacy flow.
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ });
+ const opens = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ openPermissionGuide: () =>
+ new Promise((resolve) => {
+ opens.push(resolve);
+ }),
+ closePermissionGuide: async () => true,
+ onPermissionGuideAction: () => () => {},
+ },
+ },
+ });
+ const container = installHookDom(t);
+ const vite = await createRendererServer(t, { cachePrefix: "permission-guide-hook-" });
+ const { usePermissionGuide } = await vite.ssrLoadModule(
+ "/components/onboarding/usePermissionGuide.ts"
+ );
+ const row = (id) => ({
+ id,
+ granted: false,
+ request: async () => {},
+ check: async () => ({ granted: false }),
+ openSettings: async () => {},
+ });
+ let guide;
+ function Harness() {
+ guide = usePermissionGuide({
+ enabled: true,
+ progress: null,
+ save: () => {},
+ rows: [row("accessibility"), row("microphone")],
+ });
+ return null;
+ }
+ root = createRoot(container);
+ await React.act(async () => {
+ root.render(React.createElement(Harness));
+ });
+
+ let first;
+ await React.act(async () => {
+ first = guide.start("accessibility");
+ await tick();
+ });
+ let second;
+ await React.act(async () => {
+ second = guide.start("microphone");
+ await tick();
+ opens[0](false);
+ opens[1](true);
+ await Promise.all([first, second]);
+ });
+
+ assert.equal(opens.length, 2);
+ assert.equal(guide.error, false);
+});