-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnode-config.js
More file actions
318 lines (281 loc) · 11.6 KB
/
node-config.js
File metadata and controls
318 lines (281 loc) · 11.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
// SmartCodePrompts/node-config.js
const path = require('path');
const fs = require('fs');
const Database = require('better-sqlite3');
const yaml = require('yaml');
const isElectron = !!process.env.ELECTRON_RUN;
const appDataPath = isElectron ? process.env.APP_DATA_PATH : __dirname;
const db = new Database(path.join(appDataPath, 'smart_code.sqlite'));
// Global config object, will be populated from the database.
// This object is exported and should be mutated, not reassigned.
let config = {};
/**
* Creates all necessary tables if they don't exist and runs migration logic
* for backward compatibility. This function defines the database schema.
*/
function create_tables () {
db.exec(`
CREATE TABLE IF NOT EXISTS projects (
path TEXT PRIMARY KEY,
is_archived INTEGER DEFAULT 0,
is_favorite INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS project_states (
project_path TEXT PRIMARY KEY,
open_folders TEXT,
selected_files TEXT,
open_tabs TEXT,
active_tab_identifier TEXT,
file_list_snapshot TEXT, /* NEW: Snapshot of all project files for reliable change detection. */
FOREIGN KEY (project_path) REFERENCES projects (path) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS file_metadata (
project_path TEXT NOT NULL,
file_path TEXT NOT NULL,
file_overview TEXT,
functions_overview TEXT,
last_analyze_update_time TEXT,
last_checksum TEXT,
PRIMARY KEY (project_path, file_path)
);
CREATE TABLE IF NOT EXISTS llms (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
context_length INTEGER,
prompt_price REAL,
completion_price REAL
);
CREATE TABLE IF NOT EXISTS app_settings (
key TEXT PRIMARY KEY,
value TEXT
);
CREATE TABLE IF NOT EXISTS llm_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
reason TEXT,
model_id TEXT,
prompt_tokens INTEGER,
completion_tokens INTEGER
);
`);
// --- Backward Compatibility & Migration Logic ---
db.transaction(() => {
const projectColumns = db.pragma("table_info('projects')");
if (!projectColumns.some(c => c.name === 'is_archived')) {
console.log("[DB Migration] Adding column 'is_archived' to table 'projects'.");
db.exec('ALTER TABLE projects ADD COLUMN is_archived INTEGER DEFAULT 0');
}
if (!projectColumns.some(c => c.name === 'is_favorite')) {
console.log("[DB Migration] Adding column 'is_favorite' to table 'projects'.");
db.exec('ALTER TABLE projects ADD COLUMN is_favorite INTEGER DEFAULT 0');
}
const projectStatesColumns = db.pragma("table_info('project_states')");
const oldTableExists = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='project_open_tabs'").get();
if (oldTableExists) {
console.log('[DB Migration] Old `project_open_tabs` table found. Migrating data...');
if (!projectStatesColumns.some(c => c.name === 'open_tabs')) {
db.exec('ALTER TABLE project_states ADD COLUMN open_tabs TEXT');
}
const projectsToMigrate = db.prepare('SELECT DISTINCT project_path FROM project_open_tabs').all();
for (const project of projectsToMigrate) {
const tabRows = db.prepare('SELECT file_path FROM project_open_tabs WHERE project_path = ?').all(project.project_path);
const newTabsData = tabRows.map(row => ({ filePath: row.file_path, viewState: null }));
db.prepare('UPDATE project_states SET open_tabs = ? WHERE project_path = ?').run(JSON.stringify(newTabsData), project.project_path);
}
db.exec('DROP TABLE project_open_tabs');
console.log('[DB Migration] Old `project_open_tabs` table dropped.');
}
if (projectStatesColumns.some(c => c.name === 'active_tab_id')) {
console.log("[DB Migration] Renaming 'active_tab_id' to 'active_tab_identifier'.");
db.exec('ALTER TABLE project_states RENAME COLUMN active_tab_id TO active_tab_identifier');
} else if (!projectStatesColumns.some(c => c.name === 'active_tab_identifier')) {
console.log("[DB Migration] Adding column 'active_tab_identifier' to table 'project_states'.");
db.exec('ALTER TABLE project_states ADD COLUMN active_tab_identifier TEXT');
}
// NEW: Migration for adding the file list snapshot column.
if (!projectStatesColumns.some(c => c.name === 'file_list_snapshot')) {
console.log("[DB Migration] Adding column 'file_list_snapshot' to table 'project_states'.");
db.exec('ALTER TABLE project_states ADD COLUMN file_list_snapshot TEXT');
}
})();
// --- END: Migration Logic ---
}
// This is used to create new project-specific settings files.
function get_default_settings_yaml() {
try {
const yamlPath = path.join(__dirname, 'default-settings.yaml');
if (!fs.existsSync(yamlPath)) {
throw new Error("default-settings.yaml does not exist.");
}
const yamlContent = fs.readFileSync(yamlPath, 'utf8');
return yamlContent;
} catch (error) {
console.error("FATAL: Could not read default-settings.yaml. Make sure the file exists in the application directory.", error);
process.exit(1);
}
}
/**
* Sets default application settings (like dark mode state).
* Uses INSERT OR IGNORE to prevent overwriting existing values.
*/
function set_default_app_settings () {
const initSettings_stmt = db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES (?, ?)");
const transaction = db.transaction(() => {
initSettings_stmt.run('dark_mode', 'false');
initSettings_stmt.run('last_selected_project', '');
initSettings_stmt.run('last_selected_llm_analysis', '');
initSettings_stmt.run('last_selected_llm_smart_prompt', '');
initSettings_stmt.run('last_selected_llm_qa', '');
initSettings_stmt.run('last_selected_llm_direct_prompt', '');
initSettings_stmt.run('last_smart_prompt', '');
initSettings_stmt.run('total_prompt_tokens', '0');
initSettings_stmt.run('total_completion_tokens', '0');
initSettings_stmt.run('right_sidebar_collapsed', 'false');
initSettings_stmt.run('file_tree_width', '300');
initSettings_stmt.run('openrouter_api_key', '');
});
transaction();
}
/**
* Loads the configuration from `app_settings` table into the global 'config' object.
* It resolves relative paths and ensures correct data types.
*/
function load_config_from_db () {
// Clear existing properties from the config object without creating a new reference.
Object.keys(config).forEach(key => delete config[key]);
const settings_rows = db.prepare('SELECT key, value FROM app_settings').all();
const new_config_data = {};
// Process settings data (all are strings)
settings_rows.forEach(row => {
new_config_data[row.key] = row.value;
});
// Mutate the original config object by copying the new properties into it.
Object.assign(config, new_config_data);
console.log('App-level configuration loaded from database.');
}
/**
* Initializes the entire database and configuration setup.
* This should be called once on server startup.
*/
function initialize_database_and_config () {
create_tables();
set_default_app_settings();
load_config_from_db();
}
/**
* Resets the LLM log and token counters in the database.
* @returns {{success: boolean}}
*/
function reset_llm_log () {
db.exec('DELETE FROM llm_log');
const stmt = db.prepare('UPDATE app_settings SET value = ? WHERE key = ?');
const transaction = db.transaction(() => {
stmt.run('0', 'total_prompt_tokens');
stmt.run('0', 'total_completion_tokens');
});
transaction();
return {success: true};
}
/**
* Sets the dark mode preference in the database.
* @param {boolean} is_dark_mode - The new dark mode state.
*/
function set_dark_mode (is_dark_mode) {
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(is_dark_mode ? 'true' : 'false', 'dark_mode');
}
/**
* Sets the right sidebar collapsed preference in the database.
* @param {boolean} is_collapsed - The new collapsed state.
*/
function setright_sidebar_collapsed (is_collapsed) {
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(is_collapsed ? 'true' : 'false', 'right_sidebar_collapsed');
}
/**
* Saves the global OpenRouter API key to the database.
* @param {string} api_key - The API key to save.
*/
function save_api_key(api_key) {
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(api_key, 'openrouter_api_key');
}
/**
* @param {string} prompt - The prompt text to save.
*/
function save_last_smart_prompt (prompt) {
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(prompt, 'last_smart_prompt');
}
/**
* @param {string|number} width - The width in pixels to save.
*/
function save_file_tree_width (width) {
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(String(width), 'file_tree_width');
}
/**
* Retrieves all data needed for the main page (index.html).
* @param {boolean} [show_archived=false] - Whether to include archived projects in the list.
* @returns {object} An object containing projects, settings, and LLMs.
*/
function get_main_page_data (show_archived = false) {
const project_query = show_archived
? 'SELECT path, is_archived, is_favorite FROM projects ORDER BY is_favorite DESC, path ASC'
: 'SELECT path, is_archived, is_favorite FROM projects WHERE is_archived = 0 ORDER BY is_favorite DESC, path ASC';
const projects = db.prepare(project_query).all();
const archived_count = db.prepare('SELECT COUNT(*) as count FROM projects WHERE is_archived = 1').get().count;
const settings = db.prepare('SELECT key, value FROM app_settings').all();
const app_settings = settings.reduce((acc, row) => {
acc[row.key] = row.value;
return acc;
}, {});
const llms = db.prepare('SELECT id, name FROM llms ORDER BY name ASC').all();
const prompt_tokens = app_settings.total_prompt_tokens || '0';
const completion_tokens = app_settings.total_completion_tokens || '0';
const cost_rows = db.prepare(`
SELECT l.prompt_tokens,
l.completion_tokens,
m.prompt_price,
m.completion_price
FROM llm_log l
LEFT JOIN llms m ON l.model_id = m.id
`).all();
let total_cost = 0;
for (const row of cost_rows) {
const prompt_price = row.prompt_price || 0;
const completion_price = row.completion_price || 0;
const prompt_cost = ((row.prompt_tokens || 0) ) * prompt_price;
const completion_cost = ((row.completion_tokens || 0) ) * completion_price;
total_cost += prompt_cost + completion_cost;
}
return {
projects,
archived_count,
last_selected_project: app_settings.last_selected_project || '',
dark_mode: app_settings.dark_mode === 'true',
right_sidebar_collapsed: app_settings.right_sidebar_collapsed === 'true',
file_tree_width: app_settings.file_tree_width || '300',
llms,
last_selected_llm_analysis: app_settings.last_selected_llm_analysis || '',
last_selected_llm_smart_prompt: app_settings.last_selected_llm_smart_prompt || '',
last_selected_llm_qa: app_settings.last_selected_llm_qa || '',
last_selected_llm_direct_prompt: app_settings.last_selected_llm_direct_prompt || '',
last_smart_prompt: app_settings.last_smart_prompt || '',
api_key_set: !!app_settings.openrouter_api_key,
session_tokens: {
prompt: parseInt(prompt_tokens, 10),
completion: parseInt(completion_tokens, 10),
cost: total_cost
},
};
}
module.exports = {
db,
config,
initialize_database_and_config,
load_config_from_db,
get_default_settings_yaml,
set_dark_mode,
setright_sidebar_collapsed,
save_api_key,
save_last_smart_prompt,
save_file_tree_width,
get_main_page_data,
reset_llm_log
};