-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
526 lines (446 loc) · 16.6 KB
/
main.js
File metadata and controls
526 lines (446 loc) · 16.6 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
const { app, BrowserWindow, globalShortcut, ipcMain, desktopCapturer, systemPreferences, dialog, session } = require('electron');
const path = require('path');
const fs = require('fs');
// ============================================
// Load .env file (no external packages needed)
// ============================================
function loadEnv() {
const envPath = path.join(__dirname, '.env');
if (!fs.existsSync(envPath)) {
console.warn('[Config] No .env file found. Create one from .env.example');
return;
}
const lines = fs.readFileSync(envPath, 'utf-8').split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIndex = trimmed.indexOf('=');
if (eqIndex === -1) continue;
const key = trimmed.slice(0, eqIndex).trim();
const value = trimmed.slice(eqIndex + 1).trim().replace(/^["']|["']$/g, '');
if (key) process.env[key] = value;
}
console.log('[Config] .env loaded successfully');
}
loadEnv();
let homeWindow;
let mainWindow;
// ============================================
// Home Window — Setup / Briefing Screen
// ============================================
function createHomeWindow() {
homeWindow = new BrowserWindow({
width: 700,
height: 650,
minWidth: 500,
minHeight: 500,
frame: false,
transparent: true,
hasShadow: true,
vibrancy: 'under-window',
visualEffectState: 'active',
center: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
// Make visible on all workspaces including fullscreen
homeWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
// CRITICAL: Hide from screen capture/sharing
homeWindow.setContentProtection(true);
homeWindow.loadFile('home.html');
homeWindow.on('closed', () => {
homeWindow = null;
});
}
// ============================================
// Overlay Window — Main Chat Interface
// ============================================
function createOverlayWindow(contextData) {
mainWindow = new BrowserWindow({
width: 900,
height: 600,
minWidth: 600,
minHeight: 400,
frame: false,
transparent: true,
hasShadow: true,
vibrancy: 'under-window',
visualEffectState: 'active',
alwaysOnTop: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
// Position on right side of screen
const { screen } = require('electron');
const display = screen.getPrimaryDisplay();
const { width: screenWidth } = display.workAreaSize;
mainWindow.setPosition(screenWidth - 920, 80);
// Make visible on all workspaces including fullscreen
mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
// CRITICAL: Hide from screen capture/sharing
mainWindow.setContentProtection(true);
mainWindow.loadFile('index.html');
// Send context data to overlay once it's ready
mainWindow.webContents.on('did-finish-load', () => {
if (contextData) {
mainWindow.webContents.send('receive-context', contextData);
}
});
mainWindow.on('closed', () => {
mainWindow = null;
});
}
// ============================================
// App Lifecycle
// ============================================
app.whenReady().then(() => {
// ============================================
// CRITICAL: Set up display media request handler for system audio capture.
// On macOS 14.2+ (Sonoma/Tahoe), Electron must use getDisplayMedia()
// with this handler instead of getUserMedia() for desktop audio.
// ============================================
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
// Grant access to the first screen source with audio enabled
const source = sources[0];
if (source) {
console.log('[DisplayMedia] Granting access to:', source.name);
callback({ video: source, audio: 'loopback' });
} else {
console.error('[DisplayMedia] No sources found');
callback(null);
}
}).catch((err) => {
console.error('[DisplayMedia] Error:', err);
callback(null);
});
});
// Launch home window first
createHomeWindow();
// Register global hotkey: Cmd+Shift+L
const registered = globalShortcut.register('CommandOrControl+Shift+L', () => {
if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents) {
mainWindow.webContents.send('toggle-listening');
}
});
if (!registered) {
console.error('Failed to register global shortcut');
}
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createHomeWindow();
}
});
});
app.on('will-quit', () => {
globalShortcut.unregisterAll();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// ============================================
// IPC Handlers
// ============================================
// Launch overlay from home screen
ipcMain.handle('launch-overlay', async (event, contextData) => {
// Create the overlay window with context data
createOverlayWindow(contextData);
// Hide the home window (don't destroy it)
if (homeWindow && !homeWindow.isDestroyed()) {
homeWindow.hide();
}
return true;
});
// Show home window again (from overlay)
ipcMain.on('show-home', () => {
if (homeWindow && !homeWindow.isDestroyed()) {
homeWindow.show();
homeWindow.focus();
} else {
createHomeWindow();
}
});
// Desktop capture sources
ipcMain.handle('get-sources', async () => {
try {
const permissionStatus = systemPreferences.getMediaAccessStatus('screen');
console.log('Screen permission status:', permissionStatus);
if (permissionStatus !== 'granted') {
console.log('Screen recording permission not granted.');
return { error: 'permission_denied', status: permissionStatus };
}
console.log('Attempting to get desktop sources...');
const sources = await desktopCapturer.getSources({
types: ['screen', 'window'],
thumbnailSize: { width: 0, height: 0 }
});
console.log('Found sources:', sources.length);
sources.forEach(s => console.log(' -', s.name));
return { sources: sources.map(s => ({ id: s.id, name: s.name })) };
} catch (error) {
console.error('Error getting sources:', error.message);
return { error: error.message };
}
});
// Serve API keys to renderer (read from process.env, set by .env loader)
ipcMain.handle('get-api-keys', () => {
return {
groqApiKey: process.env.GROQ_API_KEY || '',
cerebrasApiKey: process.env.CEREBRAS_API_KEY || ''
};
});
ipcMain.handle('check-screen-permission', async () => {
if (process.platform === 'darwin') {
const status = systemPreferences.getMediaAccessStatus('screen');
return status === 'granted';
}
return true;
});
ipcMain.handle('request-screen-permission', async () => {
if (process.platform === 'darwin') {
try {
await desktopCapturer.getSources({ types: ['screen'] });
return true;
} catch {
return false;
}
}
return true;
});
// Window controls — work for whichever window sent the message
ipcMain.on('window-minimize', (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) win.minimize();
});
ipcMain.on('window-close', (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) win.close();
});
ipcMain.on('window-maximize', (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
if (win.isMaximized()) {
win.unmaximize();
} else {
win.maximize();
}
}
});
// Set window opacity
ipcMain.on('set-opacity', (event, opacity) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) win.setOpacity(opacity);
});
// ============================================
// Code Viewer & Detail Windows
// ============================================
let codeViewerWindow = null;
let codeDetailWindows = [];
function createCodeViewerWindow(snippets) {
// If already open, bring to front and refresh data
if (codeViewerWindow && !codeViewerWindow.isDestroyed()) {
codeViewerWindow.webContents.send('receive-snippets', snippets);
codeViewerWindow.focus();
return;
}
const { screen } = require('electron');
const display = screen.getPrimaryDisplay();
const { width: screenWidth } = display.workAreaSize;
codeViewerWindow = new BrowserWindow({
width: 320,
height: 500,
minWidth: 260,
minHeight: 300,
frame: false,
transparent: true,
hasShadow: true,
vibrancy: 'under-window',
visualEffectState: 'active',
alwaysOnTop: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
// Position to left of the main overlay
codeViewerWindow.setPosition(screenWidth - 1260, 80);
// Make visible on all workspaces
codeViewerWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
// CRITICAL: Hide from screen capture/sharing
codeViewerWindow.setContentProtection(true);
codeViewerWindow.loadFile('code-viewer.html');
codeViewerWindow.webContents.on('did-finish-load', () => {
codeViewerWindow.webContents.send('receive-snippets', snippets);
});
codeViewerWindow.on('closed', () => {
codeViewerWindow = null;
});
}
function createCodeDetailWindow(snippet) {
const { screen } = require('electron');
const display = screen.getPrimaryDisplay();
const { width: screenWidth } = display.workAreaSize;
const detailWin = new BrowserWindow({
width: 550,
height: 500,
minWidth: 350,
minHeight: 300,
frame: false,
transparent: true,
hasShadow: true,
vibrancy: 'under-window',
visualEffectState: 'active',
alwaysOnTop: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
// Position with offset for each new window
const offset = codeDetailWindows.length * 30;
detailWin.setPosition(screenWidth - 1620 + offset, 100 + offset);
// Make visible on all workspaces
detailWin.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
// CRITICAL: Hide from screen capture/sharing
detailWin.setContentProtection(true);
detailWin.loadFile('code-detail.html');
detailWin.webContents.on('did-finish-load', () => {
detailWin.webContents.send('receive-single-code', snippet);
});
detailWin.on('closed', () => {
codeDetailWindows = codeDetailWindows.filter(w => w !== detailWin);
});
codeDetailWindows.push(detailWin);
}
// IPC: Open code viewer with snippets
ipcMain.handle('open-code-viewer', async (event, snippets) => {
createCodeViewerWindow(snippets);
return true;
});
// IPC: Open single code snippet in detail window
ipcMain.handle('open-code-window', async (event, snippet) => {
createCodeDetailWindow(snippet);
return true;
});
// ============================================
// Code Compare Window (Naive vs Optimal)
// ============================================
let codeCompareWindow = null;
function createCodeCompareWindow(data) {
// Singleton — if already open, refresh data and focus
if (codeCompareWindow && !codeCompareWindow.isDestroyed()) {
codeCompareWindow.webContents.send('receive-compare-data', data);
codeCompareWindow.focus();
return;
}
const { screen } = require('electron');
const display = screen.getPrimaryDisplay();
const { width: screenWidth } = display.workAreaSize;
codeCompareWindow = new BrowserWindow({
width: 900,
height: 550,
minWidth: 600,
minHeight: 350,
frame: false,
transparent: true,
hasShadow: true,
vibrancy: 'under-window',
visualEffectState: 'active',
alwaysOnTop: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
codeCompareWindow.setPosition(Math.max(20, screenWidth - 1920), 100);
codeCompareWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
codeCompareWindow.setContentProtection(true);
codeCompareWindow.loadFile('code-compare.html');
codeCompareWindow.webContents.on('did-finish-load', () => {
codeCompareWindow.webContents.send('receive-compare-data', data);
});
codeCompareWindow.on('closed', () => {
codeCompareWindow = null;
});
}
// IPC: Open code compare window
ipcMain.handle('open-code-compare', async (event, data) => {
createCodeCompareWindow(data);
return true;
});
// ============================================
// Download Session Transcript
// ============================================
ipcMain.handle('save-transcript', async (event, content, defaultName) => {
const result = await dialog.showSaveDialog({
title: 'Save Session Transcript',
defaultPath: defaultName || 'shadow-ai-transcript.md',
filters: [
{ name: 'Markdown', extensions: ['md'] },
{ name: 'Text', extensions: ['txt'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (result.canceled || !result.filePath) {
return { success: false, reason: 'canceled' };
}
try {
fs.writeFileSync(result.filePath, content, 'utf-8');
return { success: true, path: result.filePath };
} catch (err) {
return { success: false, reason: err.message };
}
});
// ============================================
// File Parsing (PDF + DOCX) — Main Process
// ============================================
ipcMain.handle('parse-file', async (event, arrayBuffer, fileName) => {
try {
console.log(`[ParseFile] Parsing: ${fileName} (${arrayBuffer.byteLength} bytes)`);
const buffer = Buffer.from(arrayBuffer);
if (fileName.toLowerCase().endsWith('.pdf')) {
const PDFParser = require('pdf2json');
return new Promise((resolve) => {
const pdfParser = new PDFParser(null, 1);
pdfParser.on('pdfParser_dataError', errData => {
resolve({ success: false, error: errData.parserError.message || 'Error parsing PDF' });
});
pdfParser.on('pdfParser_dataReady', pdfData => {
const text = pdfParser.getRawTextContent().replace(/\r\n/g, '\n').trim();
console.log(`[ParseFile] PDF extracted: ${text.length} chars`);
if (text.length > 20) {
resolve({ success: true, text });
} else {
resolve({ success: false, error: 'Could not extract text. The PDF may be image-based.' });
}
});
pdfParser.parseBuffer(buffer);
});
}
if (fileName.toLowerCase().endsWith('.docx') || fileName.toLowerCase().endsWith('.doc')) {
const mammoth = require('mammoth');
const result = await mammoth.extractRawText({ buffer });
const text = (result.value || '').trim();
console.log(`[ParseFile] DOCX extracted: ${text.length} chars`);
if (text.length > 10) {
return { success: true, text };
}
return { success: false, error: 'Could not extract text from this document.' };
}
return { success: false, error: 'Unsupported file type' };
} catch (err) {
console.error(`[ParseFile] Error parsing ${fileName}:`, err.message);
return { success: false, error: err.message };
}
});