-
Notifications
You must be signed in to change notification settings - Fork 281
Expand file tree
/
Copy pathmain.js
More file actions
376 lines (315 loc) · 9.98 KB
/
main.js
File metadata and controls
376 lines (315 loc) · 9.98 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
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
},
titleBarStyle: 'hiddenInset',
backgroundColor: '#1a1a2e'
});
mainWindow.loadFile('index.html');
// Open DevTools in development
if (process.argv.includes('--enable-logging')) {
mainWindow.webContents.openDevTools();
}
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// SDK Management
let manager = null;
let currentModel = null;
let chatClient = null;
let webServiceStarted = false;
const SERVICE_PORT = 47392;
const SERVICE_URL = `http://127.0.0.1:${SERVICE_PORT}`;
let initPromise = null;
async function initializeSDK() {
if (initPromise) return initPromise;
initPromise = (async () => {
const { FoundryLocalManager } = await import('foundry-local-sdk');
manager = FoundryLocalManager.create({
appName: 'foundry_local_samples',
logLevel: 'info',
webServiceUrls: SERVICE_URL
});
// Download and register all execution providers.
let currentEp = '';
await manager.downloadAndRegisterEps((epName, percent) => {
if (epName !== currentEp) {
if (currentEp !== '') process.stdout.write('\n');
currentEp = epName;
}
process.stdout.write(`\r ${epName.padEnd(30)} ${percent.toFixed(1).padStart(5)}%`);
});
if (currentEp !== '') process.stdout.write('\n');
return manager;
})();
return initPromise;
}
function ensureWebServiceStarted() {
if (!webServiceStarted && manager) {
manager.startWebService();
webServiceStarted = true;
}
}
// IPC Handlers
ipcMain.handle('get-models', async () => {
try {
console.log('get-models: initializing SDK...');
await initializeSDK();
console.log('get-models: fetching models from catalog...');
const models = await manager.catalog.getModels();
console.log(`get-models: found ${models.length} models`);
const cachedVariants = await manager.catalog.getCachedModels();
const cachedIds = new Set(cachedVariants.map(v => v.id));
console.log(`get-models: ${cachedVariants.length} cached models`);
const result = models.map(m => ({
id: m.id,
alias: m.alias,
isCached: m.isCached,
variants: m.variants.map(v => ({
id: v.id,
alias: v.alias,
displayName: v.modelInfo.displayName || v.alias,
isCached: cachedIds.has(v.id),
fileSizeMb: v.modelInfo.fileSizeMb,
modelType: v.modelInfo.modelType,
publisher: v.modelInfo.publisher
}))
}));
console.log('get-models: returning', result.length, 'models');
return result;
} catch (error) {
console.error('Error getting models:', error);
throw error;
}
});
ipcMain.handle('download-model', async (event, modelAlias) => {
try {
await initializeSDK();
const model = await manager.catalog.getModel(modelAlias);
if (!model) throw new Error(`Model ${modelAlias} not found`);
await model.download();
return { success: true };
} catch (error) {
console.error('Error downloading model:', error);
throw error;
}
});
ipcMain.handle('load-model', async (event, modelAlias) => {
try {
await initializeSDK();
// Start web service for HTTP streaming (only once)
ensureWebServiceStarted();
// Unload current model if any
if (currentModel) {
try {
await currentModel.unload();
} catch (e) {
// Ignore unload errors
}
chatClient = null;
}
const model = await manager.catalog.getModel(modelAlias);
if (!model) throw new Error(`Model ${modelAlias} not found`);
// Download if not cached
if (!model.isCached) {
await model.download();
}
await model.load();
// Wait for model to be fully loaded before creating chat client
while (!(await model.isLoaded())) {
await new Promise(resolve => setTimeout(resolve, 100));
}
currentModel = model;
chatClient = model.createChatClient();
return { success: true, modelId: model.id };
} catch (error) {
console.error('Error loading model:', error);
throw error;
}
});
ipcMain.handle('unload-model', async () => {
try {
if (currentModel) {
await currentModel.unload();
currentModel = null;
chatClient = null;
}
return { success: true };
} catch (error) {
console.error('Error unloading model:', error);
throw error;
}
});
ipcMain.handle('delete-model', async (event, modelAlias) => {
try {
await initializeSDK();
const model = await manager.catalog.getModel(modelAlias);
if (!model) throw new Error(`Model ${modelAlias} not found`);
// Unload if currently loaded
if (currentModel && currentModel.alias === modelAlias) {
await currentModel.unload();
currentModel = null;
chatClient = null;
}
model.removeFromCache();
return { success: true };
} catch (error) {
console.error('Error deleting model:', error);
throw error;
}
});
ipcMain.handle('chat', async (event, messages) => {
if (!currentModel) throw new Error('No model loaded');
const startTime = performance.now();
let firstTokenTime = null;
let tokenCount = 0;
let fullContent = '';
// Use HTTP streaming to avoid koffi callback issues with Electron
const response = await fetch(`${SERVICE_URL}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: currentModel.id,
messages,
stream: true
})
});
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split('\n').filter(line => line.startsWith('data: '));
for (const line of lines) {
const data = line.slice(6); // Remove 'data: ' prefix
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
if (firstTokenTime === null) {
firstTokenTime = performance.now();
}
tokenCount++;
fullContent += content;
mainWindow.webContents.send('chat-chunk', {
content,
tokenCount,
timeToFirstToken: firstTokenTime ? (firstTokenTime - startTime) : null
});
}
} catch (e) {
// Skip invalid JSON chunks
}
}
}
const endTime = performance.now();
const totalTime = endTime - startTime;
const tokensPerSecond = tokenCount > 0 ? (tokenCount / (totalTime / 1000)).toFixed(2) : 0;
return {
content: fullContent,
stats: {
tokenCount,
timeToFirstToken: firstTokenTime ? Math.round(firstTokenTime - startTime) : 0,
totalTime: Math.round(totalTime),
tokensPerSecond: parseFloat(tokensPerSecond)
}
};
});
ipcMain.handle('get-loaded-model', async () => {
if (!currentModel) return null;
return {
id: currentModel.id,
alias: currentModel.alias
};
});
// Transcription handlers
ipcMain.handle('get-whisper-models', async () => {
await initializeSDK();
const models = await manager.catalog.getModels();
return models
.filter(m => m.alias.toLowerCase().includes('whisper'))
.map(m => ({
alias: m.alias,
isCached: m.isCached,
fileSizeMb: m.variants[0]?.modelInfo?.fileSizeMb
}));
});
ipcMain.handle('download-whisper-model', async (event, modelAlias) => {
await initializeSDK();
const model = await manager.catalog.getModel(modelAlias);
if (!model) throw new Error(`Model ${modelAlias} not found`);
await model.download();
return { success: true };
});
ipcMain.handle('transcribe-audio', async (event, audioFilePath, base64Data) => {
await initializeSDK();
ensureWebServiceStarted();
// Use OS temp directory
const tempDir = os.tmpdir();
const tempFilePath = path.join(tempDir, `foundry_audio_${Date.now()}.wav`);
// Write audio data to temp file
const audioBuffer = Buffer.from(base64Data, 'base64');
fs.writeFileSync(tempFilePath, audioBuffer);
try {
// Find a cached whisper model
const models = await manager.catalog.getModels();
const whisperModels = models.filter(m =>
m.alias.toLowerCase().includes('whisper') && m.isCached
);
if (whisperModels.length === 0) {
throw new Error('No whisper model downloaded');
}
// Use the smallest cached whisper model
const selectedModel = whisperModels.sort((a, b) => {
const sizeA = a.variants[0]?.modelInfo?.fileSizeMb || 0;
const sizeB = b.variants[0]?.modelInfo?.fileSizeMb || 0;
return sizeA - sizeB;
})[0];
// Load whisper model
const whisperModel = await manager.catalog.getModel(selectedModel.alias);
await whisperModel.load();
// Wait for model to be loaded
while (!(await whisperModel.isLoaded())) {
await new Promise(resolve => setTimeout(resolve, 100));
}
// Create audio client and transcribe
const audioClient = whisperModel.createAudioClient();
const result = await audioClient.transcribe(tempFilePath);
// Unload whisper model
await whisperModel.unload();
return result;
} finally {
// Clean up temp file
try {
fs.unlinkSync(tempFilePath);
} catch (e) {
// Ignore cleanup errors
}
}
});