-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathvite.config.ts
More file actions
1901 lines (1747 loc) · 83 KB
/
vite.config.ts
File metadata and controls
1901 lines (1747 loc) · 83 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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { defineConfig, type Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { spawn, execSync, type ChildProcess } from 'child_process'
import { existsSync, readdirSync, createWriteStream, mkdirSync, statSync } from 'fs'
import { resolve, join, basename } from 'path'
import https from 'https'
import http from 'http'
import { config } from 'dotenv'
import { fileURLToPath } from 'url'
import { dirname } from 'path'
import os from 'os'
// Load .env file from project root
const __dirname = dirname(fileURLToPath(import.meta.url))
config({ path: resolve(__dirname, '.env') })
function findComfyUI(): string | null {
// 1. Check .env / environment variable
const envPath = process.env.COMFYUI_PATH
console.log(`[ComfyUI] COMFYUI_PATH env: ${envPath || '(not set)'}`)
if (envPath) {
// Try the path directly (handles spaces in paths)
const mainPy = join(envPath, 'main.py')
console.log(`[ComfyUI] Checking: ${mainPy} -> ${existsSync(mainPy)}`)
if (existsSync(mainPy)) return envPath
}
const home = process.env.USERPROFILE || process.env.HOME || ''
// 2. Check common locations
const fixed = [
resolve(home, 'ComfyUI'),
resolve(home, 'Desktop/ComfyUI'),
resolve(home, 'Documents/ComfyUI'),
'C:\\ComfyUI',
]
for (const p of fixed) {
if (existsSync(resolve(p, 'main.py'))) return p
}
// 3. Recursive scan Desktop, Documents, and drive roots (up to 4 levels deep)
const scanRoots = [
resolve(home, 'Desktop'),
resolve(home, 'Documents'),
resolve(home, 'Downloads'),
...(process.platform === 'win32' ? ['C:\\', 'D:\\'] : ['/opt', '/usr/local']),
]
const skipNames = new Set(['node_modules', '.git', '__pycache__', 'venv', '.venv', 'site-packages', 'Windows', 'Program Files', 'Program Files (x86)', '$Recycle.Bin', 'AppData'])
function scanForComfyUI(dir: string, depth: number): string | null {
if (depth <= 0) return null
try {
const entries = readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
if (!entry.isDirectory() || entry.name.startsWith('.') || skipNames.has(entry.name)) continue
const full = join(dir, entry.name)
// Check if this directory IS ComfyUI (has main.py + folder named ComfyUI or contains comfy-specific files)
if (entry.name === 'ComfyUI' || entry.name === 'comfyui') {
if (existsSync(join(full, 'main.py'))) return full
}
// Recurse deeper
const found = scanForComfyUI(full, depth - 1)
if (found) return found
}
} catch { /* skip unreadable dirs */ }
return null
}
for (const root of scanRoots) {
if (!existsSync(root)) continue
const found = scanForComfyUI(root, 4)
if (found) return found
}
return null
}
// Shared Python binary resolver — filters Windows Store alias, caches result
const pythonBin = (() => {
if (process.platform !== 'win32') return 'python3'
try {
const paths = execSync('where python', { encoding: 'utf8' }).trim().split('\n')
const real = paths.find((p: string) => !p.includes('WindowsApps'))
return real ? real.trim() : 'python'
} catch { return 'python' }
})()
console.log(`[Python] Resolved: ${pythonBin}`)
function isComfyRunning(): Promise<boolean> {
return fetch('http://localhost:8188/system_stats')
.then(r => r.ok)
.catch(() => false)
}
function comfyLauncher(): Plugin {
let comfyProcess: ChildProcess | null = null
let comfyLogs: string[] = []
const startComfy = (comfyPath: string): { status: string; path: string } => {
if (comfyProcess && !comfyProcess.killed) {
return { status: 'already_running', path: comfyPath }
}
comfyLogs = []
console.log(`[ComfyUI] Spawning ${pythonBin} in: ${comfyPath}`)
comfyProcess = spawn(pythonBin, ['main.py', '--listen', '127.0.0.1', '--port', '8188'], {
cwd: comfyPath,
stdio: ['ignore', 'pipe', 'pipe'],
shell: false,
windowsHide: true,
})
comfyProcess.stdout?.on('data', (d) => {
const line = d.toString()
comfyLogs.push(line)
if (comfyLogs.length > 200) comfyLogs.shift()
})
comfyProcess.stderr?.on('data', (d) => {
const line = d.toString()
comfyLogs.push(line)
if (comfyLogs.length > 200) comfyLogs.shift()
})
comfyProcess.on('exit', () => { comfyProcess = null })
console.log(`[ComfyUI] Starting from: ${comfyPath}`)
return { status: 'started', path: comfyPath }
}
const stopComfy = () => {
if (comfyProcess && !comfyProcess.killed) {
// Kill process tree on Windows
try {
if (process.platform === 'win32' && comfyProcess.pid) {
execSync(`taskkill /pid ${comfyProcess.pid} /T /F`, { stdio: 'ignore' })
} else {
comfyProcess.kill('SIGTERM')
}
} catch { /* already dead */ }
comfyProcess = null
console.log('[ComfyUI] Stopped')
}
}
return {
name: 'comfy-launcher',
configureServer(server) {
// --- Security Middleware ---
server.middlewares.use('/local-api', (req, res, next) => {
// Exclude GET proxy-image/download from strict header checks (used in <img> tags and simple fetches)
if (req.method === 'GET' && (req.url?.startsWith('/proxy-image') || req.url?.startsWith('/proxy-download'))) {
return next();
}
// 1. Strict Content-Type enforcement for POST requests
if (req.method === 'POST') {
const contentType = req.headers['content-type'] || '';
if (!contentType.includes('application/json')) {
res.writeHead(415, { 'Content-Type': 'text/plain' });
res.end('Unsupported Media Type: Must be application/json');
return;
}
}
// 2. Custom Header Requirement (CSRF Protection)
if (req.headers['x-locally-uncensored'] !== 'true') {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden: Missing x-locally-uncensored header (CSRF Protection)');
return;
}
// 3. Strict Origin Validation (Defense in Depth)
const origin = req.headers.origin;
if (origin) {
const allowedOrigins = ['http://localhost:5173', 'http://127.0.0.1:5173', 'tauri://localhost', 'http://tauri.localhost'];
if (!allowedOrigins.includes(origin)) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden: Invalid Origin (CSRF Protection)');
return;
}
}
next();
});
// Auto-start Ollama when dev server starts
try {
execSync('tasklist /FI "IMAGENAME eq ollama.exe" | find /I "ollama.exe"', { stdio: 'ignore' })
console.log('[Ollama] Already running')
} catch {
console.log('[Ollama] Starting...')
try {
const ollamaProc = spawn('ollama', ['serve'], {
detached: true,
stdio: 'ignore',
shell: false,
windowsHide: true,
})
ollamaProc.unref()
console.log('[Ollama] Started')
} catch (err) {
console.warn('[Ollama] Failed to start:', err)
}
}
// Auto-start ComfyUI when dev server starts
setTimeout(async () => {
try {
const running = await isComfyRunning()
if (!running) {
const comfyPath = findComfyUI()
if (comfyPath) {
console.log(`[ComfyUI] Auto-starting from: ${comfyPath}`)
const result = startComfy(comfyPath)
console.log(`[ComfyUI] Start result: ${result.status}`)
} else {
console.log('[ComfyUI] Not found. Set COMFYUI_PATH in .env or install ComfyUI.')
}
} else {
console.log('[ComfyUI] Already running on port 8188')
}
} catch (err) {
console.error('[ComfyUI] Auto-start error:', err)
}
}, 1000)
// Auto-stop ComfyUI when dev server closes
server.httpServer?.on('close', stopComfy)
process.on('exit', stopComfy)
process.on('SIGINT', () => { stopComfy(); process.exit() })
process.on('SIGTERM', () => { stopComfy(); process.exit() })
// API: ComfyUI POST proxy (workaround for Vite 8 blocking POST via proxy)
server.middlewares.use('/comfyui', (req, res, next) => {
if (req.method !== 'POST') return next()
const targetPath = (req.url || '').replace(/^\/comfyui/, '') || '/'
let body = ''
req.on('data', (chunk: any) => { body += chunk })
req.on('end', () => {
const proxyReq = http.request({
hostname: '127.0.0.1',
port: 8188,
path: targetPath,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}, (proxyRes) => {
const chunks: Buffer[] = []
proxyRes.on('data', (c: Buffer) => chunks.push(c))
proxyRes.on('end', () => {
const responseBody = Buffer.concat(chunks).toString()
res.writeHead(proxyRes.statusCode || 500, {
'Content-Type': proxyRes.headers['content-type'] || 'application/json',
})
res.end(responseBody)
})
})
proxyReq.on('error', (err) => {
res.writeHead(502, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: err.message }))
})
proxyReq.write(body)
proxyReq.end()
})
})
// API: Privacy image proxy — prevents external servers from tracking users
server.middlewares.use('/local-api/proxy-image', (req, res) => {
const imgUrl = new URL(req.url || '', 'http://localhost').searchParams.get('url')
if (!imgUrl) { res.writeHead(400); res.end(); return }
const proto = imgUrl.startsWith('https') ? https : http
proto.get(imgUrl, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (upstream) => {
if (upstream.statusCode && upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
proto.get(upstream.headers.location, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (redir) => {
res.writeHead(redir.statusCode || 200, {
'Content-Type': redir.headers['content-type'] || 'image/jpeg',
'Cache-Control': 'public, max-age=86400',
})
redir.pipe(res)
}).on('error', () => { res.writeHead(502); res.end() })
return
}
res.writeHead(upstream.statusCode || 200, {
'Content-Type': upstream.headers['content-type'] || 'image/jpeg',
'Cache-Control': 'public, max-age=86400',
})
upstream.pipe(res)
}).on('error', () => { res.writeHead(502); res.end() })
})
// API: Proxy download (follows redirects server-side, avoids CORS)
server.middlewares.use('/local-api/proxy-download', (req, res) => {
const url = new URL(req.url || '', 'http://localhost').searchParams.get('url')
if (!url) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Missing url parameter' }))
return
}
const protocol = url.startsWith('https') ? https : http
const fetchUrl = (targetUrl: string, redirectCount = 0) => {
if (redirectCount > 5) {
res.writeHead(502, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Too many redirects' }))
return
}
protocol.get(targetUrl, { headers: { 'User-Agent': 'LocallyUncensored/1.0' } }, (upstream) => {
if (upstream.statusCode && upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
fetchUrl(upstream.headers.location, redirectCount + 1)
return
}
res.writeHead(upstream.statusCode || 200, {
'Content-Type': upstream.headers['content-type'] || 'application/octet-stream',
'Content-Length': upstream.headers['content-length'] || '',
})
upstream.pipe(res)
}).on('error', (err) => {
res.writeHead(502, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: err.message }))
})
}
fetchUrl(url)
})
// API: Manual start
server.middlewares.use('/local-api/start-comfyui', async (_req, res) => {
const alreadyRunning = await isComfyRunning()
if (alreadyRunning) {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'already_running' }))
return
}
const comfyPath = findComfyUI()
if (!comfyPath) {
res.writeHead(404, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'not_found', message: 'ComfyUI not found. Set COMFYUI_PATH in .env file.' }))
return
}
try {
const result = startComfy(comfyPath)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(result))
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'error', message: String(err) }))
}
})
// API: Stop
server.middlewares.use('/local-api/stop-comfyui', (_req, res) => {
stopComfy()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'stopped' }))
})
// ─── Model Download Manager ───
const activeDownloads = new Map<string, { progress: number; total: number; speed: number; filename: string; status: string; error?: string }>()
function downloadFile(url: string, destPath: string, id: string): Promise<void> {
return new Promise((promiseResolve, promiseReject) => {
const filename = basename(destPath)
activeDownloads.set(id, { progress: 0, total: 0, speed: 0, filename, status: 'connecting' })
const doRequest = (requestUrl: string, redirectCount = 0) => {
if (redirectCount > 5) { promiseReject(new Error('Too many redirects')); return }
const proto = requestUrl.startsWith('https') ? https : http
proto.get(requestUrl, { headers: { 'User-Agent': 'LocallyUncensored/1.1' } }, (response) => {
if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
doRequest(response.headers.location, redirectCount + 1)
return
}
if (response.statusCode !== 200) {
activeDownloads.set(id, { ...activeDownloads.get(id)!, status: 'error', error: `HTTP ${response.statusCode}` })
promiseReject(new Error(`HTTP ${response.statusCode}`))
return
}
const total = parseInt(response.headers['content-length'] || '0', 10)
let downloaded = 0
let lastTime = Date.now()
let lastBytes = 0
const dir = dirname(destPath)
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
const file = createWriteStream(destPath)
activeDownloads.set(id, { progress: 0, total, speed: 0, filename, status: 'downloading' })
response.on('data', (chunk: Buffer) => {
downloaded += chunk.length
const now = Date.now()
const dt = (now - lastTime) / 1000
if (dt >= 1) {
const speed = (downloaded - lastBytes) / dt
lastTime = now
lastBytes = downloaded
activeDownloads.set(id, { progress: downloaded, total, speed, filename, status: 'downloading' })
}
})
response.pipe(file)
file.on('finish', () => {
file.close()
activeDownloads.set(id, { progress: total || downloaded, total: total || downloaded, speed: 0, filename, status: 'complete' })
console.log(`[Download] Complete: ${filename}`)
promiseResolve()
})
file.on('error', (err) => {
activeDownloads.set(id, { ...activeDownloads.get(id)!, status: 'error', error: err.message })
promiseReject(err)
})
}).on('error', (err) => {
activeDownloads.set(id, { ...activeDownloads.get(id)!, status: 'error', error: err.message })
promiseReject(err)
})
}
doRequest(url)
})
}
// API: Start a model download
server.middlewares.use('/local-api/download-model', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
const { url, subfolder, filename, expectedBytes } = JSON.parse(body)
if (!url || !subfolder || !filename) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Missing url, subfolder, or filename' }))
return
}
const comfyPath = findComfyUI()
if (!comfyPath) {
res.writeHead(404, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'ComfyUI not found' }))
return
}
const destDir = subfolder.startsWith('custom_nodes/') || subfolder.startsWith('custom_nodes\\')
? join(comfyPath, subfolder)
: join(comfyPath, 'models', subfolder)
const destPath = join(destDir, filename)
if (existsSync(destPath)) {
// Validate file size if expectedBytes provided (catch partial downloads)
let fileComplete = true
if (expectedBytes && expectedBytes > 0) {
try {
const actual = statSync(destPath).size
const threshold = expectedBytes * 0.9
fileComplete = actual >= threshold
if (!fileComplete) {
console.log(`[Download] File ${filename} is incomplete: ${actual} bytes vs ${expectedBytes} expected (${Math.round(actual / expectedBytes * 100)}%)`)
}
} catch { fileComplete = true }
}
if (fileComplete) {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'exists', id: filename }))
return
}
// Fall through to re-download incomplete file
}
const id = filename
console.log(`[Download] Starting: ${filename} → ${destDir}`)
downloadFile(url, destPath, id).catch(err => console.error(`[Download] Failed: ${err.message}`))
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'started', id }))
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: String(err) }))
}
})
})
// API: Download progress
server.middlewares.use('/local-api/download-progress', (_req, res) => {
const downloads: Record<string, any> = {}
for (const [id, info] of activeDownloads.entries()) {
downloads[id] = info
if (info.status === 'complete' || info.status === 'error') {
setTimeout(() => activeDownloads.delete(id), 30000)
}
}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(downloads))
})
// API: Detect model path for non-Ollama providers (LM Studio, etc.)
server.middlewares.use('/local-api/detect-model-path', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
const { provider } = JSON.parse(body)
// Try common paths for LM Studio / other providers
const { existsSync } = require('fs')
const { join } = require('path')
const home = require('os').homedir()
const candidates = [
join(home, '.cache', 'lm-studio', 'models'),
join(home, 'AppData', 'Local', 'LM Studio', 'models'),
join(home, '.local', 'share', 'lm-studio', 'models'),
]
const found = candidates.find(p => existsSync(p))
if (found) {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(found))
} else {
// Fallback: create LU models directory (same as Rust backend)
const { mkdirSync } = require('fs')
const fallback = join(home, 'locally-uncensored', 'models')
try { mkdirSync(fallback, { recursive: true }) } catch {}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(fallback))
}
} catch {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(null))
}
})
})
// API: Check model file sizes (for partial download detection)
server.middlewares.use('/local-api/check-model-sizes', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
const { files } = JSON.parse(body)
const { existsSync, statSync } = require('fs')
const { join } = require('path')
const home = require('os').homedir()
// Try to find ComfyUI path
const candidates = [
join(home, 'ComfyUI'),
join(home, 'Desktop', 'ComfyUI'),
'C:\\ComfyUI',
]
const comfyPath = candidates.find(p => existsSync(p)) || join(home, 'ComfyUI')
const results = (files as any[]).map((f: any) => {
const subfolder = f.subfolder || ''
const dir = subfolder.startsWith('custom_nodes')
? join(comfyPath, subfolder)
: join(comfyPath, 'models', subfolder)
const filePath = join(dir, f.filename)
if (existsSync(filePath)) {
const actual = statSync(filePath).size
const threshold = f.expectedBytes > 0 ? f.expectedBytes * 0.9 : 0
return { filename: f.filename, exists: true, actualBytes: actual, complete: f.expectedBytes === 0 || actual >= threshold }
}
return { filename: f.filename, exists: false, actualBytes: 0, complete: false }
})
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(results))
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: String(err) }))
}
})
})
// API: Download model to a specific path (for HuggingFace GGUF → LM Studio etc.)
server.middlewares.use('/local-api/download-model-to-path', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
const parsed = JSON.parse(body)
const url = parsed.url
const destDir = parsed.destDir || parsed.dest_dir
const filename = parsed.filename
if (!url || !destDir || !filename) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Missing url, destDir, or filename' }))
return
}
const { existsSync, mkdirSync, statSync: statSyncFs } = require('fs')
const { join } = require('path')
const expectedBytes = parsed.expectedBytes
if (!existsSync(destDir)) mkdirSync(destDir, { recursive: true })
const destPath = join(destDir, filename)
if (existsSync(destPath)) {
let fileComplete = true
if (expectedBytes && expectedBytes > 0) {
try {
const actual = statSyncFs(destPath).size
fileComplete = actual >= expectedBytes * 0.9
if (!fileComplete) console.log(`[Download] ${filename} incomplete: ${actual} vs ${expectedBytes} expected`)
} catch { fileComplete = true }
}
if (fileComplete) {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'exists', id: filename }))
return
}
}
const id = filename
console.log(`[Download] Starting to path: ${filename} → ${destDir}`)
downloadFile(url, destPath, id).catch(err => console.error(`[Download] Failed: ${err.message}`))
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'started', id }))
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: String(err) }))
}
})
})
// API: Pause download (dev mode stub — sets status to paused)
server.middlewares.use('/local-api/pause-download', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
const { id } = JSON.parse(body)
const dl = activeDownloads.get(id)
if (dl) dl.status = 'paused'
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'paused' }))
})
})
// API: Cancel download (dev mode stub — removes from map)
server.middlewares.use('/local-api/cancel-download', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
const { id } = JSON.parse(body)
activeDownloads.delete(id)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'cancelled' }))
})
})
// API: Resume download (dev mode stub — restarts download)
server.middlewares.use('/local-api/resume-download', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
const { id, url, subfolder } = JSON.parse(body)
if (url && subfolder) {
const comfyPath = findComfyUI()
if (comfyPath) {
const destPath = join(comfyPath, 'models', subfolder, id)
downloadFile(url, destPath, id).catch(err => console.error(`[Download] Resume failed: ${err.message}`))
}
}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'resuming' }))
})
})
// API: Install custom node (git clone into ComfyUI/custom_nodes/)
server.middlewares.use('/local-api/install-custom-node', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
const _parsed = JSON.parse(body)
const repo_url = _parsed.repoUrl || _parsed.repo_url
const node_name = _parsed.nodeName || _parsed.node_name
const comfyPath = findComfyUI()
if (!comfyPath) {
res.writeHead(404, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'ComfyUI not found. Install ComfyUI first.' }))
return
}
const customNodesDir = join(comfyPath, 'custom_nodes')
if (!existsSync(customNodesDir)) mkdirSync(customNodesDir, { recursive: true })
const targetDir = join(customNodesDir, node_name || basename(repo_url, '.git'))
if (existsSync(targetDir)) {
console.log(`[CustomNode] Already installed: ${node_name}`)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'already_installed', path: targetDir }))
return
}
console.log(`[CustomNode] Installing ${node_name} from ${repo_url}...`)
try {
execSync(`git clone "${repo_url}" "${targetDir}"`, { timeout: 120000 })
// Try pip install if requirements.txt exists
const reqFile = join(targetDir, 'requirements.txt')
if (existsSync(reqFile)) {
try {
execSync(`pip install -r "${reqFile}"`, { cwd: targetDir, timeout: 300000 })
} catch (pipErr: any) {
console.warn(`[CustomNode] pip install failed for ${node_name}:`, pipErr.message)
}
}
console.log(`[CustomNode] Installed: ${node_name}`)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'installed', path: targetDir }))
} catch (gitErr: any) {
console.error(`[CustomNode] Git clone failed:`, gitErr.message)
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: `Git clone failed: ${gitErr.message}` }))
}
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: String(err) }))
}
})
})
// API: Set ComfyUI path (writes to .env and starts ComfyUI)
server.middlewares.use('/local-api/set-comfyui-path', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
const { path: newPath } = JSON.parse(body)
const mainPy = join(newPath, 'main.py')
if (!existsSync(mainPy)) {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'error', error: `main.py not found in "${newPath}". Make sure this is the ComfyUI root folder.` }))
return
}
// Write to .env file
const envPath = resolve(__dirname, '.env')
const { writeFileSync, readFileSync } = require('fs')
let envContent = ''
try { envContent = readFileSync(envPath, 'utf8') } catch { /* no .env yet */ }
const currentMatch = envContent.match(/^COMFYUI_PATH=(.*)$/m)
if (!currentMatch || currentMatch[1].trim() !== newPath) {
if (envContent.includes('COMFYUI_PATH=')) {
envContent = envContent.replace(/COMFYUI_PATH=.*/g, `COMFYUI_PATH=${newPath}`)
} else {
envContent += `${envContent.endsWith('\n') || envContent === '' ? '' : '\n'}COMFYUI_PATH=${newPath}\n`
}
writeFileSync(envPath, envContent, 'utf8')
}
// Update process.env
process.env.COMFYUI_PATH = newPath
console.log(`[ComfyUI] Path set to: ${newPath}`)
// Auto-start ComfyUI
const result = startComfy(newPath)
console.log(`[ComfyUI] Start result: ${result.status}`)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'ok', path: newPath }))
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'error', error: String(err) }))
}
})
})
// API: Install ComfyUI from scratch
const installLogs: string[] = []
let installStatus: 'idle' | 'installing' | 'complete' | 'error' = 'idle'
let installError = ''
server.middlewares.use('/local-api/install-comfyui', (req, res) => {
if (req.method === 'GET') {
// Return install status
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: installStatus, error: installError, logs: installLogs.slice(-30) }))
return
}
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
if (installStatus === 'installing') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'already_installing' }))
return
}
// Check Python is available
try {
execSync('python --version', { stdio: 'ignore' })
} catch {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'error', error: 'Python not found. Install Python 3.10+ from python.org first.' }))
return
}
installStatus = 'installing'
installError = ''
installLogs.length = 0
const home = process.env.USERPROFILE || process.env.HOME || ''
const installDir = join(home, 'ComfyUI')
const log = (msg: string) => {
installLogs.push(msg)
if (installLogs.length > 200) installLogs.shift()
console.log(`[ComfyUI Install] ${msg}`)
}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'started', path: installDir }))
// Run installation in background
;(async () => {
try {
// Step 1: Clone
if (!existsSync(installDir)) {
log('Cloning ComfyUI from GitHub...')
const clone = spawn('git', ['clone', 'https://github.com/comfyanonymous/ComfyUI.git', installDir], { shell: true, stdio: ['ignore', 'pipe', 'pipe'] })
clone.stdout?.on('data', (d) => log(d.toString().trim()))
clone.stderr?.on('data', (d) => log(d.toString().trim()))
await new Promise<void>((resolve, reject) => {
clone.on('exit', (code) => code === 0 ? resolve() : reject(new Error(`git clone failed (exit ${code})`)))
})
log('Clone complete.')
} else if (existsSync(join(installDir, 'main.py'))) {
log('ComfyUI directory already exists, skipping clone.')
} else {
throw new Error(`${installDir} exists but is not ComfyUI. Delete it or choose another location.`)
}
// Step 2: Install Python dependencies
log('Installing Python dependencies (this may take several minutes)...')
const pip = spawn('pip', ['install', '-r', 'requirements.txt'], { cwd: installDir, shell: true, stdio: ['ignore', 'pipe', 'pipe'] })
pip.stdout?.on('data', (d) => {
const lines = d.toString().split('\n').filter((l: string) => l.trim())
lines.forEach((l: string) => log(l.trim()))
})
pip.stderr?.on('data', (d) => {
const lines = d.toString().split('\n').filter((l: string) => l.trim())
lines.forEach((l: string) => log(l.trim()))
})
await new Promise<void>((resolve, reject) => {
pip.on('exit', (code) => code === 0 ? resolve() : reject(new Error(`pip install failed (exit ${code})`)))
})
log('Dependencies installed.')
// Step 3: Install PyTorch with CUDA (if NVIDIA GPU detected)
log('Checking for NVIDIA GPU...')
let hasNvidia = false
try {
execSync('nvidia-smi', { stdio: 'ignore' })
hasNvidia = true
} catch { /* no nvidia */ }
if (hasNvidia) {
log('NVIDIA GPU found. Installing PyTorch with CUDA support...')
const torch = spawn('pip', ['install', 'torch', 'torchvision', 'torchaudio', '--index-url', 'https://download.pytorch.org/whl/cu121'], { cwd: installDir, shell: true, stdio: ['ignore', 'pipe', 'pipe'] })
torch.stdout?.on('data', (d) => log(d.toString().trim()))
torch.stderr?.on('data', (d) => log(d.toString().trim()))
await new Promise<void>((resolve, reject) => {
torch.on('exit', (code) => code === 0 ? resolve() : reject(new Error(`PyTorch CUDA install failed (exit ${code})`)))
})
log('PyTorch with CUDA installed.')
} else {
log('No NVIDIA GPU — using CPU PyTorch (already in requirements).')
}
// Step 4: Save path to .env
const envPath = resolve(__dirname, '.env')
const { writeFileSync, readFileSync } = require('fs')
let envContent = ''
try { envContent = readFileSync(envPath, 'utf8') } catch { /* no .env */ }
const currentMatch = envContent.match(/^COMFYUI_PATH=(.*)$/m)
if (!currentMatch || currentMatch[1].trim() !== installDir) {
if (envContent.includes('COMFYUI_PATH=')) {
envContent = envContent.replace(/COMFYUI_PATH=.*/g, `COMFYUI_PATH=${installDir}`)
} else {
envContent += `${envContent.endsWith('\n') || envContent === '' ? '' : '\n'}COMFYUI_PATH=${installDir}\n`
}
writeFileSync(envPath, envContent, 'utf8')
}
process.env.COMFYUI_PATH = installDir
log(`Path saved to .env: ${installDir}`)
// Step 5: Start ComfyUI
log('Starting ComfyUI...')
startComfy(installDir)
log('ComfyUI started! You can now download models and generate images/videos.')
installStatus = 'complete'
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
log(`ERROR: ${msg}`)
installError = msg
installStatus = 'error'
}
})()
})
// API: Status + logs
server.middlewares.use('/local-api/comfyui-status', async (_req, res) => {
let running = false
try { running = await isComfyRunning() } catch { /* ignore */ }
const comfyPath = findComfyUI()
const processAlive = comfyProcess !== null && !comfyProcess.killed
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({
running,
starting: processAlive && !running,
found: comfyPath !== null,
path: comfyPath,
logs: comfyLogs.slice(-20),
processAlive,
}))
})
// --- Agent Tool Endpoints ---
// API: Execute Python code
server.middlewares.use('/local-api/execute-code', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
const { code, timeout: timeoutMs } = JSON.parse(body)
if (!code) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Missing code parameter' }))
return
}
const os = require('os')
const fs = require('fs')
const tmpDir = join(os.tmpdir(), 'agent-exec-' + Date.now())
fs.mkdirSync(tmpDir, { recursive: true })
const limit = timeoutMs || 30000
let stdout = ''
let stderr = ''
let killed = false
const pythonBin = (() => {
if (process.platform !== 'win32') return 'python3'
try {
const { execSync } = require('child_process')
const paths = execSync('where python', { encoding: 'utf8' }).trim().split('\n')
const real = paths.find((p) => !p.includes('WindowsApps'))
return real ? '"' + real.trim() + '"' : 'python'
} catch { return 'python' }
})()
const proc = spawn(pythonBin, ['-c', code], {
cwd: tmpDir,
stdio: ['ignore', 'pipe', 'pipe'],
shell: false,
})
const timer = setTimeout(() => {
killed = true
try { proc.kill('SIGKILL') } catch { /* already dead */ }
}, limit)
proc.stdout?.on('data', (d: Buffer) => { stdout += d.toString() })
proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString() })
proc.on('exit', (exitCode) => {
clearTimeout(timer)
try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch { /* ignore */ }
if (killed) {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ stdout: '', stderr: 'Execution timed out', exitCode: 124 }))
return
}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ stdout, stderr, exitCode: exitCode ?? 1 }))
})
proc.on('error', (err: Error) => {
clearTimeout(timer)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ stdout: '', stderr: err.message, exitCode: 1 }))
})
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: String(err) }))
}
})
})
// API: Read file from agent workspace
server.middlewares.use('/local-api/file-read', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
const { path: filePath } = JSON.parse(body)
if (!filePath || filePath.includes('..')) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Invalid path' }))
return
}
const os = require('os')
const fs = require('fs')
const workspaceDir = join(os.homedir(), 'agent-workspace')
if (!existsSync(workspaceDir)) mkdirSync(workspaceDir, { recursive: true })