-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathindex.ts
More file actions
3633 lines (3250 loc) · 117 KB
/
Copy pathindex.ts
File metadata and controls
3633 lines (3250 loc) · 117 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
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
import axios from 'axios';
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
nativeTheme,
protocol,
safeStorage,
session,
shell,
} from 'electron';
import log from 'electron-log';
import FormData from 'form-data';
import fsp from 'fs/promises';
import mime from 'mime';
import { ChildProcessWithoutNullStreams, spawn } from 'node:child_process';
import crypto from 'node:crypto';
import fs, { existsSync } from 'node:fs';
import http from 'node:http';
import os, { homedir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import kill from 'tree-kill';
import * as unzipper from 'unzipper';
import { copyBrowserData } from './copy';
import { FileReader } from './fileReader';
import {
checkToolInstalled,
findAvailablePort,
killProcessOnPort,
startBackend,
} from './init';
import {
checkAndInstallDepsOnUpdate,
getInstallationStatus,
PromiseReturnType,
} from './install-deps';
import { registerUpdateIpcHandlers, update } from './update';
import {
getEmailFolderPath,
getEnvPath,
maskProxyUrl,
readGlobalEnvKey,
removeEnvKey,
updateEnvBlock,
} from './utils/envUtil';
import { zipFolder } from './utils/log';
import { addMcp, readMcpConfig, removeMcp, updateMcp } from './utils/mcpConfig';
import {
checkVenvExistsForPreCheck,
getBackendPath,
isBinaryExists,
} from './utils/process';
import { WebViewManager } from './webview';
const userData = app.getPath('userData');
// ==================== constants ====================
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const MAIN_DIST = path.join(__dirname, '../..');
const RENDERER_DIST = path.join(MAIN_DIST, 'dist');
const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL;
const VITE_PUBLIC = VITE_DEV_SERVER_URL
? path.join(MAIN_DIST, 'public')
: RENDERER_DIST;
// ==================== global variables ====================
let win: BrowserWindow | null = null;
let webViewManager: WebViewManager | null = null;
let fileReader: FileReader | null = null;
let python_process: ChildProcessWithoutNullStreams | null = null;
let backendPort: number = 5001;
let browser_port = 9222;
let use_external_cdp = false;
let proxyUrl: string | null = null;
// CDP Browser Pool
interface CdpBrowser {
id: string;
port: number;
isExternal: boolean;
name?: string;
addedAt: number;
}
let cdp_browser_pool: CdpBrowser[] = [];
let cdpHealthCheckTimer: ReturnType<typeof setInterval> | null = null;
const CDP_POOL_FILE = path.join(os.homedir(), '.eigent', 'cdp-browsers.json');
/** Persist pool to disk. */
function saveCdpPool(): void {
try {
fs.writeFileSync(CDP_POOL_FILE, JSON.stringify(cdp_browser_pool, null, 2));
} catch (e) {
log.error(`[CDP POOL] Failed to save pool: ${e}`);
}
}
/** Load pool from disk. Mark all as external (process handles are lost after restart). */
function loadCdpPool(): void {
try {
if (fs.existsSync(CDP_POOL_FILE)) {
const data = JSON.parse(fs.readFileSync(CDP_POOL_FILE, 'utf-8'));
cdp_browser_pool = (data as CdpBrowser[]).map((b) => ({
...b,
isExternal: true,
}));
log.info(
`[CDP POOL] Loaded ${cdp_browser_pool.length} browser(s) from disk`
);
}
} catch (e) {
log.error(`[CDP POOL] Failed to load pool: ${e}`);
cdp_browser_pool = [];
}
}
/** Push current pool to frontend. */
function notifyCdpPoolChanged(): void {
if (win && !win.isDestroyed()) {
log.info(
`[CDP POOL] Pushing pool update to frontend (size=${cdp_browser_pool.length})`
);
win.webContents.send('cdp-pool-changed', cdp_browser_pool);
} else {
log.warn('[CDP POOL] Cannot notify: win is null or destroyed');
}
}
/** Probe a CDP port. Returns true if alive. */
async function isCdpPortAlive(port: number): Promise<boolean> {
try {
const resp = await axios.get(`http://localhost:${port}/json/version`, {
timeout: 1500,
});
return resp.status === 200;
} catch {
return false;
}
}
/** Run one health-check cycle: remove dead browsers, persist & notify if changed. */
async function runPoolHealthCheck(): Promise<void> {
if (cdp_browser_pool.length === 0) return;
// Probe a snapshot so add/remove IPC handlers can run safely in parallel.
const snapshot = [...cdp_browser_pool];
const results = await Promise.all(
snapshot.map((b) => isCdpPortAlive(b.port))
);
const deadIds = snapshot
.filter((_, idx) => !results[idx])
.map((browser) => browser.id);
if (deadIds.length === 0) return;
const deadIdSet = new Set(deadIds);
const removedBrowsers = cdp_browser_pool.filter((b) => deadIdSet.has(b.id));
if (removedBrowsers.length === 0) return;
cdp_browser_pool = cdp_browser_pool.filter((b) => !deadIdSet.has(b.id));
const deadPorts = removedBrowsers.map((b) => b.port);
if (deadPorts.length > 0) {
log.info(
`[CDP POOL] Health-check removed dead ports: ${deadPorts.join(', ')}. pool_size=${cdp_browser_pool.length}`
);
saveCdpPool();
notifyCdpPoolChanged();
}
}
/** Start periodic health check (call after window is created). */
function startCdpHealthCheck(): void {
if (cdpHealthCheckTimer) {
clearInterval(cdpHealthCheckTimer);
cdpHealthCheckTimer = null;
}
log.info('[CDP POOL] Starting health check (interval=3s)');
// Run once immediately
runPoolHealthCheck();
cdpHealthCheckTimer = setInterval(runPoolHealthCheck, 3000);
}
function stopCdpHealthCheck(): void {
if (cdpHealthCheckTimer) {
clearInterval(cdpHealthCheckTimer);
cdpHealthCheckTimer = null;
}
}
/** Close a browser via CDP Browser.close() WebSocket command. Best-effort.
* Uses raw Node.js http upgrade (no external ws dependency needed).
* IMPORTANT: Never close the Electron app's own CDP port. */
async function closeBrowserViaCdp(port: number): Promise<void> {
// Guard: refuse to close the Electron app's own CDP port
if (port === browser_port) {
log.warn(
`[CDP CLOSE] Refusing to close port ${port} (Electron app's own CDP port)`
);
return;
}
try {
const resp = await axios.get(`http://localhost:${port}/json/version`, {
timeout: 2000,
});
const wsUrl: string | undefined = resp.data?.webSocketDebuggerUrl;
if (!wsUrl) {
log.warn(`[CDP CLOSE] No webSocketDebuggerUrl for port ${port}`);
return;
}
const url = new URL(wsUrl);
const key = crypto.randomBytes(16).toString('base64');
await new Promise<void>((resolve) => {
let resolved = false;
const done = () => {
if (!resolved) {
resolved = true;
resolve();
}
};
const req = http.request(
{
hostname: url.hostname,
port: url.port,
path: url.pathname,
method: 'GET',
headers: {
Connection: 'Upgrade',
Upgrade: 'websocket',
'Sec-WebSocket-Version': '13',
'Sec-WebSocket-Key': key,
},
},
() => done()
);
const timer = setTimeout(() => {
req.destroy();
done();
}, 3000);
req.on('upgrade', (_res, socket) => {
// Handle socket errors to prevent uncaught exceptions
socket.on('error', () => {});
// Build a masked WebSocket text frame with Browser.close
const payload = Buffer.from(
JSON.stringify({ id: 1, method: 'Browser.close' })
);
const mask = crypto.randomBytes(4);
const header = Buffer.alloc(6);
header[0] = 0x81; // FIN + text opcode
header[1] = 0x80 | payload.length; // MASK bit + length (<126)
mask.copy(header, 2);
const masked = Buffer.alloc(payload.length);
for (let i = 0; i < payload.length; i++) {
masked[i] = payload[i] ^ mask[i & 3];
}
socket.write(Buffer.concat([header, masked]));
log.info(`[CDP CLOSE] Sent Browser.close to port ${port}`);
// Give Chrome a moment to process, then clean up
setTimeout(() => {
clearTimeout(timer);
socket.destroy();
done();
}, 500);
});
req.on('error', (err) => {
log.warn(`[CDP CLOSE] Request error for port ${port}: ${err.message}`);
clearTimeout(timer);
done();
});
req.end();
});
log.info(`[CDP CLOSE] Successfully closed browser on port ${port}`);
} catch (err) {
log.warn(`[CDP CLOSE] Best-effort close failed for port ${port}: ${err}`);
}
}
// Protocol URL queue for handling URLs before window is ready
let protocolUrlQueue: string[] = [];
let isWindowReady = false;
// ==================== path config ====================
const preload = path.join(__dirname, '../preload/index.mjs');
const indexHtml = path.join(RENDERER_DIST, 'index.html');
const logPath = log.transports.file.getFile().path;
// Profile initialization promise
let profileInitPromise: Promise<void>;
// Set remote debugging port
// Storage strategy:
// 1. Main window: partition 'persist:main_window' in app userData → Eigent account (persistent)
// 2. WebView: partition 'persist:user_login' in app userData → will import cookies from tool_controller via session API
// 3. tool_controller: ~/.eigent/browser_profiles/profile_user_login → source of truth for login cookies
// 4. CDP browser: uses separate profile (doesn't share with main app)
profileInitPromise = findAvailablePort(browser_port).then(async (port) => {
browser_port = port;
app.commandLine.appendSwitch('remote-debugging-port', port + '');
// Create isolated profile for CDP browser only
const browserProfilesBase = path.join(
os.homedir(),
'.eigent',
'browser_profiles'
);
const cdpProfile = path.join(browserProfilesBase, `cdp_profile_${port}`);
try {
await fsp.mkdir(cdpProfile, { recursive: true });
log.info(`[CDP BROWSER] Created CDP profile directory at ${cdpProfile}`);
} catch (error) {
log.error(`[CDP BROWSER] Failed to create directory: ${error}`);
}
// Set user-data-dir for Chrome DevTools Protocol only
app.commandLine.appendSwitch('user-data-dir', cdpProfile);
log.info(`[CDP BROWSER] Chrome DevTools Protocol enabled on port ${port}`);
log.info(`[CDP BROWSER] CDP profile directory: ${cdpProfile}`);
log.info(`[STORAGE] Main app userData: ${app.getPath('userData')}`);
});
// Memory optimization settings
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=4096');
app.commandLine.appendSwitch('force-gpu-mem-available-mb', '512');
app.commandLine.appendSwitch('max_old_space_size', '4096');
app.commandLine.appendSwitch('enable-features', 'MemoryPressureReduction');
app.commandLine.appendSwitch('renderer-process-limit', '8');
// Disable Fontations (Rust-based font engine) to prevent crashes on macOS
app.commandLine.appendSwitch('disable-features', 'Fontations');
// ==================== Proxy configuration ====================
// Read proxy from global .env file on startup
proxyUrl = readGlobalEnvKey('HTTP_PROXY');
if (proxyUrl) {
log.info(`[PROXY] Applying proxy configuration: ${maskProxyUrl(proxyUrl)}`);
app.commandLine.appendSwitch('proxy-server', proxyUrl);
} else {
log.info('[PROXY] No proxy configured');
}
// ==================== Anti-fingerprint settings ====================
// Disable automation controlled indicator to avoid detection
app.commandLine.appendSwitch('disable-blink-features', 'AutomationControlled');
// Override User Agent to remove Electron/eigent identifiers
// Dynamically generate User Agent based on actual platform and Chrome version
const getPlatformUA = () => {
// Use actual Chrome version from Electron instead of hardcoded value
const chromeVersion = process.versions.chrome || '131.0.0.0';
switch (process.platform) {
case 'darwin':
return `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`;
case 'win32':
return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`;
case 'linux':
return `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`;
default:
return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`;
}
};
const normalUserAgent = getPlatformUA();
app.userAgentFallback = normalUserAgent;
// ==================== protocol privileges ====================
// Register custom protocol privileges before app ready
protocol.registerSchemesAsPrivileged([
{
scheme: 'localfile',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: false,
bypassCSP: false,
},
},
]);
// ==================== app config ====================
process.env.APP_ROOT = MAIN_DIST;
process.env.VITE_PUBLIC = VITE_PUBLIC;
// Respect system theme on Windows, keep light theme on macOS for consistency
const isWindows = process.platform === 'win32';
if (isWindows) {
nativeTheme.themeSource = 'system'; // Respect Windows dark/light mode
} else {
nativeTheme.themeSource = 'light'; // Keep existing behavior for macOS
}
// Set log level
log.transports.console.level = 'info';
log.transports.file.level = 'info';
log.transports.console.format = '[{level}]{text}';
log.transports.file.format = '[{level}]{text}';
// Disable GPU Acceleration for Windows 7
if (os.release().startsWith('6.1')) app.disableHardwareAcceleration();
// Set application name for Windows 10+ notifications
if (process.platform === 'win32') app.setAppUserModelId(app.getName());
if (!app.requestSingleInstanceLock()) {
app.quit();
process.exit(0);
}
// ==================== protocol config ====================
const setupProtocolHandlers = () => {
if (process.env.NODE_ENV === 'development') {
const isDefault = app.isDefaultProtocolClient('eigent', process.execPath, [
path.resolve(process.argv[1]),
]);
if (!isDefault) {
app.setAsDefaultProtocolClient('eigent', process.execPath, [
path.resolve(process.argv[1]),
]);
}
} else {
app.setAsDefaultProtocolClient('eigent');
}
};
// ==================== protocol url handle ====================
function handleProtocolUrl(url: string) {
log.info('enter handleProtocolUrl', url);
// If window is not ready, queue the URL
if (!isWindowReady || !win || win.isDestroyed()) {
log.info('Window not ready, queuing protocol URL:', url);
protocolUrlQueue.push(url);
return;
}
processProtocolUrl(url);
}
// Process a single protocol URL
function processProtocolUrl(url: string) {
const urlObj = new URL(url);
const code = urlObj.searchParams.get('code');
const share_token = urlObj.searchParams.get('share_token');
log.info('urlObj', urlObj);
log.info('code', code);
log.info('share_token', share_token);
if (win && !win.isDestroyed()) {
log.info('urlObj.pathname', urlObj.pathname);
if (urlObj.pathname === '/oauth') {
log.info('oauth');
const provider = urlObj.searchParams.get('provider');
const code = urlObj.searchParams.get('code');
log.info('protocol oauth', provider, code);
win.webContents.send('oauth-authorized', { provider, code });
return;
}
if (code) {
log.error('protocol code:', code);
win.webContents.send('auth-code-received', code);
}
if (share_token) {
win.webContents.send('auth-share-token-received', share_token);
}
} else {
log.error('window not available');
}
}
// Process all queued protocol URLs
function processQueuedProtocolUrls() {
if (protocolUrlQueue.length > 0) {
log.info('Processing queued protocol URLs:', protocolUrlQueue.length);
// Verify window is ready before processing
if (!win || win.isDestroyed() || !isWindowReady) {
log.warn(
'Window not ready for processing queued URLs, keeping URLs in queue'
);
return;
}
const urls = [...protocolUrlQueue];
protocolUrlQueue = [];
urls.forEach((url) => {
processProtocolUrl(url);
});
}
}
// ==================== single instance lock ====================
const setupSingleInstanceLock = () => {
// The lock is already acquired at module level (requestSingleInstanceLock
// above). Calling it again here would release and re-acquire the lock,
// creating a window where a second instance could start. We only need
// to register the event handlers.
app.on('second-instance', (event, argv) => {
log.info('second-instance', argv);
const url = argv.find((arg) => arg.startsWith('eigent://'));
if (url) handleProtocolUrl(url);
if (win) win.show();
});
app.on('open-url', (event, url) => {
log.info('open-url');
event.preventDefault();
handleProtocolUrl(url);
});
};
// ==================== initialize config ====================
const initializeApp = () => {
setupProtocolHandlers();
setupSingleInstanceLock();
};
/**
* Registers all IPC handlers once when the app starts
* This prevents "Attempted to register a second handler" errors
* when windows are reopened
*/
// Get backup log path
const getBackupLogPath = () => {
const userDataPath = app.getPath('userData');
return path.join(userDataPath, 'logs', 'main.log');
};
// Constants define
const BROWSER_PATHS = {
win32: {
chrome: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
edge: 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
firefox: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
qq: 'C:\\Program Files\\Tencent\\QQBrowser\\QQBrowser.exe',
'360': path.join(
homedir(),
'AppData\\Local\\360Chrome\\Chrome\\Application\\360chrome.exe'
),
arc: path.join(homedir(), 'AppData\\Local\\Arc\\User Data\\Arc.exe'),
dia: path.join(homedir(), 'AppData\\Local\\Dia\\Application\\dia.exe'),
fellou: path.join(
homedir(),
'AppData\\Local\\Fellou\\Application\\fellou.exe'
),
},
darwin: {
chrome: '/Applications/Google Chrome.app',
edge: '/Applications/Microsoft Edge.app',
firefox: '/Applications/Firefox.app',
safari: '/Applications/Safari.app',
arc: '/Applications/Arc.app',
dia: '/Applications/Dia.app',
fellou: '/Applications/Fellou.app',
},
} as const;
// Tool function
const getSystemLanguage = async () => {
const locale = app.getLocale();
return locale === 'zh-CN' ? 'zh-cn' : 'en';
};
const checkManagerInstance = (manager: any, name: string) => {
if (!manager) {
throw new Error(`${name} not initialized`);
}
return manager;
};
function registerIpcHandlers() {
// ==================== basic info handler ====================
ipcMain.handle('get-browser-port', () => {
log.info('Getting browser port');
return browser_port;
});
// Set browser port
ipcMain.handle(
'set-browser-port',
(event, port: number, isExternal: boolean = false) => {
log.info(`Setting browser port to ${port}, external: ${isExternal}`);
browser_port = port;
use_external_cdp = isExternal;
return { success: true, port: browser_port, use_external_cdp };
}
);
// Get external CDP flag
ipcMain.handle('get-use-external-cdp', () => {
log.info(`Getting use_external_cdp: ${use_external_cdp}`);
return use_external_cdp;
});
// ==================== CDP Browser Pool Management ====================
// Get all browsers in the pool
ipcMain.handle('get-cdp-browsers', () => {
log.debug(`[CDP POOL] GET pool (size=${cdp_browser_pool.length})`);
return cdp_browser_pool;
});
// Add browser to pool
ipcMain.handle(
'add-cdp-browser',
(event, port: number, isExternal: boolean, name?: string) => {
const existing = cdp_browser_pool.find((b) => b.port === port);
if (existing) {
log.warn(
`[CDP POOL] ADD rejected: port ${port} already exists (id=${existing.id})`
);
return {
success: false,
error: 'Browser with this port already exists',
};
}
const newBrowser: CdpBrowser = {
id: `cdp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
port,
isExternal,
name,
addedAt: Date.now(),
};
cdp_browser_pool.push(newBrowser);
saveCdpPool();
notifyCdpPoolChanged();
log.info(
`[CDP POOL] ADD: port=${port}, isExternal=${isExternal}, id=${newBrowser.id}, pool_size=${cdp_browser_pool.length}`
);
return { success: true, browser: newBrowser };
}
);
// Remove browser from pool (also closes the browser via CDP)
ipcMain.handle(
'remove-cdp-browser',
async (event, browserId: string, closeBrowser: boolean = true) => {
const index = cdp_browser_pool.findIndex((b) => b.id === browserId);
if (index === -1) {
log.warn(`[CDP POOL] REMOVE: browser not found: ${browserId}`);
return { success: false, error: 'Browser not found' };
}
const removed = cdp_browser_pool.splice(index, 1)[0];
// Close the browser via CDP (best-effort)
if (closeBrowser) {
await closeBrowserViaCdp(removed.port);
}
saveCdpPool();
notifyCdpPoolChanged();
log.info(
`[CDP POOL] REMOVE: port=${removed.port}, id=${removed.id}, closed=${closeBrowser}, pool_size=${cdp_browser_pool.length}`
);
return { success: true, browser: removed };
}
);
// Launch CDP browser with automatic port assignment
ipcMain.handle('launch-cdp-browser', async () => {
try {
// 1. Find available port (9224–9300) by checking no CDP browser is listening
// Port 9223 is reserved for the login browser
let port: number | null = null;
for (let p = 9224; p < 9300; p++) {
if (
!cdp_browser_pool.some((b) => b.port === p) &&
!(await isCdpPortAlive(p))
) {
port = p;
break;
}
}
if (port === null) {
return { success: false, error: 'No available port in 9224-9299' };
}
// 2. Find Playwright Chromium executable
const platform = process.platform;
let cacheDir: string;
if (platform === 'darwin')
cacheDir = path.join(homedir(), 'Library/Caches/ms-playwright');
else if (platform === 'linux')
cacheDir = path.join(homedir(), '.cache/ms-playwright');
else if (platform === 'win32')
cacheDir = path.join(homedir(), 'AppData/Local/ms-playwright');
else
return { success: false, error: `Unsupported platform: ${platform}` };
if (!existsSync(cacheDir)) {
return {
success: false,
error:
'Playwright Chromium not found. Please run: npx playwright install chromium',
};
}
const chromiumDirs = fs
.readdirSync(cacheDir)
.filter((d) => d.startsWith('chromium-'))
.sort()
.reverse();
if (chromiumDirs.length === 0) {
return {
success: false,
error:
'No Playwright Chromium found. Run: npx playwright install chromium',
};
}
const platformPaths: Record<string, (base: string) => string[]> = {
darwin: (base) => [
path.join(
base,
'chrome-mac-arm64/Chromium.app/Contents/MacOS/Chromium'
),
path.join(
base,
'chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing'
),
path.join(base, 'chrome-mac/Chromium.app/Contents/MacOS/Chromium'),
path.join(
base,
'chrome-mac/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing'
),
],
linux: (base) => [path.join(base, 'chrome-linux/chrome')],
win32: (base) => [
path.join(base, 'chrome-win64/chrome.exe'),
path.join(base, 'chrome-win/chrome.exe'),
],
};
let chromeExe: string | null = null;
for (const dir of chromiumDirs) {
const base = path.join(cacheDir, dir);
const candidates = platformPaths[platform](base);
const found = candidates.find((p) => existsSync(p));
if (found) {
chromeExe = found;
break;
}
}
if (!chromeExe) {
return { success: false, error: 'Chromium executable not found' };
}
// 3. Launch browser
const userDataDir = path.join(
app.getPath('userData'),
`cdp_browser_profile_${port}`
);
if (!existsSync(userDataDir)) {
await fsp.mkdir(userDataDir, { recursive: true });
}
const proc = spawn(
chromeExe,
[
`--remote-debugging-port=${port}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run',
'--no-default-browser-check',
'--disable-blink-features=AutomationControlled',
'about:blank',
],
{ detached: false, stdio: 'ignore' }
);
proc.on('error', (err) =>
log.error(`[CDP LAUNCH] Process error port=${port}: ${err}`)
);
// 4. Poll for readiness (max 5s)
let data: any = null;
const start = Date.now();
while (Date.now() - start < 5000) {
try {
const resp = await axios.get(
`http://localhost:${port}/json/version`,
{ timeout: 1000 }
);
if (resp.status === 200) {
data = resp.data;
break;
}
} catch {}
await new Promise((r) => setTimeout(r, 300));
}
if (!data) {
proc.kill();
return {
success: false,
error: `Browser not responding on port ${port} after 5s`,
};
}
// 5. Add to pool automatically
const newBrowser: CdpBrowser = {
id: `cdp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
port,
isExternal: false,
name: `Launched Browser (${port})`,
addedAt: Date.now(),
};
cdp_browser_pool.push(newBrowser);
saveCdpPool();
notifyCdpPoolChanged();
log.info(
`[CDP LAUNCH] Success: port=${port}, id=${newBrowser.id}, pool_size=${cdp_browser_pool.length}`
);
return { success: true, port, data };
} catch (err: any) {
log.error(`[CDP LAUNCH] Failed: ${err}`);
return { success: false, error: err.message };
}
});
ipcMain.handle('get-app-version', () => app.getVersion());
ipcMain.handle('get-backend-port', () => backendPort);
// ==================== restart app handler ====================
ipcMain.handle('restart-app', async () => {
log.info('[RESTART] Restarting app to apply user profile changes');
// Clean up Python process first
await cleanupPythonProcess();
// Schedule relaunch after a short delay
setTimeout(() => {
app.relaunch();
app.quit();
}, 100);
});
ipcMain.handle('restart-backend', async () => {
try {
if (backendPort) {
log.info('Restarting backend service...');
await cleanupPythonProcess();
await checkAndStartBackend();
log.info('Backend restart completed successfully');
return { success: true };
} else {
log.warn('No backend port found, starting fresh backend');
await checkAndStartBackend();
return { success: true };
}
} catch (error) {
log.error('Failed to restart backend:', error);
return { success: false, error: String(error) };
}
});
ipcMain.handle('get-system-language', getSystemLanguage);
ipcMain.handle('is-fullscreen', () => win?.isFullScreen() || false);
ipcMain.handle('get-home-dir', () => {
const platform = process.platform;
return platform === 'win32' ? process.env.USERPROFILE : process.env.HOME;
});
// ==================== command execution handler ====================
ipcMain.handle('get-email-folder-path', async (event, email: string) => {
return getEmailFolderPath(email);
});
ipcMain.handle(
'execute-command',
async (event, command: string, email: string) => {
log.info('execute-command', command);
const { MCP_REMOTE_CONFIG_DIR } = getEmailFolderPath(email);
try {
const { spawn } = await import('child_process');
const commandWithHost = command;
log.info(' start execute command:', commandWithHost);
// Parse command and arguments
const [cmd, ...args] = commandWithHost.split(' ');
log.info('start execute command:', commandWithHost.split(' '));
console.log(cmd, args);
return new Promise((resolve) => {
const child = spawn(cmd, args, {
cwd: process.cwd(),
env: { ...process.env, MCP_REMOTE_CONFIG_DIR },
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
// Realtime listen standard output
child.stdout.on('data', (data) => {
const output = data.toString();
stdout += output;
log.info('Real-time output:', output.trim());
});
// Realtime listen error output
child.stderr.on('data', (data) => {
const output = data.toString();
stderr += output;
if (output.includes('OAuth callback server running at')) {
const url = output
.split('OAuth callback server running at')[1]
.trim();
log.info('detect OAuth callback URL:', url);
// Notify frontend to callback URL
if (win && !win.isDestroyed()) {
const match = url.match(/^https?:\/\/[^:\n]+:\d+/);
const cleanedUrl = match ? match[0] : null;
log.info('cleanedUrl', cleanedUrl);
win.webContents.send('oauth-callback-url', {
url: cleanedUrl,
provider: 'notion', // TODO: can be set dynamically according to actual situation
});
}
}
if (output.includes('Press Ctrl+C to exit')) {
child.kill();
}
log.info(' real-time error output:', output.trim());
});
// Listen process exit
child.on('close', (code) => {
log.info(` command execute complete, exit code: ${code}`);
resolve({ success: code === null, stdout, stderr });
});
// Listen process error
child.on('error', (error) => {
log.error(' command execute error:', error);
resolve({ success: false, error: error.message });
});
});
} catch (error: any) {
log.error(' command execute failed:', error);
return { success: false, error: error.message };
}
}
);
ipcMain.handle('read-file-dataurl', async (event, filePath) => {
try {
const file = fs.readFileSync(filePath);
const mimeType =
mime.getType(path.extname(filePath)) || 'application/octet-stream';
return `data:${mimeType};base64,${file.toString('base64')}`;
} catch (error: any) {
log.error('Failed to read file as data URL:', filePath, error);
throw new Error(`Failed to read file: ${error.message}`);
}
});
// ==================== log export handler ====================
ipcMain.handle('export-log', async () => {
try {
let targetLogPath = logPath;
if (!fs.existsSync(targetLogPath)) {
const backupPath = getBackupLogPath();
if (fs.existsSync(backupPath)) {
targetLogPath = backupPath;