-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
868 lines (751 loc) · 26 KB
/
main.js
File metadata and controls
868 lines (751 loc) · 26 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
const { app, BrowserWindow, ipcMain, dialog, Menu } = require('electron');
const path = require('path');
const fs = require('fs');
// Add Ollama import
const { Ollama } = require('ollama');
// Replace sqlite3 with better-sqlite3
const Database = require('better-sqlite3');
// Keep a global reference of the window object
let mainWindow;
let db;
let ollamaClient;
let ollamaReady = false;
// Initialize Ollama and pull Mistral model
async function initOllama() {
try {
console.log('Initializing Ollama...');
// Get Ollama path and model from settings
let ollamaPath = 'http://127.0.0.1:11434'; // Changed from localhost to explicit IPv4
let aiModel = 'mistral';
try {
const pathStmt = db.prepare("SELECT value FROM settings WHERE key = 'ollamaPath'");
const pathRow = pathStmt.get();
if (pathRow && pathRow.value) {
ollamaPath = pathRow.value;
}
const modelStmt = db.prepare("SELECT value FROM settings WHERE key = 'aiModel'");
const modelRow = modelStmt.get();
if (modelRow && modelRow.value) {
aiModel = modelRow.value;
}
} catch (settingsError) {
console.log('Could not retrieve Ollama settings, using defaults:', settingsError);
}
console.log(`Using Ollama at ${ollamaPath} with model ${aiModel}`);
// Check if Ollama is installed by making a simple HTTP request
try {
const http = require('http');
const url = new URL(ollamaPath);
// Force IPv4 by using the numeric IP address
await new Promise((resolve, reject) => {
const req = http.request(
{
hostname: url.hostname === 'localhost' ? '127.0.0.1' : url.hostname,
port: url.port,
path: '/api/tags',
method: 'GET',
timeout: 5000, // 5 second timeout
family: 4 // Force IPv4
},
(res) => {
if (res.statusCode === 200) {
resolve();
} else {
reject(new Error(`Ollama server returned status code ${res.statusCode}`));
}
}
);
req.on('error', (error) => {
reject(new Error(`Cannot connect to Ollama: ${error.message}`));
});
req.on('timeout', () => {
req.destroy();
reject(new Error('Connection to Ollama timed out'));
});
req.end();
});
console.log('Ollama server is running');
} catch (connectionError) {
console.error('Ollama server connection failed:', connectionError);
throw connectionError;
}
// Create Ollama client with path from settings
ollamaClient = new Ollama({ host: ollamaPath });
// Check if Ollama is running by listing models
console.log('Checking available models...');
const models = await ollamaClient.list();
console.log('Available models:', models);
// Check if the selected model is already available
const modelExists = models.models && models.models.some(model => model.name === aiModel);
// Pull the model if it doesn't exist
if (!modelExists) {
console.log(`Pulling ${aiModel} model...`);
await ollamaClient.pull({ model: aiModel });
console.log(`${aiModel} model pulled successfully`);
} else {
console.log(`${aiModel} model already available`);
}
ollamaReady = true;
console.log('Ollama initialization complete. AI features are ready.');
} catch (error) {
console.error('Error initializing Ollama:', error);
console.error('Error details:', error.message);
ollamaReady = false;
console.log('AI features will be disabled. Please ensure Ollama is running on your system.');
}
}
// In the app.whenReady() function, let's add better error handling
app.whenReady().then(async () => {
// Initialize database
initDatabase();
// Initialize Ollama
try {
await initOllama();
} catch (error) {
console.error('Failed to initialize Ollama:', error);
ollamaReady = false;
}
// Create window
createWindow();
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// Quit when all windows are closed, except on macOS
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
});
// Handle IPC messages from renderer
ipcMain.handle('export-journal', async (event, format, data) => {
const { filePath } = await dialog.showSaveDialog({
buttonLabel: 'Export',
defaultPath: `ReflectAI-Journal.${format}`
});
if (filePath) {
fs.writeFileSync(filePath, data);
return { success: true, path: filePath };
}
return { success: false };
});
// Entry operations
ipcMain.handle('save-entry', async (event, entry) => {
try {
if (entry.id) {
// Update existing entry
const stmt = db.prepare(`
UPDATE entries
SET content = ?, mood = ?, summary = ?, sentiment = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
stmt.run(entry.content, entry.mood, entry.summary, entry.sentiment, entry.id);
return { id: entry.id };
} else {
// Create new entry
const stmt = db.prepare(`
INSERT INTO entries (date, content, mood, summary, sentiment)
VALUES (?, ?, ?, ?, ?)
`);
const result = stmt.run(entry.date, entry.content, entry.mood, entry.summary, entry.sentiment);
return { id: result.lastInsertRowid };
}
} catch (error) {
console.error('Error saving entry:', error);
throw error;
}
});
ipcMain.handle('get-entries', async (event, filters = {}) => {
try {
let query = `SELECT * FROM entries`;
const queryParams = [];
// Build WHERE clause based on filters
const whereConditions = [];
if (filters.startDate) {
whereConditions.push(`date >= ?`);
queryParams.push(filters.startDate);
}
if (filters.endDate) {
whereConditions.push(`date <= ?`);
queryParams.push(filters.endDate);
}
if (filters.mood) {
whereConditions.push(`mood = ?`);
queryParams.push(filters.mood);
}
if (filters.search) {
whereConditions.push(`content LIKE ?`);
queryParams.push(`%${filters.search}%`);
}
if (whereConditions.length > 0) {
query += ` WHERE ${whereConditions.join(' AND ')}`;
}
// Add order by
query += ` ORDER BY date DESC, created_at DESC`;
const stmt = db.prepare(query);
return stmt.all(...queryParams);
} catch (error) {
console.error('Error getting entries:', error);
throw error;
}
});
ipcMain.handle('get-entry-by-id', async (event, id) => {
try {
const stmt = db.prepare(`SELECT * FROM entries WHERE id = ?`);
return stmt.get(id) || null;
} catch (error) {
console.error('Error getting entry by id:', error);
throw error;
}
});
// Settings operations
ipcMain.handle('get-setting', async (event, key) => {
try {
const stmt = db.prepare(`SELECT value FROM settings WHERE key = ?`);
const row = stmt.get(key);
return row ? row.value : null;
} catch (error) {
console.error('Error getting setting:', error);
throw error;
}
});
ipcMain.handle('save-setting', async (event, key, value) => {
try {
const stmt = db.prepare(`
INSERT OR REPLACE INTO settings (key, value)
VALUES (?, ?)
`);
stmt.run(key, value);
return { success: true };
} catch (error) {
console.error('Error saving setting:', error);
throw error;
}
});
// Stats operations
// Add this after your other IPC handlers
ipcMain.handle('get-available-fonts', async () => {
try {
// Get system fonts - this is a simplified approach
// For Windows, we'll return a curated list of common fonts
const commonFonts = [
'Arial', 'Calibri', 'Cambria', 'Comic Sans MS', 'Courier New',
'Georgia', 'Helvetica', 'Impact', 'Segoe UI', 'Tahoma',
'Times New Roman', 'Trebuchet MS', 'Verdana'
];
return commonFonts;
} catch (error) {
console.error('Error getting available fonts:', error);
return ['Arial', 'Helvetica', 'Times New Roman']; // Fallback fonts
}
});
// Improve the stats handler to include more detailed information
ipcMain.handle('get-stats', async (event) => {
try {
const stats = {
entriesByDate: [],
moodDistribution: [],
wordCountByDate: [],
entriesPerWeekday: [],
averageEntryLength: 0,
totalEntries: 0,
streakData: { current: 0, longest: 0 }
};
// Get entry count by date
const entriesStmt = db.prepare(`
SELECT date, COUNT(*) as count
FROM entries
GROUP BY date
ORDER BY date
`);
stats.entriesByDate = entriesStmt.all();
// Get mood distribution
const moodStmt = db.prepare(`
SELECT mood, COUNT(*) as count
FROM entries
WHERE mood IS NOT NULL
GROUP BY mood
`);
stats.moodDistribution = moodStmt.all();
// Get word count over time
const wordCountStmt = db.prepare(`
SELECT date,
SUM(LENGTH(content) - LENGTH(REPLACE(content, ' ', '')) + 1) as word_count
FROM entries
GROUP BY date
ORDER BY date
`);
stats.wordCountByDate = wordCountStmt.all();
// Get entries per weekday
const weekdayStmt = db.prepare(`
SELECT strftime('%w', date) as weekday, COUNT(*) as count
FROM entries
GROUP BY weekday
ORDER BY weekday
`);
stats.entriesPerWeekday = weekdayStmt.all().map(row => {
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return {
weekday: weekdays[parseInt(row.weekday)],
count: row.count
};
});
// Get average entry length and total entries
const avgLengthStmt = db.prepare(`
SELECT COUNT(*) as total,
AVG(LENGTH(content)) as avg_length
FROM entries
`);
const avgResult = avgLengthStmt.get();
stats.averageEntryLength = Math.round(avgResult.avg_length || 0);
stats.totalEntries = avgResult.total || 0;
// Calculate streak data
if (stats.entriesByDate.length > 0) {
const dates = stats.entriesByDate.map(entry => new Date(entry.date));
dates.sort((a, b) => a - b);
let currentStreak = 1;
let longestStreak = 1;
let yesterday = new Date(dates[dates.length - 1]);
yesterday.setDate(yesterday.getDate() - 1);
// Check if the most recent entry is from today or yesterday
const today = new Date();
today.setHours(0, 0, 0, 0);
const mostRecent = new Date(dates[dates.length - 1]);
mostRecent.setHours(0, 0, 0, 0);
const isActiveStreak = (mostRecent.getTime() === today.getTime() ||
mostRecent.getTime() === yesterday.getTime());
// Calculate streaks
for (let i = dates.length - 2; i >= 0; i--) {
const current = dates[i];
const next = dates[i + 1];
// Check if dates are consecutive
const diffTime = Math.abs(next - current);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays === 1) {
currentStreak++;
longestStreak = Math.max(longestStreak, currentStreak);
} else {
currentStreak = 1;
}
}
stats.streakData = {
current: isActiveStreak ? currentStreak : 0,
longest: longestStreak
};
}
return stats;
} catch (error) {
console.error('Error getting stats:', error);
throw error;
}
});
// Add font settings handlers
ipcMain.handle('get-font-settings', async () => {
try {
const fontSettings = {
fontFamily: 'Segoe UI',
fontSize: 16,
lineHeight: 1.5
};
// Get font settings from database
try {
const fontFamilyStmt = db.prepare("SELECT value FROM settings WHERE key = 'fontFamily'");
const fontFamilyRow = fontFamilyStmt.get();
if (fontFamilyRow && fontFamilyRow.value) {
fontSettings.fontFamily = fontFamilyRow.value;
}
const fontSizeStmt = db.prepare("SELECT value FROM settings WHERE key = 'fontSize'");
const fontSizeRow = fontSizeStmt.get();
if (fontSizeRow && fontSizeRow.value) {
fontSettings.fontSize = parseInt(fontSizeRow.value);
}
const lineHeightStmt = db.prepare("SELECT value FROM settings WHERE key = 'lineHeight'");
const lineHeightRow = lineHeightStmt.get();
if (lineHeightRow && lineHeightRow.value) {
fontSettings.lineHeight = parseFloat(lineHeightRow.value);
}
} catch (error) {
console.log('Could not retrieve font settings, using defaults:', error);
}
return fontSettings;
} catch (error) {
console.error('Error getting font settings:', error);
return { fontFamily: 'Segoe UI', fontSize: 16, lineHeight: 1.5 };
}
});
ipcMain.handle('save-font-settings', async (event, settings) => {
try {
// Validate settings
if (!settings.fontFamily) settings.fontFamily = 'Segoe UI';
if (!settings.fontSize || settings.fontSize < 8) settings.fontSize = 16;
if (!settings.lineHeight || settings.lineHeight < 1) settings.lineHeight = 1.5;
// Save to database
const fontFamilyStmt = db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)");
fontFamilyStmt.run('fontFamily', settings.fontFamily);
const fontSizeStmt = db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)");
fontSizeStmt.run('fontSize', settings.fontSize.toString());
const lineHeightStmt = db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)");
lineHeightStmt.run('lineHeight', settings.lineHeight.toString());
return { success: true };
} catch (error) {
console.error('Error saving font settings:', error);
throw error;
}
});
// Add Ollama-related IPC handlers
ipcMain.handle('generate-prompt', async () => {
if (!ollamaReady || !ollamaClient) {
console.log('Ollama not ready, returning fallback prompt');
return "What's on your mind today?";
}
try {
// Get AI model from settings
let aiModel = 'mistral';
try {
const modelStmt = db.prepare("SELECT value FROM settings WHERE key = 'aiModel'");
const modelRow = modelStmt.get();
if (modelRow && modelRow.value) {
aiModel = modelRow.value;
}
} catch (error) {
console.log('Could not retrieve AI model setting, using default:', error);
}
console.log(`Generating prompt with Ollama using ${aiModel} model...`);
const response = await ollamaClient.generate({
model: aiModel,
prompt: 'Generate a single thoughtful journal prompt question that encourages self-reflection. Keep it concise and under 15 words. Only return the prompt with no additional text or quotes.',
options: {
temperature: 0.7
}
});
console.log('Prompt generated successfully');
return response.response.trim();
} catch (error) {
// Rest of the function remains the same
console.error('Error generating prompt:', error);
console.error('Error details:', error.message);
// Fallback prompts if Ollama fails
const fallbackPrompts = [
"What made you smile today?",
"What's weighing on your mind?",
"What are you grateful for today?",
"What's one thing you learned today?",
"How did you take care of yourself today?",
"What's something you're looking forward to?",
"What challenged you today?",
"Describe a moment that stood out today."
];
return fallbackPrompts[Math.floor(Math.random() * fallbackPrompts.length)];
}
});
// Add a new IPC handler to test Ollama connection
ipcMain.handle('test-ollama-connection', async (event, ollamaPath) => {
try {
// If path contains localhost, replace with 127.0.0.1
if (ollamaPath && ollamaPath.includes('localhost')) {
ollamaPath = ollamaPath.replace('localhost', '127.0.0.1');
}
const testClient = new Ollama({ host: ollamaPath });
const models = await testClient.list();
return { success: true, models: models.models };
} catch (error) {
console.error('Error testing Ollama connection:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('summarize-entry', async (event, text) => {
if (!text || text.trim().length === 0) {
console.log('Cannot summarize: Empty text provided');
return "Summary not available. Please add content to your entry first.";
}
if (!ollamaReady || !ollamaClient) {
console.log('Cannot summarize: Ollama not ready');
return "Summary not available. Please ensure Ollama is running on your system.";
}
try {
// Get AI model from settings
let aiModel = 'mistral';
try {
const modelStmt = db.prepare("SELECT value FROM settings WHERE key = 'aiModel'");
const modelRow = modelStmt.get();
if (modelRow && modelRow.value) {
aiModel = modelRow.value;
}
} catch (error) {
console.log('Could not retrieve AI model setting, using default:', error);
}
console.log(`Summarizing entry with ${aiModel} model...`);
const response = await ollamaClient.generate({
model: aiModel,
prompt: `Summarize the following journal entry in 2-3 sentences, highlighting key emotions and insights:\n\n${text}`,
options: {
temperature: 0.3
}
});
console.log('Summary generated successfully');
return response.response.trim();
} catch (error) {
console.error('Error summarizing entry:', error);
console.error('Error details:', error.message);
// Try to reconnect to Ollama
try {
console.log('Attempting to reconnect to Ollama...');
await initOllama();
if (ollamaReady) {
console.log('Reconnected to Ollama, retrying summary...');
const response = await ollamaClient.generate({
model: 'mistral',
prompt: `Summarize the following journal entry in 2-3 sentences, highlighting key emotions and insights:\n\n${text}`,
options: {
temperature: 0.3
}
});
return response.response.trim();
}
} catch (reconnectError) {
console.error('Failed to reconnect to Ollama:', reconnectError);
}
return "Unable to generate summary. Please ensure Ollama is running and try again.";
}
});
ipcMain.handle('analyze-sentiment', async (event, text) => {
if (!ollamaReady || !text) {
return "neutral";
}
try {
const response = await ollamaClient.generate({
model: 'mistral',
prompt: `Analyze the sentiment of this journal entry and respond with only one word: "positive", "negative", or "neutral".\n\n${text}`,
options: {
temperature: 0.1
}
});
const sentiment = response.response.trim().toLowerCase();
if (["positive", "negative", "neutral"].includes(sentiment)) {
return sentiment;
}
return "neutral";
} catch (error) {
console.error('Error analyzing sentiment:', error);
return "neutral";
}
});
// Add these new IPC handlers for enhanced statistics
// Get word frequency for word cloud
ipcMain.handle('get-word-frequency', async () => {
try {
const stmt = db.prepare(`
SELECT content FROM entries
WHERE date >= date('now', '-3 months')
`);
const entries = stmt.all();
const allContent = entries.map(entry => entry.content).join(' ');
// Simple word frequency analysis
const words = allContent.toLowerCase()
.replace(/[^\w\s]/g, '')
.split(/\s+/)
.filter(word => word.length > 3 && !['this', 'that', 'with', 'from', 'have', 'were', 'they', 'their', 'would', 'about', 'there'].includes(word));
const wordFreq = {};
words.forEach(word => {
wordFreq[word] = (wordFreq[word] || 0) + 1;
});
// Convert to array and sort by frequency
const result = Object.entries(wordFreq)
.map(([text, value]) => ({ text, value }))
.sort((a, b) => b.value - a.value)
.slice(0, 50); // Top 50 words
return result;
} catch (error) {
console.error('Error getting word frequency:', error);
throw error;
}
});
// Get writing times
ipcMain.handle('get-writing-times', async () => {
try {
const stmt = db.prepare(`
SELECT strftime('%H', created_at) as hour, COUNT(*) as count
FROM entries
GROUP BY hour
ORDER BY hour
`);
return stmt.all();
} catch (error) {
console.error('Error getting writing times:', error);
throw error;
}
});
// Get entry length trend
ipcMain.handle('get-entry-length-trend', async () => {
try {
const stmt = db.prepare(`
SELECT date, length(content) as length
FROM entries
ORDER BY date
`);
return stmt.all();
} catch (error) {
console.error('Error getting entry length trend:', error);
throw error;
}
});
// Get mood correlations
ipcMain.handle('get-mood-correlations', async () => {
try {
const stmt = db.prepare(`
SELECT mood, sentiment, COUNT(*) as count
FROM entries
WHERE mood IS NOT NULL AND sentiment IS NOT NULL
GROUP BY mood, sentiment
`);
return stmt.all();
} catch (error) {
console.error('Error getting mood correlations:', error);
throw error;
}
});
// Add this after your other IPC handlers
ipcMain.handle('reinitialize-ollama', async () => {
try {
console.log('Manually reinitializing Ollama...');
// First, check if Ollama is installed
let ollamaPath = 'http://127.0.0.1:11434'; // Changed from localhost to explicit IPv4
try {
const pathStmt = db.prepare("SELECT value FROM settings WHERE key = 'ollamaPath'");
const pathRow = pathStmt.get();
if (pathRow && pathRow.value) {
ollamaPath = pathRow.value;
}
} catch (error) {
console.log('Could not retrieve Ollama path setting:', error);
}
// Try to make a direct HTTP request to check if Ollama is running
const http = require('http');
const url = new URL(ollamaPath);
try {
const isRunning = await new Promise((resolve, reject) => {
const req = http.request(
{
hostname: url.hostname === 'localhost' ? '127.0.0.1' : url.hostname,
port: url.port,
path: '/api/tags',
method: 'GET',
timeout: 3000,
family: 4 // Force IPv4
},
(res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
resolve(true);
} else {
reject(new Error(`Ollama server returned status code ${res.statusCode}`));
}
});
}
);
req.on('error', (error) => {
reject(new Error(`Cannot connect to Ollama: ${error.message}`));
});
req.on('timeout', () => {
req.destroy();
reject(new Error('Connection to Ollama timed out'));
});
req.end();
});
if (!isRunning) {
return {
success: false,
message: 'Ollama server is not responding. Please make sure it is running.'
};
}
// If we get here, Ollama is running, so reinitialize
await initOllama();
return {
success: ollamaReady,
message: ollamaReady
? 'Ollama connected successfully!'
: 'Failed to initialize Ollama client. Please check your settings.'
};
} catch (error) {
console.error('Error checking Ollama server:', error);
return {
success: false,
message: `Ollama is not running: ${error.message}. Please install Ollama from https://ollama.ai/download/windows and make sure it's running.`
};
}
} catch (error) {
console.error('Error reinitializing Ollama:', error);
return {
success: false,
message: `Failed to connect to Ollama: ${error.message}`
};
}
});
// Find where you handle other database operations and add this handler
ipcMain.handle('delete-entry', async (event, id) => {
try {
// Check how other database operations are performed in your code
// If you're using better-sqlite3, the syntax would be:
const stmt = db.prepare('DELETE FROM entries WHERE id = ?');
const result = stmt.run(id);
return { success: true, id };
} catch (error) {
console.error('Error deleting entry:', error);
throw error;
}
});
// Initialize database
function initDatabase() {
try {
const userDataPath = app.getPath('userData');
const dbPath = path.join(userDataPath, 'reflectai.db');
console.log('Initializing database at:', dbPath);
// Open database with better-sqlite3
db = new Database(dbPath, { verbose: console.log });
// Create tables if they don't exist
db.exec(`
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
content TEXT NOT NULL,
mood TEXT,
summary TEXT,
sentiment TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
`);
console.log('Database initialized successfully');
} catch (error) {
console.error('Error initializing database:', error);
throw error;
}
}
// Add the createWindow function
function createWindow() {
// Create the browser window
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
Menu.setApplicationMenu(null);
// Load the index.html file
mainWindow.loadFile('index.html');
// Open DevTools in development
mainWindow.webContents.openDevTools();
// Emitted when the window is closed
mainWindow.on('closed', function () {
mainWindow = null;
});
}