Repository navigation
Expand file tree
/
Copy pathmain.mjs
More file actions
2441 lines (2109 loc) · 78.2 KB
/
Copy pathmain.mjs
File metadata and controls
2441 lines (2109 loc) · 78.2 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
import { app, BrowserWindow, ipcMain, dialog, WebContentsView, Menu, shell, clipboard } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import fsSync from 'fs';
import Store from 'electron-store';
import os from 'os';
import pty from 'node-pty';
import { simpleGit } from 'simple-git';
import { lspServerManager } from './lsp-server-manager.mjs';
import { Client } from 'ssh2';
import crypto from 'crypto';
import SSHConnectionManager from './src/services/SSHConnectionManager.js';
// Get __dirname equivalent in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const store = new Store();
// Performance profiling flag
const enableProfiling = process.argv.includes('--profile');
let mainWindow = null;
if (enableProfiling) {
console.log('[PROFILING] 🎯 ENABLED - Recording performance data');
}
// SSH connection management - using proper architecture
const sshConnectionManager = new SSHConnectionManager();
const sshTerminals = new Map(); // terminalId -> { stream, connectionId }
const sshTempCredentials = new Map(); // workspaceId -> credentials
// Encryption for stored credentials
// IMPORTANT: This key is generated at runtime and changes each app restart
// This means credentials are only valid for the current session
// For production, you'd want to use a persistent key stored securely
let ENCRYPTION_KEY = null;
const ENCRYPTION_IV_LENGTH = 16;
function getEncryptionKey() {
if (!ENCRYPTION_KEY) {
// Try to load existing key from store, or create new one
const storedKey = store.get('encryptionKey');
if (storedKey) {
ENCRYPTION_KEY = Buffer.from(storedKey, 'hex');
} else {
ENCRYPTION_KEY = crypto.randomBytes(32);
store.set('encryptionKey', ENCRYPTION_KEY.toString('hex'));
}
}
return ENCRYPTION_KEY;
}
function encrypt(text) {
if (!text) return undefined;
const key = getEncryptionKey();
const iv = crypto.randomBytes(ENCRYPTION_IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
function decrypt(text) {
if (!text) return undefined;
try {
const key = getEncryptionKey();
const parts = text.split(':');
const iv = Buffer.from(parts.shift(), 'hex');
const encryptedText = parts.join(':');
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (err) {
console.error('[Decrypt] Failed to decrypt:', err.message);
return undefined;
}
}
// Browser management
const browsers = new Map(); // browserId -> WebContentsView
const browserBounds = new Map(); // Track last bounds for each browser
const workspaceBrowsers = new Map(); // Track which browsers belong to which workspace
let currentlyFocusedBrowserId = null; // Track which browser has focus (prevents event interception)
function createWindow() {
const mainWindow = new BrowserWindow({
width: 1400,
height: 900,
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
devTools: true,
},
});
mainWindow.removeMenu();
// Enable performance profiling if --profile flag is passed
if (enableProfiling) {
setTimeout(() => {
mainWindow.webContents.startProfiling();
console.log('[PROFILING] ✅ CPU profiling started');
}, 500);
}
// Prevent Ctrl+R and F5 from reloading the entire Electron app
// BUT: Only intercept when main window has focus, not when browser views are focused
mainWindow.webContents.on('before-input-event', (event, input) => {
// CRITICAL FIX: If a browser view is focused, don't intercept ANY events
// Let the WebContentsView handle all keyboard input
if (currentlyFocusedBrowserId !== null) {
return; // Don't intercept - let browser handle it
}
// Only block reload keys when main window has focus
if ((input.control || input.meta) && input.key.toLowerCase() === 'r') {
event.preventDefault();
}
if (input.key === 'F5') {
event.preventDefault();
}
});
// Clear focus tracking when main window regains focus
mainWindow.webContents.on('focus', () => {
if (currentlyFocusedBrowserId !== null) {
currentlyFocusedBrowserId = null;
}
});
// Set CSP ONLY for the main window's HTML (not for browser WebContentsView)
// This prevents the restrictive CSP from blocking external websites
mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
// Only apply CSP to our own app files (dist/index.html)
// Don't apply to external websites loaded in WebContentsView
const isAppFile = details.url.startsWith('file://');
if (isAppFile) {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
"default-src 'self'; " +
"script-src 'self'; " +
"style-src 'self' 'unsafe-inline'; " +
"font-src 'self' data:; " +
"img-src 'self' data:"
]
}
});
} else {
// External website - don't modify CSP
callback({
responseHeaders: details.responseHeaders
});
}
});
// Always load from dist folder (production build)
mainWindow.loadFile(path.join(__dirname, 'dist', 'index.html'));
// mainWindow.webContents.openDevTools(); // Uncomment for debugging
}
// IPC Handlers
ipcMain.handle('dialog:openFolder', async () => {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
});
if (!result.canceled && result.filePaths.length > 0) {
const folderPath = result.filePaths[0];
const folderName = path.basename(folderPath);
const project = {
path: folderPath,
name: folderName,
lastOpened: new Date().toISOString(),
};
// Save to recent projects
const recentProjects = store.get('recentProjects', []);
const filtered = recentProjects.filter((p) => p.path !== folderPath);
filtered.unshift(project);
store.set('recentProjects', filtered.slice(0, 10)); // Keep last 10
return project;
}
return null;
});
ipcMain.handle('store:getRecentProjects', () => {
return store.get('recentProjects', []);
});
// Workspace IPC Handlers
ipcMain.handle('workspace:getAll', () => {
return store.get('workspaces', []);
});
ipcMain.handle('workspace:save', (event, workspaces) => {
store.set('workspaces', workspaces);
// Also save to lastSession for restore functionality
store.set('lastSession', {
workspaces,
timestamp: new Date().toISOString(),
});
return true;
});
ipcMain.handle('workspace:getActive', () => {
return store.get('activeWorkspaceId', null);
});
ipcMain.handle('workspace:setActive', (event, workspaceId) => {
store.set('activeWorkspaceId', workspaceId);
return true;
});
ipcMain.handle('workspace:clear', () => {
store.set('workspaces', []);
store.set('activeWorkspaceId', null);
return true;
});
ipcMain.handle('workspace:getLastSession', () => {
return store.get('lastSession', null);
});
ipcMain.handle('workspace:restoreSession', () => {
const lastSession = store.get('lastSession', null);
if (lastSession && lastSession.workspaces) {
store.set('workspaces', lastSession.workspaces);
// Set first workspace as active
if (lastSession.workspaces.length > 0) {
store.set('activeWorkspaceId', lastSession.workspaces[0].id);
}
return lastSession.workspaces;
}
return null;
});
ipcMain.handle('fs:readDirectory', async (event, dirPath) => {
try {
// Skip if SSH path
if (dirPath && dirPath.startsWith('ssh://')) {
return [];
}
const entries = await fs.readdir(dirPath, { withFileTypes: true });
const items = await Promise.all(
entries.map(async (entry) => {
const fullPath = path.join(dirPath, entry.name);
const stats = await fs.stat(fullPath);
return {
name: entry.name,
path: fullPath,
isDirectory: entry.isDirectory(),
size: stats.size,
modified: stats.mtime,
};
})
);
// Sort: directories first, then files
return items.sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1;
if (!a.isDirectory && b.isDirectory) return 1;
return a.name.localeCompare(b.name);
});
} catch (error) {
console.error('Error reading directory:', error);
return [];
}
});
// List of text-based file extensions that are safe to open
const TEXT_FILE_EXTENSIONS = new Set([
'.txt', '.md', '.json', '.js', '.jsx', '.ts', '.tsx', '.css', '.scss', '.sass',
'.html', '.htm', '.xml', '.svg', '.vue', '.py', '.rb', '.php', '.java', '.c',
'.cpp', '.h', '.hpp', '.cs', '.go', '.rs', '.swift', '.kt', '.scala', '.sh',
'.bash', '.zsh', '.fish', '.ps1', '.yaml', '.yml', '.toml', '.ini', '.conf',
'.config', '.env', '.gitignore', '.gitattributes', '.editorconfig', '.sql',
'.graphql', '.gql', '.proto', '.dockerfile', '.r', '.lua', '.vim', '.el',
'.clj', '.ex', '.exs', '.erl', '.hrl', '.ml', '.fs', '.fsx', '.pl', '.pm',
'.t', '.cgi', '.psgi', '.rake', '.gemfile', '.podfile', '.gradle', '.sbt',
'.cmake', '.mk', '.mak', '.makefile', '.asm', '.s', '.diff', '.patch',
'.log', '.csv', '.tsv', '.properties', '.plist', '.xsd', '.dtd', '.rss',
'.atom', '.opml', '.tex', '.latex', '.bib', '.rst', '.asciidoc', '.adoc',
'.textile', '.wiki', '.mediawiki', '.org', '.markdown', '.mdown', '.mkd',
'.cjs', '.mjs', '.cts', '.mts', '.svelte'
]);
// Maximum file size to attempt reading (5MB)
const MAX_FILE_SIZE = 5 * 1024 * 1024;
ipcMain.handle('fs:readFile', async (event, filePath) => {
try {
// Get file extension
const ext = path.extname(filePath).toLowerCase();
// Check if file extension is supported
if (!TEXT_FILE_EXTENSIONS.has(ext)) {
return {
error: 'unsupported',
message: `Cannot open ${ext} files. Only text-based files are supported.`
};
}
// Check file size
const stats = await fs.stat(filePath);
if (stats.size > MAX_FILE_SIZE) {
return {
error: 'too_large',
message: `File is too large (${(stats.size / 1024 / 1024).toFixed(2)}MB). Maximum size is 5MB.`
};
}
// Read file content
const content = await fs.readFile(filePath, 'utf-8');
return { content };
} catch (error) {
console.error('Error reading file:', error);
return {
error: 'read_error',
message: `Error reading file: ${error.message}`
};
}
});
// Read file as binary (for PDFs, Word docs, Excel, etc.)
ipcMain.handle('fs:readFileBinary', async (event, filePath) => {
try {
const buffer = await fs.readFile(filePath);
return {
success: true,
data: Array.from(buffer) // Convert buffer to array for IPC transfer
};
} catch (error) {
console.error('Error reading binary file:', error);
return {
success: false,
error: error.message
};
}
});
// Write file
ipcMain.handle('fs:writeFile', async (event, filePath, content) => {
try {
await fs.writeFile(filePath, content, 'utf-8');
return { success: true };
} catch (error) {
console.error('Error writing file:', error);
return {
success: false,
error: error.message
};
}
});
// Clipboard - Get image from clipboard
ipcMain.handle('clipboard:getImage', async (event) => {
try {
const image = clipboard.readImage();
if (image.isEmpty()) {
return { success: false, error: 'No image in clipboard' };
}
// Create temp file for the image
const tempDir = path.join(app.getPath('temp'), 'swarmide-clipboard');
await fs.mkdir(tempDir, { recursive: true });
// Generate unique filename
const timestamp = Date.now();
const filename = `screenshot-${timestamp}.png`;
const filepath = path.join(tempDir, filename);
// Save PNG to temp file
const pngBuffer = image.toPNG();
await fs.writeFile(filepath, pngBuffer);
return {
success: true,
path: filepath,
filename: filename
};
} catch (error) {
console.error('Error reading clipboard image:', error);
return { success: false, error: error.message };
}
});
// File Upload - Copy file to destination
ipcMain.handle('file:upload', async (event, { sourcePath, destinationPath }) => {
try {
await fs.copyFile(sourcePath, destinationPath);
return { success: true };
} catch (error) {
console.error('Error uploading file:', error);
return { success: false, error: error.message };
}
});
// Timeline/History management (stored in .swarm/history/)
// Save a snapshot of a file
ipcMain.handle('timeline:saveSnapshot', async (event, { workspacePath, filePath, content, source = 'user' }) => {
try {
const historyDir = path.join(workspacePath, '.swarm', 'history');
await fs.mkdir(historyDir, { recursive: true });
// Create a hash of the file path for the folder name
const fileHash = crypto.createHash('md5').update(filePath).digest('hex').substring(0, 12);
const fileHistoryDir = path.join(historyDir, fileHash);
await fs.mkdir(fileHistoryDir, { recursive: true });
// Save metadata file if it doesn't exist
const metaPath = path.join(fileHistoryDir, 'meta.json');
try {
await fs.access(metaPath);
} catch {
await fs.writeFile(metaPath, JSON.stringify({ filePath }), 'utf-8');
}
// Create snapshot with timestamp
const timestamp = Date.now();
const snapshotName = `${timestamp}-${source}.snapshot`;
const snapshotPath = path.join(fileHistoryDir, snapshotName);
await fs.writeFile(snapshotPath, content, 'utf-8');
// Keep only last 100 snapshots per file
const entries = await fs.readdir(fileHistoryDir);
const snapshots = entries.filter(e => e.endsWith('.snapshot')).sort();
if (snapshots.length > 100) {
const toDelete = snapshots.slice(0, snapshots.length - 100);
for (const snap of toDelete) {
await fs.unlink(path.join(fileHistoryDir, snap));
}
}
return { success: true, timestamp };
} catch (error) {
console.error('Error saving timeline snapshot:', error);
return { success: false, error: error.message };
}
});
// Get timeline entries for a file
ipcMain.handle('timeline:getEntries', async (event, { workspacePath, filePath }) => {
try {
const historyDir = path.join(workspacePath, '.swarm', 'history');
const fileHash = crypto.createHash('md5').update(filePath).digest('hex').substring(0, 12);
const fileHistoryDir = path.join(historyDir, fileHash);
try {
await fs.access(fileHistoryDir);
} catch {
return { success: true, entries: [] };
}
const files = await fs.readdir(fileHistoryDir);
const snapshots = files.filter(f => f.endsWith('.snapshot'));
const entries = snapshots.map(snap => {
const parts = snap.replace('.snapshot', '').split('-');
const timestamp = parseInt(parts[0]);
const source = parts.slice(1).join('-') || 'unknown';
return {
id: snap,
timestamp,
source,
date: new Date(timestamp).toISOString(),
};
}).sort((a, b) => b.timestamp - a.timestamp);
return { success: true, entries };
} catch (error) {
console.error('Error getting timeline entries:', error);
return { success: false, error: error.message };
}
});
// Get snapshot content
ipcMain.handle('timeline:getSnapshot', async (event, { workspacePath, filePath, snapshotId }) => {
try {
const historyDir = path.join(workspacePath, '.swarm', 'history');
const fileHash = crypto.createHash('md5').update(filePath).digest('hex').substring(0, 12);
const snapshotPath = path.join(historyDir, fileHash, snapshotId);
const content = await fs.readFile(snapshotPath, 'utf-8');
return { success: true, content };
} catch (error) {
console.error('Error getting snapshot:', error);
return { success: false, error: error.message };
}
});
// Restore a snapshot (copy content back to original file)
ipcMain.handle('timeline:restoreSnapshot', async (event, { workspacePath, filePath, snapshotId }) => {
try {
const historyDir = path.join(workspacePath, '.swarm', 'history');
const fileHash = crypto.createHash('md5').update(filePath).digest('hex').substring(0, 12);
const snapshotPath = path.join(historyDir, fileHash, snapshotId);
const content = await fs.readFile(snapshotPath, 'utf-8');
await fs.writeFile(filePath, content, 'utf-8');
return { success: true };
} catch (error) {
console.error('Error restoring snapshot:', error);
return { success: false, error: error.message };
}
});
// Watch file for external changes (agent edits)
const fileWatchers = new Map();
ipcMain.handle('timeline:watchFile', async (event, { workspacePath, filePath }) => {
try {
const watchKey = `${workspacePath}:${filePath}`;
if (fileWatchers.has(watchKey)) {
return { success: true, message: 'Already watching' };
}
const watcher = fsSync.watch(filePath, async (eventType) => {
if (eventType === 'change') {
try {
const content = await fs.readFile(filePath, 'utf-8');
// Notify renderer about external change
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('timeline:fileChanged', { filePath, content });
}
} catch (err) {
console.error('Error reading changed file:', err);
}
}
});
fileWatchers.set(watchKey, watcher);
return { success: true };
} catch (error) {
console.error('Error watching file:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('timeline:unwatchFile', async (event, { workspacePath, filePath }) => {
try {
const watchKey = `${workspacePath}:${filePath}`;
const watcher = fileWatchers.get(watchKey);
if (watcher) {
watcher.close();
fileWatchers.delete(watchKey);
}
return { success: true };
} catch (error) {
console.error('Error unwatching file:', error);
return { success: false, error: error.message };
}
});
// Mind file management (stored in .swarm/mind/)
ipcMain.handle('mind:list', async (event, workspacePath) => {
try {
const mindDir = path.join(workspacePath, '.swarm', 'mind');
// Create directory if it doesn't exist
await fs.mkdir(mindDir, { recursive: true });
const entries = await fs.readdir(mindDir, { withFileTypes: true });
const mindFiles = entries
.filter(entry => entry.isFile() && entry.name.endsWith('.html'))
.map(entry => ({
name: entry.name.replace('.html', ''),
path: path.join(mindDir, entry.name),
}));
return { success: true, files: mindFiles };
} catch (error) {
console.error('Error listing mind files:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('mind:read', async (event, { workspacePath, name }) => {
try {
const mindPath = path.join(workspacePath, '.swarm', 'mind', `${name}.html`);
const content = await fs.readFile(mindPath, 'utf-8');
return { success: true, content };
} catch (error) {
console.error('Error reading mind file:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('mind:write', async (event, { workspacePath, name, content }) => {
try {
const mindDir = path.join(workspacePath, '.swarm', 'mind');
await fs.mkdir(mindDir, { recursive: true });
const mindPath = path.join(mindDir, `${name}.html`);
await fs.writeFile(mindPath, content, 'utf-8');
return { success: true };
} catch (error) {
console.error('Error writing mind file:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('mind:delete', async (event, { workspacePath, name }) => {
try {
const mindPath = path.join(workspacePath, '.swarm', 'mind', `${name}.html`);
await fs.unlink(mindPath);
return { success: true };
} catch (error) {
console.error('Error deleting mind file:', error);
return { success: false, error: error.message };
}
});
// Terminal management
const terminals = new Map();
// Get default shell based on OS
function getDefaultShell() {
const platform = os.platform();
if (platform === 'win32') {
return process.env.COMSPEC || 'cmd.exe';
}
// Unix-like systems
return process.env.SHELL || '/bin/bash';
}
// Create terminal
ipcMain.handle('terminal:create', (event, { cwd, terminalId }) => {
try {
const shell = getDefaultShell();
const ptyProcess = pty.spawn(shell, [], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: cwd || os.homedir(),
env: process.env,
});
terminals.set(terminalId, ptyProcess);
// Send data from PTY to renderer
ptyProcess.onData((data) => {
const window = BrowserWindow.getAllWindows()[0];
if (window) {
window.webContents.send('terminal:data', { terminalId, data });
}
});
// Handle PTY exit
ptyProcess.onExit(({ exitCode, signal }) => {
const window = BrowserWindow.getAllWindows()[0];
if (window) {
window.webContents.send('terminal:exit', { terminalId, exitCode, signal });
}
terminals.delete(terminalId);
});
return { success: true, terminalId };
} catch (error) {
console.error('Error creating terminal:', error);
return { success: false, error: error.message };
}
});
// Write to terminal
ipcMain.handle('terminal:write', (event, { terminalId, data }) => {
const terminal = terminals.get(terminalId);
if (terminal) {
terminal.write(data);
return { success: true };
}
return { success: false, error: 'Terminal not found' };
});
// Resize terminal
ipcMain.handle('terminal:resize', (event, { terminalId, cols, rows }) => {
const terminal = terminals.get(terminalId);
if (terminal) {
terminal.resize(cols, rows);
return { success: true };
}
return { success: false, error: 'Terminal not found' };
});
// Kill terminal
ipcMain.handle('terminal:kill', (event, { terminalId }) => {
const terminal = terminals.get(terminalId);
if (terminal) {
terminal.kill();
terminals.delete(terminalId);
return { success: true };
}
return { success: false, error: 'Terminal not found' };
});
// Browser IPC Handlers
ipcMain.handle('browser:create', (event, { browserId, url, workspaceId }) => {
try {
// 🔧 FIX: Prevent duplicate browser creation when tabs are dragged between panes
// Check if browser already exists in the browsers Map
if (browsers.has(browserId)) {
console.log('[browser:create] ✓ Browser already exists, skipping duplicate creation:', browserId);
return { success: true, alreadyExists: true };
}
// 🔧 PERSISTENT BROWSERS: Set up persistent session with cookies
// Use app's userData directory for persistent storage
const userDataPath = app.getPath('userData');
const browserProfilePath = path.join(userDataPath, 'browser-profiles', 'default');
const view = new WebContentsView({
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
// 🔧 FIX: Enable automatic zoom adjustment to fit content to view bounds
zoomFactor: 1.0,
// 🔧 PERSISTENT SESSION: Enable persistent cookies and storage
partition: 'persist:browserprofile', // This creates a persistent session
webSecurity: true,
}
});
// Set User-Agent to Chrome on Windows to prevent content blocking
const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
view.webContents.setUserAgent(userAgent);
// 🔧 FIX: Set visual zoom level to fit browser content within pane bounds
// This ensures web pages render at the right scale for the container
view.webContents.setVisualZoomLevelLimits(0.5, 3.0).catch(err => {
console.log('[Browser] Could not set zoom limits:', err);
});
// Prevent Ctrl+R from reloading the main Electron app (should only reload the browser page)
view.webContents.on('before-input-event', (event, input) => {
// Intercept Alt+Arrow keys for app-level navigation (tab/pane switching)
if (input.type === 'keyDown' && input.alt &&
(input.key === 'ArrowLeft' || input.key === 'ArrowRight' ||
input.key === 'ArrowUp' || input.key === 'ArrowDown')) {
console.log('[Browser] Alt+Arrow intercepted, sending to main window:', input.key);
event.preventDefault();
// Send to main window renderer for navigation
const mainWindow = BrowserWindow.getAllWindows()[0];
if (mainWindow) {
mainWindow.webContents.send('browser:keyboard-nav', {
key: input.key,
code: input.code,
altKey: true
});
}
return;
}
// Allow Ctrl+R and F5 in browser views (they reload the page, not the app)
// But prevent Ctrl+Shift+R (hard reload) to avoid confusion
if ((input.control || input.meta) && input.shift && input.key.toLowerCase() === 'r') {
console.log('[Browser] Blocked Ctrl+Shift+R hard reload');
event.preventDefault();
}
// Ctrl+R and F5 are allowed - they reload the browser page only
});
// Load the URL
view.webContents.loadURL(url).catch(err => {
console.error('Error loading URL:', err);
// Try to load error page or about:blank
view.webContents.loadURL('about:blank');
});
browsers.set(browserId, view);
// Track which workspace this browser belongs to
if (workspaceId) {
if (!workspaceBrowsers.has(workspaceId)) {
workspaceBrowsers.set(workspaceId, new Set());
}
workspaceBrowsers.get(workspaceId).add(browserId);
}
// 🔧 FIX: Handle middle-click and target="_blank" - open in new tab instead of new window
view.webContents.setWindowOpenHandler(({ url, frameName, disposition }) => {
console.log(`[Browser] Window open request: ${url}, disposition: ${disposition}`);
// disposition can be: 'new-window', 'foreground-tab', 'background-tab', 'save-to-disk', 'other'
// IMPORTANT: 'other' is often middle-click, so we need to handle it too
// Only allow 'save-to-disk' and 'current-tab' to proceed normally
if (disposition !== 'save-to-disk' && disposition !== 'current-tab') {
const mainWindow = BrowserWindow.getAllWindows()[0];
if (mainWindow) {
// Send request to renderer to create a new browser tab in the current pane
mainWindow.webContents.send('browser:open-in-tab', {
url,
sourceId: browserId,
background: disposition === 'background-tab'
});
}
// Deny the window creation - we'll handle it as a tab
return { action: 'deny' };
}
// Allow save-to-disk and current-tab dispositions
return { action: 'allow' };
});
// Navigation events - send to renderer
view.webContents.on('did-navigate', (event, url) => {
const mainWindow = BrowserWindow.getAllWindows()[0];
if (mainWindow) {
mainWindow.webContents.send('browser:navigation', {
browserId,
url,
canGoBack: view.webContents.canGoBack(),
canGoForward: view.webContents.canGoForward()
});
}
});
view.webContents.on('did-navigate-in-page', (event, url) => {
const mainWindow = BrowserWindow.getAllWindows()[0];
if (mainWindow) {
mainWindow.webContents.send('browser:navigation', {
browserId,
url,
canGoBack: view.webContents.canGoBack(),
canGoForward: view.webContents.canGoForward()
});
}
});
view.webContents.on('page-title-updated', (event, title) => {
const mainWindow = BrowserWindow.getAllWindows()[0];
if (mainWindow) {
mainWindow.webContents.send('browser:title', { browserId, title });
}
});
view.webContents.on('did-start-loading', () => {
const mainWindow = BrowserWindow.getAllWindows()[0];
if (mainWindow) {
mainWindow.webContents.send('browser:loading', { browserId, isLoading: true });
}
});
view.webContents.on('did-stop-loading', () => {
const mainWindow = BrowserWindow.getAllWindows()[0];
if (mainWindow) {
mainWindow.webContents.send('browser:loading', { browserId, isLoading: false });
}
});
// Add context menu with DevTools support
view.webContents.on('context-menu', (event, params) => {
const menuTemplate = [];
// Link-specific items
if (params.linkURL) {
menuTemplate.push(
{
label: 'Open Link in New Tab',
click: () => {
shell.openExternal(params.linkURL);
}
},
{
label: 'Copy Link Address',
click: () => {
// Note: clipboard requires importing from electron
const { clipboard } = require('electron');
clipboard.writeText(params.linkURL);
}
},
{ type: 'separator' }
);
}
// Image-specific items
if (params.mediaType === 'image') {
menuTemplate.push(
{
label: 'Open Image in New Tab',
click: () => {
shell.openExternal(params.srcURL);
}
},
{
label: 'Copy Image Address',
click: () => {
const { clipboard } = require('electron');
clipboard.writeText(params.srcURL);
}
},
{ type: 'separator' }
);
}
// Editable field items
if (params.isEditable) {
menuTemplate.push(
{
label: 'Undo',
role: 'undo'
},
{
label: 'Redo',
role: 'redo'
},
{ type: 'separator' },
{
label: 'Cut',
role: 'cut'
},
{
label: 'Copy',
role: 'copy'
},
{
label: 'Paste',
role: 'paste'
},
{
label: 'Select All',
role: 'selectAll'
},
{ type: 'separator' }
);
} else if (params.selectionText) {
// Text selected but not in editable field
menuTemplate.push(
{
label: 'Copy',
role: 'copy'
},
{ type: 'separator' }
);
}
// Standard browser actions
menuTemplate.push(
{
label: 'Back',
enabled: view.webContents.canGoBack(),
click: () => {
view.webContents.goBack();
}
},
{
label: 'Forward',
enabled: view.webContents.canGoForward(),
click: () => {
view.webContents.goForward();
}
},
{
label: 'Reload',
click: () => {
view.webContents.reload();
}
},
{ type: 'separator' }
);
// DevTools items
menuTemplate.push(
{
label: 'Inspect Element',
click: () => {
view.webContents.inspectElement(params.x, params.y);
}
},
{
label: 'Open DevTools',
click: () => {
view.webContents.openDevTools();
}
},