-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1632 lines (1394 loc) · 64.1 KB
/
Copy pathmain.js
File metadata and controls
1632 lines (1394 loc) · 64.1 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, BrowserWindow, ipcMain, dialog, shell, session, WebContentsView, Notification, nativeImage, nativeTheme, safeStorage, Menu, MenuItem } = require('electron');
// Default spellchecker languages for new sessions. Multi-language: each session
// can override this with its own list (sessionData.spellLanguages).
const DEFAULT_SPELL_LANGUAGES = ['pt-BR', 'en-US'];
const path = require('path');
const fs = require('fs');
const { JsonDB, Config } = require('node-json-db');
const { createProvider } = require('./ai-provider');
const updater = require('./updater');
const LINUX_DESKTOP_NAME = 'multi-browser.desktop';
const LINUX_WM_CLASS = path.basename(LINUX_DESKTOP_NAME, '.desktop');
if (process.platform === 'linux') {
app.commandLine.appendSwitch('class', LINUX_WM_CLASS);
// On Wayland, an app can only raise/focus itself when it holds an
// xdg-activation token (e.g. one handed to it by a notification click).
// That mechanism only exists in native Wayland mode — under XWayland the
// compositor refuses the raise and just flashes the icon. Prefer native
// Wayland when the session is Wayland so notification-click can focus the
// window; fall back to X11 automatically otherwise.
if (process.env.XDG_SESSION_TYPE === 'wayland') {
app.commandLine.appendSwitch('ozone-platform-hint', 'auto');
}
}
// Get icon path - ensure absolute path for better reliability
function getIconPath() {
const candidatePaths = [];
const iconFileNames = ['icon-512x512.png', 'icon.png'];
const addCandidates = (basePath) => {
if (!basePath) {
return;
}
for (const iconFileName of iconFileNames) {
candidatePaths.push(path.join(basePath, 'assets', iconFileName));
}
};
if (app.isPackaged) {
addCandidates(process.resourcesPath);
}
try {
addCandidates(app.getAppPath());
} catch (e) {
// app.getAppPath() might not be available yet
}
addCandidates(__dirname);
for (const iconPath of candidatePaths) {
if (fs.existsSync(iconPath)) {
return path.resolve(iconPath);
}
}
// If icon doesn't exist, return undefined (Electron will use default)
console.warn('⚠️ Icon not found. Tried:', candidatePaths);
return undefined;
}
// Get icon as nativeImage for better Linux support
function getIconNativeImage() {
const iconPath = getIconPath();
if (!iconPath) {
return undefined;
}
try {
const icon = nativeImage.createFromPath(iconPath);
if (icon.isEmpty()) {
console.warn('⚠️ Icon image is empty');
return undefined;
}
return icon;
} catch (error) {
console.error('⚠️ Error loading icon:', error);
return undefined;
}
}
// Session metadata lives in the per-user app data directory. Older builds used
// a relative path, which wrote sessions.json into whatever the working
// directory happened to be (the repo in dev, $HOME for an installed .deb), so
// the first run here adopts any file left in those places.
function resolveDatabasePath() {
const target = path.join(app.getPath('userData'), 'sessions.json');
if (fs.existsSync(target)) return target;
const legacyPaths = [
path.join(process.cwd(), 'sessions.json'),
path.join(__dirname, 'sessions.json'),
path.join(app.getPath('home'), 'sessions.json')
];
for (const legacy of legacyPaths) {
if (legacy !== target && fs.existsSync(legacy)) {
try {
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.copyFileSync(legacy, target);
console.log(`📦 Migrated session data from ${legacy} to ${target}`);
return target;
} catch (error) {
console.warn(`⚠️ Could not migrate ${legacy}: ${error.message}`);
}
}
}
return target;
}
// Initialize database for storing sessions (path without the .json suffix)
const db = new JsonDB(new Config(resolveDatabasePath().replace(/\.json$/, ''), true, false, '/'));
// ── Secrets at rest ───────────────────────────────────────────────────────
// API keys and the update token are kept in the OS keychain-backed
// safeStorage, not in the clear. Values are stored as "enc:v1:<base64>".
// When the platform has no keychain (some headless Linux setups),
// isEncryptionAvailable() is false and values stay plain — the app keeps
// working, it just cannot protect them.
const SECRET_FIELDS = ['claudeApiKey', 'openaiApiKey', 'openrouterApiKey', 'githubToken'];
const ENC_PREFIX = 'enc:v1:';
function encryptSecret(value) {
if (typeof value !== 'string' || !value || value.startsWith(ENC_PREFIX)) return value;
try {
if (!safeStorage.isEncryptionAvailable()) return value;
return ENC_PREFIX + safeStorage.encryptString(value).toString('base64');
} catch (error) {
console.warn('⚠️ Could not encrypt a stored secret:', error.message);
return value;
}
}
function decryptSecret(value) {
if (typeof value !== 'string' || !value.startsWith(ENC_PREFIX)) return value;
try {
return safeStorage.decryptString(Buffer.from(value.slice(ENC_PREFIX.length), 'base64'));
} catch (error) {
// Wrong machine, reset keychain, or a corrupted value: treat as unset
// rather than handing an unusable string to a provider.
console.warn('⚠️ Could not decrypt a stored secret:', error.message);
return '';
}
}
function mapSecrets(settings, fn) {
const out = { ...settings };
for (const field of SECRET_FIELDS) {
if (field in out) out[field] = fn(out[field]);
}
return out;
}
// Parse a WhatsApp link in any of its public forms and convert it to the
// equivalent WhatsApp Web URL, or return null if it isn't a WhatsApp link:
// whatsapp://send/?phone=55...&text=... (the "Open app" deep link)
// https://wa.me/5511999999999?text=...
// https://api.whatsapp.com/send/?phone=55...&text=...
function parseWhatsAppLink(rawUrl) {
if (typeof rawUrl !== 'string') return null;
let url;
try {
url = new URL(rawUrl.trim());
} catch {
return null;
}
let phone = null;
let text = null;
if (url.protocol === 'whatsapp:') {
phone = url.searchParams.get('phone');
text = url.searchParams.get('text');
} else if (url.protocol === 'https:' || url.protocol === 'http:') {
const host = url.hostname.replace(/^www\./, '');
const pathname = url.pathname.replace(/\/+$/, '');
if (host === 'wa.me') {
if (/^\/\+?\d[\d\-\s]*$/.test(pathname)) {
phone = pathname.slice(1);
} else if (pathname === '/send' || pathname === '') {
phone = url.searchParams.get('phone');
} else {
return null; // wa.me/message/<code> etc. — can't map to web.whatsapp.com
}
text = url.searchParams.get('text');
} else if (host === 'api.whatsapp.com' || host === 'whatsapp.com') {
if (pathname !== '/send') return null;
phone = url.searchParams.get('phone');
text = url.searchParams.get('text');
} else {
return null;
}
} else {
return null;
}
phone = (phone || '').replace(/\D/g, '');
if (phone.length < 5) return null;
const target = new URL('https://web.whatsapp.com/send');
target.searchParams.set('phone', phone);
if (text) target.searchParams.set('text', text);
return target.toString();
}
class MultiBrowserApp {
constructor() {
this.mainWindow = null;
this.sessionCounter = 0;
this.browserViews = new Map(); // sessionId -> WebContentsView
this.activeBrowserView = null;
this.activeNotifications = new Map(); // sessionId -> notification objects
this.recentlyOpenedFolders = new Set(); // Track folders that were recently opened
this.pendingSessionNavigations = new Map(); // sessionId -> URL to load once the view is created
this.pendingUpdate = null; // release info from the last successful update check
this.init();
}
// Bring the window back for a launch that hit the single-instance lock.
// Recreates it when it is gone: without this, a window that closed without
// quitting leaves a process that owns the lock but can never be seen.
restoreMainWindow() {
if (!this.mainWindow || this.mainWindow.isDestroyed()) {
console.log('🪟 No live window — creating one for this activation');
this.createMainWindow();
return;
}
if (this.mainWindow.isMinimized()) this.mainWindow.restore();
if (!this.mainWindow.isVisible()) this.mainWindow.show();
this.mainWindow.show();
this.mainWindow.focus();
}
// Resolve a sessionId from a WebContents reference
getSessionIdByWebContents(webContents) {
for (const [sid, view] of this.browserViews) {
if (view && view.webContents === webContents) {
return sid;
}
}
return null;
}
init() {
// Single instance: clicking a whatsapp:// link while the app is running
// launches a second instance with the URL in argv — forward it to the
// running instance instead of opening a second window.
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
return;
}
app.on('second-instance', (_event, argv) => {
const link = argv.find(arg => parseWhatsAppLink(arg));
console.log(`📲 second-instance received${link ? ` with WhatsApp link: ${link}` : ''}`);
if (link) {
this.handleWhatsAppLink(link);
} else {
this.restoreMainWindow();
}
});
// macOS delivers protocol URLs via open-url instead of argv
app.on('open-url', (event, url) => {
event.preventDefault();
this.handleWhatsAppLink(url);
});
app.whenReady().then(() => {
// Register as the OS handler for whatsapp:// deep links so the
// "Open app" button on wa.me / api.whatsapp.com pages opens us.
// (On Linux this needs the packaged .desktop file — see CLAUDE.md.)
try {
if (process.defaultApp) {
// Dev mode: point the handler at "electron <app path>"
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient('whatsapp', process.execPath, [path.resolve(process.argv[1])]);
}
} else {
app.setAsDefaultProtocolClient('whatsapp');
}
} catch (error) {
console.warn('⚠️ Could not register whatsapp:// protocol handler:', error.message);
}
// Ensure proper Windows notification activation routing
try {
app.setAppUserModelId('com.multibrowser.app');
} catch { }
// Restore the saved UI theme so native chrome (menus, dialogs,
// form controls) matches the shell.
this.getUITheme().then(theme => { nativeTheme.themeSource = theme; }).catch(() => { });
// Move any secrets written by older builds into the keychain.
this.encryptStoredSecrets().catch(() => { });
// Set app icon (important for Linux taskbar/dock)
const icon = getIconNativeImage();
const iconPath = getIconPath();
console.log('🖼️ App icon path:', iconPath);
if (icon) {
console.log('✅ Icon file found and loaded as nativeImage');
// Set icon on app (works on Linux for taskbar/dock)
if (process.platform === 'linux') {
// On Linux, the app icon is typically set via the window icon
// but we can also try setting it here
try {
app.dock?.setIcon(icon); // macOS
} catch (e) {
// Not macOS, continue
}
}
} else if (iconPath && fs.existsSync(iconPath)) {
console.log('✅ Icon file found at path');
} else {
console.warn('⚠️ Icon file not found, using default Electron icon');
}
// Check and log notification support
console.log('🔔 Notification support:', Notification.isSupported());
console.log('Electron version:', process.versions.electron);
console.log('Chrome/Chromium version:', process.versions.chrome);
console.log('Node version:', process.versions.node);
this.createMainWindow();
this.loadSavedSessions();
// Cold start from a WhatsApp link click: the URL arrives in argv.
// Wait for the shell to load so the renderer can open the tab.
const startupLink = process.argv.find(arg => parseWhatsAppLink(arg));
if (startupLink) {
console.log(`📲 Launched with WhatsApp link: ${startupLink}`);
this.mainWindow.webContents.once('did-finish-load', () => {
setTimeout(() => this.handleWhatsAppLink(startupLink), 800);
});
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
this.cleanup();
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
this.createMainWindow();
}
});
this.setupIPC();
// Notification IPC: map notifications back to sessions and log
ipcMain.on('site-notification', (event, { title, options, url }) => {
const sessionId = this.getSessionIdByWebContents(event.sender);
console.log(`[Site notification] session=${sessionId || 'unknown'} title="${title}" body="${options?.body || ''}" url=${url}`);
if (this.mainWindow) {
this.mainWindow.webContents.send('site-notification', { sessionId, title, options, url });
}
});
// The site's own notification was clicked: bring its window/tab to the
// front. The page keeps showing the real notification and handles
// conversation navigation itself; we only focus the right session.
ipcMain.on('focus-session-from-notification', (event) => {
const sessionId = this.getSessionIdByWebContents(event.sender);
console.log(`🔔 Notification clicked for session ${sessionId}`);
if (sessionId) {
this.handleNotificationClick(sessionId);
} else {
console.warn('🔔 Could not resolve session for clicked notification');
}
});
}
// Test notification functionality
testNotification() {
console.log('🧪 Creating test notification...');
try {
// Get first available session for testing
const firstSessionId = Array.from(this.browserViews.keys())[0];
if (!firstSessionId) {
console.log('🧪 No active sessions found for testing');
return;
}
// Main-process notification used only for the Ctrl+T self-test.
const { Notification } = require('electron');
const notification = new Notification({
title: 'Test Notification',
body: `Click to focus session: ${firstSessionId}`,
icon: getIconPath()
});
notification.on('click', () => {
console.log(`🧪 Test notification clicked - focusing session ${firstSessionId}`);
this.handleNotificationClick(firstSessionId);
this.activeNotifications.delete(firstSessionId);
});
notification.on('close', () => {
console.log('🧪 Test notification closed');
this.activeNotifications.delete(firstSessionId);
});
this.activeNotifications.set(firstSessionId, notification);
notification.show();
console.log(`🧪 Test notification created for session ${firstSessionId}`);
} catch (error) {
console.error('🧪 Error creating test notification:', error);
}
}
// Handle notification click events
handleNotificationClick(sessionId) {
console.log(`🎯 ========== NOTIFICATION CLICK HANDLER ==========`);
console.log(`🎯 Session ID: ${sessionId}`);
console.log(`🎯 Main window exists: ${!!this.mainWindow}`);
console.log(`🎯 Main window destroyed: ${this.mainWindow ? this.mainWindow.isDestroyed() : 'N/A'}`);
if (!this.mainWindow) {
console.warn('Main window not available for notification click');
return;
}
try {
console.log(`🎯 Current window state:`);
console.log(` - Minimized: ${this.mainWindow.isMinimized()}`);
console.log(` - Visible: ${this.mainWindow.isVisible()}`);
console.log(` - Focused: ${this.mainWindow.isFocused()}`);
// Bring window to front and focus it. Order matters and every step
// runs unconditionally: an already-visible-but-occluded window still
// needs show()/moveTop() — focus() alone is ignored by most Linux WMs.
if (this.mainWindow.isMinimized()) {
this.mainWindow.restore();
console.log('🔄 Window restored from minimized state');
}
this.mainWindow.setAlwaysOnTop(true);
this.mainWindow.show(); // re-maps + raises even when already visible
this.mainWindow.focus();
try { this.mainWindow.moveTop(); } catch { /* not supported on some WMs */ }
console.log('🎯 Window shown, focused and raised');
// Remove always on top shortly after so it doesn't stay pinned.
setTimeout(() => {
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.setAlwaysOnTop(false);
console.log('🎯 Always on top removed');
}
}, 500);
console.log('🎯 Window focused and brought to front');
// Send focus command to renderer to switch to the correct session
this.mainWindow.webContents.send('focus-session', {
sessionId,
source: 'notification-click'
});
console.log(`📨 Sent focus-session command for ${sessionId}`);
console.log(`🎯 ===============================================`);
} catch (error) {
console.error('Error handling notification click:', error);
}
}
// Route a WhatsApp link (whatsapp://, wa.me, api.whatsapp.com) to the
// WhatsApp session's tab: convert it to a web.whatsapp.com/send URL,
// navigate the session there and bring its tab to the front.
async handleWhatsAppLink(rawUrl) {
const targetUrl = parseWhatsAppLink(rawUrl);
console.log(`📲 WhatsApp link: ${rawUrl} → ${targetUrl || 'not parseable'}`);
if (!targetUrl) return false;
const sessionId = await this.findWhatsAppSessionId();
if (!sessionId) {
console.warn('📲 No WhatsApp session found to receive the link');
if (this.mainWindow) {
this.mainWindow.show();
this.mainWindow.focus();
this.mainWindow.webContents.send('app-message', {
text: 'WhatsApp link received, but no WhatsApp session exists. Create one pointing to web.whatsapp.com.',
type: 'error'
});
}
return false;
}
const view = this.browserViews.get(sessionId);
if (view) {
view.webContents.loadURL(targetUrl);
} else {
// Tab not open yet: remember the URL; createBrowserView will load
// it instead of the session's start URL when the tab opens below.
this.pendingSessionNavigations.set(sessionId, targetUrl);
}
// Raises the window and tells the renderer to open/switch to the tab
this.handleNotificationClick(sessionId);
return true;
}
// Pick the session that should receive WhatsApp links: the active view if
// it's on WhatsApp Web, then any open WhatsApp view, then the most
// recently used saved session whose URL points at WhatsApp.
async findWhatsAppSessionId() {
const isWhatsAppView = (view) => {
try {
return view.webContents.getURL().includes('web.whatsapp.com');
} catch {
return false;
}
};
if (this.activeBrowserView && isWhatsAppView(this.activeBrowserView)) {
return this.getSessionIdByWebContents(this.activeBrowserView.webContents);
}
for (const [sessionId, view] of this.browserViews) {
if (isWhatsAppView(view)) return sessionId;
}
const sessions = await this.getSessions();
sessions.sort((a, b) => new Date(b.lastAccessed) - new Date(a.lastAccessed));
const match = sessions.find(s => (s.url || '').includes('whatsapp.com'));
return match ? match.id : null;
}
createMainWindow() {
// Get icon as nativeImage for better cross-platform support
const icon = getIconNativeImage();
const iconPath = getIconPath();
if (icon) {
console.log('✅ Using nativeImage icon:', iconPath);
// Log icon size for debugging
const size = icon.getSize();
console.log(`📐 Icon size: ${size.width}x${size.height}`);
} else {
console.warn('⚠️ Using default icon');
}
this.mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
webSecurity: false,
webviewTag: true // Enable webview tag
},
icon: icon || iconPath, // Use nativeImage if available, fallback to path
title: `Multi Browser v${app.getVersion()}`,
show: false // Don't show until ready
});
// Keep the version in the window title — otherwise index.html's <title>
// would overwrite it once the shell loads.
const windowTitle = `Multi Browser v${app.getVersion()}`;
this.mainWindow.on('page-title-updated', (event) => {
event.preventDefault();
this.mainWindow.setTitle(windowTitle);
});
// Set icon explicitly (important for Linux)
if (icon) {
this.mainWindow.setIcon(icon);
console.log('🖼️ Icon set explicitly on window');
}
this.mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Show window after icon is set
this.mainWindow.once('ready-to-show', () => {
this.mainWindow.show();
});
// Safety net: if the shell never reaches ready-to-show (a failed load,
// a half-written asar after an update), show the window anyway. An
// invisible process still holds the single-instance lock, so every
// later launch would exit silently and the app would look unopenable.
setTimeout(() => {
if (this.mainWindow && !this.mainWindow.isDestroyed() && !this.mainWindow.isVisible()) {
console.warn('⚠️ Window never reported ready-to-show — showing it anyway');
this.mainWindow.show();
}
}, 8000);
this.mainWindow.webContents.on('did-fail-load', (_event, errorCode, errorDescription, url) => {
console.error(`❌ App shell failed to load (${errorCode} ${errorDescription}): ${url}`);
});
this.mainWindow.webContents.on('render-process-gone', (_event, details) => {
console.error(`💥 App shell renderer gone: ${details.reason}`);
});
// Remove menu bar for cleaner look
this.mainWindow.setMenuBarVisibility(false);
// Open DevTools in development
if (process.env.NODE_ENV === 'development') {
this.mainWindow.webContents.openDevTools();
}
// Add keyboard shortcut to test notifications (Ctrl+T)
this.mainWindow.webContents.on('before-input-event', (event, input) => {
if (input.control && input.key.toLowerCase() === 't' && input.type === 'keyDown') {
console.log('🧪 Testing notification...');
this.testNotification();
}
});
// Handle window resize to update browser view bounds
this.statusBarVisible = false;
this.updateBrowserViewBounds = () => {
if (this.activeBrowserView) {
const bounds = this.mainWindow.getContentBounds();
const tabBarHeight = 45;
const statusBarHeight = this.statusBarVisible ? 30 : 0;
this.activeBrowserView.setBounds({
x: 0,
y: tabBarHeight,
width: bounds.width,
height: bounds.height - tabBarHeight - statusBarHeight
});
}
};
this.mainWindow.on('resize', this.updateBrowserViewBounds);
this.mainWindow.on('maximize', this.updateBrowserViewBounds);
this.mainWindow.on('unmaximize', this.updateBrowserViewBounds);
this.mainWindow.on('restore', this.updateBrowserViewBounds);
}
setupIPC() {
ipcMain.on('status-bar-visibility', (event, visible) => {
this.statusBarVisible = visible;
this.updateBrowserViewBounds();
});
ipcMain.handle('create-browser-session', async (event, config) => {
return await this.createBrowserSession(config);
});
ipcMain.handle('get-sessions', async () => {
return this.getSessions();
});
ipcMain.handle('delete-session', async (event, sessionId) => {
return this.deleteSession(sessionId);
});
ipcMain.handle('get-session-partition', async (event, sessionId) => {
return `persist:session-${sessionId}`;
});
ipcMain.handle('create-browser-view', async (event, sessionId) => {
return await this.createBrowserView(sessionId);
});
ipcMain.handle('show-browser-view', async (event, sessionId) => {
return this.showBrowserView(sessionId);
});
ipcMain.handle('hide-browser-view', async (event, sessionId) => {
return this.hideBrowserView(sessionId);
});
ipcMain.handle('close-browser-view', async (event, sessionId) => {
return this.closeBrowserView(sessionId);
});
ipcMain.handle('navigate-browser-view', async (event, sessionId, url) => {
return this.navigateBrowserView(sessionId, url);
});
ipcMain.handle('rename-session', async (event, sessionId, newName) => {
return this.renameSession(sessionId, newName);
});
ipcMain.handle('update-session-auto-open', async (event, sessionId, autoOpen) => {
return this.updateSessionAutoOpen(sessionId, autoOpen);
});
ipcMain.handle('update-session-languages', async (event, sessionId, languages) => {
return this.updateSessionLanguages(sessionId, languages);
});
ipcMain.handle('get-available-spellchecker-languages', async () => {
try {
return session.defaultSession.availableSpellCheckerLanguages || [];
} catch {
return [];
}
});
ipcMain.handle('get-app-version', () => app.getVersion());
// ── Updates (GitHub Releases) ──
ipcMain.handle('updates-check', async () => {
try {
const info = await updater.checkForUpdate(await this.getGithubToken());
this.pendingUpdate = info.installable ? info : null;
return { success: true, ...info };
} catch (error) {
console.error('Update check failed:', error.message);
return { success: false, error: error.message };
}
});
ipcMain.handle('updates-download', async (event) => {
if (!this.pendingUpdate) return { success: false, error: 'No update to download.' };
try {
const filePath = await updater.downloadAsset(this.pendingUpdate.asset, (progress) => {
try {
event.sender.send('updates-progress', progress);
} catch { }
}, await this.getGithubToken());
this.pendingUpdate.filePath = filePath;
return { success: true, filePath };
} catch (error) {
console.error('Update download failed:', error.message);
return { success: false, error: error.message };
}
});
ipcMain.handle('updates-install', async () => {
if (!this.pendingUpdate || !this.pendingUpdate.filePath) {
return { success: false, error: 'Nothing downloaded yet.' };
}
return updater.installUpdate(this.pendingUpdate.filePath, this.pendingUpdate.format);
});
ipcMain.handle('updates-open-release', async () => {
const url = this.pendingUpdate?.releaseUrl || updater.releasesUrl();
await shell.openExternal(url);
return { success: true };
});
// UI theme: 'system' | 'light' | 'dark'
ipcMain.handle('get-ui-theme', async () => this.getUITheme());
ipcMain.handle('save-ui-theme', async (event, theme) => this.saveUITheme(theme));
// AI Assistant IPC handlers
ipcMain.handle('ai-get-settings', async () => {
return this.getAISettings();
});
ipcMain.handle('ai-save-settings', async (event, settings) => {
return this.saveAISettings(settings);
});
ipcMain.handle('ai-request', async (event, { action, text }) => {
return this.handleAIRequest(action, text);
});
// Floating AI button position (shared by every session view)
ipcMain.handle('ai-get-fab-position', async () => {
return this.getAIFabPosition();
});
ipcMain.handle('ai-save-fab-position', async (event, pos) => {
return this.saveAIFabPosition(pos, event.sender);
});
}
async createBrowserSession(config) {
try {
const sessionId = config.sessionId || `session_${Date.now()}_${++this.sessionCounter}`;
// Create isolated session partition
const partitionName = `persist:session-${sessionId}`;
const sessionInstance = session.fromPartition(partitionName);
// Configure session settings for better isolation
sessionInstance.setPermissionRequestHandler((webContents, permission, callback) => {
// Auto-grant basic permissions, you can customize this
const allowedPermissions = ['notifications', 'geolocation', 'media'];
callback(allowedPermissions.includes(permission));
});
// Save session info
const sessionData = {
id: sessionId,
name: config.name || `Session ${this.sessionCounter}`,
url: config.url || 'about:blank',
autoOpen: false,
created: new Date().toISOString(),
lastAccessed: new Date().toISOString(),
partition: partitionName,
spellLanguages: Array.isArray(config.spellLanguages) && config.spellLanguages.length
? config.spellLanguages
: DEFAULT_SPELL_LANGUAGES
};
await db.push(`/sessions/${sessionId}`, sessionData);
return { success: true, sessionId, sessionData };
} catch (error) {
console.error('Error creating browser session:', error);
return { success: false, error: error.message };
}
}
async getSessions() {
try {
const sessions = await db.getData('/sessions');
return Object.values(sessions || {});
} catch (error) {
return [];
}
}
async deleteSession(sessionId) {
try {
// Remove from database
await db.delete(`/sessions/${sessionId}`);
// Clear the session partition data
const partitionName = `persist:session-${sessionId}`;
try {
const sessionInstance = session.fromPartition(partitionName);
await sessionInstance.clearStorageData();
} catch (error) {
console.log(`Could not clear session data for ${sessionId}:`, error.message);
}
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
}
async loadSavedSessions() {
// Initialize session partitions for existing sessions
try {
const sessions = await this.getSessions();
for (const sessionData of sessions) {
// Pre-initialize session partitions
session.fromPartition(sessionData.partition || `persist:session-${sessionData.id}`);
}
} catch (error) {
console.log('Error loading saved sessions:', error.message);
}
}
async createBrowserView(sessionId) {
try {
const sessionData = await db.getData(`/sessions/${sessionId}`);
const partitionName = sessionData.partition || `persist:session-${sessionId}`;
// Apply this session's spellchecker languages to its partition before
// the view loads, so the redline matches the language the user types in.
this.applySpellCheckerLanguages(session.fromPartition(partitionName), sessionData.spellLanguages);
const preloadPath = path.join(__dirname, 'preload', 'index.js');
console.log('[ai] Creating browser view with preload:', preloadPath);
const view = new WebContentsView({
webPreferences: {
partition: partitionName,
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // Required for preload require() in Electron 20+
webSecurity: true,
preload: preloadPath
}
});
this.browserViews.set(sessionId, view);
// Set up event handlers for the browser view
this.setupBrowserViewEvents(view, sessionId, sessionData.name);
// Configurar User Agent do Chrome para compatibilidade com WhatsApp Web
const chromeUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36';
view.webContents.setUserAgent(chromeUserAgent);
// Load the URL (a routed WhatsApp link takes precedence over the
// session's start URL — see handleWhatsAppLink)
const pendingUrl = this.pendingSessionNavigations.get(sessionId);
this.pendingSessionNavigations.delete(sessionId);
view.webContents.loadURL(pendingUrl || sessionData.url);
return { success: true, sessionId };
} catch (error) {
console.error('Error creating browser view:', error);
return { success: false, error: error.message };
}
}
showBrowserView(sessionId) {
try {
console.log('🔧 [main] showBrowserView called for', sessionId);
const view = this.browserViews.get(sessionId);
if (!view) {
return { success: false, error: 'Browser view not found' };
}
// Hide current view first
if (this.activeBrowserView && this.activeBrowserView !== view) {
this.mainWindow.contentView.removeChildView(this.activeBrowserView);
}
// Add the new view
this.mainWindow.contentView.addChildView(view);
this.activeBrowserView = view;
// Set bounds to content area
const bounds = this.mainWindow.getContentBounds();
const tabBarHeight = 45;
const statusBarHeight = this.statusBarVisible ? 30 : 0;
view.setBounds({
x: 0,
y: tabBarHeight,
width: bounds.width,
height: bounds.height - tabBarHeight - statusBarHeight
});
// Ensure the view is visible but not intercepting all events
view.webContents.setZoomFactor(1.0);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
}
hideBrowserView(sessionId) {
try {
console.log('🔧 [main] hideBrowserView called for', sessionId);
const view = this.browserViews.get(sessionId);
if (view && this.activeBrowserView === view) {
this.mainWindow.contentView.removeChildView(view);
this.activeBrowserView = null;
}
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
}
closeBrowserView(sessionId) {
try {
const view = this.browserViews.get(sessionId);
if (view) {
if (this.activeBrowserView === view) {
this.mainWindow.contentView.removeChildView(view);
this.activeBrowserView = null;
}
view.webContents.destroy();
this.browserViews.delete(sessionId);
}
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
}
navigateBrowserView(sessionId, url) {
try {
const view = this.browserViews.get(sessionId);
if (view) {
// Configurar User Agent antes de navegar
const chromeUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36';
view.webContents.setUserAgent(chromeUserAgent);
view.webContents.loadURL(url);
return { success: true };
}
return { success: false, error: 'Browser view not found' };
} catch (error) {
return { success: false, error: error.message };
}
}
async renameSession(sessionId, newName) {
try {