-
-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathmain.js
More file actions
1149 lines (1001 loc) · 38.3 KB
/
main.js
File metadata and controls
1149 lines (1001 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const {
app,
globalShortcut,
BrowserWindow,
dialog,
ipcMain,
session,
systemPreferences,
} = require("electron");
const path = require("path");
const http = require("http");
require("dotenv").config({ path: path.join(__dirname, ".env") });
const VALID_CHANNELS = new Set(["development", "staging", "production"]);
const DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL = {
development: "openwhispr-dev",
staging: "openwhispr-staging",
production: "openwhispr",
};
const BASE_WINDOWS_APP_ID = "com.herotools.openwispr";
const DEFAULT_AUTH_BRIDGE_PORT = 5199;
function isElectronBinaryExec() {
const execPath = (process.execPath || "").toLowerCase();
return (
execPath.includes("/electron.app/contents/macos/electron") ||
execPath.endsWith("/electron") ||
execPath.endsWith("\\electron.exe")
);
}
function inferDefaultChannel() {
if (process.env.NODE_ENV === "development" || process.defaultApp || isElectronBinaryExec()) {
return "development";
}
return "production";
}
function resolveAppChannel() {
const rawChannel = (process.env.OPENWHISPR_CHANNEL || process.env.VITE_OPENWHISPR_CHANNEL || "")
.trim()
.toLowerCase();
if (VALID_CHANNELS.has(rawChannel)) {
return rawChannel;
}
return inferDefaultChannel();
}
const APP_CHANNEL = resolveAppChannel();
process.env.OPENWHISPR_CHANNEL = APP_CHANNEL;
function configureChannelUserDataPath() {
if (APP_CHANNEL === "production") {
return;
}
const isolatedPath = path.join(app.getPath("appData"), `OpenWhispr-${APP_CHANNEL}`);
app.setPath("userData", isolatedPath);
}
configureChannelUserDataPath();
// Fix transparent window flickering on Linux: --enable-transparent-visuals requires
// the compositor to set up an ARGB visual before any windows are created.
// --disable-gpu-compositing prevents GPU compositing conflicts with the compositor.
if (process.platform === "linux") {
app.commandLine.appendSwitch("gtk-version", "3");
app.commandLine.appendSwitch("enable-transparent-visuals");
app.commandLine.appendSwitch("disable-gpu-compositing");
}
if (process.platform === "win32") {
app.commandLine.appendSwitch("disable-gpu-compositing");
}
// Enable native Wayland support: Ozone platform for native rendering.
// KDE uses XWayland for reliable clipboard access, with KGlobalAccel D-Bus
// for global shortcuts. GNOME and Hyprland run native Wayland with their
// own D-Bus shortcut managers.
if (process.platform === "linux" && process.env.XDG_SESSION_TYPE === "wayland") {
const desktop = (process.env.XDG_CURRENT_DESKTOP || "").toLowerCase();
if (desktop.includes("kde")) {
app.commandLine.appendSwitch("ozone-platform-hint", "x11");
} else {
app.commandLine.appendSwitch("ozone-platform-hint", "auto");
}
app.commandLine.appendSwitch("enable-features", "UseOzonePlatform,WaylandWindowDecorations");
}
// Set desktop filename so Wayland compositors can match windows to the .desktop entry.
// This allows XDG portals (e.g. PipeWire) to persist permissions across sessions.
if (process.platform === "linux") {
app.setDesktopName("open-whispr.desktop");
}
// Group all windows under single taskbar entry on Windows
if (process.platform === "win32") {
const windowsAppId =
APP_CHANNEL === "production" ? BASE_WINDOWS_APP_ID : `${BASE_WINDOWS_APP_ID}.${APP_CHANNEL}`;
app.setAppUserModelId(windowsAppId);
}
function getOAuthProtocol() {
const fromEnv = (process.env.VITE_OPENWHISPR_PROTOCOL || process.env.OPENWHISPR_PROTOCOL || "")
.trim()
.toLowerCase();
if (/^[a-z][a-z0-9+.-]*$/.test(fromEnv)) {
return fromEnv;
}
return (
DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL[APP_CHANNEL] || DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL.production
);
}
const OAUTH_PROTOCOL = getOAuthProtocol();
function shouldRegisterProtocolWithAppArg() {
return Boolean(process.defaultApp) || isElectronBinaryExec();
}
// Register custom protocol for OAuth callbacks.
// In development, always include the app path argument so macOS/Windows/Linux
// can launch the project app instead of opening bare Electron.
function registerOpenWhisprProtocol() {
const protocol = OAUTH_PROTOCOL;
if (shouldRegisterProtocolWithAppArg()) {
const appArg = process.argv[1] ? path.resolve(process.argv[1]) : path.resolve(".");
return app.setAsDefaultProtocolClient(protocol, process.execPath, [appArg]);
}
return app.setAsDefaultProtocolClient(protocol);
}
const protocolRegistered = registerOpenWhisprProtocol();
if (!protocolRegistered) {
console.warn(`[Auth] Failed to register ${OAUTH_PROTOCOL}:// protocol handler`);
}
const gotSingleInstanceLock = app.requestSingleInstanceLock();
if (!gotSingleInstanceLock) {
app.exit(0);
}
const isLiveWindow = (window) => window && !window.isDestroyed();
// Ensure macOS menus use the proper casing for the app name
if (process.platform === "darwin" && app.getName() !== "OpenWhispr") {
app.setName("OpenWhispr");
}
// Add global error handling for uncaught exceptions
process.on("uncaughtException", (error) => {
console.error("Uncaught Exception:", error);
// Don't exit the process for EPIPE errors as they're harmless
if (error.code === "EPIPE") {
return;
}
// For other errors, log and continue
console.error("Error stack:", error.stack);
});
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled Rejection at:", promise, "reason:", reason);
});
// Import helper module classes (but don't instantiate yet - wait for app.whenReady())
const EnvironmentManager = require("./src/helpers/environment");
const WindowManager = require("./src/helpers/windowManager");
const DatabaseManager = require("./src/helpers/database");
const ClipboardManager = require("./src/helpers/clipboard");
const WhisperManager = require("./src/helpers/whisper");
const ParakeetManager = require("./src/helpers/parakeet");
const TrayManager = require("./src/helpers/tray");
const IPCHandlers = require("./src/helpers/ipcHandlers");
const UpdateManager = require("./src/updater");
const GlobeKeyManager = require("./src/helpers/globeKeyManager");
const DevServerManager = require("./src/helpers/devServerManager");
const WindowsKeyManager = require("./src/helpers/windowsKeyManager");
const TextEditMonitor = require("./src/helpers/textEditMonitor");
const WhisperCudaManager = require("./src/helpers/whisperCudaManager");
const GoogleCalendarManager = require("./src/helpers/googleCalendarManager");
const MeetingProcessDetector = require("./src/helpers/meetingProcessDetector");
const AudioActivityDetector = require("./src/helpers/audioActivityDetector");
const AudioTapManager = require("./src/helpers/audioTapManager");
const MeetingDetectionEngine = require("./src/helpers/meetingDetectionEngine");
const { i18nMain, changeLanguage } = require("./src/helpers/i18nMain");
const { ensureYdotool } = require("./src/helpers/ensureYdotool");
// Manager instances - initialized after app.whenReady()
let debugLogger = null;
let environmentManager = null;
let windowManager = null;
let hotkeyManager = null;
let databaseManager = null;
let clipboardManager = null;
let whisperManager = null;
let parakeetManager = null;
let trayManager = null;
let updateManager = null;
let globeKeyManager = null;
let windowsKeyManager = null;
let textEditMonitor = null;
let whisperCudaManager = null;
let googleCalendarManager = null;
let meetingDetectionEngine = null;
let audioTapManager = null;
let ipcHandlers = null;
let globeKeyAlertShown = false;
let authBridgeServer = null;
function parseAuthBridgePort() {
const raw = (process.env.OPENWHISPR_AUTH_BRIDGE_PORT || "").trim();
if (!raw) return DEFAULT_AUTH_BRIDGE_PORT;
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
return DEFAULT_AUTH_BRIDGE_PORT;
}
return parsed;
}
const AUTH_BRIDGE_HOST = "127.0.0.1";
const AUTH_BRIDGE_PORT = parseAuthBridgePort();
const AUTH_BRIDGE_PATH = "/oauth/callback";
// Set up PATH for production builds to find system tools (whisper.cpp, ffmpeg)
function setupProductionPath() {
if (process.platform === "darwin" && process.env.NODE_ENV !== "development") {
const commonPaths = [
"/usr/local/bin",
"/opt/homebrew/bin",
"/usr/bin",
"/bin",
"/usr/sbin",
"/sbin",
];
const currentPath = process.env.PATH || "";
const pathsToAdd = commonPaths.filter((p) => !currentPath.includes(p));
if (pathsToAdd.length > 0) {
process.env.PATH = `${currentPath}:${pathsToAdd.join(":")}`;
}
}
}
// Phase 1: Initialize managers + IPC handlers before window content loads
function initializeCoreManagers() {
setupProductionPath();
debugLogger = require("./src/helpers/debugLogger");
debugLogger.ensureFileLogging();
environmentManager = new EnvironmentManager();
const uiLanguage = environmentManager.getUiLanguage();
process.env.UI_LANGUAGE = uiLanguage;
changeLanguage(uiLanguage);
debugLogger.refreshLogLevel();
windowManager = new WindowManager();
hotkeyManager = windowManager.hotkeyManager;
databaseManager = new DatabaseManager();
clipboardManager = new ClipboardManager();
whisperManager = new WhisperManager();
if (process.platform !== "darwin") {
whisperCudaManager = new WhisperCudaManager();
}
parakeetManager = new ParakeetManager();
googleCalendarManager = new GoogleCalendarManager(databaseManager, windowManager);
meetingDetectionEngine = new MeetingDetectionEngine(
googleCalendarManager,
new MeetingProcessDetector(),
new AudioActivityDetector(),
windowManager,
databaseManager
);
windowManager.meetingDetectionEngine = meetingDetectionEngine;
updateManager = new UpdateManager();
updateManager.setWindowManager(windowManager);
windowsKeyManager = new WindowsKeyManager();
textEditMonitor = new TextEditMonitor();
audioTapManager = new AudioTapManager();
windowManager.textEditMonitor = textEditMonitor;
// IPC handlers must be registered before window content loads
ipcHandlers = new IPCHandlers({
environmentManager,
databaseManager,
clipboardManager,
whisperManager,
parakeetManager,
windowManager,
updateManager,
windowsKeyManager,
textEditMonitor,
whisperCudaManager,
googleCalendarManager,
meetingDetectionEngine,
audioTapManager,
getTrayManager: () => trayManager,
});
}
// Phase 2: Non-critical setup after windows are visible
function initializeDeferredManagers() {
ensureYdotool().catch((err) => {
require("./src/helpers/debugLogger").warn(
"ydotool setup error",
{ error: err?.message },
"clipboard"
);
});
clipboardManager.preWarmAccessibility();
trayManager = new TrayManager();
globeKeyManager = new GlobeKeyManager();
if (process.platform === "darwin") {
globeKeyManager.on("error", (error) => {
if (globeKeyAlertShown) {
return;
}
globeKeyAlertShown = true;
const detailLines = [
error?.message || i18nMain.t("startup.globeHotkey.details.unknown"),
i18nMain.t("startup.globeHotkey.details.fallback"),
];
if (process.env.NODE_ENV === "development") {
detailLines.push(i18nMain.t("startup.globeHotkey.details.devHint"));
} else {
detailLines.push(i18nMain.t("startup.globeHotkey.details.reinstallHint"));
}
dialog.showMessageBox({
type: "warning",
title: i18nMain.t("startup.globeHotkey.title"),
message: i18nMain.t("startup.globeHotkey.message"),
detail: detailLines.join("\n\n"),
});
});
}
googleCalendarManager.start();
meetingDetectionEngine.start();
}
app.on("open-url", (event, url) => {
event.preventDefault();
if (!url.startsWith(`${OAUTH_PROTOCOL}://`)) return;
if (url.includes("upgrade-success")) {
handleUpgradeDeepLink();
return;
}
handleOAuthDeepLink(url);
if (windowManager && isLiveWindow(windowManager.controlPanelWindow)) {
windowManager.controlPanelWindow.show();
windowManager.controlPanelWindow.focus();
}
});
// Extract the session verifier from the deep link and navigate the control
// panel to its app URL with the verifier param so the Neon Auth SDK can
// read it from window.location.search and complete authentication.
function navigateControlPanelWithVerifier(verifier) {
if (!verifier) return;
if (!isLiveWindow(windowManager?.controlPanelWindow)) return;
const appUrl = DevServerManager.getAppUrl(true);
if (appUrl) {
const separator = appUrl.includes("?") ? "&" : "?";
const urlWithVerifier = `${appUrl}${separator}neon_auth_session_verifier=${encodeURIComponent(verifier)}`;
windowManager.controlPanelWindow.loadURL(urlWithVerifier);
} else {
const fileInfo = DevServerManager.getAppFilePath(true);
if (!fileInfo) return;
fileInfo.query.neon_auth_session_verifier = verifier;
windowManager.controlPanelWindow.loadFile(fileInfo.path, { query: fileInfo.query });
}
if (debugLogger) {
debugLogger.debug("Navigating control panel with OAuth verifier", {
appChannel: APP_CHANNEL,
oauthProtocol: OAUTH_PROTOCOL,
});
}
windowManager.controlPanelWindow.show();
windowManager.controlPanelWindow.focus();
}
function handleOAuthDeepLink(deepLinkUrl) {
try {
const parsed = new URL(deepLinkUrl);
const verifier = parsed.searchParams.get("neon_auth_session_verifier");
if (!verifier) return;
navigateControlPanelWithVerifier(verifier);
} catch (err) {
if (debugLogger) debugLogger.error("Failed to handle OAuth deep link:", err);
}
}
function handleUpgradeDeepLink() {
if (isLiveWindow(windowManager?.controlPanelWindow)) {
windowManager.controlPanelWindow.webContents.executeJavaScript(
'window.dispatchEvent(new Event("upgrade-success"))'
);
windowManager.controlPanelWindow.show();
windowManager.controlPanelWindow.focus();
}
}
function parseJsonBody(req) {
return new Promise((resolve, reject) => {
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
if (raw.length > 32 * 1024) {
reject(new Error("Request body too large"));
req.destroy();
}
});
req.on("end", () => {
if (!raw) return resolve({});
try {
resolve(JSON.parse(raw));
} catch {
reject(new Error("Invalid JSON payload"));
}
});
req.on("error", reject);
});
}
function writeCorsHeaders(res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
}
function startAuthBridgeServer() {
if (APP_CHANNEL !== "development" || authBridgeServer) {
return;
}
authBridgeServer = http.createServer(async (req, res) => {
writeCorsHeaders(res);
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
const requestUrl = new URL(req.url || "/", `http://${AUTH_BRIDGE_HOST}:${AUTH_BRIDGE_PORT}`);
if (requestUrl.pathname !== AUTH_BRIDGE_PATH) {
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not found");
return;
}
let verifier = requestUrl.searchParams.get("neon_auth_session_verifier");
if (!verifier && req.method === "POST") {
try {
const body = await parseJsonBody(req);
verifier = body?.neon_auth_session_verifier || body?.verifier || null;
} catch (error) {
res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
res.end(error.message || "Invalid request");
return;
}
}
if (!verifier) {
res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Missing neon_auth_session_verifier");
return;
}
navigateControlPanelWithVerifier(verifier);
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(
"<html><body><h3>OpenWhispr sign-in complete.</h3><p>You can close this tab.</p></body></html>"
);
});
authBridgeServer.on("error", (error) => {
if (debugLogger) {
debugLogger.error("OAuth auth bridge server failed:", error);
}
});
authBridgeServer.listen(AUTH_BRIDGE_PORT, AUTH_BRIDGE_HOST, () => {
if (debugLogger) {
debugLogger.debug("OAuth auth bridge server started", {
url: `http://${AUTH_BRIDGE_HOST}:${AUTH_BRIDGE_PORT}${AUTH_BRIDGE_PATH}`,
});
}
});
}
// Main application startup
async function startApp() {
// Phase 1: Core managers + IPC handlers before windows
initializeCoreManagers();
startAuthBridgeServer();
// Electron's file:// sends no Origin header, which Neon Auth rejects.
session.defaultSession.webRequest.onBeforeSendHeaders(
{ urls: ["https://*.neon.tech/*"] },
(details, callback) => {
try {
details.requestHeaders["Origin"] = new URL(details.url).origin;
} catch {
/* malformed URL — leave Origin as-is */
}
callback({ requestHeaders: details.requestHeaders });
}
);
windowManager.setActivationModeCache(environmentManager.getActivationMode());
windowManager.setFloatingIconAutoHide(environmentManager.getFloatingIconAutoHide());
windowManager.setPanelStartPosition(environmentManager.getPanelStartPosition());
ipcMain.on("activation-mode-changed", (_event, mode) => {
windowManager.setActivationModeCache(mode);
environmentManager.saveActivationMode(mode);
});
ipcMain.on("floating-icon-auto-hide-changed", (_event, enabled) => {
windowManager.setFloatingIconAutoHide(enabled);
environmentManager.saveFloatingIconAutoHide(enabled);
// Relay to the floating icon window so it can react immediately
if (windowManager.mainWindow && !windowManager.mainWindow.isDestroyed()) {
windowManager.mainWindow.webContents.send("floating-icon-auto-hide-changed", enabled);
}
});
ipcMain.on("start-minimized-changed", (_event, enabled) => {
if (debugLogger) debugLogger.info("Start minimized changed", { enabled });
environmentManager.saveStartMinimized(enabled);
});
ipcMain.on("panel-start-position-changed", (_event, position) => {
windowManager.setPanelStartPosition(position);
environmentManager.savePanelStartPosition(position);
});
if (process.platform === "darwin") {
app.setActivationPolicy("regular");
}
// In development, wait for Vite dev server to be ready
if (process.env.NODE_ENV === "development") {
await new Promise((resolve) => setTimeout(resolve, 500));
}
// Create windows FIRST so the user sees UI as soon as possible
const startMinimized = environmentManager.getStartMinimized();
if (debugLogger) debugLogger.info("Start minimized", { enabled: startMinimized });
await windowManager.createMainWindow();
if (!startMinimized) {
await windowManager.createControlPanelWindow();
}
// Create agent window (hidden) and set up agent hotkey
await windowManager.createAgentWindow();
const agentHotkeyCallback = () => {
if (hotkeyManager.isInListeningMode()) return;
windowManager.toggleAgentOverlay();
};
windowManager._agentHotkeyCallback = agentHotkeyCallback;
const savedAgentKey = environmentManager.getAgentKey?.() || "";
if (savedAgentKey) {
const result = await hotkeyManager.registerSlot("agent", savedAgentKey, agentHotkeyCallback);
if (!result.success) {
debugLogger.warn("Failed to restore agent hotkey", { hotkey: savedAgentKey }, "hotkey");
}
}
// Set up meeting mode hotkey
const meetingHotkeyCallback = () => {
if (hotkeyManager.isInListeningMode()) return;
debugLogger.info("Meeting hotkey triggered", {}, "meeting");
meetingDetectionEngine?.startManualMeeting();
};
const savedMeetingKey = environmentManager.getMeetingKey?.() || "";
if (savedMeetingKey) {
const result = await hotkeyManager.registerSlot(
"meeting",
savedMeetingKey,
meetingHotkeyCallback
);
debugLogger.info(
"Meeting hotkey startup registration",
{ savedMeetingKey, ...result },
"meeting"
);
}
ipcMain.handle("register-meeting-hotkey", async (_event, hotkey) => {
if (hotkey) {
const result = await hotkeyManager.registerSlot("meeting", hotkey, meetingHotkeyCallback);
if (result.success) {
environmentManager.saveMeetingKey(hotkey);
return { success: true };
}
return { success: false, message: result.error };
} else {
hotkeyManager.unregisterSlot("meeting");
environmentManager.saveMeetingKey("");
return { success: true };
}
});
// Phase 2: Initialize remaining managers after windows are visible
initializeDeferredManagers();
app.on("browser-window-focus", () => {
if (googleCalendarManager) googleCalendarManager.syncOnFocus();
});
const { powerMonitor } = require("electron");
powerMonitor.on("resume", () => {
if (googleCalendarManager) {
googleCalendarManager.onWakeFromSleep();
}
});
// Non-blocking server pre-warming
const whisperSettings = {
localTranscriptionProvider: process.env.LOCAL_TRANSCRIPTION_PROVIDER || "",
whisperModel: process.env.LOCAL_WHISPER_MODEL,
useCuda: process.env.WHISPER_CUDA_ENABLED === "true" && whisperCudaManager?.isDownloaded(),
};
whisperManager.initializeAtStartup(whisperSettings).catch((err) => {
debugLogger.debug("Whisper startup init error (non-fatal)", { error: err.message });
});
const parakeetSettings = {
localTranscriptionProvider: process.env.LOCAL_TRANSCRIPTION_PROVIDER || "",
parakeetModel: process.env.PARAKEET_MODEL,
};
parakeetManager.initializeAtStartup(parakeetSettings).catch((err) => {
debugLogger.debug("Parakeet startup init error (non-fatal)", { error: err.message });
});
if (process.env.REASONING_PROVIDER === "local" && process.env.LOCAL_REASONING_MODEL) {
const modelManager = require("./src/helpers/modelManagerBridge").default;
modelManager.prewarmServer(process.env.LOCAL_REASONING_MODEL).catch((err) => {
debugLogger.debug("llama-server pre-warm error (non-fatal)", { error: err.message });
});
}
if (process.platform === "win32") {
const nircmdStatus = clipboardManager.getNircmdStatus();
debugLogger.debug("Windows paste tool status", nircmdStatus);
}
trayManager.setWindows(windowManager.mainWindow, windowManager.controlPanelWindow);
trayManager.setWindowManager(windowManager);
trayManager.setCreateControlPanelCallback(() => windowManager.createControlPanelWindow());
await trayManager.createTray();
updateManager.setWindows(windowManager.mainWindow, windowManager.controlPanelWindow);
updateManager.checkForUpdatesOnStartup();
if (process.platform === "darwin") {
const { isGlobeLikeHotkey } = require("./src/helpers/hotkeyManager");
let globeKeyDownTime = 0;
let globeKeyIsRecording = false;
let globeLastStopTime = 0;
const MIN_HOLD_DURATION_MS = 150;
const POST_STOP_COOLDOWN_MS = 300;
globeKeyManager.on("globe-down", async () => {
const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();
const mainWindowLive = isLiveWindow(windowManager.mainWindow);
debugLogger?.debug("[Globe] globe-down received", {
currentHotkey,
mainWindowLive,
activationMode: mainWindowLive ? windowManager.getActivationMode() : "n/a",
});
// Forward to control panel for hotkey capture
if (isLiveWindow(windowManager.controlPanelWindow)) {
windowManager.controlPanelWindow.webContents.send("globe-key-pressed");
}
// Handle dictation if Globe/Fn is the current hotkey
if (isGlobeLikeHotkey(currentHotkey)) {
if (mainWindowLive) {
// Capture target app PID BEFORE showing the overlay
if (textEditMonitor) textEditMonitor.captureTargetPid();
const activationMode = windowManager.getActivationMode();
if (activationMode === "push") {
const now = Date.now();
if (now - globeLastStopTime < POST_STOP_COOLDOWN_MS) {
debugLogger?.debug("[Globe] Ignored — cooldown active");
return;
}
windowManager.showDictationPanel();
const pressTime = now;
globeKeyDownTime = pressTime;
globeKeyIsRecording = false;
setTimeout(async () => {
if (globeKeyDownTime === pressTime && !globeKeyIsRecording) {
globeKeyIsRecording = true;
debugLogger?.debug("[Globe] Starting dictation (push hold)");
windowManager.sendStartDictation();
}
}, MIN_HOLD_DURATION_MS);
} else {
windowManager.sendToggleDictation();
}
} else {
debugLogger?.debug("[Globe] Ignored — mainWindow not live");
}
}
// Check agent slot for Globe/Fn key
const agentHotkey = hotkeyManager.getSlotHotkey("agent");
if (agentHotkey && isGlobeLikeHotkey(agentHotkey)) {
windowManager.toggleAgentOverlay();
} else if (!isGlobeLikeHotkey(currentHotkey)) {
debugLogger?.debug("[Globe] Ignored — hotkey is not GLOBE", { currentHotkey });
}
});
globeKeyManager.on("globe-up", async () => {
debugLogger?.debug("[Globe] globe-up received", { wasRecording: globeKeyIsRecording });
// Forward to control panel for hotkey capture (Fn key released)
if (isLiveWindow(windowManager.controlPanelWindow)) {
windowManager.controlPanelWindow.webContents.send("globe-key-released");
}
if (hotkeyManager.getCurrentHotkey && isGlobeLikeHotkey(hotkeyManager.getCurrentHotkey())) {
const activationMode = windowManager.getActivationMode();
if (activationMode === "push") {
globeKeyDownTime = 0;
globeLastStopTime = Date.now();
if (globeKeyIsRecording) {
globeKeyIsRecording = false;
debugLogger?.debug("[Globe] Stopping dictation (push release)");
windowManager.sendStopDictation();
}
}
}
// Fn release also stops compound push-to-talk for Fn+F-key hotkeys
windowManager.handleMacPushModifierUp("fn");
});
globeKeyManager.on("modifier-up", (modifier) => {
if (windowManager?.handleMacPushModifierUp) {
windowManager.handleMacPushModifierUp(modifier);
}
});
// Right-side single modifier handling (e.g., RightOption as hotkey)
let rightModDownTime = 0;
let rightModIsRecording = false;
let rightModLastStopTime = 0;
globeKeyManager.on("right-modifier-down", async (modifier) => {
const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();
// Check agent slot for right-modifier
const agentHotkey = hotkeyManager.getSlotHotkey("agent");
if (agentHotkey === modifier) {
windowManager.toggleAgentOverlay();
}
if (currentHotkey !== modifier) return;
if (!isLiveWindow(windowManager.mainWindow)) return;
const activationMode = windowManager.getActivationMode();
if (textEditMonitor) textEditMonitor.captureTargetPid();
if (activationMode === "push") {
const now = Date.now();
if (now - rightModLastStopTime < POST_STOP_COOLDOWN_MS) return;
windowManager.showDictationPanel();
const pressTime = now;
rightModDownTime = pressTime;
rightModIsRecording = false;
setTimeout(() => {
if (rightModDownTime === pressTime && !rightModIsRecording) {
rightModIsRecording = true;
windowManager.sendStartDictation();
}
}, MIN_HOLD_DURATION_MS);
} else {
windowManager.sendToggleDictation();
}
});
globeKeyManager.on("right-modifier-up", async (modifier) => {
const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();
if (currentHotkey === modifier) {
if (!isLiveWindow(windowManager.mainWindow)) return;
const activationMode = windowManager.getActivationMode();
if (activationMode === "push") {
rightModDownTime = 0;
rightModLastStopTime = Date.now();
if (rightModIsRecording) {
rightModIsRecording = false;
windowManager.sendStopDictation();
} else {
windowManager.hideDictationPanel();
}
}
}
const rightModToBase = {
RightCommand: "command",
RightOption: "option",
RightControl: "control",
RightShift: "shift",
};
const baseMod = rightModToBase[modifier];
if (baseMod && windowManager?.handleMacPushModifierUp) {
windowManager.handleMacPushModifierUp(baseMod);
}
});
globeKeyManager.start();
// After starting globe-listener, check if accessibility is granted.
// If not, notify both windows so they 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");
}
if (isLiveWindow(windowManager.mainWindow)) {
windowManager.mainWindow.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", () => {
const trusted = systemPreferences.isTrustedAccessibilityClient(false);
if (!trusted) {
checkAndNotifyAccessibility();
}
return trusted;
});
// Reset native key state when hotkey changes
ipcMain.on("hotkey-changed", (_event, _newHotkey) => {
globeKeyDownTime = 0;
globeKeyIsRecording = false;
globeLastStopTime = 0;
rightModDownTime = 0;
rightModIsRecording = false;
rightModLastStopTime = 0;
});
}
// Set up Windows Push-to-Talk handling
if (process.platform === "win32") {
debugLogger.debug("[Push-to-Talk] Windows Push-to-Talk setup starting");
const {
isGlobeLikeHotkey: isGlobeLike,
isModifierOnlyHotkey,
} = require("./src/helpers/hotkeyManager");
const isValidHotkey = (hotkey) => hotkey && !isGlobeLike(hotkey);
const isRightSideMod = (hotkey) =>
/^Right(Control|Ctrl|Alt|Option|Shift|Super|Win|Meta|Command|Cmd)$/i.test(hotkey);
const needsNativeListener = (hotkey, mode) => {
if (!isValidHotkey(hotkey)) return false;
if (mode === "push") return true;
return isRightSideMod(hotkey) || isModifierOnlyHotkey(hotkey);
};
windowsKeyManager.on("key-down", (_key) => {
if (!isLiveWindow(windowManager.mainWindow)) return;
const activationMode = windowManager.getActivationMode();
if (activationMode === "push") {
windowManager.startWindowsPushToTalk();
} else if (activationMode === "tap") {
windowManager.sendToggleDictation();
}
});
windowsKeyManager.on("key-up", () => {
if (!isLiveWindow(windowManager.mainWindow)) return;
const activationMode = windowManager.getActivationMode();
if (activationMode === "push") {
windowManager.handleWindowsPushKeyUp();
}
});
windowsKeyManager.on("error", (error) => {
debugLogger.warn("[Push-to-Talk] Windows key listener error", { error: error.message });
if (isLiveWindow(windowManager.mainWindow)) {
windowManager.mainWindow.webContents.send("windows-ptt-unavailable", {
reason: "error",
message: error.message,
});
}
});
windowsKeyManager.on("unavailable", () => {
debugLogger.debug(
"[Push-to-Talk] Windows key listener not available - falling back to toggle mode"
);
if (isLiveWindow(windowManager.mainWindow)) {
windowManager.mainWindow.webContents.send("windows-ptt-unavailable", {
reason: "binary_not_found",
message: i18nMain.t("windows.pttUnavailable"),
});
}
});
windowsKeyManager.on("ready", () => {
debugLogger.debug("[Push-to-Talk] WindowsKeyManager is ready and listening");
});
const startWindowsKeyListener = () => {
if (!isLiveWindow(windowManager.mainWindow)) return;
const activationMode = windowManager.getActivationMode();
const currentHotkey = hotkeyManager.getCurrentHotkey();
if (needsNativeListener(currentHotkey, activationMode)) {
windowsKeyManager.start(currentHotkey);
}
};
const STARTUP_DELAY_MS = 3000;
setTimeout(startWindowsKeyListener, STARTUP_DELAY_MS);
ipcMain.on("activation-mode-changed", (_event, mode) => {
windowManager.resetWindowsPushState();
const currentHotkey = hotkeyManager.getCurrentHotkey();
if (needsNativeListener(currentHotkey, mode)) {
windowsKeyManager.start(currentHotkey);
} else {
windowsKeyManager.stop();
}
});
ipcMain.on("hotkey-changed", (_event, hotkey) => {
if (!isLiveWindow(windowManager.mainWindow)) return;
windowManager.resetWindowsPushState();
const activationMode = windowManager.getActivationMode();
windowsKeyManager.stop();
if (needsNativeListener(hotkey, activationMode)) {
windowsKeyManager.start(hotkey);
}
});
}
}
// Listen for usage limit reached from dictation overlay, forward to control panel
ipcMain.on("limit-reached", (_event, data) => {
if (isLiveWindow(windowManager?.controlPanelWindow)) {
windowManager.controlPanelWindow.webContents.send("limit-reached", data);
}
});
// App event handlers
if (gotSingleInstanceLock) {
app.on("second-instance", async (_event, commandLine) => {
await app.whenReady();
if (!windowManager) {
return;
}
if (isLiveWindow(windowManager.controlPanelWindow)) {
if (windowManager.controlPanelWindow.isMinimized()) {
windowManager.controlPanelWindow.restore();
}