Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
602 lines (532 loc) · 20.3 KB
/
Copy pathmain.js
File metadata and controls
602 lines (532 loc) · 20.3 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
const { app, BrowserWindow, ipcMain, dialog, clipboard, systemPreferences, session, Menu } = require('electron');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const os = require('os');
let mainWindow;
let speakProcess = null;
const dbPath = path.join(app.getPath('userData'), 'luna_db.json');
// Initialize Simple JSON Database
function loadDB() {
try {
if (fs.existsSync(dbPath)) {
const data = fs.readFileSync(dbPath, 'utf8');
return JSON.parse(data);
}
} catch (err) {
console.error('Failed to load database, resetting...', err);
}
return {};
}
function saveDB(data) {
try {
fs.writeFileSync(dbPath, JSON.stringify(data, null, 2), 'utf8');
return true;
} catch (err) {
console.error('Failed to save database', err);
return false;
}
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1100,
height: 750,
minWidth: 800,
minHeight: 600,
// Custom frameless look on macOS for premium glassmorphism
titleBarStyle: 'hiddenInset',
vibrancy: 'under-window', // macOS native vibrancy effect
visualEffectState: 'active',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
// Load the compiled frontend files directly from the dist directory.
// This prevents port conflicts with other running dev servers (like Aura Insights on port 5173).
mainWindow.loadFile(path.join(__dirname, 'dist/index.html'));
// Handle closed window
mainWindow.on('closed', () => {
mainWindow = null;
});
// Forward renderer console statements to terminal log output for troubleshooting
mainWindow.webContents.on('console-message', (event, level, message, line, sourceId) => {
console.log(`[RENDERER] ${message} (at ${path.basename(sourceId)}:${line})`);
});
}
app.whenReady().then(() => {
// Request microphone permissions on macOS system level
if (process.platform === 'darwin') {
systemPreferences.askForMediaAccess('microphone').then(accessGranted => {
console.log(`[SYSTEM] macOS Microphone Access Status: ${accessGranted}`);
}).catch(err => {
console.error('[SYSTEM] Error requesting macOS microphone access:', err);
});
}
// Approve media/microphone request permission handler for the renderer process
session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
if (permission === 'media') {
return callback(true); // Approved
}
callback(false); // Refused other permissions for security
});
// Set up custom application menu to ensure "Start Dictation" exists in the Edit menu
const template = [
{
label: 'Luna',
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
]
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'selectAll' },
{ type: 'separator' },
{ role: 'startSpeech', label: 'Start Dictation' },
{ role: 'stopSpeech', label: 'Stop Dictation' }
]
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' }
]
},
{
label: 'Window',
submenu: [
{ role: 'minimize' },
{ role: 'zoom' },
{ type: 'separator' },
{ role: 'front' }
]
}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// IPC Handler: Database Operations
ipcMain.handle('db-save', (event, { key, data }) => {
const db = loadDB();
db[key] = data;
return saveDB(db);
});
ipcMain.handle('db-load', (event, { key }) => {
const db = loadDB();
return db[key] || null;
});
ipcMain.handle('db-delete', (event, { key }) => {
const db = loadDB();
delete db[key];
return saveDB(db);
});
ipcMain.handle('db-wipe-all', () => {
return saveDB({});
});
// IPC Handler: Clipboard Shelf
ipcMain.handle('read-clipboard-text', () => {
return clipboard.readText();
});
// IPC Handler: System Information
ipcMain.handle('get-system-info', () => {
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = totalMem - freeMem;
const cpus = os.cpus();
return {
platform: process.platform,
ramUsage: {
usedGB: (usedMem / (1024 ** 3)).toFixed(1),
totalGB: (totalMem / (1024 ** 3)).toFixed(1),
percent: Math.round((usedMem / totalMem) * 100)
},
cpuCount: cpus.length,
cpuModel: cpus[0].model
};
});
// IPC Handler: Directory Selector dialog
ipcMain.handle('select-directory', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (result.canceled) {
return null;
}
return result.filePaths[0];
});
// IPC Handler: File Selector dialog
ipcMain.handle('select-file', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile']
});
if (result.canceled) {
return null;
}
const filePath = result.filePaths[0];
return {
path: filePath,
name: path.basename(filePath),
size: fs.statSync(filePath).size
};
});
// IPC Handler: Ask Permission (Native dialog fallback)
ipcMain.handle('request-permission', async (event, { title, message }) => {
const result = await dialog.showMessageBox(mainWindow, {
type: 'question',
buttons: ['Deny', 'Allow'],
defaultId: 1,
title: title || 'Permission Requested',
message: message || 'Luna is requesting permission to run a system action.'
});
return result.response === 1; // 1 represents Allow
});
// IPC Handler: System Automations Runner
ipcMain.handle('run-automation', async (event, { action, data }) => {
switch (action) {
case 'trigger-macos-dictation':
return new Promise((resolve) => {
if (process.platform !== 'darwin') {
return resolve({ success: false, error: 'Supported only on macOS' });
}
try {
if (mainWindow) {
mainWindow.focus();
}
// Natively send startSpeech: Cocoa message down macOS responder chain (requires zero accessibility permissions)
Menu.sendActionToFirstResponder('startSpeech:');
resolve({ success: true, message: 'Natively triggered dictation overlay.' });
} catch (err) {
resolve({ success: false, error: err.message });
}
});
case 'open-app':
return new Promise((resolve) => {
const rawAppName = data.appName ? data.appName.toLowerCase().trim() : '';
// Dictionary mapping common queries, aliases, and typos to exact macOS app names
const appMapping = {
'calendar': 'Calendar',
'calender': 'Calendar',
'maps': 'Maps',
'apple maps': 'Maps',
'chrome': 'Google Chrome',
'google chrome': 'Google Chrome',
'spotify': 'Spotify',
'mail': 'Mail',
'email': 'Mail',
'music': 'Music',
'apple music': 'Music',
'notes': 'Notes',
'safari': 'Safari',
'terminal': 'Terminal',
'vscode': 'Visual Studio Code',
'visual studio code': 'Visual Studio Code',
'code': 'Visual Studio Code',
'xcode': 'Xcode',
'finder': 'Finder',
'reminders': 'Reminders',
'calculator': 'Calculator'
};
const targetApp = appMapping[rawAppName] || data.appName;
// Escape quotes to prevent injections
const sanitizedAppName = targetApp.replace(/["'\\]/g, '');
exec(`open -a "${sanitizedAppName}"`, (err, stdout, stderr) => {
if (err) {
resolve({ success: false, error: err.message });
} else {
resolve({ success: true, message: `Successfully opened ${targetApp}.` });
}
});
});
case 'create-reminder':
return new Promise((resolve) => {
if (process.platform !== 'darwin') {
return resolve({ success: false, error: 'Supported only on macOS' });
}
const title = data.title;
// Escape quotes for AppleScript syntax compatibility
const escapedTitle = title.replace(/"/g, '\\"');
const appleScript = `tell application "Reminders" to make new reminder with properties {name:"${escapedTitle}"}`;
exec(`osascript -e '${appleScript}'`, (err, stdout, stderr) => {
if (err) {
console.error('[REMINDERS] AppleScript execution error:', stderr || err.message);
resolve({ success: false, error: err.message });
} else {
resolve({ success: true, message: `Added "${title}" to macOS Reminders.` });
}
});
});
case 'draft-email':
return new Promise((resolve) => {
if (process.platform !== 'darwin') {
return resolve({ success: false, error: 'Supported only on macOS' });
}
const subject = data.subject || 'New Email Draft';
const body = data.body || '';
const appleScript = `tell application "Mail" to make new outgoing message with properties {subject:"${subject.replace(/"/g, '\\"')}", content:"${body.replace(/"/g, '\\"')}", visible:true}`;
exec(`osascript -e '${appleScript}' -e 'tell application "Mail" to activate'`, (err) => {
if (err) resolve({ success: false, error: err.message });
else resolve({ success: true, message: `Created draft email about "${subject}".` });
});
});
case 'create-calendar-event':
return new Promise((resolve) => {
if (process.platform !== 'darwin') {
return resolve({ success: false, error: 'Supported only on macOS' });
}
const title = data.title || 'New Event';
const appleScript = `tell application "Calendar" to tell calendar 1 to make new event with properties {summary:"${title.replace(/"/g, '\\"')}"}`;
exec(`osascript -e '${appleScript}'`, (err) => {
if (err) resolve({ success: false, error: err.message });
else resolve({ success: true, message: `Created calendar event for "${title}".` });
});
});
case 'create-note':
return new Promise((resolve) => {
if (process.platform !== 'darwin') {
return resolve({ success: false, error: 'Supported only on macOS' });
}
const body = data.body || 'New Note';
const appleScript = `tell application "Notes" to make new note with properties {body:"${body.replace(/"/g, '\\"')}"}`;
exec(`osascript -e '${appleScript}'`, (err) => {
if (err) resolve({ success: false, error: err.message });
else resolve({ success: true, message: `Created note: "${body.slice(0, 30)}...".` });
});
});
case 'music-control':
return new Promise((resolve) => {
if (process.platform !== 'darwin') {
return resolve({ success: false, error: 'Supported only on macOS' });
}
const cmd = data.command || 'play';
const appleScript = `tell application "Music" to ${cmd}`;
exec(`osascript -e '${appleScript}'`, (err) => {
if (err) resolve({ success: false, error: err.message });
else resolve({ success: true, message: `Sent music control: ${cmd}.` });
});
});
case 'search-contacts':
return new Promise((resolve) => {
if (process.platform !== 'darwin') {
return resolve({ success: false, error: 'Supported only on macOS' });
}
const query = data.query || '';
const appleScript = `tell application "Contacts" to name of every person whose name contains "${query.replace(/"/g, '\\"')}"`;
exec(`osascript -e '${appleScript}'`, (err, stdout, stderr) => {
if (err) {
resolve({ success: false, error: err.message });
} else {
const list = stdout.trim();
resolve({ success: true, message: list ? `Found contact(s): ${list}` : `No contacts found matching "${query}".` });
}
});
});
case 'open-link':
return new Promise((resolve) => {
const url = data.url;
if (!url) return resolve({ success: false, error: 'No URL provided' });
// Sanitize characters to prevent shell escapes
const sanitizedUrl = url.replace(/[^a-zA-Z0-9.\-_:/?=&%#]/g, '');
exec(`open "${sanitizedUrl}"`, (err) => {
if (err) resolve({ success: false, error: err.message });
else resolve({ success: true, message: `Opened link in web browser: ${url}` });
});
});
case 'search-files':
return new Promise((resolve) => {
const query = data.query;
// Clean query to avoid shell injections
const sanitizedQuery = query.replace(/[^a-zA-Z0-9.\-_ ]/g, '');
// Spotlight search command (mdfind) limited to top 15 results
// Searching downloads and documents for speed
const searchPath = data.searchPath || '~/';
const cmd = `mdfind -onlyin ${searchPath} -name "${sanitizedQuery}" | head -n 15`;
exec(cmd, (err, stdout, stderr) => {
if (err) {
resolve({ success: false, error: err.message });
} else {
const files = stdout.split('\n').filter(line => line.trim().length > 0).map(filePath => {
return {
name: path.basename(filePath),
path: filePath,
dir: path.dirname(filePath)
};
});
resolve({ success: true, files });
}
});
});
case 'organize-files':
return new Promise((resolve) => {
const targetDir = data.targetDir || path.join(os.homedir(), 'Downloads');
if (!fs.existsSync(targetDir)) {
return resolve({ success: false, error: 'Directory does not exist' });
}
const categories = {
Documents: ['.pdf', '.docx', '.doc', '.txt', '.xlsx', '.xls', '.ppt', '.pptx', '.md', '.csv'],
Images: ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.heic', '.bmp'],
Code: ['.js', '.jsx', '.ts', '.tsx', '.html', '.css', '.py', '.rb', '.go', '.rs', '.json', '.c', '.cpp'],
Audios: ['.mp3', '.wav', '.m4a', '.flac', '.ogg'],
Videos: ['.mp4', '.mov', '.avi', '.mkv', '.webm'],
Archives: ['.zip', '.tar', '.gz', '.rar', '.7z', '.dmg', '.pkg']
};
try {
const files = fs.readdirSync(targetDir);
let movedCount = 0;
files.forEach(file => {
const fullPath = path.join(targetDir, file);
const stat = fs.statSync(fullPath);
// Process only files, skip directories
if (stat.isFile() && !file.startsWith('.')) {
const ext = path.extname(file).toLowerCase();
let matchedCategory = 'Others';
for (const [category, extensions] of Object.entries(categories)) {
if (extensions.includes(ext)) {
matchedCategory = category;
break;
}
}
const destDir = path.join(targetDir, matchedCategory);
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir);
}
const destPath = path.join(destDir, file);
fs.renameSync(fullPath, destPath);
movedCount++;
}
});
resolve({ success: true, message: `Organized ${movedCount} files in ${path.basename(targetDir)} into category folders.` });
} catch (err) {
resolve({ success: false, error: err.message });
}
});
case 'read-file':
return new Promise((resolve) => {
const filePath = data.filePath;
if (!fs.existsSync(filePath)) {
return resolve({ success: false, error: 'File does not exist' });
}
try {
const stat = fs.statSync(filePath);
const extension = path.extname(filePath).toLowerCase();
if (extension === '.pdf') {
const { PDFParse } = require('pdf-parse');
const dataBuffer = fs.readFileSync(filePath);
const uint8 = new Uint8Array(dataBuffer.buffer, dataBuffer.byteOffset, dataBuffer.byteLength);
const p = new PDFParse(uint8);
p.getText().then(function(pdfData) {
resolve({ success: true, content: pdfData.text, size: stat.size });
}).catch(err => {
resolve({ success: false, error: 'Failed to parse PDF: ' + err.message });
});
} else {
if (stat.size > 2 * 1024 * 1024) { // Limit to 2MB to avoid freezing
return resolve({ success: false, error: 'File size exceeds 2MB limit for summarization' });
}
const content = fs.readFileSync(filePath, 'utf8');
resolve({ success: true, content, size: stat.size });
}
} catch (err) {
resolve({ success: false, error: err.message });
}
});
default:
return Promise.resolve({ success: false, error: `Unknown automation action: ${action}` });
}
});
// Native macOS Speech Output Handler
ipcMain.handle('speak-text', async (event, { text, voice, rate }) => {
console.log(`[SYSTEM] Speak request received: "${text.slice(0, 40)}${text.length > 40 ? '...' : ''}" (voice: ${voice || 'default'}, rate: ${rate || 'default'})`);
return new Promise((resolve) => {
if (process.platform !== 'darwin') {
console.warn('[SYSTEM] Speak request rejected: Not on macOS.');
return resolve({ success: false, error: 'Supported only on macOS' });
}
// Terminate any active say process
if (speakProcess) {
try { speakProcess.kill(); } catch (e) {}
speakProcess = null;
}
exec('/usr/bin/killall say 2>/dev/null || true');
const cleanText = text.replace(/"/g, '\\"').replace(/`/g, '\\`').replace(/\$/g, '\\$');
const voiceFlag = voice ? `-v "${voice}"` : '';
const rateFlag = rate ? `-r ${rate}` : '';
speakProcess = exec(`/usr/bin/say ${voiceFlag} ${rateFlag} "${cleanText}"`, (err) => {
speakProcess = null;
if (err) {
console.error('[SYSTEM] Speech execution failed:', err.message);
resolve({ success: false, error: err.message });
} else {
console.log('[SYSTEM] Speech execution finished successfully.');
resolve({ success: true });
}
});
});
});
ipcMain.handle('stop-speaking', async () => {
if (speakProcess) {
try { speakProcess.kill(); } catch (e) {}
speakProcess = null;
}
exec('/usr/bin/killall say 2>/dev/null || true');
return { success: true };
});
ipcMain.handle('transcribe-audio', async (event, { base64Data }) => {
return new Promise((resolve) => {
try {
const fs = require('fs');
const audioBuffer = Buffer.from(base64Data, 'base64');
const tempPath = path.join(__dirname, 'temp_voice.wav');
fs.writeFileSync(tempPath, audioBuffer);
const scriptPath = path.join(__dirname, 'transcribe.swift');
const cmd = `swift "${scriptPath}" "${tempPath}"`;
exec(cmd, (err, stdout, stderr) => {
// Clean up temporary audio file
try { fs.unlinkSync(tempPath); } catch (e) {}
if (err) {
console.error('[SYSTEM] Speech-to-Text script error:', stderr || err.message);
resolve({ success: false, error: err.message });
} else {
const transcription = stdout.trim();
console.log(`[SYSTEM] Transcribed text: "${transcription}"`);
resolve({ success: true, text: transcription });
}
});
} catch (err) {
resolve({ success: false, error: err.message });
}
});
});