Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
2070 lines (1867 loc) · 75.9 KB
/
Copy pathmain.js
File metadata and controls
2070 lines (1867 loc) · 75.9 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
// Chromium picks the display backend before JS runs, so appendSwitch is too
// late — the flag has to come from a relaunch.
const { XWAYLAND_FLAG, shouldForceXWayland } = require("./src/helpers/xwayland");
const { createHotkeyRepeatGate } = require("./src/helpers/hotkeyRepeatGate");
if (shouldForceXWayland(process.argv)) {
const { spawn } = require("child_process");
spawn(process.execPath, [...process.argv.slice(1), XWAYLAND_FLAG], {
stdio: "inherit",
detached: true,
}).unref();
process.exit(0);
}
const {
app,
desktopCapturer,
globalShortcut,
BrowserWindow,
dialog,
ipcMain,
net,
session,
systemPreferences,
} = require("electron");
const path = require("path");
const http = require("http");
const tls = require("tls");
require("dotenv").config({ path: path.join(__dirname, ".env") });
// Extend Node's TLS trust with the OS store so ws and https.get see corporate
// CAs that Chromium already trusts.
try {
const currentCAs = tls.getCACertificates();
const systemCAs = tls.getCACertificates("system");
if (systemCAs?.length) {
tls.setDefaultCACertificates([...currentCAs, ...systemCAs]);
}
} catch (err) {
require("./src/helpers/debugLogger").warn("System CA merge failed; using existing CA list", {
error: err?.message,
});
}
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.gizmolabs.openwhispr";
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();
// Load userData .env (contains DICTATION_KEY, API keys, etc.) early — before
// hotkey registration, which needs DICTATION_KEY before the renderer loads.
require("dotenv").config({
path: path.join(app.getPath("userData"), ".env"),
override: false,
});
// Chromium's Windows-only occlusion tracker misclassifies the always-on-top
// transparent pill as occluded, throttling its renderer and jittering animations.
if (process.platform === "win32") {
app.commandLine.appendSwitch("disable-features", "CalculateNativeWinOcclusion");
}
// 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");
}
// Wayland: packaged builds use the wrapper script (scripts/afterPack.js) to
// force --ozone-platform=x11 before Electron starts. appendSwitch below is a
// best-effort fallback for unpackaged dev mode (may not take effect on E39+).
if (process.platform === "linux" && process.env.XDG_SESSION_TYPE === "wayland") {
app.commandLine.appendSwitch("enable-features", "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();
const { registerLinuxUrlSchemeHandler } = require("./src/helpers/linuxUrlSchemeHandler");
function shouldRegisterProtocolWithAppArg() {
return Boolean(process.defaultApp) || isElectronBinaryExec();
}
function getDefaultHtmlHandler() {
try {
const { execFileSync } = require("child_process");
return (
execFileSync("xdg-mime", ["query", "default", "text/html"], {
encoding: "utf8",
timeout: 3000,
}).trim() || null
);
} catch {
return null;
}
}
function restoreHtmlHandlerIfChanged(original) {
try {
const { execFileSync } = require("child_process");
const current = execFileSync("xdg-mime", ["query", "default", "text/html"], {
encoding: "utf8",
timeout: 3000,
}).trim();
if (current && current !== original) {
execFileSync("xdg-mime", ["default", original, "text/html"], { timeout: 3000 });
}
} catch {
// xdg-mime unavailable or failed
}
}
// True source of truth for whether openwhispr:// resolves on Linux — the same
// MIME database xdg-open consults. Returns true for deb/rpm/flatpak/AUR installs
// (scheme registered via the packaged .desktop MimeType; registerLinuxUrlSchemeHandler
// first takes it back from an AppImage/tar.gz entry) and false for AppImage/tar.gz
// runs whose own registration failed, so we never enable a dead-end OAuth flow.
// Used to recover from setAsDefaultProtocolClient's KDE false negative.
function isOAuthSchemeRegistered() {
if (process.platform !== "linux") return false;
try {
const { execFileSync } = require("child_process");
const handler = execFileSync(
"xdg-mime",
["query", "default", `x-scheme-handler/${OAUTH_PROTOCOL}`],
{ encoding: "utf8", timeout: 3000 }
).trim();
return handler.length > 0;
} catch {
return false;
}
}
// In development, always include the app path argument so macOS/Windows/Linux
// can launch the project app instead of opening bare Electron.
function getProtocolAppArgs() {
if (!shouldRegisterProtocolWithAppArg()) return [];
return [process.argv[1] ? path.resolve(process.argv[1]) : path.resolve(".")];
}
// Register custom protocol for OAuth callbacks.
function registerOpenWhisprProtocol() {
const protocol = OAUTH_PROTOCOL;
const htmlHandler = process.platform === "linux" ? getDefaultHtmlHandler() : null;
const appArgs = getProtocolAppArgs();
let result;
if (appArgs.length > 0) {
result = app.setAsDefaultProtocolClient(protocol, process.execPath, appArgs);
} else {
result = app.setAsDefaultProtocolClient(protocol);
}
if (htmlHandler) {
restoreHtmlHandlerIfChanged(htmlHandler);
}
return result;
}
// On Linux, setAsDefaultProtocolClient can only name open-whispr.desktop, which
// AppImage and tar.gz installs don't have, so those (and development) register
// their own handler entry first and skip it. Otherwise it runs as before, and
// since it returns a false negative on KDE/Wayland, fall back to probing the
// system MIME database for an actual handler. This keeps OAuth enabled where the
// callback can resolve and correctly gated where it can't.
const linuxSchemeHandler =
process.platform === "linux"
? registerLinuxUrlSchemeHandler(OAUTH_PROTOCOL, getProtocolAppArgs())
: null;
const protocolRegistered =
linuxSchemeHandler?.registered || registerOpenWhisprProtocol() || isOAuthSchemeRegistered();
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 DiarizationManager = require("./src/helpers/diarization");
const TrayManager = require("./src/helpers/tray");
const dockManager = require("./src/helpers/dockManager");
const autoStart = require("./src/helpers/autoStart");
const IPCHandlers = require("./src/helpers/ipcHandlers");
const CliBridge = require("./src/helpers/cliBridge");
const UpdateManager = require("./src/updater");
const GlobeKeyManager = require("./src/helpers/globeKeyManager");
const DevServerManager = require("./src/helpers/devServerManager");
const WindowsKeyManager = require("./src/helpers/windowsKeyManager");
const LinuxKeyManager = require("./src/helpers/linuxKeyManager");
const TextEditMonitor = require("./src/helpers/textEditMonitor");
const SelectionManager = require("./src/helpers/selectionManager");
const WhisperCudaManager = require("./src/helpers/whisperCudaManager");
const WhisperVulkanManager = require("./src/helpers/whisperVulkanManager");
const { migrateLegacyBinDir, detectOrphanedGpuPacks } = require("./src/helpers/gpuBinaryManager");
const { resetWhisperGpuFailureOnUpgrade } = require("./src/helpers/whisperGpuUpgradeReset");
const GoogleCalendarManager = require("./src/helpers/googleCalendarManager");
const MicrosoftCalendarManager = require("./src/helpers/microsoftCalendarManager");
const AppleCalendarManager = require("./src/helpers/appleCalendarManager");
const CalendarReminderScheduler = require("./src/helpers/calendarReminderScheduler");
const MeetingProcessDetector = require("./src/helpers/meetingProcessDetector");
const AudioActivityDetector = require("./src/helpers/audioActivityDetector");
const {
collectAudioCaptureHelperPids,
createExcludedProcessIdProvider,
} = require("./src/helpers/electronProcessIds");
const AudioTapManager = require("./src/helpers/audioTapManager");
const LinuxPortalAudioManager = require("./src/helpers/linuxPortalAudioManager");
const WindowsLoopbackAudioManager = require("./src/helpers/windowsLoopbackAudioManager");
const MeetingAecManager = require("./src/helpers/meetingAecManager");
const MeetingDetectionEngine = require("./src/helpers/meetingDetectionEngine");
const { applyOpenWhisprOriginHeader } = require("./src/helpers/sessionHeaders");
const { i18nMain, changeLanguage } = require("./src/helpers/i18nMain");
const { ensureYdotool } = require("./src/helpers/ensureYdotool");
const sidecarRegistry = require("./src/helpers/sidecarRegistry");
const { reapStaleSidecars } = require("./src/helpers/sidecarReaper");
// 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 connectorManager = null;
let whisperManager = null;
let parakeetManager = null;
let diarizationManager = null;
let trayManager = null;
let updateManager = null;
let globeKeyManager = null;
let windowsKeyManager = null;
let linuxKeyManager = null;
let textEditMonitor = null;
let selectionManager = null;
let whisperCudaManager = null;
let whisperVulkanManager = null;
let googleCalendarManager = null;
let microsoftCalendarManager = null;
let appleCalendarManager = null;
let calendarReminderScheduler = null;
let meetingDetectionEngine = null;
let audioTapManager = null;
let linuxPortalAudioManager = null;
let windowsLoopbackAudioManager = null;
let meetingAecManager = null;
let semanticSearch = 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;
let pendingNoteRetryCount = 0;
const WHISPER_WAKE_REWARM_DELAY_MS = 3000;
let wakeRewarmTimer = 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
// Best-effort cleanup of the orphaned portal restore-token file older builds wrote. See PR #904.
const LINUX_RESTORE_TOKEN_FILENAME = ".linux-system-audio-restore-token.json";
function cleanupOrphanedLinuxRestoreToken() {
if (process.platform !== "linux") return;
try {
const fs = require("fs");
fs.unlinkSync(path.join(app.getPath("userData"), LINUX_RESTORE_TOKEN_FILENAME));
} catch {}
}
function syncAutoStartEntry() {
try {
if (autoStart.syncAutoStartEntry()) {
debugLogger.info("Re-pointed the launch-at-login entry at the current executable");
}
} catch (error) {
debugLogger.warn("Failed to sync the launch-at-login entry", { error: error?.message });
}
}
// Reading the login item touches the OS, and failing to answer "did the session
// start us?" must not stop the app from starting at all. Falling back to false
// just shows the window, which is what every launch did before.
function wasLaunchedAtLoginHidden() {
try {
return autoStart.wasLaunchedAtLoginHidden();
} catch (error) {
if (debugLogger) debugLogger.warn("Failed to detect a login launch", { error: error?.message });
return false;
}
}
function initializeCoreManagers() {
setupProductionPath();
debugLogger = require("./src/helpers/debugLogger");
debugLogger.ensureFileLogging();
// Registration runs before app ready, when the logger cannot write its file yet.
if (linuxSchemeHandler?.reason) {
debugLogger.warn("Could not register the Linux URL scheme handler entry", {
protocol: OAUTH_PROTOCOL,
reason: linuxSchemeHandler.reason,
protocolRegistered,
});
}
environmentManager = new EnvironmentManager();
const uiLanguage = environmentManager.getUiLanguage(app.getLocale());
changeLanguage(uiLanguage);
debugLogger.refreshLogLevel();
windowManager = new WindowManager();
hotkeyManager = windowManager.hotkeyManager;
databaseManager = new DatabaseManager();
// Restore the last validated account scope before any window, IPC handler,
// or meeting flow can read or create notes. Offline launches keep the
// account's data visible; a stale or rotated credential fails the hash
// check and restores nothing.
const accountScopeBinding = require("./src/helpers/accountScopeBinding");
const bootAccountId = accountScopeBinding.resolveBootAccountScope({
token: require("./src/helpers/tokenStore").get(),
binding: accountScopeBinding.read(),
});
if (bootAccountId) databaseManager.setActiveAccountId(bootAccountId);
clipboardManager = new ClipboardManager();
const { createConnectorManager } = require("./src/helpers/connectors/connectorManager");
const { createPendingActions } = require("./src/helpers/connectors/pendingActions");
const { createActionLog } = require("./src/helpers/connectors/actionLog");
const { createCredentialStore } = require("./src/helpers/connectors/credentialStore");
const { createConnectorCredentials } = require("./src/helpers/connectors/connectorCredentials");
const { createConnectors } = require("./src/helpers/connectors/createConnectors");
const { runOAuthLoopbackFlow, OAuthFlowError } = require("./src/helpers/oauthLoopbackFlow");
const { broadcastToWindows } = require("./src/helpers/windowBroadcast");
const { connectorAccountIdFrom } = require("./src/helpers/connectors/connectorIpc");
// The same account receipts are filed under (ipcHandlers' getAccountScope):
// the one bound to the credential in use. databaseManager's scope doesn't
// move when one signed-in token replaces another.
const getConnectorAccountScope = () =>
accountScopeBinding.resolveActiveAccountScope({
...require("./src/helpers/tokenStore").getState(),
binding: accountScopeBinding.read(),
});
const getConnectorAccountId = connectorAccountIdFrom(getConnectorAccountScope);
const connectorCredentials = createConnectorCredentials({
store: createCredentialStore({
dir: path.join(app.getPath("userData"), "connectors"),
secretCrypto: require("./src/helpers/secretCrypto"),
logger: debugLogger,
}),
getAccountId: getConnectorAccountId,
});
connectorManager = createConnectorManager({
connectors: createConnectors({
fetch: (url, init) => net.fetch(url, { ...init, useSessionCookies: false }),
i18n: i18nMain,
runOAuthLoopbackFlow,
OAuthFlowError,
credentials: connectorCredentials,
logger: debugLogger,
env: process.env,
openExternal: (url) => require("./src/helpers/externalUrlOpener").openExternalUrl(url),
writeClipboard: (text, webContents) => clipboardManager.writeClipboard(text, webContents),
// Read only when revoking a Gmail login on the calendar's Google project;
// the calendar manager is created below.
getGoogleCalendarAccounts: () => googleCalendarManager?.getAccounts() ?? [],
broadcast: broadcastToWindows,
}),
pendingActions: createPendingActions(),
actionLog: createActionLog(databaseManager),
logger: debugLogger,
getAccountId: getConnectorAccountId,
credentials: connectorCredentials,
onStatusChanged: (statuses) => broadcastToWindows("connector-status-changed", statuses),
});
// Pending cards expire in main even when no renderer ever answers them.
setInterval(() => connectorManager.sweepExpired(), 60 * 1000).unref();
whisperManager = new WhisperManager();
if (process.platform !== "darwin") {
whisperCudaManager = new WhisperCudaManager();
whisperVulkanManager = new WhisperVulkanManager();
// Heal installs from before GPU packs got per-pack directories; must run
// before startup pre-warm resolves any GPU binary path.
const LlamaVulkanManager = require("./src/helpers/llamaVulkanManager");
const llamaVulkanManager = new LlamaVulkanManager();
const clearedPacks = migrateLegacyBinDir([
whisperCudaManager,
whisperVulkanManager,
llamaVulkanManager,
]);
if (clearedPacks.length > 0) {
// No window exists yet — persist the notice; a control panel window
// shows it as a toast and clears it. See #1606.
require("./src/helpers/gpuPackMigrationNotice").record(clearedPacks);
}
// The 1.8.3 migration deleted lib-carrying packs without recording that
// notice, leaving those users on a silent CPU fallback: an enabled flag
// with no pack on disk only happens via such data loss. recordOnce gates
// each pack to one notice so a dismissed toast doesn't return every launch.
const orphanedPacks = detectOrphanedGpuPacks([
{ manager: whisperCudaManager, enabledEnvVar: "WHISPER_CUDA_ENABLED" },
{ manager: whisperVulkanManager, enabledEnvVar: "WHISPER_VULKAN_ENABLED" },
{ manager: llamaVulkanManager, enabledEnvVar: "LLAMA_VULKAN_ENABLED" },
]);
if (orphanedPacks.length > 0) {
require("./src/helpers/gpuPackMigrationNotice").recordOnce(orphanedPacks);
}
// Lets every server start resolve its GPU backend from installed packs
whisperManager.setGpuBinaryManagers({ cuda: whisperCudaManager, vulkan: whisperVulkanManager });
}
parakeetManager = new ParakeetManager();
diarizationManager = new DiarizationManager();
calendarReminderScheduler = new CalendarReminderScheduler(databaseManager);
googleCalendarManager = new GoogleCalendarManager(
databaseManager,
windowManager,
calendarReminderScheduler
);
microsoftCalendarManager = new MicrosoftCalendarManager(
databaseManager,
calendarReminderScheduler
);
appleCalendarManager = new AppleCalendarManager(databaseManager, calendarReminderScheduler);
const meetingProcessDetector = new MeetingProcessDetector();
meetingDetectionEngine = new MeetingDetectionEngine(
calendarReminderScheduler,
meetingProcessDetector,
new AudioActivityDetector(
// The capture-helper managers are created a few lines below; the provider
// is only invoked on mic events, long after initialization completes.
createExcludedProcessIdProvider(() =>
collectAudioCaptureHelperPids([
audioTapManager,
linuxPortalAudioManager,
windowsLoopbackAudioManager,
])
),
() => meetingProcessDetector.getDetectedProcesses().length > 0
),
windowManager,
databaseManager
);
windowManager.meetingDetectionEngine = meetingDetectionEngine;
calendarReminderScheduler.meetingDetectionEngine = meetingDetectionEngine;
updateManager = new UpdateManager();
updateManager.setWindowManager(windowManager);
windowsKeyManager = new WindowsKeyManager();
linuxKeyManager = new LinuxKeyManager();
textEditMonitor = new TextEditMonitor();
selectionManager = new SelectionManager({ clipboardManager, textEditMonitor });
audioTapManager = new AudioTapManager();
linuxPortalAudioManager = new LinuxPortalAudioManager();
windowsLoopbackAudioManager = new WindowsLoopbackAudioManager();
// Warm the capability cache off the hot path so the first meeting start
// doesn't pay the probe spawn. No-ops on non-Windows.
windowsLoopbackAudioManager.getCapability().catch(() => {});
cleanupOrphanedLinuxRestoreToken();
syncAutoStartEntry();
meetingAecManager = new MeetingAecManager();
windowManager.textEditMonitor = textEditMonitor;
windowManager.selectionManager = selectionManager;
windowManager.windowsKeyManager = windowsKeyManager;
windowManager.linuxKeyManager = linuxKeyManager;
if (process.platform === "linux") {
windowManager.hotkeyManager.nativeListenerProbe = () => linuxKeyManager.checkAvailability();
}
// IPC handlers must be registered before window content loads
ipcHandlers = new IPCHandlers({
environmentManager,
databaseManager,
clipboardManager,
whisperManager,
parakeetManager,
diarizationManager,
windowManager,
updateManager,
windowsKeyManager,
linuxKeyManager,
textEditMonitor,
selectionManager,
whisperCudaManager,
whisperVulkanManager,
googleCalendarManager,
microsoftCalendarManager,
appleCalendarManager,
connectorManager,
meetingDetectionEngine,
audioTapManager,
linuxPortalAudioManager,
windowsLoopbackAudioManager,
meetingAecManager,
getSemanticSearch: () => semanticSearch,
getTrayManager: () => trayManager,
oauthProtocolRegistered: protocolRegistered,
oauthProtocol: OAUTH_PROTOCOL,
});
}
function registerSidecars() {
if (whisperManager) sidecarRegistry.register("whisper", () => whisperManager.stopServer());
if (parakeetManager) sidecarRegistry.register("parakeet", () => parakeetManager.stopServer());
if (diarizationManager) {
sidecarRegistry.register("diarization", () => diarizationManager.shutdown());
}
const modelManager = require("./src/helpers/modelManagerBridge").default;
sidecarRegistry.register("llama", () => modelManager.stopServer());
const onnxWorkerClient = require("./src/helpers/onnxWorkerClient");
sidecarRegistry.register("onnx", () => onnxWorkerClient.stop());
}
// 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"
);
});
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.
preferenceStatePath: path.join(app.getPath("userData"), "globe-preference-state.json"),
});
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();
microsoftCalendarManager.start();
appleCalendarManager.start();
meetingDetectionEngine.start();
}
app.on("open-url", (event, url) => {
event.preventDefault();
if (!url.startsWith(`${OAUTH_PROTOCOL}://`)) return;
if (url.includes("upgrade-success")) {
handleUpgradeDeepLink();
return;
}
if (isNoteDeepLink(url)) {
void handleNoteDeepLink(url);
return;
}
if (isInvitationDeepLink(url)) {
handleInvitationDeepLink(url);
return;
}
void handleOAuthDeepLink(url);
if (windowManager && isLiveWindow(windowManager.controlPanelWindow)) {
windowManager.controlPanelWindow.show();
windowManager.controlPanelWindow.focus();
dockManager.setControlPanelVisible(true);
}
});
function isInvitationDeepLink(url) {
return url.slice(`${OAUTH_PROTOCOL}://`.length).startsWith("invitations/");
}
// Deep links can arrive before windowManager exists (cold start) or before the
// renderer has mounted its listener. The token is stashed here and the renderer
// pulls it via `get-pending-invitation-token` on mount; the push below is a
// best-effort fast path for an already-running app.
let pendingInvitationDeepLinkToken = null;
ipcMain.handle("get-pending-invitation-token", () => {
const token = pendingInvitationDeepLinkToken;
pendingInvitationDeepLinkToken = null;
return token;
});
function isNoteDeepLink(url) {
return url.slice(`${OAUTH_PROTOCOL}://`.length).startsWith("notes/");
}
function parseNoteCloudId(deepLinkUrl) {
try {
const match = deepLinkUrl.match(/notes\/([^/?#]+)/);
const cloudId = match?.[1] ? decodeURIComponent(match[1]) : "";
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(cloudId)
? cloudId
: null;
} catch {
return null;
}
}
function clearPendingNoteDeepLink() {
clearTimeout(pendingNoteRetryTimer);
pendingNoteRetryTimer = null;
pendingNoteCloudId = null;
pendingNoteRetryCount = 0;
}
async function flushPendingNoteDeepLink() {
if (!pendingNoteCloudId || !windowManager || !databaseManager) return;
try {
// Surface the panel on the first attempt only; retries just poll the
// database so they can't repeatedly steal focus.
if (pendingNoteRetryCount === 0) {
await windowManager.createControlPanelWindow();
}
const note = databaseManager.getNoteByCloudId(pendingNoteCloudId);
if (!note) {
// Cloud sync may still be hydrating during a cold launch. Retry briefly so
// the handoff can resolve a note pulled after the protocol event arrived.
pendingNoteRetryCount += 1;
if (pendingNoteRetryCount <= 10) {
clearTimeout(pendingNoteRetryTimer);
pendingNoteRetryTimer = setTimeout(() => {
void flushPendingNoteDeepLink();
}, 1000);
} else {
console.warn("Note deep link could not resolve a local note", {
cloudId: pendingNoteCloudId,
});
clearPendingNoteDeepLink();
}
return;
}
const payload = { noteId: note.id, folderId: note.folder_id ?? null };
clearPendingNoteDeepLink();
await windowManager.queueNoteNavigation(payload);
} catch (error) {
console.error("Note deep link failed:", error);
clearPendingNoteDeepLink();
}
}
async function handleNoteDeepLink(deepLinkUrl) {
const cloudId = parseNoteCloudId(deepLinkUrl);
if (!cloudId) {
console.warn("Invalid note deep link");
return;
}
clearPendingNoteDeepLink();
pendingNoteCloudId = cloudId;
await flushPendingNoteDeepLink();
}
function handleInvitationDeepLink(deepLinkUrl) {
try {
const match = deepLinkUrl.match(/invitations\/([^/?#]+)/);
const token = match?.[1];
if (!token) return;
pendingInvitationDeepLinkToken = token;
if (!windowManager) return;
if (isLiveWindow(windowManager.controlPanelWindow)) {
windowManager.controlPanelWindow.show();
windowManager.controlPanelWindow.focus();
dockManager.setControlPanelVisible(true);
// Best-effort fast path — the get-pending-invitation-token pull is the reliable path.
windowManager.controlPanelWindow.webContents.send("workspace-invitation-token", token);
} else {
windowManager.createControlPanelWindow();
}
} catch (error) {
console.error("Invitation deep link parse failed:", error);
}
}
function resolveAuthUrl() {
const fs = require("fs");
const envPath = path.join(__dirname, "src", "dist", "runtime-env.json");
let runtimeEnv = {};
try {
if (fs.existsSync(envPath)) runtimeEnv = JSON.parse(fs.readFileSync(envPath, "utf8"));
} catch {}
return (
process.env.AUTH_URL ||
process.env.VITE_AUTH_URL ||
runtimeEnv.VITE_AUTH_URL ||
"https://auth.openwhispr.com"
);
}
function getOauthCookieName() {
return process.env.NODE_ENV === "production"
? "__Secure-openwhispr.session_token"
: "openwhispr.session_token";
}
// Older website builds send the signed cookie value as `?token=`; trade it
// for the raw session.token the bearer plugin expects.
async function exchangeSignedTokenForRawBearer(signedToken) {
try {
const res = await net.fetch(`${resolveAuthUrl()}/api/auth/get-session`, {
headers: { Cookie: `${getOauthCookieName()}=${signedToken}` },
signal: AbortSignal.timeout(5000),
useSessionCookies: false,
});
if (!res.ok) return null;
const data = await res.json();
return data?.session?.token || null;
} catch (err) {
if (debugLogger) {
debugLogger.warn("Signed-token bearer exchange failed (non-fatal)", {
error: err?.message,
});
}
return null;
}
}
// One-time bridge for users upgrading from a build that injected the session
// cookie into Electron's jar: exchange the existing cookie for a raw bearer
// token, store it, and remove the cookie. Non-fatal — failures fall through
// to the normal sign-in flow.
async function migrateCookieToBearerToken() {
const tokenStore = require("./src/helpers/tokenStore");
if (tokenStore.get()) return;
const cookieName = getOauthCookieName();
const authUrl = resolveAuthUrl();
try {
const cookies = await session.defaultSession.cookies.get({ url: authUrl, name: cookieName });
if (!cookies.length) return;
const rawToken = await exchangeSignedTokenForRawBearer(cookies[0].value);
if (!rawToken) return;
tokenStore.set(rawToken);
await session.defaultSession.cookies.remove(authUrl, cookieName);
if (debugLogger) debugLogger.debug("Migrated cookie to bearer token");
} catch (err) {
if (debugLogger) {
debugLogger.warn("Cookie→bearer token migration failed (non-fatal)", {
error: err?.message,
});
}
}
}
// Persist the bearer token and reload the control panel so the renderer's
// authClient sends `Authorization: Bearer <token>` on its next request.
async function applySessionTokenAndRefresh(token) {
if (!token) return;
if (!isLiveWindow(windowManager?.controlPanelWindow)) return;
const tokenStore = require("./src/helpers/tokenStore");
tokenStore.set(token);
const appUrl = DevServerManager.getAppUrl(true);
if (appUrl) {
windowManager.controlPanelWindow.loadURL(appUrl);
} else {
const fileInfo = DevServerManager.getAppFilePath(true);
if (fileInfo) {
windowManager.controlPanelWindow.loadFile(fileInfo.path, { query: fileInfo.query });
}
}
if (debugLogger) {
debugLogger.debug("Applied bearer token and reloaded control panel", {
appChannel: APP_CHANNEL,
oauthProtocol: OAUTH_PROTOCOL,
});
}
windowManager.controlPanelWindow.show();
windowManager.controlPanelWindow.focus();
dockManager.setControlPanelVisible(true);
}
async function handleOAuthDeepLink(deepLinkUrl) {
try {
const parsed = new URL(deepLinkUrl);
const bearerToken = parsed.searchParams.get("bearer_token");
if (bearerToken) {
void applySessionTokenAndRefresh(bearerToken);
return;
}
const signedToken = parsed.searchParams.get("token");
if (!signedToken) return;
const rawToken = await exchangeSignedTokenForRawBearer(signedToken);
if (rawToken) void applySessionTokenAndRefresh(rawToken);
} 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();
dockManager.setControlPanelVisible(true);
}
}
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", "*");