forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.ts
More file actions
568 lines (486 loc) · 20.2 KB
/
db.ts
File metadata and controls
568 lines (486 loc) · 20.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
import Database from 'better-sqlite3';
import path from 'path';
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import type { ChatSession, Message, SettingsMap, TaskItem, TaskStatus, ApiProvider, CreateProviderRequest, UpdateProviderRequest } from '@/types';
const dataDir = process.env.CLAUDE_GUI_DATA_DIR || path.join(os.homedir(), '.codepilot');
const DB_PATH = path.join(dataDir, 'codepilot.db');
let db: Database.Database | null = null;
export function getDb(): Database.Database {
if (!db) {
const dir = path.dirname(DB_PATH);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Migrate from old locations if the new DB doesn't exist yet
if (!fs.existsSync(DB_PATH)) {
const home = os.homedir();
const oldPaths = [
// Old Electron userData paths (app.getPath('userData'))
path.join(home, 'Library', 'Application Support', 'CodePilot', 'codepilot.db'),
path.join(home, 'Library', 'Application Support', 'codepilot', 'codepilot.db'),
path.join(home, 'Library', 'Application Support', 'Claude GUI', 'codepilot.db'),
// Old dev-mode fallback
path.join(process.cwd(), 'data', 'codepilot.db'),
// Legacy name
path.join(home, 'Library', 'Application Support', 'CodePilot', 'claude-gui.db'),
path.join(home, 'Library', 'Application Support', 'codepilot', 'claude-gui.db'),
];
for (const oldPath of oldPaths) {
if (fs.existsSync(oldPath)) {
try {
fs.copyFileSync(oldPath, DB_PATH);
// Also copy WAL/SHM if they exist
if (fs.existsSync(oldPath + '-wal')) fs.copyFileSync(oldPath + '-wal', DB_PATH + '-wal');
if (fs.existsSync(oldPath + '-shm')) fs.copyFileSync(oldPath + '-shm', DB_PATH + '-shm');
console.log(`[db] Migrated database from ${oldPath}`);
break;
} catch (err) {
console.warn(`[db] Failed to migrate from ${oldPath}:`, err);
}
}
}
}
db = new Database(DB_PATH);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
initDb(db);
}
return db;
}
function initDb(db: Database.Database): void {
db.exec(`
CREATE TABLE IF NOT EXISTS chat_sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL DEFAULT 'New Chat',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
model TEXT NOT NULL DEFAULT '',
system_prompt TEXT NOT NULL DEFAULT '',
working_directory TEXT NOT NULL DEFAULT '',
sdk_session_id TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
role TEXT NOT NULL CHECK(role IN ('user', 'assistant')),
content TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
token_usage TEXT,
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL UNIQUE,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
title TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'in_progress', 'completed', 'failed')),
description TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS api_providers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
provider_type TEXT NOT NULL DEFAULT 'anthropic',
base_url TEXT NOT NULL DEFAULT '',
api_key TEXT NOT NULL DEFAULT '',
is_active INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
extra_env TEXT NOT NULL DEFAULT '{}',
notes TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_messages_session_id ON messages(session_id);
CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at);
CREATE INDEX IF NOT EXISTS idx_sessions_updated_at ON chat_sessions(updated_at);
CREATE INDEX IF NOT EXISTS idx_tasks_session_id ON tasks(session_id);
`);
// Run migrations for existing databases
migrateDb(db);
}
function migrateDb(db: Database.Database): void {
const columns = db.prepare("PRAGMA table_info(chat_sessions)").all() as { name: string }[];
const colNames = columns.map(c => c.name);
if (!colNames.includes('model')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN model TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('system_prompt')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN system_prompt TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('sdk_session_id')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN sdk_session_id TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('project_name')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN project_name TEXT NOT NULL DEFAULT ''");
// Backfill project_name from working_directory for existing rows
db.exec(`
UPDATE chat_sessions
SET project_name = CASE
WHEN working_directory != '' THEN REPLACE(REPLACE(working_directory, RTRIM(working_directory, REPLACE(working_directory, '/', '')), ''), '/', '')
ELSE ''
END
WHERE project_name = ''
`);
}
if (!colNames.includes('status')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN status TEXT NOT NULL DEFAULT 'active'");
}
if (!colNames.includes('mode')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN mode TEXT NOT NULL DEFAULT 'code'");
}
const msgColumns = db.prepare("PRAGMA table_info(messages)").all() as { name: string }[];
const msgColNames = msgColumns.map(c => c.name);
if (!msgColNames.includes('token_usage')) {
db.exec("ALTER TABLE messages ADD COLUMN token_usage TEXT");
}
// Ensure tasks table exists for databases created before this migration
db.exec(`
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
title TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'in_progress', 'completed', 'failed')),
description TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_tasks_session_id ON tasks(session_id);
`);
// Ensure api_providers table exists for databases created before this migration
db.exec(`
CREATE TABLE IF NOT EXISTS api_providers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
provider_type TEXT NOT NULL DEFAULT 'anthropic',
base_url TEXT NOT NULL DEFAULT '',
api_key TEXT NOT NULL DEFAULT '',
is_active INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
extra_env TEXT NOT NULL DEFAULT '{}',
notes TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
`);
// Migrate existing settings to a default provider if api_providers is empty
const providerCount = db.prepare('SELECT COUNT(*) as count FROM api_providers').get() as { count: number };
if (providerCount.count === 0) {
const tokenRow = db.prepare("SELECT value FROM settings WHERE key = 'anthropic_auth_token'").get() as { value: string } | undefined;
const baseUrlRow = db.prepare("SELECT value FROM settings WHERE key = 'anthropic_base_url'").get() as { value: string } | undefined;
if (tokenRow || baseUrlRow) {
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
db.prepare(
'INSERT INTO api_providers (id, name, provider_type, base_url, api_key, is_active, sort_order, extra_env, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(id, 'Default', 'anthropic', baseUrlRow?.value || '', tokenRow?.value || '', 1, 0, '{}', 'Migrated from settings', now, now);
}
}
}
// ==========================================
// Session Operations
// ==========================================
export function getAllSessions(): ChatSession[] {
const db = getDb();
return db.prepare('SELECT * FROM chat_sessions ORDER BY updated_at DESC').all() as ChatSession[];
}
export function getSession(id: string): ChatSession | undefined {
const db = getDb();
return db.prepare('SELECT * FROM chat_sessions WHERE id = ?').get(id) as ChatSession | undefined;
}
export function createSession(
title?: string,
model?: string,
systemPrompt?: string,
workingDirectory?: string,
mode?: string,
): ChatSession {
const db = getDb();
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
const wd = workingDirectory || '';
const projectName = path.basename(wd);
db.prepare(
'INSERT INTO chat_sessions (id, title, created_at, updated_at, model, system_prompt, working_directory, sdk_session_id, project_name, status, mode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(id, title || 'New Chat', now, now, model || '', systemPrompt || '', wd, '', projectName, 'active', mode || 'code');
return getSession(id)!;
}
export function deleteSession(id: string): boolean {
const db = getDb();
const result = db.prepare('DELETE FROM chat_sessions WHERE id = ?').run(id);
return result.changes > 0;
}
export function updateSessionTimestamp(id: string): void {
const db = getDb();
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
db.prepare('UPDATE chat_sessions SET updated_at = ? WHERE id = ?').run(now, id);
}
export function updateSessionTitle(id: string, title: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET title = ? WHERE id = ?').run(title, id);
}
export function updateSdkSessionId(id: string, sdkSessionId: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET sdk_session_id = ? WHERE id = ?').run(sdkSessionId, id);
}
export function updateSessionWorkingDirectory(id: string, workingDirectory: string): void {
const db = getDb();
const projectName = path.basename(workingDirectory);
db.prepare('UPDATE chat_sessions SET working_directory = ?, project_name = ? WHERE id = ?').run(workingDirectory, projectName, id);
}
export function updateSessionMode(id: string, mode: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET mode = ? WHERE id = ?').run(mode, id);
}
// ==========================================
// Message Operations
// ==========================================
export function getMessages(
sessionId: string,
options?: { limit?: number; beforeRowId?: number },
): { messages: Message[]; hasMore: boolean } {
const db = getDb();
const limit = options?.limit ?? 100;
const beforeRowId = options?.beforeRowId;
let rows: Message[];
if (beforeRowId) {
// Fetch `limit + 1` rows before the cursor to detect if there are more
rows = db.prepare(
'SELECT *, rowid as _rowid FROM messages WHERE session_id = ? AND rowid < ? ORDER BY rowid DESC LIMIT ?'
).all(sessionId, beforeRowId, limit + 1) as Message[];
} else {
// Fetch the most recent `limit + 1` messages
rows = db.prepare(
'SELECT *, rowid as _rowid FROM messages WHERE session_id = ? ORDER BY rowid DESC LIMIT ?'
).all(sessionId, limit + 1) as Message[];
}
const hasMore = rows.length > limit;
if (hasMore) {
rows = rows.slice(0, limit);
}
// Reverse to chronological order (ASC)
rows.reverse();
return { messages: rows, hasMore };
}
export function addMessage(
sessionId: string,
role: 'user' | 'assistant',
content: string,
tokenUsage?: string | null,
): Message {
const db = getDb();
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
db.prepare(
'INSERT INTO messages (id, session_id, role, content, created_at, token_usage) VALUES (?, ?, ?, ?, ?, ?)'
).run(id, sessionId, role, content, now, tokenUsage || null);
updateSessionTimestamp(sessionId);
return db.prepare('SELECT * FROM messages WHERE id = ?').get(id) as Message;
}
export function clearSessionMessages(sessionId: string): void {
const db = getDb();
db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
// Reset SDK session ID so next message starts fresh
db.prepare('UPDATE chat_sessions SET sdk_session_id = ? WHERE id = ?').run('', sessionId);
}
// ==========================================
// Settings Operations
// ==========================================
export function getSetting(key: string): string | undefined {
const db = getDb();
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as { value: string } | undefined;
return row?.value;
}
export function setSetting(key: string, value: string): void {
const db = getDb();
db.prepare(
'INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'
).run(key, value);
}
export function getAllSettings(): SettingsMap {
const db = getDb();
const rows = db.prepare('SELECT key, value FROM settings').all() as { key: string; value: string }[];
const settings: SettingsMap = {};
for (const row of rows) {
settings[row.key] = row.value;
}
return settings;
}
// ==========================================
// Session Status Operations
// ==========================================
export function updateSessionStatus(id: string, status: 'active' | 'archived'): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET status = ? WHERE id = ?').run(status, id);
}
// ==========================================
// Task Operations
// ==========================================
export function getTasksBySession(sessionId: string): TaskItem[] {
const db = getDb();
return db.prepare('SELECT * FROM tasks WHERE session_id = ? ORDER BY created_at ASC').all(sessionId) as TaskItem[];
}
export function getTask(id: string): TaskItem | undefined {
const db = getDb();
return db.prepare('SELECT * FROM tasks WHERE id = ?').get(id) as TaskItem | undefined;
}
export function createTask(sessionId: string, title: string, description?: string): TaskItem {
const db = getDb();
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
db.prepare(
'INSERT INTO tasks (id, session_id, title, status, description, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)'
).run(id, sessionId, title, 'pending', description || null, now, now);
return getTask(id)!;
}
export function updateTask(id: string, updates: { title?: string; status?: TaskStatus; description?: string }): TaskItem | undefined {
const db = getDb();
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
const existing = getTask(id);
if (!existing) return undefined;
const title = updates.title ?? existing.title;
const status = updates.status ?? existing.status;
const description = updates.description !== undefined ? updates.description : existing.description;
db.prepare(
'UPDATE tasks SET title = ?, status = ?, description = ?, updated_at = ? WHERE id = ?'
).run(title, status, description, now, id);
return getTask(id);
}
export function deleteTask(id: string): boolean {
const db = getDb();
const result = db.prepare('DELETE FROM tasks WHERE id = ?').run(id);
return result.changes > 0;
}
// ==========================================
// API Provider Operations
// ==========================================
export function getAllProviders(): ApiProvider[] {
const db = getDb();
return db.prepare('SELECT * FROM api_providers ORDER BY sort_order ASC, created_at ASC').all() as ApiProvider[];
}
export function getProvider(id: string): ApiProvider | undefined {
const db = getDb();
return db.prepare('SELECT * FROM api_providers WHERE id = ?').get(id) as ApiProvider | undefined;
}
export function getActiveProvider(): ApiProvider | undefined {
const db = getDb();
return db.prepare('SELECT * FROM api_providers WHERE is_active = 1 LIMIT 1').get() as ApiProvider | undefined;
}
export function createProvider(data: CreateProviderRequest): ApiProvider {
const db = getDb();
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
// Get max sort_order to append at end
const maxRow = db.prepare('SELECT MAX(sort_order) as max_order FROM api_providers').get() as { max_order: number | null };
const sortOrder = (maxRow.max_order ?? -1) + 1;
db.prepare(
'INSERT INTO api_providers (id, name, provider_type, base_url, api_key, is_active, sort_order, extra_env, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(
id,
data.name,
data.provider_type || 'anthropic',
data.base_url || '',
data.api_key || '',
0,
sortOrder,
data.extra_env || '{}',
data.notes || '',
now,
now,
);
return getProvider(id)!;
}
export function updateProvider(id: string, data: UpdateProviderRequest): ApiProvider | undefined {
const db = getDb();
const existing = getProvider(id);
if (!existing) return undefined;
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
const name = data.name ?? existing.name;
const providerType = data.provider_type ?? existing.provider_type;
const baseUrl = data.base_url ?? existing.base_url;
const apiKey = data.api_key ?? existing.api_key;
const extraEnv = data.extra_env ?? existing.extra_env;
const notes = data.notes ?? existing.notes;
const sortOrder = data.sort_order ?? existing.sort_order;
db.prepare(
'UPDATE api_providers SET name = ?, provider_type = ?, base_url = ?, api_key = ?, extra_env = ?, notes = ?, sort_order = ?, updated_at = ? WHERE id = ?'
).run(name, providerType, baseUrl, apiKey, extraEnv, notes, sortOrder, now, id);
return getProvider(id);
}
export function deleteProvider(id: string): boolean {
const db = getDb();
const result = db.prepare('DELETE FROM api_providers WHERE id = ?').run(id);
return result.changes > 0;
}
export function activateProvider(id: string): boolean {
const db = getDb();
const existing = getProvider(id);
if (!existing) return false;
const transaction = db.transaction(() => {
db.prepare('UPDATE api_providers SET is_active = 0').run();
db.prepare('UPDATE api_providers SET is_active = 1 WHERE id = ?').run(id);
});
transaction();
return true;
}
export function deactivateAllProviders(): void {
const db = getDb();
db.prepare('UPDATE api_providers SET is_active = 0').run();
}
// ==========================================
// Graceful Shutdown
// ==========================================
/**
* Close the database connection gracefully.
* In WAL mode, this ensures the WAL is checkpointed and the
* -wal/-shm files are cleaned up properly.
*/
export function closeDb(): void {
if (db) {
try {
db.close();
console.log('[db] Database closed gracefully');
} catch (err) {
console.warn('[db] Error closing database:', err);
}
db = null;
}
}
// Register shutdown handlers to close the database when the process exits.
// This prevents WAL file accumulation and potential data loss.
function registerShutdownHandlers(): void {
let shuttingDown = false;
const shutdown = (signal: string) => {
if (shuttingDown) return;
shuttingDown = true;
console.log(`[db] Received ${signal}, closing database...`);
closeDb();
};
// 'exit' fires synchronously when the process is about to exit
process.on('exit', () => shutdown('exit'));
// Handle termination signals (Docker stop, systemd, Ctrl+C, etc.)
process.on('SIGTERM', () => {
shutdown('SIGTERM');
process.exit(0);
});
process.on('SIGINT', () => {
shutdown('SIGINT');
process.exit(0);
});
// Handle Windows-specific close events
if (process.platform === 'win32') {
process.on('SIGHUP', () => {
shutdown('SIGHUP');
process.exit(0);
});
}
}
registerShutdownHandlers();