Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(macos): defer accessibility features until permissions (#2101)
void38a23c012dc1
diff --git a/main.js b/main.jsindex 90dd4c4b8..857e446e0 100644--- a/main.js+++ b/main.js@@ -339,6 +339,8 @@ let qdrantManager = null;let ipcHandlers = null;let cliBridge = null;let globeKeyAlertShown = false;+let macAccessibilityFeaturesReady = false;+let startMacAccessibilityFeatures = null;let authBridgeServer = null;let pendingNoteCloudId = null;let pendingNoteRetryTimer = null;@@ -581,7 +583,9 @@ function initializeDeferredManagers() {"clipboard");});- clipboardManager.preWarmAccessibility();+ if (process.platform !== "darwin") {+ clipboardManager.preWarmAccessibility();+ }trayManager = new TrayManager();globeKeyManager = new GlobeKeyManager({// Lets the listener put the user's macOS Globe action back after a crash.@@ -1179,6 +1183,11 @@ async function startApp() {// Phase 2: Initialize remaining managers after windows are visibleinitializeDeferredManagers();+ if (process.platform === "darwin") {+ // Restore a Globe preference marker left by a crash without starting any+ // Accessibility-protected event monitors during onboarding.+ await globeKeyManager.restoreLeftoverSystemPreference();+ }app.on("browser-window-focus", () => {if (googleCalendarManager) googleCalendarManager.syncOnFocus();@@ -1607,12 +1616,37 @@ async function startApp() {}});- syncMacNativeHotkeyConfiguration();- globeKeyManager.start();+ // If accessibility is missing, notify the normal control panel after the+ // protected macOS features have started. During onboarding the permissions+ // screen owns this guidance, so its event has no ControlPanel listener.+ const checkAndNotifyAccessibility = () => {+ if (!systemPreferences.isTrustedAccessibilityClient(false)) {+ debugLogger.info("[Accessibility] macOS accessibility not trusted — notifying renderers");+ if (isLiveWindow(windowManager.controlPanelWindow)) {+ windowManager.controlPanelWindow.webContents.send("accessibility-missing");+ }+ }+ };++ let accessibilityFeaturesStarted = false;+ startMacAccessibilityFeatures = () => {+ if (accessibilityFeaturesStarted) return;+ accessibilityFeaturesStarted = true;+ clipboardManager.preWarmAccessibility();+ syncMacNativeHotkeyConfiguration();+ globeKeyManager.start();+ setTimeout(checkAndNotifyAccessibility, 3000);+ };++ if (macAccessibilityFeaturesReady) {+ startMacAccessibilityFeatures();+ }+hotkeyManager.on("hotkey-loaded", syncMacNativeHotkeyConfiguration);ipcMain.on("hotkey-listening-mode-changed", (_event, enabled) => {if (enabled) {+ startMacAccessibilityFeatures();// Let mouse buttons through so they can be captured, but keep macOS's// Globe action down so choosing Globe cannot flash the emoji viewer.globeKeyManager.setConfiguration({ mouseButtons: [], suppressGlobeAction: true });@@ -1621,20 +1655,6 @@ async function startApp() {}});- // After starting globe-listener, check if accessibility is granted.- // If not, notify the control panel so it can prompt the user.- const checkAndNotifyAccessibility = () => {- if (!systemPreferences.isTrustedAccessibilityClient(false)) {- debugLogger.info("[Accessibility] macOS accessibility not trusted — notifying renderers");- if (isLiveWindow(windowManager.controlPanelWindow)) {- windowManager.controlPanelWindow.webContents.send("accessibility-missing");- }- }- };-- // Check shortly after startup (give windows time to load)- setTimeout(checkAndNotifyAccessibility, 3000);-// Allow renderer to request an accessibility check (e.g. on sign-in).// Also sends accessibility-missing events if untrusted.ipcMain.handle("check-accessibility-trusted", () => {@@ -1755,6 +1775,23 @@ async function startApp() {}}+ipcMain.on("mac-accessibility-features-ready", (_event, expectedAccountScope) => {+ if (process.platform !== "darwin") return;+ if (expectedAccountScope) {+ const accountScopeBinding = require("./src/helpers/accountScopeBinding");+ const currentAccountScope = accountScopeBinding.resolveActiveAccountScope({+ ...require("./src/helpers/tokenStore").getState(),+ binding: accountScopeBinding.read(),+ });+ if (!accountScopeBinding.matchesActiveAccountScope(expectedAccountScope, currentAccountScope)) {+ debugLogger.info("[Accessibility] Ignoring stale account-scoped readiness signal");+ return;+ }+ }+ macAccessibilityFeaturesReady = true;+ startMacAccessibilityFeatures?.();+});+// Listen for usage limit reached from dictation overlay, forward to control panelipcMain.on("limit-reached", (_event, data) => {if (isLiveWindow(windowManager?.controlPanelWindow)) {diff --git a/preload.js b/preload.jsindex 9c0f0d7af..bc8245c07 100644--- a/preload.js+++ b/preload.js@@ -65,6 +65,10 @@ const registerListener = (channel, handlerFactory) => {contextBridge.exposeInMainWorld("electronAPI", {setOnboardingWindowMode: (mode) => ipcRenderer.invoke("onboarding-set-window-mode", mode),setOnboardingActive: (active) => ipcRenderer.invoke("onboarding-set-active", active),+ markMacAccessibilityFeaturesReady: (expectedAccountScope) =>+ expectedAccountScope+ ? ipcRenderer.send("mac-accessibility-features-ready", expectedAccountScope)+ : ipcRenderer.send("mac-accessibility-features-ready"),beginOnboardingDemo: (session) => ipcRenderer.invoke("onboarding-demo-begin", session),endOnboardingDemo: (id) => ipcRenderer.invoke("onboarding-demo-end", id),stopOnboardingDemo: (id) => ipcRenderer.invoke("onboarding-demo-stop", id),diff --git a/resources/macos-globe-listener.swift b/resources/macos-globe-listener.swiftindex 1b8402e1f..72e51cf6b 100644--- a/resources/macos-globe-listener.swift+++ b/resources/macos-globe-listener.swift@@ -22,9 +22,10 @@ func emitWarning(_ message: String) {// Mouse buttons arrive as a positional comma-separated list; everything else is// an explicit flag.-func parseArguments() -> (config: ListenerConfig, statePath: String?) {+func parseArguments() -> (config: ListenerConfig, statePath: String?, restoreLeftoverPreferenceOnly: Bool) {var config = ListenerConfig()var statePath: String?+ var restoreLeftoverPreferenceOnly = falsevar arguments = CommandLine.arguments.dropFirst().makeIterator()while let argument = arguments.next() {@@ -33,6 +34,8 @@ func parseArguments() -> (config: ListenerConfig, statePath: String?) {config.suppressGlobeAction = truecase "--globe-preference-state":statePath = arguments.next()+ case "--restore-leftover-globe-preference":+ restoreLeftoverPreferenceOnly = truedefault:config.mouseButtons.formUnion(argument.split(separator: ",")@@ -42,7 +45,7 @@ func parseArguments() -> (config: ListenerConfig, statePath: String?) {}}- return (config, statePath)+ return (config, statePath, restoreLeftoverPreferenceOnly)}struct GlobePreferenceState: Codable {@@ -175,6 +178,7 @@ enum GlobeSystemAction {func applyConfiguration(_ config: ListenerConfig) {suppressedMouseButtons = config.mouseButtons+ updateMouseEventTap()if config.suppressGlobeAction {GlobeSystemAction.apply()} else {@@ -185,6 +189,10 @@ func applyConfiguration(_ config: ListenerConfig) {let launchOptions = parseArguments()GlobeSystemAction.statePath = launchOptions.statePathGlobeSystemAction.recoverLeftoverState()+if launchOptions.restoreLeftoverPreferenceOnly {+ GlobeSystemAction.restore()+ exit(0)+}let rightModifiers: [(UInt16, NSEvent.ModifierFlags, String)] = [(61, .option, "RightOption"),@@ -228,37 +236,53 @@ let mouseEventMask =(1 << CGEventType.otherMouseUp.rawValue)var mouseEventTapPort: CFMachPort?+var mouseRunLoopSource: CFRunLoopSource?-let mouseEventTap = CGEvent.tapCreate(- tap: .cgSessionEventTap,- place: .headInsertEventTap,- options: .defaultTap,- eventsOfInterest: CGEventMask(mouseEventMask),- callback: { _, type, event, _ in- if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {- if let mouseEventTapPort {- CGEvent.tapEnable(tap: mouseEventTapPort, enable: true)+// The active tap can suppress configured side buttons and is Accessibility-+// protected, so keep it absent until a mouse-button hotkey actually needs it.+func updateMouseEventTap() {+ if suppressedMouseButtons.isEmpty {+ if let mouseEventTapPort {+ CGEvent.tapEnable(tap: mouseEventTapPort, enable: false)+ if let mouseRunLoopSource {+ CFRunLoopRemoveSource(CFRunLoopGetMain(), mouseRunLoopSource, .commonModes)}- return Unmanaged.passUnretained(event)}+ mouseEventTapPort = nil+ mouseRunLoopSource = nil+ return+ }+ if mouseEventTapPort != nil { return }++ guard let tap = CGEvent.tapCreate(+ tap: .cgSessionEventTap,+ place: .headInsertEventTap,+ options: .defaultTap,+ eventsOfInterest: CGEventMask(mouseEventMask),+ callback: { _, type, event, _ in+ if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {+ if let mouseEventTapPort {+ CGEvent.tapEnable(tap: mouseEventTapPort, enable: true)+ }+ return Unmanaged.passUnretained(event)+ }- if emitMouseEvent(type, event) {- return nil- }+ if emitMouseEvent(type, event) {+ return nil+ }- return Unmanaged.passUnretained(event)- },- userInfo: nil-)+ return Unmanaged.passUnretained(event)+ },+ userInfo: nil+ ) else {+ emitWarning("Failed to create mouse event tap")+ return+ }-var mouseRunLoopSource: CFRunLoopSource?-if let mouseEventTap {- mouseEventTapPort = mouseEventTap- mouseRunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, mouseEventTap, 0)+ mouseEventTapPort = tap+ mouseRunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0)CFRunLoopAddSource(CFRunLoopGetMain(), mouseRunLoopSource, .commonModes)- CGEvent.tapEnable(tap: mouseEventTap, enable: true)-} else {- emitWarning("Failed to create mouse event tap")+ CGEvent.tapEnable(tap: tap, enable: true)}guard let monitor = NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged, handler: { event in@@ -314,8 +338,8 @@ func shutdownListener() -> Never {if let keyMonitor {NSEvent.removeMonitor(keyMonitor)}- if let mouseEventTap {- CGEvent.tapEnable(tap: mouseEventTap, enable: false)+ if let mouseEventTapPort {+ CGEvent.tapEnable(tap: mouseEventTapPort, enable: false)}if let mouseRunLoopSource {CFRunLoopRemoveSource(CFRunLoopGetMain(), mouseRunLoopSource, .commonModes)diff --git a/src/AppRouter.jsx b/src/AppRouter.jsxindex 7a26cc1f4..56949fdb5 100644--- a/src/AppRouter.jsx+++ b/src/AppRouter.jsx@@ -13,6 +13,7 @@ import { useTheme } from "./hooks/useTheme";import { mirrorActiveAccountScope } from "./lib/accountScopeMirror";import { usePolicyStore } from "./stores/policyStore";import { resolveSettledControlPanelWindowMode } from "./utils/controlPanelWindowMode.ts";+import { resolveMacAccessibilityReadiness } from "./utils/macAccessibilityReadiness.ts";import { isControlPanelWindow } from "./utils/windowContext.ts";// Either marker means the flow is mid-way: the legacy step key is kept for@@ -162,11 +163,31 @@ function MainApp() {const onboardingCompleted = localStorage.getItem("onboardingCompleted") === "true";const normalAppVisible =onboardingCompleted && (!isControlPanel || (!showOnboarding && !needsReauth));+ const authSkipped =+ localStorage.getItem("authenticationSkipped") === "true" ||+ localStorage.getItem("skipAuth") === "true";// Main starts fail-closed. Only a renderer that has resolved the route and// actually committed the normal app may release global hotkeys and popup// surfaces; fresh installs and onboarding reloads keep them suppressed.void window.electronAPI?.setOnboardingActive?.(!normalAppVisible);- }, [isControlPanel, isLoading, isWaitingForPolicyStart, needsReauth, showOnboarding]);+ let cancelled = false;+ void resolveMacAccessibilityReadiness({+ normalAppVisible,+ isControlPanel,+ isSignedIn,+ authSkipped,+ // The hidden dictation window cannot resolve Better Auth itself. Its+ // persisted main-process scope proves this is a validated returning user.+ readActiveAccountScope: window.electronAPI?.getActiveAccountScope,+ }).then((readiness) => {+ if (!cancelled && readiness) {+ window.electronAPI?.markMacAccessibilityFeaturesReady?.(readiness.expectedAccountScope);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [isControlPanel, isLoading, isSignedIn, isWaitingForPolicyStart, needsReauth, showOnboarding]);const handleOnboardingComplete = (options) => {if (options?.openSettings) {diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex c47e56ed0..7564cd136 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -53,6 +53,7 @@ import {reconcileStepWithRoute,resetOnboardingProgress,resolveEnterpriseWorkspaceForOnboarding,+ shouldInitializeMacAccessibilityFeatures,shouldOfferOnboardingLogout,shouldSkipOnboardingSetupChoice,type OnboardingAuthDraft,@@ -189,9 +190,6 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {[setSession]);- const permissions = usePermissions((dialog) =>- setPermissionAlert({ title: dialog.title, description: dialog.description })- );useClipboard((dialog) =>setPermissionAlert({ title: dialog.title, description: dialog.description }));@@ -312,6 +310,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {);const currentStepId = reconcileStepWithRoute(session.currentStepId, route);const compact = COMPACT_STEPS.has(currentStepId);+ const permissions = usePermissions(+ (dialog) => setPermissionAlert({ title: dialog.title, description: dialog.description }),+ {+ macAccessibilityChecksEnabled: shouldInitializeMacAccessibilityFeatures(currentStepId),+ }+ );const updateCurrentByokDraft = useCallback((state: OnboardingByokDraft) => {if (currentStepId !== "byok-dictation" && currentStepId !== "byok-assistant") return;@@ -376,6 +380,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {void window.electronAPI?.setOnboardingWindowMode?.(compact ? "compact" : "expanded");}, [compact]);+ useEffect(() => {+ if (platform === "darwin" && shouldInitializeMacAccessibilityFeatures(currentStepId)) {+ window.electronAPI?.markMacAccessibilityFeaturesReady?.();+ }+ }, [currentStepId, platform]);+useEffect(() => {setStageReady(false);}, [currentStepId]);diff --git a/src/components/onboarding/flow.ts b/src/components/onboarding/flow.tsindex 93f962211..8ec814314 100644--- a/src/components/onboarding/flow.ts+++ b/src/components/onboarding/flow.ts@@ -141,6 +141,11 @@ const STEP_ORDER: OnboardingStepId[] = [];const KNOWN_STEPS = new Set<OnboardingStepId>(STEP_ORDER);+const PERMISSIONS_STEP_INDEX = STEP_ORDER.indexOf("permissions");++export function shouldInitializeMacAccessibilityFeatures(stepId: OnboardingStepId): boolean {+ return STEP_ORDER.indexOf(stepId) >= PERMISSIONS_STEP_INDEX;+}/*** Steps that render in the compact frame. That frame has no footer, so thesediff --git a/src/helpers/accountScopeBinding.js b/src/helpers/accountScopeBinding.jsindex c47781f07..2ad88c1d4 100644--- a/src/helpers/accountScopeBinding.js+++ b/src/helpers/accountScopeBinding.js@@ -54,6 +54,15 @@ function resolveActiveAccountScope({ token, generation, binding }) {return accountId ? { accountId, authGeneration: generation } : null;}+function matchesActiveAccountScope(expected, current) {+ return Boolean(+ expected &&+ current &&+ expected.accountId === current.accountId &&+ expected.authGeneration === current.authGeneration+ );+}+function read() {try {const parsed = JSON.parse(fs.readFileSync(bindingFile(), "utf8"));@@ -90,6 +99,7 @@ module.exports = {clear,evaluateScopeRequest,hashToken,+ matchesActiveAccountScope,persist,read,resolveActiveAccountScope,diff --git a/src/helpers/globeKeyManager.js b/src/helpers/globeKeyManager.jsindex 46f8ffee0..c14b02da6 100644--- a/src/helpers/globeKeyManager.js+++ b/src/helpers/globeKeyManager.js@@ -16,6 +16,9 @@ const MAX_RESTART_ATTEMPTS = 3;const RESTART_DELAY_MS = 1000;// After this much sustained uptime, reset restart counter (allows future restarts after sleep/wake)const RESTART_RESET_MS = 10000;+// Crash recovery is best-effort and must never hold the rest of app startup.+const PREFERENCE_RECOVERY_TIMEOUT_MS = 2000;+const PREFERENCE_RECOVERY_TERMINATION_TIMEOUT_MS = 1000;class GlobeKeyManager extends EventEmitter {constructor({ preferenceStatePath = null } = {}) {@@ -26,6 +29,7 @@ class GlobeKeyManager extends EventEmitter {this._isStopping = false;this._restartCount = 0;this._restartResetTimer = null;+ this._preferenceRecoveryBlocked = false;this.preferenceStatePath = preferenceStatePath;this.config = { mouseButtons: [], suppressGlobeAction: false };}@@ -86,11 +90,111 @@ class GlobeKeyManager extends EventEmitter {return args;}+ restoreLeftoverSystemPreference() {+ if (!this.isSupported || !this.preferenceStatePath) {+ return Promise.resolve();+ }+ if (!fs.existsSync(this.preferenceStatePath)) {+ return Promise.resolve();+ }++ const listenerPath = this.resolveListenerBinary();+ if (!listenerPath) {+ debugLogger.warn("[GlobeKeyManager] Preference recovery skipped — binary not found");+ return Promise.resolve();+ }++ const archMismatch = this._checkArchMismatch(listenerPath);+ if (archMismatch) {+ debugLogger.warn("[GlobeKeyManager] Preference recovery skipped", { error: archMismatch });+ return Promise.resolve();+ }++ return new Promise((resolve) => {+ let settled = false;+ let recoveryTimeout = null;+ let terminationTimeout = null;+ let terminationRequested = false;+ const finish = (error, code) => {+ if (settled) return;+ settled = true;+ if (recoveryTimeout) clearTimeout(recoveryTimeout);+ if (terminationTimeout) clearTimeout(terminationTimeout);+ if (error || code !== 0) {+ debugLogger.warn("[GlobeKeyManager] Preference recovery failed", {+ error: error?.message,+ code,+ });+ }+ resolve();+ };+ const blockListenerStart = (error) => {+ this._preferenceRecoveryBlocked = true;+ finish(error);+ };++ try {+ const child = spawn(+ listenerPath,+ [+ "--globe-preference-state",+ this.preferenceStatePath,+ "--restore-leftover-globe-preference",+ ],+ { stdio: "ignore" }+ );+ child.once("error", (error) => {+ if (terminationRequested) {+ blockListenerStart(error);+ } else {+ finish(error);+ }+ });+ child.once("exit", (code) =>+ finish(+ terminationRequested+ ? new Error("Preference recovery helper was terminated after timing out")+ : null,+ code+ )+ );+ recoveryTimeout = setTimeout(() => {+ terminationRequested = true;+ try {+ child.kill("SIGKILL");+ } catch (error) {+ blockListenerStart(error);+ return;+ }+ if (!settled) {+ terminationTimeout = setTimeout(+ () =>+ blockListenerStart(+ new Error(+ `Preference recovery helper did not exit within ${PREFERENCE_RECOVERY_TERMINATION_TIMEOUT_MS}ms after SIGKILL`+ )+ ),+ PREFERENCE_RECOVERY_TERMINATION_TIMEOUT_MS+ );+ }+ }, PREFERENCE_RECOVERY_TIMEOUT_MS);+ } catch (error) {+ finish(error);+ }+ });+ }+start() {if (!this.isSupported) {debugLogger.info("[GlobeKeyManager] Skipped — not macOS");return;}+ if (this._preferenceRecoveryBlocked) {+ this.reportError(+ new Error("Globe listener blocked because preference recovery could not be terminated")+ );+ return;+ }if (this.process) {debugLogger.info("[GlobeKeyManager] Skipped — already running");return;diff --git a/src/hooks/usePermissions.ts b/src/hooks/usePermissions.tsindex 127616b18..31049c368 100644--- a/src/hooks/usePermissions.ts+++ b/src/hooks/usePermissions.ts@@ -27,6 +27,10 @@ export interface UsePermissionsProps {showAlertDialog: (dialog: { title: string; description?: string }) => void;}+interface UsePermissionsOptions {+ macAccessibilityChecksEnabled?: boolean;+}+const stopTracks = (stream?: MediaStream) => {try {stream?.getTracks?.().forEach((track) => track.stop());@@ -103,7 +107,8 @@ const describeMicError = (error: unknown, t: TFunction): string => {};export const usePermissions = (- showAlertDialog?: UsePermissionsProps["showAlertDialog"]+ showAlertDialog?: UsePermissionsProps["showAlertDialog"],+ { macAccessibilityChecksEnabled = true }: UsePermissionsOptions = {}): UsePermissionsReturn => {const { t } = useTranslation();const [micPermissionGranted, setMicPermissionGranted] = useLocalStorage(@@ -275,18 +280,18 @@ export const usePermissions = (});}, [setMicPermissionGranted]);- // On macOS, re-validate accessibility permission on mount to override stale- // localStorage values (e.g. after app update changes the code signature).+ // On macOS, re-validate accessibility permission once this screen is allowed+ // to touch protected features, overriding stale localStorage values.useEffect(() => {- if (getPlatform() !== "darwin") return;+ if (getPlatform() !== "darwin" || !macAccessibilityChecksEnabled) return;window.electronAPI?.checkAccessibilityPermission?.(true).then((granted) => {setAccessibilityPermissionGranted(granted);});- }, [setAccessibilityPermissionGranted]);+ }, [macAccessibilityChecksEnabled, setAccessibilityPermissionGranted]);// Poll for accessibility permission changes on macOS (e.g. user grants in System Settings)useEffect(() => {- if (getPlatform() !== "darwin") return;+ if (getPlatform() !== "darwin" || !macAccessibilityChecksEnabled) return;if (accessibilityPermissionGranted) {setAccessibilityTroubleshooting(false);accessibilityPollCount.current = 0;@@ -310,7 +315,11 @@ export const usePermissions = (}, 2000);return () => clearInterval(interval);- }, [accessibilityPermissionGranted, setAccessibilityPermissionGranted]);+ }, [+ accessibilityPermissionGranted,+ macAccessibilityChecksEnabled,+ setAccessibilityPermissionGranted,+ ]);return {micPermissionGranted,diff --git a/src/types/electron.ts b/src/types/electron.tsindex 2a66e085a..0ccd9bee8 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -2028,6 +2028,7 @@ declare global {onShowSettings?: (callback: () => void) => () => void;// Accessibility permission events (macOS)+ markMacAccessibilityFeaturesReady?: (expectedAccountScope?: ActiveAccountScope) => void;onAccessibilityMissing?: (callback: () => void) => () => void;checkAccessibilityTrusted?: () => Promise<boolean>;diff --git a/src/utils/macAccessibilityReadiness.ts b/src/utils/macAccessibilityReadiness.tsnew file mode 100644index 000000000..3c5970a9e--- /dev/null+++ b/src/utils/macAccessibilityReadiness.ts@@ -0,0 +1,32 @@+import type { ActiveAccountScope } from "../types/electron";++type ReadinessOptions = {+ normalAppVisible: boolean;+ isControlPanel: boolean;+ isSignedIn: boolean;+ authSkipped: boolean;+ readActiveAccountScope?: () => Promise<ActiveAccountScope | null>;+};++type MacAccessibilityReadiness = {+ expectedAccountScope?: ActiveAccountScope;+};++export async function resolveMacAccessibilityReadiness({+ normalAppVisible,+ isControlPanel,+ isSignedIn,+ authSkipped,+ readActiveAccountScope,+}: ReadinessOptions): Promise<MacAccessibilityReadiness | null> {+ if (!normalAppVisible) return null;+ if (isSignedIn || authSkipped) return {};+ if (isControlPanel || !readActiveAccountScope) return null;++ try {+ const expectedAccountScope = await readActiveAccountScope();+ return expectedAccountScope ? { expectedAccountScope } : null;+ } catch {+ return null;+ }+}diff --git a/test/components/macAccessibilityReadiness.test.js b/test/components/macAccessibilityReadiness.test.jsnew file mode 100644index 000000000..1a854caac--- /dev/null+++ b/test/components/macAccessibilityReadiness.test.js@@ -0,0 +1,81 @@+const assert = require("node:assert/strict");+const test = require("node:test");++const load = () => import("../../src/utils/macAccessibilityReadiness.ts");++const defaults = {+ normalAppVisible: true,+ isControlPanel: false,+ isSignedIn: false,+ authSkipped: false,+};++test("completed hidden startup accepts the validated main-process account scope", async () => {+ const { resolveMacAccessibilityReadiness } = await load();+ const ready = await resolveMacAccessibilityReadiness({+ ...defaults,+ readActiveAccountScope: async () => ({ accountId: "account-a", authGeneration: 3 }),+ });++ assert.deepEqual(ready, {+ expectedAccountScope: { accountId: "account-a", authGeneration: 3 },+ });+});++test("hidden startup rejects stale completion state without a validated account scope", async () => {+ const { resolveMacAccessibilityReadiness } = await load();+ const ready = await resolveMacAccessibilityReadiness({+ ...defaults,+ readActiveAccountScope: async () => null,+ });++ assert.equal(ready, null);+});++test("hidden startup fails closed when the account scope cannot be read", async () => {+ const { resolveMacAccessibilityReadiness } = await load();+ const ready = await resolveMacAccessibilityReadiness({+ ...defaults,+ readActiveAccountScope: async () => {+ throw new Error("scope unavailable");+ },+ });++ assert.equal(ready, null);+});++test("control panel never substitutes the main-process scope for resolved auth", async () => {+ const { resolveMacAccessibilityReadiness } = await load();+ let scopeRead = false;+ const ready = await resolveMacAccessibilityReadiness({+ ...defaults,+ isControlPanel: true,+ readActiveAccountScope: async () => {+ scopeRead = true;+ return { accountId: "account-a", authGeneration: 3 };+ },+ });++ assert.equal(ready, null);+ assert.equal(scopeRead, false);+});++test("resolved account and guest sessions keep their immediate readiness paths", async () => {+ const { resolveMacAccessibilityReadiness } = await load();++ assert.deepEqual(await resolveMacAccessibilityReadiness({ ...defaults, isSignedIn: true }), {});+ assert.deepEqual(await resolveMacAccessibilityReadiness({ ...defaults, authSkipped: true }), {});+});++test("onboarding remains fail-closed for every authentication state", async () => {+ const { resolveMacAccessibilityReadiness } = await load();++ assert.equal(+ await resolveMacAccessibilityReadiness({+ ...defaults,+ normalAppVisible: false,+ isSignedIn: true,+ }),+ null+ );+});diff --git a/test/components/onboardingFlow.test.js b/test/components/onboardingFlow.test.jsindex c09f6be1d..ba78ca0da 100644--- a/test/components/onboardingFlow.test.js+++ b/test/components/onboardingFlow.test.js@@ -1,4 +1,5 @@const assert = require("node:assert/strict");+const { readFileSync } = require("node:fs");const test = require("node:test");const load = () => import("../../src/components/onboarding/flow.ts");@@ -23,6 +24,30 @@ test("account flow includes the complete guided setup", async () => {);});+test("macOS accessibility features stay deferred until the permissions screen", async () => {+ const { shouldInitializeMacAccessibilityFeatures } = await load();++ assert.equal(shouldInitializeMacAccessibilityFeatures("auth"), false);+ assert.equal(shouldInitializeMacAccessibilityFeatures("required-models"), false);+ assert.equal(shouldInitializeMacAccessibilityFeatures("permissions"), true);+ assert.equal(shouldInitializeMacAccessibilityFeatures("dictation-hotkey"), true);+ assert.equal(shouldInitializeMacAccessibilityFeatures("notes"), true);+});++test("onboarding permission checks use the resolved macOS feature gate", () => {+ const source = readFileSync("src/components/OnboardingFlow.tsx", "utf8");++ assert.ok(+ source.indexOf("const currentStepId = reconcileStepWithRoute") <+ source.indexOf("const permissions = usePermissions")+ );+ assert.ok(+ source.includes(+ "macAccessibilityChecksEnabled: shouldInitializeMacAccessibilityFeatures(currentStepId)"+ )+ );+});+test("guest flow keeps permissions and the hotkey before setup choice", async () => {const { getOnboardingRoute } = await load();// finalizeOnboarding registers the dictation hotkey on every path, so guestsdiff --git a/test/helpers/accountScopeBinding.test.js b/test/helpers/accountScopeBinding.test.jsindex b3303dfbb..621918a3d 100644--- a/test/helpers/accountScopeBinding.test.js+++ b/test/helpers/accountScopeBinding.test.js@@ -146,3 +146,19 @@ test("resolveActiveAccountScope pairs the restorable account with the current crnull);});++test("matchesActiveAccountScope rejects a stale readiness generation", () => {+ const expected = { accountId: "account-a", authGeneration: 3 };++ assert.equal(binding.matchesActiveAccountScope(expected, { ...expected }), true);+ assert.equal(+ binding.matchesActiveAccountScope(expected, { accountId: "account-a", authGeneration: 4 }),+ false+ );+ assert.equal(+ binding.matchesActiveAccountScope(expected, { accountId: "account-b", authGeneration: 3 }),+ false+ );+ assert.equal(binding.matchesActiveAccountScope(expected, null), false);+ assert.equal(binding.matchesActiveAccountScope(null, expected), false);+});diff --git a/test/helpers/accountScopeRestoreContract.test.js b/test/helpers/accountScopeRestoreContract.test.jsindex 3dfc19d6d..c8b3a182b 100644--- a/test/helpers/accountScopeRestoreContract.test.js+++ b/test/helpers/accountScopeRestoreContract.test.js@@ -47,6 +47,21 @@ test("boot restores the validated scope before any main-process consumer construassert.ok(bootWindow[1].includes("databaseManager.setActiveAccountId(bootAccountId)"));});+test("account-scoped accessibility readiness is revalidated before opening the sticky gate", () => {+ const source = read("main.js");+ const handler = source.match(+ /ipcMain\.on\("mac-accessibility-features-ready"([\s\S]*?)\/\/ Listen for usage limit/+ );+ assert.ok(handler, "macOS accessibility readiness handler is present");+ assert.ok(handler[1].includes("resolveActiveAccountScope"));+ assert.ok(handler[1].includes("matchesActiveAccountScope"));+ assert.ok(+ handler[1].indexOf("matchesActiveAccountScope") <+ handler[1].indexOf("macAccessibilityFeaturesReady = true"),+ "the current scope is checked before the readiness gate opens"+ );+});+test("clearing the bearer token broadcasts the cleared account scope to every window", () => {const source = read("src/helpers/ipcHandlers.js");const subscription = source.match(diff --git a/test/helpers/globeKeyManager.test.js b/test/helpers/globeKeyManager.test.jsindex b95d2a6d5..00285ce9f 100644--- a/test/helpers/globeKeyManager.test.js+++ b/test/helpers/globeKeyManager.test.js@@ -38,15 +38,39 @@ function makeChild() {return true;},});- child.kill = () => {+ child.kill = (signal) => {child.killed = true;+ child.killSignal = signal;};return child;}+function installFakeTimers() {+ const originalSetTimeout = global.setTimeout;+ const originalClearTimeout = global.clearTimeout;+ const timers = [];++ global.setTimeout = (callback, delay) => {+ const timer = { callback, delay, cleared: false };+ timers.push(timer);+ return timer;+ };+ global.clearTimeout = (timer) => {+ timer.cleared = true;+ };++ return {+ timers,+ restore() {+ global.setTimeout = originalSetTimeout;+ global.clearTimeout = originalClearTimeout;+ },+ };+}+// Returns the manager plus the spawn calls it made, so tests can assert on the// arguments handed to the native listener.-function loadManager() {+function loadManager({ markerExists = true } = {}) {delete require.cache[managerModulePath];setPlatform("darwin");@@ -68,6 +92,7 @@ function loadManager() {return {constants: { X_OK: 1 },statSync: () => ({ isFile: () => true }),+ existsSync: () => markerExists,accessSync() {},// Architecture verification is best-effort; failing it here keeps the// test independent of the host CPU.@@ -104,8 +129,103 @@ test("spawn args carry the state path and omit suppression by default", () => {assert.deepEqual(spawnCalls[0].args, ["--globe-preference-state", "/tmp/state.json"]);});+test("leftover preference recovery uses a one-shot helper without starting the listener", async () => {+ const { GlobeKeyManager, spawnCalls } = loadManager();+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });++ const recovery = manager.restoreLeftoverSystemPreference();++ assert.equal(spawnCalls.length, 1);+ assert.deepEqual(spawnCalls[0].args, [+ "--globe-preference-state",+ "/tmp/state.json",+ "--restore-leftover-globe-preference",+ ]);+ assert.equal(manager.process, null);++ spawnCalls[0].child.emit("exit", 0, null);+ await recovery;++ assert.equal(manager.process, null);+});++test("timed-out preference recovery waits for the helper to exit", async () => {+ const fakeTimers = installFakeTimers();+ try {+ const { GlobeKeyManager, spawnCalls } = loadManager();+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });+ const recovery = manager.restoreLeftoverSystemPreference();+ let resolved = false;+ recovery.then(() => {+ resolved = true;+ });++ assert.equal(fakeTimers.timers[0].delay, 2000);+ fakeTimers.timers[0].callback();+ await Promise.resolve();++ assert.equal(resolved, false, "startup must wait until the one-shot helper exits");+ assert.equal(fakeTimers.timers[1].delay, 1000);+ assert.equal(spawnCalls[0].child.killed, true);+ assert.equal(spawnCalls[0].child.killSignal, "SIGKILL");++ spawnCalls[0].child.emit("exit", null, "SIGKILL");+ await recovery;++ assert.equal(resolved, true);+ assert.equal(fakeTimers.timers[0].cleared, true);+ assert.equal(fakeTimers.timers[1].cleared, true);+ assert.equal(manager.process, null);+ } finally {+ fakeTimers.restore();+ }+});++test("an unconfirmed recovery termination blocks the long-lived listener", async () => {+ const fakeTimers = installFakeTimers();+ try {+ const { GlobeKeyManager, spawnCalls } = loadManager();+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });+ const errors = [];+ manager.on("error", (error) => errors.push(error));++ const recovery = manager.restoreLeftoverSystemPreference();+ fakeTimers.timers[0].callback();+ fakeTimers.timers[1].callback();+ await recovery;++ manager.start();++ assert.equal(spawnCalls.length, 1, "a second helper must not race the wedged recovery");+ assert.match(errors[0].message, /preference recovery could not be terminated/);+ assert.equal(manager.process, null);+ } finally {+ fakeTimers.restore();+ }+});++test("leftover preference recovery is skipped without a marker or off macOS", async () => {+ const { GlobeKeyManager, spawnCalls } = loadManager();+ const manager = new GlobeKeyManager();++ await manager.restoreLeftoverSystemPreference();+ setPlatform("win32");+ await new GlobeKeyManager({+ preferenceStatePath: "/tmp/state.json",+ }).restoreLeftoverSystemPreference();++ assert.equal(spawnCalls.length, 0);++ const withoutMarker = loadManager({ markerExists: false });+ await new withoutMarker.GlobeKeyManager({+ preferenceStatePath: "/tmp/state.json",+ }).restoreLeftoverSystemPreference();+ assert.equal(withoutMarker.spawnCalls.length, 0);+});+test("spawn args include mouse buttons, a spaced state path, and the suppression flag", () => {- const statePath = "/Users/a b/Library/Application Support/open whispr/globe-preference-state.json";+ const statePath =+ "/Users/a b/Library/Application Support/open whispr/globe-preference-state.json";const { GlobeKeyManager, spawnCalls } = loadManager();const manager = new GlobeKeyManager({ preferenceStatePath: statePath });diff --git a/test/helpers/preloadOnboardingBridge.test.js b/test/helpers/preloadOnboardingBridge.test.jsindex f803c70d7..271d00043 100644--- a/test/helpers/preloadOnboardingBridge.test.js+++ b/test/helpers/preloadOnboardingBridge.test.js@@ -7,6 +7,7 @@ const vm = require("node:vm");function loadPreloadApi() {let exposedApi;const invocations = [];+ const sends = [];const listeners = new Map();const ipcRenderer = {invoke: async (channel, ...args) => {@@ -17,7 +18,7 @@ function loadPreloadApi() {removeListener: (channel, listener) => {if (listeners.get(channel) === listener) listeners.delete(channel);},- send: () => undefined,+ send: (channel, ...args) => sends.push([channel, ...args]),sendSync: () => undefined,};const electron = {@@ -37,7 +38,7 @@ function loadPreloadApi() {},process,});- return { api: exposedApi, invocations, listeners };+ return { api: exposedApi, invocations, listeners, sends };}test("onboarding demo bridge invokes only its allowlisted channels", async () => {@@ -70,6 +71,19 @@ test("onboarding active bridge invokes only its allowlisted channel", async () =]);});+test("macOS accessibility readiness forwards an optional account scope", () => {+ const { api, sends } = loadPreloadApi();+ const expectedAccountScope = { accountId: "account-a", authGeneration: 3 };++ api.markMacAccessibilityFeaturesReady();+ api.markMacAccessibilityFeaturesReady(expectedAccountScope);++ assert.deepEqual(sends, [+ ["mac-accessibility-features-ready"],+ ["mac-accessibility-features-ready", expectedAccountScope],+ ]);+});+test("onboarding demo listener strips the Electron event and disposes cleanly", () => {const { api, listeners } = loadPreloadApi();const payload = {diff --git a/test/hooks/usePermissionsAccessibilityGate.test.js b/test/hooks/usePermissionsAccessibilityGate.test.jsnew file mode 100644index 000000000..e90d54585--- /dev/null+++ b/test/hooks/usePermissionsAccessibilityGate.test.js@@ -0,0 +1,93 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");++test("macOS accessibility checks follow the onboarding feature gate", async (t) => {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });++ let accessibilityChecks = 0;+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ getPlatform: () => "darwin",+ checkAccessibilityPermission: async () => {+ accessibilityChecks += 1;+ return false;+ },+ checkMicrophoneAccess: async () => ({ granted: false }),+ checkPasteTools: async () => ({+ platform: "darwin",+ available: true,+ method: "cgevent",+ requiresPermission: true,+ tools: [],+ }),+ },+ },+ });+ const container = installHookDom(t);++ const originalSetInterval = globalThis.setInterval;+ const originalClearInterval = globalThis.clearInterval;+ const activeIntervals = new Set();+ let nextIntervalId = 1;+ globalThis.setInterval = () => {+ const id = nextIntervalId++;+ activeIntervals.add(id);+ return id;+ };+ globalThis.clearInterval = (id) => activeIntervals.delete(id);+ t.after(() => {+ globalThis.setInterval = originalSetInterval;+ globalThis.clearInterval = originalClearInterval;+ });++ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-permissions-accessibility-gate-",+ noExternal: ["react-i18next"],+ mockModules: {+ "react-i18next": `+ const t = (key) => key;+ export function useTranslation() { return { t }; }+ `,+ },+ });+ const { usePermissions } = await vite.ssrLoadModule("/hooks/usePermissions.ts");++ let macAccessibilityChecksEnabled = false;+ function Harness() {+ usePermissions(undefined, { macAccessibilityChecksEnabled });+ return null;+ }++ root = createRoot(container);+ const render = async () => {+ await React.act(async () => {+ root.render(React.createElement(Harness));+ await Promise.resolve();+ });+ };++ await render();+ assert.equal(accessibilityChecks, 0);+ assert.equal(activeIntervals.size, 0);++ macAccessibilityChecksEnabled = true;+ await render();+ assert.equal(accessibilityChecks, 1);+ assert.equal(activeIntervals.size, 1);++ macAccessibilityChecksEnabled = false;+ await render();+ assert.equal(accessibilityChecks, 1);+ assert.equal(activeIntervals.size, 0);+});