Skip to content

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

fix(macos): stop the system Globe action firing alongside the Globe hotkey (#1567)

Gabriel Stein0a121c24db7c
diff --git a/main.js b/main.js
index c69ef7929..41030422a 100644
--- a/main.js
+++ b/main.js
@@ -528,7 +528,10 @@ function initializeDeferredManagers() {
});
clipboardManager.preWarmAccessibility();
trayManager = new TrayManager();
- globeKeyManager = new GlobeKeyManager();
+ globeKeyManager = new GlobeKeyManager({
+ // Lets the listener put the user's macOS Globe action back after a crash.
+ preferenceStatePath: path.join(app.getPath("userData"), "globe-preference-state.json"),
+ });
if (process.platform === "darwin") {
globeKeyManager.on("error", (error) => {
@@ -1439,14 +1442,11 @@ async function startApp() {
}
});
- const syncSuppressedMouseButtons = () => {
- const buttons = [];
- for (const slotName of ["dictation", "agent", "voiceAgent", "translation"]) {
- for (const hotkey of hotkeyManager.getSlotHotkeys(slotName)) {
- if (isMouseButtonHotkey(hotkey)) buttons.push(hotkey);
- }
- }
- globeKeyManager.setSuppressedMouseButtons(buttons);
+ const MAC_NATIVE_HOTKEY_SLOTS = ["dictation", "agent", "voiceAgent", "translation"];
+ const syncMacNativeHotkeyConfiguration = () => {
+ globeKeyManager.setConfiguration(
+ hotkeyManager.getMacNativeListenerConfig(MAC_NATIVE_HOTKEY_SLOTS)
+ );
};
// Mouse Button 4/5 handling (e.g., Logitech MX Master side buttons)
@@ -1521,15 +1521,17 @@ async function startApp() {
}
});
- syncSuppressedMouseButtons();
+ syncMacNativeHotkeyConfiguration();
globeKeyManager.start();
- hotkeyManager.once("hotkey-loaded", syncSuppressedMouseButtons);
+ hotkeyManager.on("hotkey-loaded", syncMacNativeHotkeyConfiguration);
ipcMain.on("hotkey-listening-mode-changed", (_event, enabled) => {
if (enabled) {
- globeKeyManager.setSuppressedMouseButtons([]);
+ // 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 });
} else {
- syncSuppressedMouseButtons();
+ syncMacNativeHotkeyConfiguration();
}
});
@@ -1568,7 +1570,7 @@ async function startApp() {
mouseButtonDownTime = 0;
mouseButtonIsRecording = false;
mouseButtonLastStopTime = 0;
- syncSuppressedMouseButtons();
+ syncMacNativeHotkeyConfiguration();
});
}
diff --git a/resources/macos-globe-listener.swift b/resources/macos-globe-listener.swift
index c2992183d..1b8402e1f 100644
--- a/resources/macos-globe-listener.swift
+++ b/resources/macos-globe-listener.swift
@@ -4,13 +4,187 @@ import Darwin
var fnIsDown = false
var fnInterrupted = false
var lastModifierFlags: NSEvent.ModifierFlags = []
+var suppressedMouseButtons: Set<String> = []
-let suppressedMouseButtons = Set(
- CommandLine.arguments.dropFirst()
- .flatMap { $0.split(separator: ",") }
- .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) }
- .filter { !$0.isEmpty }
-)
+struct ListenerConfig: Decodable {
+ var mouseButtons: Set<String> = []
+ var suppressGlobeAction: Bool = false
+}
+
+func emit(_ message: String) {
+ FileHandle.standardOutput.write((message + "\n").data(using: .utf8)!)
+ fflush(stdout)
+}
+
+func emitWarning(_ message: String) {
+ FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
+}
+
+// Mouse buttons arrive as a positional comma-separated list; everything else is
+// an explicit flag.
+func parseArguments() -> (config: ListenerConfig, statePath: String?) {
+ var config = ListenerConfig()
+ var statePath: String?
+ var arguments = CommandLine.arguments.dropFirst().makeIterator()
+
+ while let argument = arguments.next() {
+ switch argument {
+ case "--suppress-system-globe-action":
+ config.suppressGlobeAction = true
+ case "--globe-preference-state":
+ statePath = arguments.next()
+ default:
+ config.mouseButtons.formUnion(
+ argument.split(separator: ",")
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ )
+ }
+ }
+
+ return (config, statePath)
+}
+
+struct GlobePreferenceState: Codable {
+ let version: Int
+ let originalValue: Int32
+ let keyExisted: Bool
+}
+
+// macOS runs the standalone Globe action (emoji viewer, input-source switch,
+// dictation) from WindowServer ahead of every event tap, so a listener cannot
+// consume the key — the only way to stop it firing alongside an OpenWhispr Globe
+// hotkey is to hold AppleFnUsageType at "Do Nothing" while we own the key.
+// TISUpdateFnUsageType is what System Settings itself calls: it persists the
+// preference and broadcasts the change so it applies live. Writing the
+// preference directly is ignored until the user's next login.
+enum GlobeSystemAction {
+ private typealias GetUsageType = @convention(c) () -> Int32
+ private typealias UpdateUsageType = @convention(c) (Int32) -> Void
+
+ private static let doNothing: Int32 = 0
+ private static let stateVersion = 1
+ private static let domain = "com.apple.HIToolbox" as CFString
+ private static let key = "AppleFnUsageType" as CFString
+
+ private static let entryPoints: (get: GetUsageType, update: UpdateUsageType)? = {
+ guard let carbon = dlopen("/System/Library/Frameworks/Carbon.framework/Carbon", RTLD_LAZY),
+ let get = dlsym(carbon, "TISGetFnUsageType"),
+ let update = dlsym(carbon, "TISUpdateFnUsageType")
+ else { return nil }
+ return (unsafeBitCast(get, to: GetUsageType.self), unsafeBitCast(update, to: UpdateUsageType.self))
+ }()
+
+ static var statePath: String?
+ private static var owned: GlobePreferenceState?
+
+ // Adopts a marker left by a crashed run so its recorded original value is
+ // used instead of mistaking our own override for the user's preference.
+ static func recoverLeftoverState() {
+ guard let state = readMarker(), let entryPoints else { return }
+ if entryPoints.get() == doNothing {
+ owned = state
+ } else {
+ // The user picked a new action since we died — theirs wins.
+ removeMarker()
+ }
+ }
+
+ static func apply() {
+ guard owned == nil else { return }
+ guard let entryPoints else {
+ emitWarning("Cannot suppress the macOS Globe action: TISUpdateFnUsageType unavailable")
+ return
+ }
+
+ let original = entryPoints.get()
+ guard original != doNothing else { return }
+
+ let state = GlobePreferenceState(
+ version: stateVersion,
+ originalValue: original,
+ keyExisted: rawValueExists()
+ )
+ // Record how to get back before changing anything.
+ guard writeMarker(state) else { return }
+
+ owned = state
+ entryPoints.update(doNothing)
+ }
+
+ static func restore() {
+ guard let state = owned, let entryPoints else { return }
+ owned = nil
+
+ // Only put the value back while it is still ours: if the user picked a
+ // new action while we were running, that choice wins.
+ if entryPoints.get() == doNothing {
+ entryPoints.update(state.originalValue)
+ // The value was a macOS-computed default before we touched it, so
+ // clear the key again to keep it tracking hardware and input sources.
+ if !state.keyExisted {
+ clearRawValue()
+ }
+ }
+
+ removeMarker()
+ }
+
+ // CFPreferencesCopyAppValue caches foreign domains for the life of the
+ // process and would miss changes made after launch.
+ private static func rawValueExists() -> Bool {
+ CFPreferencesSynchronize(domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
+ return CFPreferencesCopyValue(key, domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) != nil
+ }
+
+ private static func clearRawValue() {
+ CFPreferencesSetValue(key, nil, domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
+ CFPreferencesSynchronize(domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
+ }
+
+ private static func readMarker() -> GlobePreferenceState? {
+ guard let statePath, let data = FileManager.default.contents(atPath: statePath) else { return nil }
+ guard let state = try? JSONDecoder().decode(GlobePreferenceState.self, from: data),
+ state.version == stateVersion
+ else {
+ removeMarker()
+ return nil
+ }
+ return state
+ }
+
+ private static func writeMarker(_ state: GlobePreferenceState) -> Bool {
+ guard let statePath else {
+ emitWarning("Cannot suppress the macOS Globe action: no state path provided")
+ return false
+ }
+ do {
+ try JSONEncoder().encode(state).write(to: URL(fileURLWithPath: statePath), options: .atomic)
+ return true
+ } catch {
+ emitWarning("Cannot suppress the macOS Globe action: \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ private static func removeMarker() {
+ guard let statePath else { return }
+ try? FileManager.default.removeItem(atPath: statePath)
+ }
+}
+
+func applyConfiguration(_ config: ListenerConfig) {
+ suppressedMouseButtons = config.mouseButtons
+ if config.suppressGlobeAction {
+ GlobeSystemAction.apply()
+ } else {
+ GlobeSystemAction.restore()
+ }
+}
+
+let launchOptions = parseArguments()
+GlobeSystemAction.statePath = launchOptions.statePath
+GlobeSystemAction.recoverLeftoverState()
let rightModifiers: [(UInt16, NSEvent.ModifierFlags, String)] = [
(61, .option, "RightOption"),
@@ -28,11 +202,6 @@ let releases: [(NSEvent.ModifierFlags, String)] = [
(.shift, "shift"),
]
-func emit(_ message: String) {
- FileHandle.standardOutput.write((message + "\n").data(using: .utf8)!)
- fflush(stdout)
-}
-
func mouseButtonName(_ buttonNumber: Int) -> String? {
switch buttonNumber {
case 3:
@@ -89,7 +258,7 @@ if let mouseEventTap {
CFRunLoopAddSource(CFRunLoopGetMain(), mouseRunLoopSource, .commonModes)
CGEvent.tapEnable(tap: mouseEventTap, enable: true)
} else {
- FileHandle.standardError.write("Failed to create mouse event tap\n".data(using: .utf8)!)
+ emitWarning("Failed to create mouse event tap")
}
guard let monitor = NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged, handler: { event in
@@ -125,7 +294,8 @@ guard let monitor = NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged, h
lastModifierFlags = currentModifiers
}
}) else {
- FileHandle.standardError.write("Failed to create event monitor\n".data(using: .utf8)!)
+ emitWarning("Failed to create event monitor")
+ GlobeSystemAction.restore()
exit(1)
}
@@ -138,9 +308,8 @@ let keyMonitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { _ in
}
}
-let signalSource = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .main)
-signal(SIGTERM, SIG_IGN)
-signalSource.setEventHandler {
+func shutdownListener() -> Never {
+ GlobeSystemAction.restore()
NSEvent.removeMonitor(monitor)
if let keyMonitor {
NSEvent.removeMonitor(keyMonitor)
@@ -153,7 +322,49 @@ signalSource.setEventHandler {
}
exit(0)
}
-signalSource.resume()
+
+// Only take over the system Globe action once the listener is known to work.
+applyConfiguration(launchOptions.config)
+
+// Reconfiguration arrives as one JSON object per line so the hotkey can change
+// without restarting; EOF means the app is gone and the Globe key goes back.
+var stdinBuffer = [UInt8]()
+let stdinSource = DispatchSource.makeReadSource(fileDescriptor: STDIN_FILENO, queue: .main)
+stdinSource.setEventHandler {
+ var chunk = [UInt8](repeating: 0, count: 4096)
+ let bytesRead = read(STDIN_FILENO, &chunk, chunk.count)
+
+ guard bytesRead > 0 else {
+ if bytesRead == 0 || (errno != EAGAIN && errno != EINTR) {
+ shutdownListener()
+ }
+ return
+ }
+
+ stdinBuffer.append(contentsOf: chunk[0..<bytesRead])
+ while let newline = stdinBuffer.firstIndex(of: UInt8(ascii: "\n")) {
+ let line = Data(stdinBuffer[..<newline])
+ stdinBuffer.removeSubrange(...newline)
+ if let config = try? JSONDecoder().decode(ListenerConfig.self, from: line) {
+ applyConfiguration(config)
+ } else {
+ emitWarning("Ignored malformed configuration line")
+ }
+ }
+}
+stdinSource.resume()
+
+func installTerminationSource(for signalNumber: Int32) -> DispatchSourceSignal {
+ signal(signalNumber, SIG_IGN)
+ let source = DispatchSource.makeSignalSource(signal: signalNumber, queue: .main)
+ source.setEventHandler { shutdownListener() }
+ source.resume()
+ return source
+}
+
+// Held for the process lifetime: releasing these sources would drop the signal
+// handlers and with them the preference restore on quit.
+let terminationSources = [SIGTERM, SIGINT].map(installTerminationSource(for:))
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
diff --git a/src/helpers/globeKeyManager.js b/src/helpers/globeKeyManager.js
index 013993e4f..46f8ffee0 100644
--- a/src/helpers/globeKeyManager.js
+++ b/src/helpers/globeKeyManager.js
@@ -18,7 +18,7 @@ const RESTART_DELAY_MS = 1000;
const RESTART_RESET_MS = 10000;
class GlobeKeyManager extends EventEmitter {
- constructor() {
+ constructor({ preferenceStatePath = null } = {}) {
super();
this.process = null;
this.isSupported = process.platform === "darwin";
@@ -26,27 +26,66 @@ class GlobeKeyManager extends EventEmitter {
this._isStopping = false;
this._restartCount = 0;
this._restartResetTimer = null;
- this.suppressedMouseButtons = [];
+ this.preferenceStatePath = preferenceStatePath;
+ this.config = { mouseButtons: [], suppressGlobeAction: false };
}
- setSuppressedMouseButtons(buttons = []) {
- const normalized = [...new Set(buttons.filter((button) => /^MouseButton[45]$/i.test(button)))];
- const unchanged =
- normalized.length === this.suppressedMouseButtons.length &&
- normalized.every((button, index) => button === this.suppressedMouseButtons[index]);
+ // Replaces the listener's whole state, so every call has to pass all of it.
+ setConfiguration({ mouseButtons = [], suppressGlobeAction = false } = {}) {
+ const next = {
+ mouseButtons: [
+ ...new Set(mouseButtons.filter((button) => /^MouseButton[45]$/i.test(button))),
+ ].sort(),
+ suppressGlobeAction: Boolean(suppressGlobeAction),
+ };
- if (unchanged) {
+ if (JSON.stringify(next) === JSON.stringify(this.config)) {
return;
}
- this.suppressedMouseButtons = normalized;
+ this.config = next;
- if (this.process) {
+ if (!this.process) {
+ return;
+ }
+
+ // Reconfigure the running listener rather than restarting it: a restart
+ // drops events and briefly hands the Globe key back to macOS.
+ if (!this._sendConfiguration()) {
this.stop();
this.start();
}
}
+ _sendConfiguration() {
+ const child = this.process;
+ if (!child?.stdin?.writable) {
+ return false;
+ }
+ try {
+ // write() returning false is backpressure, not failure.
+ child.stdin.write(`${JSON.stringify(this.config)}\n`);
+ return true;
+ } catch (error) {
+ debugLogger.warn("[GlobeKeyManager] Failed to send configuration", { error: error.message });
+ return false;
+ }
+ }
+
+ _listenerArgs() {
+ const args = [];
+ if (this.config.mouseButtons.length > 0) {
+ args.push(this.config.mouseButtons.join(","));
+ }
+ if (this.preferenceStatePath) {
+ args.push("--globe-preference-state", this.preferenceStatePath);
+ }
+ if (this.config.suppressGlobeAction) {
+ args.push("--suppress-system-globe-action");
+ }
+ return args;
+ }
+
start() {
if (!this.isSupported) {
debugLogger.info("[GlobeKeyManager] Skipped — not macOS");
@@ -94,11 +133,17 @@ class GlobeKeyManager extends EventEmitter {
}
this.hasReportedError = false;
- const child = spawn(listenerPath, this.suppressedMouseButtons);
+ const child = spawn(listenerPath, this._listenerArgs());
this.process = child;
debugLogger.info("[GlobeKeyManager] Process spawned", {
pid: child.pid,
- suppressedMouseButtons: this.suppressedMouseButtons,
+ config: this.config,
+ });
+
+ // A write racing the listener's shutdown can raise EPIPE, and an unhandled
+ // stream "error" event throws.
+ child.stdin.on("error", (error) => {
+ debugLogger.warn("[GlobeKeyManager] Listener stdin error", { error: error.message });
});
// After sustained uptime, reset the restart counter so future sleep/wake
@@ -175,7 +220,7 @@ class GlobeKeyManager extends EventEmitter {
child.on("exit", (code, signal) => {
debugLogger.info("[GlobeKeyManager] Process exited", { code, signal });
// Only clear instance state if this is still the current process — a prior
- // stop()+start() (e.g. setSuppressedMouseButtons) may have already replaced it.
+ // stop()+start() (e.g. a setConfiguration fallback) may have already replaced it.
if (this.process !== child) {
return;
}
diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.js
index b927a1ee4..18aa772ad 100644
--- a/src/helpers/hotkeyManager.js
+++ b/src/helpers/hotkeyManager.js
@@ -385,6 +385,26 @@ class HotkeyManager extends EventEmitter {
return keys;
}
+ // Which mouse buttons the macOS listener must swallow for these slots, and
+ // whether OpenWhispr owns Globe — if it does, macOS's own standalone Globe
+ // action has to stand down.
+ getMacNativeListenerConfig(slotNames) {
+ const mouseButtons = new Set();
+ let suppressGlobeAction = false;
+
+ for (const slotName of slotNames) {
+ for (const hotkey of this.getSlotHotkeys(slotName)) {
+ if (isMouseButtonHotkey(hotkey)) {
+ mouseButtons.add(hotkey);
+ } else if (isGlobeLikeHotkey(hotkey)) {
+ suppressGlobeAction = true;
+ }
+ }
+ }
+
+ return { mouseButtons: [...mouseButtons], suppressGlobeAction };
+ }
+
// Register one hotkey without mutating any slot. `accelerator` is null for
// hotkeys handled by native listeners.
_registerSingleHotkey(hotkey, callback) {
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 06193e9db..56b0a4876 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -607,6 +607,13 @@ class IPCHandlers {
}
}
+ // The dictation slot reports its own changes from the renderer. Slots
+ // registered through IPC have to announce theirs here so macOS can re-derive
+ // which keys the native Globe listener owns.
+ _notifyHotkeyChanged(hotkey) {
+ ipcMain.emit("hotkey-changed", null, hotkey);
+ }
+
_releaseMicHold(sender) {
const release = this._micHoldSenders.get(sender.id);
if (!release) return;
@@ -9303,6 +9310,7 @@ class IPCHandlers {
hotkeyManager.unregisterSlot("agent");
this.environmentManager.saveAgentKey?.("");
this.windowManager.reconcileNativeKeyListeners();
+ this._notifyHotkeyChanged("");
return { success: true, message: "Agent hotkey cleared" };
}
@@ -9312,6 +9320,7 @@ class IPCHandlers {
this.windowManager.reconcileNativeKeyListeners();
if (result.success) {
this.environmentManager.saveAgentKey?.(hotkey);
+ this._notifyHotkeyChanged(hotkey);
return { success: true, message: `Agent hotkey updated to: ${hotkey}` };
}
@@ -9332,6 +9341,7 @@ class IPCHandlers {
hotkeyManager.unregisterSlot("voiceAgent");
this.environmentManager.saveVoiceAgentKey?.("");
this.windowManager.reconcileNativeKeyListeners();
+ this._notifyHotkeyChanged("");
return { success: true, message: "Voice agent hotkey cleared" };
}
@@ -9341,6 +9351,7 @@ class IPCHandlers {
this.windowManager.reconcileNativeKeyListeners();
if (result.success) {
this.environmentManager.saveVoiceAgentKey?.(hotkey);
+ this._notifyHotkeyChanged(hotkey);
return { success: true, message: `Voice agent hotkey updated to: ${hotkey}` };
}
@@ -9365,6 +9376,7 @@ class IPCHandlers {
hotkeyManager.unregisterSlot("translation");
this.environmentManager.saveTranslationKey?.("");
this.windowManager.reconcileNativeKeyListeners();
+ this._notifyHotkeyChanged("");
return { success: true, message: "Translation hotkey cleared" };
}
@@ -9374,6 +9386,7 @@ class IPCHandlers {
this.windowManager.reconcileNativeKeyListeners();
if (result.success) {
this.environmentManager.saveTranslationKey?.(hotkey);
+ this._notifyHotkeyChanged(hotkey);
return { success: true, message: `Translation hotkey updated to: ${hotkey}` };
}
diff --git a/test/helpers/globeKeyManager.test.js b/test/helpers/globeKeyManager.test.js
new file mode 100644
index 000000000..b95d2a6d5
--- /dev/null
+++ b/test/helpers/globeKeyManager.test.js
@@ -0,0 +1,233 @@
+const test = require("node:test");
+const { afterEach } = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const path = require("node:path");
+const { EventEmitter } = require("node:events");
+const childProcess = require("node:child_process");
+
+const managerModulePath = require.resolve("../../src/helpers/globeKeyManager");
+const originalLoad = Module._load;
+const originalPlatform = process.platform;
+
+// resolveListenerBinary walks real candidate paths, so the first one is pinned
+// here instead of depending on whether the binary happens to be built.
+const LISTENER_PATH = path.join(
+ path.dirname(managerModulePath),
+ "..",
+ "..",
+ "resources",
+ "bin",
+ "macos-globe-listener"
+);
+
+function setPlatform(platform) {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+}
+
+function makeChild() {
+ const child = new EventEmitter();
+ child.pid = 4242;
+ child.stdout = Object.assign(new EventEmitter(), { setEncoding() {} });
+ child.stderr = Object.assign(new EventEmitter(), { setEncoding() {} });
+ child.stdin = Object.assign(new EventEmitter(), {
+ writable: true,
+ writes: [],
+ write(chunk) {
+ this.writes.push(chunk);
+ return true;
+ },
+ });
+ child.kill = () => {
+ child.killed = true;
+ };
+ return child;
+}
+
+// Returns the manager plus the spawn calls it made, so tests can assert on the
+// arguments handed to the native listener.
+function loadManager() {
+ delete require.cache[managerModulePath];
+ setPlatform("darwin");
+
+ const spawnCalls = [];
+ const spawn = (command, args) => {
+ const child = makeChild();
+ spawnCalls.push({ command, args, child });
+ return child;
+ };
+
+ Module._load = function loadWithMocks(request, parent, isMain) {
+ if (request === "./debugLogger") {
+ return { info() {}, warn() {}, debug() {}, error() {} };
+ }
+ if (request === "child_process") {
+ return { ...childProcess, spawn };
+ }
+ if (request === "fs") {
+ return {
+ constants: { X_OK: 1 },
+ statSync: () => ({ isFile: () => true }),
+ accessSync() {},
+ // Architecture verification is best-effort; failing it here keeps the
+ // test independent of the host CPU.
+ openSync() {
+ throw new Error("unavailable in test");
+ },
+ };
+ }
+ return originalLoad(request, parent, isMain);
+ };
+
+ try {
+ const GlobeKeyManager = require(managerModulePath);
+ return { GlobeKeyManager, spawnCalls };
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+afterEach(() => {
+ Module._load = originalLoad;
+ setPlatform(originalPlatform);
+});
+
+test("spawn args carry the state path and omit suppression by default", () => {
+ const { GlobeKeyManager, spawnCalls } = loadManager();
+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });
+
+ manager.start();
+ manager.stop();
+
+ assert.equal(spawnCalls.length, 1);
+ assert.equal(spawnCalls[0].command, LISTENER_PATH);
+ assert.deepEqual(spawnCalls[0].args, ["--globe-preference-state", "/tmp/state.json"]);
+});
+
+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 { GlobeKeyManager, spawnCalls } = loadManager();
+ const manager = new GlobeKeyManager({ preferenceStatePath: statePath });
+
+ manager.setConfiguration({
+ mouseButtons: ["MouseButton5", "MouseButton4", "MouseButton4"],
+ suppressGlobeAction: true,
+ });
+ manager.start();
+ manager.stop();
+
+ // The path stays a single argv entry, so spaces need no escaping.
+ assert.deepEqual(spawnCalls[0].args, [
+ "MouseButton4,MouseButton5",
+ "--globe-preference-state",
+ statePath,
+ "--suppress-system-globe-action",
+ ]);
+});
+
+test("a configuration change reconfigures the running listener instead of restarting it", () => {
+ const { GlobeKeyManager, spawnCalls } = loadManager();
+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });
+
+ manager.start();
+ manager.setConfiguration({ mouseButtons: ["MouseButton4"], suppressGlobeAction: true });
+
+ assert.equal(spawnCalls.length, 1, "listener should not be respawned");
+ assert.deepEqual(spawnCalls[0].child.stdin.writes, [
+ '{"mouseButtons":["MouseButton4"],"suppressGlobeAction":true}\n',
+ ]);
+
+ manager.stop();
+});
+
+test("an unchanged configuration writes nothing", () => {
+ const { GlobeKeyManager, spawnCalls } = loadManager();
+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });
+
+ manager.setConfiguration({ mouseButtons: ["MouseButton4"], suppressGlobeAction: true });
+ manager.start();
+ // Same values, different order — must not look like a change.
+ manager.setConfiguration({ mouseButtons: ["MouseButton4"], suppressGlobeAction: true });
+
+ assert.deepEqual(spawnCalls[0].child.stdin.writes, []);
+
+ manager.stop();
+});
+
+test("successive changes each reach the listener as one full-state line", () => {
+ const { GlobeKeyManager, spawnCalls } = loadManager();
+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });
+
+ manager.start();
+ manager.setConfiguration({ suppressGlobeAction: true });
+ manager.setConfiguration({ mouseButtons: ["MouseButton5"], suppressGlobeAction: true });
+ manager.setConfiguration({});
+
+ assert.equal(spawnCalls.length, 1);
+ assert.deepEqual(spawnCalls[0].child.stdin.writes, [
+ '{"mouseButtons":[],"suppressGlobeAction":true}\n',
+ '{"mouseButtons":["MouseButton5"],"suppressGlobeAction":true}\n',
+ '{"mouseButtons":[],"suppressGlobeAction":false}\n',
+ ]);
+
+ manager.stop();
+});
+
+test("a dead stdin falls back to respawning with the new configuration", () => {
+ const { GlobeKeyManager, spawnCalls } = loadManager();
+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });
+
+ manager.start();
+ spawnCalls[0].child.stdin.writable = false;
+ manager.setConfiguration({ suppressGlobeAction: true });
+
+ assert.equal(spawnCalls.length, 2);
+ // The old listener has to be terminated so it restores the system preference.
+ assert.equal(spawnCalls[0].child.killed, true);
+ assert.deepEqual(spawnCalls[1].args, [
+ "--globe-preference-state",
+ "/tmp/state.json",
+ "--suppress-system-globe-action",
+ ]);
+
+ manager.stop();
+});
+
+test("a restart picks up the latest configuration", () => {
+ const { GlobeKeyManager, spawnCalls } = loadManager();
+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });
+
+ manager.start();
+ manager.stop();
+ manager.setConfiguration({ mouseButtons: ["MouseButton4"], suppressGlobeAction: true });
+ manager.start();
+ manager.stop();
+
+ assert.deepEqual(spawnCalls[1].args, [
+ "MouseButton4",
+ "--globe-preference-state",
+ "/tmp/state.json",
+ "--suppress-system-globe-action",
+ ]);
+});
+
+test("no state path means no state argument", () => {
+ const { GlobeKeyManager, spawnCalls } = loadManager();
+ const manager = new GlobeKeyManager();
+
+ manager.setConfiguration({ suppressGlobeAction: true });
+ manager.start();
+ manager.stop();
+
+ assert.deepEqual(spawnCalls[0].args, ["--suppress-system-globe-action"]);
+});
+
+test("the listener is not started off macOS", () => {
+ const { GlobeKeyManager, spawnCalls } = loadManager();
+ setPlatform("win32");
+ const manager = new GlobeKeyManager({ preferenceStatePath: "/tmp/state.json" });
+
+ manager.start();
+
+ assert.equal(spawnCalls.length, 0);
+});
diff --git a/test/helpers/nativeListenerKeys.test.js b/test/helpers/nativeListenerKeys.test.js
index 80dd26122..d3e2b843e 100644
--- a/test/helpers/nativeListenerKeys.test.js
+++ b/test/helpers/nativeListenerKeys.test.js
@@ -78,6 +78,57 @@ test("membership and lookup helpers work across multi-hotkey slots", () => {
assert.equal(mgr.getSlotHotkey("dictation"), "GLOBE");
});
+// The macOS Globe listener config drives both mouse-button suppression and
+// whether macOS's own standalone Globe action has to stand down.
+const MAC_SLOTS = ["dictation", "agent", "voiceAgent", "translation"];
+
+test("Globe in any supported slot asks for system Globe suppression", () => {
+ for (const slot of MAC_SLOTS) {
+ const mgr = makeManager({ [slot]: "GLOBE" });
+ assert.equal(
+ mgr.getMacNativeListenerConfig(MAC_SLOTS).suppressGlobeAction,
+ true,
+ `slot "${slot}" should request suppression`
+ );
+ }
+});
+
+test("Fn is treated as Globe, including as a secondary hotkey", () => {
+ const mgr = makeManager({ voiceAgent: ["Control+Shift+R", "Fn"] });
+ assert.deepEqual(mgr.getMacNativeListenerConfig(MAC_SLOTS), {
+ mouseButtons: [],
+ suppressGlobeAction: true,
+ });
+});
+
+test("mouse buttons are collected across slots and de-duplicated", () => {
+ const mgr = makeManager({
+ dictation: ["MouseButton4", "F8"],
+ agent: "MouseButton5",
+ voiceAgent: "MouseButton4",
+ });
+ const config = mgr.getMacNativeListenerConfig(MAC_SLOTS);
+ assert.deepEqual(config.mouseButtons.sort(), ["MouseButton4", "MouseButton5"]);
+ assert.equal(config.suppressGlobeAction, false);
+});
+
+test("slots outside the requested list are ignored", () => {
+ // meeting is not wired to the macOS native listener.
+ const mgr = makeManager({ dictation: "F8", meeting: "GLOBE" });
+ assert.deepEqual(mgr.getMacNativeListenerConfig(MAC_SLOTS), {
+ mouseButtons: [],
+ suppressGlobeAction: false,
+ });
+});
+
+test("no native macOS hotkeys means nothing to configure", () => {
+ const mgr = makeManager({ dictation: "F8", agent: "Control+Shift+A", voiceAgent: "" });
+ assert.deepEqual(mgr.getMacNativeListenerConfig(MAC_SLOTS), {
+ mouseButtons: [],
+ suppressGlobeAction: false,
+ });
+});
+
test("_findSlotConflict detects a hotkey already bound to another slot's list", () => {
const mgr = makeManager({
dictation: ["GLOBE", "Control+Shift+R"],