-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathserver.js
More file actions
6253 lines (5363 loc) · 211 KB
/
server.js
File metadata and controls
6253 lines (5363 loc) · 211 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 express from 'express';
import cors from 'cors';
import multer from 'multer';
import path from 'path';
import { Buffer } from 'buffer';
import { randomUUID } from 'crypto';
import { createAssetEditRecord, createBrushChildRecord, resolveProjectImageSource, resolveProjectMeshSource } from './storage.js';
import fs from 'fs/promises';
import { createWriteStream, existsSync } from 'node:fs';
import { spawn } from 'node:child_process';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import si from 'systeminformation';
import tencentcloudSdk from 'tencentcloud-sdk-nodejs-intl-en';
import {
ASSETS_DIR,
DATA_DIR,
DEFAULT_SETTINGS,
WORKFLOW_ASSETS_DIR,
WIKI_ASSETS_DIR,
THUMBNAIL_ASSETS_DIR,
createProject,
createLibraryAsset,
createCardAttribute,
createProjectAsset,
createTask,
createWorkflowRecord,
clearCardProcessingState,
clearStaleProcessingCards,
deleteCard,
deleteCardAttribute,
deleteAssetEditByFilePath,
deleteAssetById,
deleteProjectConnection,
deleteProjectNode,
deleteLibraryAssetByFilePath,
deleteProjectById,
findLibraryAssetByFilePath,
getAssetDirectory,
listAttributeTypes,
listProjectConnections,
listProjectCards,
listProjectCardAttributes,
listProjectNodes,
getProjectById,
getSettings,
getWorkflowRecordById,
initializeStorage,
listLibraryAssetsByType,
listProjectAssets,
listProjectTasks,
listProjects,
listWorkflowRecords,
listWikiPages as dbListWikiPages,
getWikiPage as dbGetWikiPage,
moveCard,
createProjectConnection,
createProjectNode,
createAssetVersion,
findAssetByFilePath,
getAssetRecordById,
getPaintDocumentByAssetId,
upsertPaintDocument,
PAINT_DOCS_DIR,
toStoredPaintDocPath,
getPaintDocSubdir,
renameLibraryAssetByFilePath,
replaceAssetFileById,
renameAssetEditByFilePath,
saveSettings,
toAssetUrlPath,
setCardProcessingState,
toAbsoluteStoragePath,
toStoredAssetPath,
toStoredThumbnailPath,
updateAssetThumbnail,
updateCardAttribute,
updateProjectNode,
updateProjectNodePosition,
updateWorkflowRecord
} from './storage.js';
import {
WIKI_MEDIA_DIR,
wikiManifestExists,
listWikiPages,
getWikiPage,
createWikiPage,
updateWikiPage,
deleteWikiPage,
moveWikiPage,
seedWikiFiles,
importWikiPages
} from './wikiStorage.js';
const app = express();
const PORT = 3001;
const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp']);
const MESH_EXTENSIONS = new Set(['.glb', '.gltf', '.obj', '.fbx', '.stl', '.ply']);
const comfyProgressSubscribers = new Map();
const comfyProgressSnapshots = new Map();
const TENCENT_MESH_GENERATION_API_ID = 'tencent_meshgeneration';
const TENCENT_HUNYUAN_ENDPOINT = 'hunyuan.intl.tencentcloudapi.com';
const TENCENT_HUNYUAN_VERSION = '2023-09-01';
const TENCENT_REGIONS = new Set(['ap-singapore', 'eu-frankfurt', 'na-siliconvalley']);
const TENCENT_MODEL_VERSIONS = new Set(['3.0', '3.1']);
const TENCENT_GENERATION_TYPES = new Set(['Normal', 'LowPoly', 'Geometry']);
const TENCENT_POLYGON_TYPES = new Set(['triangle', 'quadrilaterial']);
const TRIPO_MESH_GENERATION_API_ID = 'tripo_meshgeneration';
const TRIPO_API_BASE_URL = 'https://api.tripo3d.ai/v2/openapi';
const TRIPO_MODEL_VERSIONS = new Set(['v2.0-20240919', 'v2.5-20250123', 'v3.0-20250812', 'v3.1-20260211', 'Turbo-v1.0-20250506', 'P1-20260311']);
const TRIPO_TEXTURE_ALIGNMENT_OPTIONS = new Set(['original_image', 'geometry']);
const TRIPO_TEXTURE_QUALITY_OPTIONS = new Set(['standard', 'detailed']);
const TRIPO_ORIENTATION_OPTIONS = new Set(['default', 'align_image']);
const TRIPO_GEOMETRY_QUALITY_OPTIONS = new Set(['standard', 'detailed']);
const TRIPO_RUNNING_STATUSES = new Set(['queued', 'running']);
const TRIPO_SUCCESS_STATUS = 'success';
const TRIPO_FAILURE_STATUSES = new Set(['failed', 'banned', 'expired', 'cancelled', 'unknown']);
console.log('DEBUG: DATA_DIR is', DATA_DIR);
console.log('DEBUG: DB_FILE is', path.join(DATA_DIR, 'app.db'));
// Middleware
app.use(cors());
app.use('/api/meshes/editor/save', express.json({ limit: '50mb' }));
app.use(express.json({ limit: '10mb' }));
app.use('/assets', express.static(ASSETS_DIR));
app.use('/wiki-media', express.static(WIKI_MEDIA_DIR));
// Multer Config for Asset Uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const destinationDir = getAssetDirectory(req.body.type || inferAssetTypeFromFilename(file.originalname));
fs.mkdir(destinationDir, { recursive: true })
.then(() => cb(null, destinationDir))
.catch(err => cb(err));
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + path.extname(file.originalname));
}
});
app.delete('/api/assets/library/edits', async (req, res) => {
try {
const { filePath } = req.query;
if (!filePath) {
return res.status(400).json({ error: 'filePath is required' });
}
const result = await deleteAssetEditByFilePath(String(filePath));
if (result.status === 'not-found') {
return res.status(404).json({ error: 'Edit not found' });
}
res.status(204).end();
} catch (err) {
console.error('Failed to delete asset edit:', err);
res.status(500).json({ error: err.message || 'Failed to delete asset edit' });
}
});
app.put('/api/assets/library/edits', async (req, res) => {
try {
const { filePath, name } = req.body;
if (!filePath || !name?.trim()) {
return res.status(400).json({ error: 'filePath and name are required' });
}
res.json(await renameAssetEditByFilePath(String(filePath), name));
} catch (err) {
console.error('Failed to rename asset edit:', err);
res.status(500).json({ error: err.message || 'Failed to rename asset edit' });
}
});
app.get('/api/library/comfy-workflows', async (req, res) => {
try {
const workflowRecords = await listWorkflowRecords();
const workflows = (await Promise.all(workflowRecords.map(async record => {
try {
return await buildWorkflowResponse(record);
} catch (err) {
console.warn(`Skipping invalid workflow ${record?.id}:`, err.message);
return null;
}
}))).filter(Boolean);
res.json(workflows);
} catch (err) {
console.error('Failed to list ComfyUI workflows:', err);
res.status(500).json({ error: 'Failed to list ComfyUI workflows' });
}
});
app.post('/api/library/comfy-workflows/inspect', async (req, res) => {
try {
const { workflowJson } = req.body;
const parsed = parseComfyWorkflow(workflowJson);
res.json(parsed);
} catch (err) {
console.error('Failed to inspect ComfyUI workflow:', err);
res.status(400).json({ error: err.message || 'Failed to inspect workflow JSON' });
}
});
app.post('/api/library/comfy-workflows', async (req, res) => {
try {
const { name, workflowJson, parameters = [], outputs = [] } = req.body;
if (!name?.trim()) {
return res.status(400).json({ error: 'A workflow name is required' });
}
const parsed = parseComfyWorkflow(workflowJson);
const availableParameters = new Map(parsed.inputs.map(input => [input.id, input]));
const availableOutputs = new Map(parsed.outputs.map(output => [output.nodeId, output]));
const selectedParameters = parameters.map(parameter => {
const sourceParameter = availableParameters.get(parameter.id);
if (!sourceParameter) {
throw new Error(`Unknown workflow parameter: ${parameter.id}`);
}
return {
...sourceParameter,
name: sanitizeDisplayName(parameter.name || sourceParameter.name, sourceParameter.name),
valueType: normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter))
};
});
const selectedOutputs = outputs.map(output => {
const outputId = String(output.nodeId || output.id);
const sourceOutput = availableOutputs.get(outputId);
if (!sourceOutput) {
throw new Error(`Unknown workflow output: ${outputId}`);
}
return {
...sourceOutput,
name: sanitizeDisplayName(output.name || sourceOutput.nodeTitle, sourceOutput.nodeTitle),
valueType: normalizeComfyValueType(output.valueType, getDefaultComfyValueType(sourceOutput, true))
};
});
if (selectedOutputs.length === 0) {
return res.status(400).json({ error: 'Select at least one output node to save images from' });
}
const filePath = await saveWorkflowFile(name, workflowJson);
const workflowRecord = await createWorkflowRecord({
name: sanitizeDisplayName(name, 'Workflow'),
filePath,
parameters: selectedParameters,
outputs: selectedOutputs
});
res.status(201).json(await buildWorkflowResponse(workflowRecord));
} catch (err) {
console.error('Failed to save ComfyUI workflow:', err);
res.status(400).json({ error: err.message || 'Failed to save ComfyUI workflow' });
}
});
app.put('/api/library/comfy-workflows/:id', async (req, res) => {
try {
const { name, parameters = [], outputs = [] } = req.body;
const existingWorkflowRecord = await getWorkflowRecordById(Number(req.params.id));
if (!existingWorkflowRecord) {
return res.status(404).json({ error: 'ComfyUI workflow not found' });
}
const existingWorkflow = await buildWorkflowResponse(existingWorkflowRecord);
const availableParameters = new Map((existingWorkflow.availableInputs || []).map(input => [input.id, input]));
const availableOutputs = new Map((existingWorkflow.availableOutputs || []).map(output => [output.nodeId, output]));
const nextParameters = parameters.map(parameter => {
const sourceParameter = availableParameters.get(parameter.id);
if (!sourceParameter) {
throw new Error(`Unknown workflow parameter: ${parameter.id}`);
}
return {
...sourceParameter,
name: sanitizeDisplayName(parameter.name || sourceParameter.name, sourceParameter.name),
valueType: normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter))
};
});
const nextOutputs = outputs.map(output => {
const outputId = String(output.nodeId || output.id);
const sourceOutput = availableOutputs.get(outputId);
if (!sourceOutput) {
throw new Error(`Unknown workflow output: ${outputId}`);
}
return {
...sourceOutput,
name: sanitizeDisplayName(output.name || sourceOutput.nodeTitle, sourceOutput.nodeTitle),
valueType: normalizeComfyValueType(output.valueType, getDefaultComfyValueType(sourceOutput, true))
};
});
if (nextOutputs.length === 0) {
return res.status(400).json({ error: 'Select at least one output node to save images from' });
}
const nextWorkflow = await updateWorkflowRecord(existingWorkflow.id, {
name: sanitizeDisplayName(name || existingWorkflow.name, existingWorkflow.name),
parameters: nextParameters,
outputs: nextOutputs
});
res.json(await buildWorkflowResponse(nextWorkflow));
} catch (err) {
console.error('Failed to update ComfyUI workflow:', err);
res.status(400).json({ error: err.message || 'Failed to update ComfyUI workflow' });
}
});
const upload = multer({ storage });
const workflowExecutionUpload = multer({ storage: multer.memoryStorage() });
const libraryImportUpload = multer({ storage: multer.memoryStorage() });
const thumbnailUpload = multer({ storage: multer.memoryStorage() });
const meshEditorSaveUpload = multer({ storage: multer.memoryStorage() });
const paintDocumentUpload = multer({ storage: multer.memoryStorage() });
const wikiMediaUpload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 256 * 1024 * 1024 } });
const WIKI_MEDIA_EXTENSIONS = new Set([
'.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg',
'.mp4', '.webm', '.ogg', '.mov', '.m4v'
]);
function buildWikiPageTree(pages) {
const byId = new Map(pages.map(page => [page.id, { ...page, children: [] }]));
const roots = [];
for (const page of byId.values()) {
if (page.parentId !== null && page.parentId !== undefined && byId.has(page.parentId)) {
byId.get(page.parentId).children.push(page);
} else {
roots.push(page);
}
}
const sortNodes = nodes => {
nodes.sort((a, b) => (a.position - b.position) || (a.id - b.id));
nodes.forEach(node => sortNodes(node.children));
};
sortNodes(roots);
return roots;
}
// ── Wiki ──────────────────────────────────────────────────────────────────
// Author mode is unlocked only when the gitignored `.wiki-author` marker file
// exists at the project root. Checked live so it can be toggled without a
// restart. Read-only installations (end users) never have this file.
const WIKI_AUTHOR_FLAG = path.join(process.cwd(), '.wiki-author');
function isWikiAuthorMode() {
return existsSync(WIKI_AUTHOR_FLAG);
}
function requireWikiAuthor(req, res, next) {
if (!isWikiAuthorMode()) {
return res.status(403).json({ error: 'The Wiki is read-only on this installation.' });
}
next();
}
app.get('/api/wiki/config', (req, res) => {
res.json({ authorMode: isWikiAuthorMode() });
});
app.get('/api/wiki/pages', async (req, res) => {
try {
const pages = await listWikiPages();
res.json({ pages, tree: buildWikiPageTree(pages) });
} catch (err) {
console.error('Failed to list wiki pages:', err);
res.status(500).json({ error: err.message || 'Failed to list wiki pages' });
}
});
app.get('/api/wiki/pages/:id', async (req, res) => {
try {
const page = await getWikiPage(req.params.id);
if (!page) {
return res.status(404).json({ error: 'Wiki page not found' });
}
res.json(page);
} catch (err) {
console.error('Failed to load wiki page:', err);
res.status(500).json({ error: err.message || 'Failed to load wiki page' });
}
});
app.post('/api/wiki/pages', requireWikiAuthor, async (req, res) => {
try {
const { parentId = null, title, icon = null, content = '' } = req.body || {};
const page = await createWikiPage({ parentId, title, icon, content });
res.status(201).json(page);
} catch (err) {
console.error('Failed to create wiki page:', err);
res.status(400).json({ error: err.message || 'Failed to create wiki page' });
}
});
app.put('/api/wiki/pages/:id', requireWikiAuthor, async (req, res) => {
try {
const { title, icon, content } = req.body || {};
const page = await updateWikiPage(req.params.id, { title, icon, content });
if (!page) {
return res.status(404).json({ error: 'Wiki page not found' });
}
res.json(page);
} catch (err) {
console.error('Failed to update wiki page:', err);
res.status(400).json({ error: err.message || 'Failed to update wiki page' });
}
});
app.put('/api/wiki/pages/:id/move', requireWikiAuthor, async (req, res) => {
try {
const { parentId, position } = req.body || {};
const page = await moveWikiPage(req.params.id, { parentId, position });
if (!page) {
return res.status(404).json({ error: 'Wiki page not found' });
}
res.json(page);
} catch (err) {
console.error('Failed to move wiki page:', err);
res.status(400).json({ error: err.message || 'Failed to move wiki page' });
}
});
app.delete('/api/wiki/pages/:id', requireWikiAuthor, async (req, res) => {
try {
const result = await deleteWikiPage(req.params.id);
if (result.status === 'not-found') {
return res.status(404).json({ error: 'Wiki page not found' });
}
res.status(204).end();
} catch (err) {
console.error('Failed to delete wiki page:', err);
res.status(500).json({ error: err.message || 'Failed to delete wiki page' });
}
});
app.post('/api/wiki/media', requireWikiAuthor, wikiMediaUpload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
const extension = path.extname(req.file.originalname).toLowerCase();
if (!WIKI_MEDIA_EXTENSIONS.has(extension)) {
return res.status(400).json({ error: `Unsupported file type: ${extension || 'unknown'}` });
}
await fs.mkdir(WIKI_MEDIA_DIR, { recursive: true });
const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1e9)}${extension}`;
await fs.writeFile(path.join(WIKI_MEDIA_DIR, uniqueName), req.file.buffer);
const isVideo = ['.mp4', '.webm', '.ogg', '.mov', '.m4v'].includes(extension);
res.status(201).json({
url: `http://localhost:${PORT}/wiki-media/${encodeURIComponent(uniqueName)}`,
kind: isVideo ? 'video' : 'image',
name: req.file.originalname
});
} catch (err) {
console.error('Failed to upload wiki media:', err);
res.status(500).json({ error: err.message || 'Failed to upload wiki media' });
}
});
const INITIAL_SCHEMA = {
projects: [
{
id: 1,
name: 'Cyberpunk_District_V1',
description: 'High-fidelity urban environment with neon-lit architecture.',
preset: 'Photorealistic ArchViz',
createdAt: Date.now(),
status: 'active'
}
],
assets: [],
tasks: [],
settings: {
profile: {
name: 'User',
avatar: null
},
apis: {
google: {
apiKey: '',
imageGeneration: {
headerName: 'x-goog-api-key',
payloadTemplate: {
contents: [
{
parts: [
{ text: '{prompt}' }
]
}
],
generationConfig: {
responseModalities: ['Image']
}
},
models: {
nanobana: {
name: 'Nanobanana',
url: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent'
},
nanobana_pro: {
name: 'Nanobanana Pro',
url: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent'
},
nanobana_2: {
name: 'Nanobanana 2',
url: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent'
}
}
}
},
openai: { apiKey: '' },
tencentcloud: {
secretId: '',
secretKey: '',
meshGeneration: {
models: {
meshgeneration: {
name: 'Hunyuan3D Pro',
model: 'meshgeneration'
}
}
}
},
tripoai: {
apiKey: '',
meshGeneration: {
models: {
meshgeneration: {
name: 'Tripo AI',
model: 'meshgeneration'
}
}
}
},
comfyui: {
path: '',
url: 'http://127.0.0.1',
port: '8188'
},
custom: []
}
},
library: {
comfyWorkflows: []
}
};
async function updateCardProcessingSnapshot(projectId, cardId, {
columnName = 'Images',
name = null,
status = 'processing',
progressPercent = null,
detail = '',
currentNodeLabel = '',
promptId = null,
source = 'ComfyUI',
operationType = 'workflow',
workflowId = null,
workflowName = null,
startedAt = Date.now(),
...processingMetadata
} = {}) {
if (!projectId || !cardId) {
return null;
}
return await setCardProcessingState(Number(projectId), cardId, {
columnName,
name,
status,
progress: Number.isFinite(progressPercent) ? Math.max(0, Math.min(100, Math.round(progressPercent))) : null,
processing: {
status,
name,
progressPercent: Number.isFinite(progressPercent) ? Math.max(0, Math.min(100, Math.round(progressPercent))) : null,
detail,
currentNodeLabel,
promptId,
source,
operationType,
workflowId,
workflowName,
startedAt,
updatedAt: Date.now(),
...processingMetadata
},
creationDate: startedAt
});
}
function isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function cloneSerializable(value) {
return JSON.parse(JSON.stringify(value));
}
function sanitizeDisplayName(value = '', fallback = 'Workflow') {
const normalized = String(value)
.trim()
.replace(/\.[^/.]+$/, '')
.replace(/[_-]+/g, ' ')
.replace(/\s+/g, ' ');
return normalized || fallback;
}
function sanitizeFileSegment(value = '', fallback = 'mesh') {
const normalized = String(value)
.trim()
.toLowerCase()
.replace(/\.[^/.]+$/, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
return normalized || fallback;
}
function createMeshEditorFilePath(name = 'mesh') {
return `data/assets/meshes/${sanitizeFileSegment(name)}-${Date.now()}.glb`;
}
async function resolveEditableMeshAsset({ assetId, filePath }) {
const numericAssetId = Number(assetId)
if (Number.isFinite(numericAssetId) && numericAssetId > 0) {
return await getAssetRecordById(numericAssetId);
}
if (!filePath) {
return null;
}
return await findAssetByFilePath('mesh', filePath);
}
function inferComfyParameterType(value) {
if (typeof value === 'number') return 'number';
if (typeof value === 'boolean') return 'boolean';
if (typeof value === 'string') return 'string';
if (Array.isArray(value) || isPlainObject(value)) return 'json';
return 'string';
}
function getDefaultComfyValueType(item, isOutput = false) {
if (isOutput) return 'image';
if (item?.type === 'boolean') return 'boolean';
return item?.type === 'number' ? 'number' : 'string';
}
function normalizeComfyValueType(value, fallback = 'string') {
return ['string', 'number', 'boolean', 'image', 'video', 'mesh'].includes(value) ? value : fallback;
}
function getComfyNodeLabel(nodeId, node = {}) {
return sanitizeDisplayName(node._meta?.title || node.title || node.class_type || `Node ${nodeId}`, `Node ${nodeId}`);
}
function parseComfyWorkflow(workflowJson) {
if (!isPlainObject(workflowJson) || Object.keys(workflowJson).length === 0) {
throw new Error('The workflow JSON is empty or invalid');
}
const nodes = Object.entries(workflowJson)
.filter(([, node]) => isPlainObject(node))
.map(([nodeId, node]) => [String(nodeId), node]);
if (nodes.length === 0) {
throw new Error('The workflow JSON does not contain any nodes');
}
const referencedNodeIds = new Set();
for (const [, node] of nodes) {
for (const value of Object.values(node.inputs || {})) {
if (Array.isArray(value) && value.length >= 2 && (typeof value[0] === 'string' || typeof value[0] === 'number')) {
referencedNodeIds.add(String(value[0]));
}
}
}
const inputs = [];
for (const [nodeId, node] of nodes) {
const nodeLabel = getComfyNodeLabel(nodeId, node);
for (const [inputKey, value] of Object.entries(node.inputs || {})) {
const isNodeReference = Array.isArray(value) && value.length >= 2 && (typeof value[0] === 'string' || typeof value[0] === 'number');
if (isNodeReference || value === null || value === undefined) continue;
const type = inferComfyParameterType(value);
if (!['string', 'number', 'boolean', 'json'].includes(type)) continue;
inputs.push({
id: `${nodeId}.${inputKey}`,
nodeId,
inputKey,
nodeTitle: nodeLabel,
classType: node.class_type || 'Unknown',
name: sanitizeDisplayName(`${nodeLabel} ${inputKey}`, inputKey),
label: `${nodeLabel} • ${inputKey}`,
type,
defaultValue: cloneSerializable(value)
});
}
}
const outputs = nodes
.filter(([nodeId]) => !referencedNodeIds.has(nodeId))
.map(([nodeId, node]) => ({
id: nodeId,
nodeId,
nodeTitle: getComfyNodeLabel(nodeId, node),
classType: node.class_type || 'Unknown',
label: `${getComfyNodeLabel(nodeId, node)} • ${node.class_type || 'Output'}`
}));
return { inputs, outputs };
}
function buildComfyUiBaseUrl(settings = {}) {
const comfySettings = settings?.apis?.comfyui || {};
const rawUrl = String(comfySettings.url || 'http://127.0.0.1').trim();
const normalizedUrl = /^https?:\/\//i.test(rawUrl) ? rawUrl : `http://${rawUrl}`;
const parsedUrl = new URL(normalizedUrl);
const port = String(comfySettings.port || parsedUrl.port || '8188').trim();
parsedUrl.port = port;
parsedUrl.pathname = '';
parsedUrl.search = '';
parsedUrl.hash = '';
return parsedUrl.toString().replace(/\/$/, '');
}
function buildComfyUiWebSocketUrl(baseUrl, clientId) {
const parsedUrl = new URL(baseUrl);
const currentPath = parsedUrl.pathname && parsedUrl.pathname !== '/' ? parsedUrl.pathname.replace(/\/$/, '') : '';
parsedUrl.protocol = parsedUrl.protocol === 'https:' ? 'wss:' : 'ws:';
parsedUrl.pathname = `${currentPath}/ws`;
parsedUrl.search = '';
parsedUrl.hash = '';
parsedUrl.searchParams.set('clientId', clientId);
return parsedUrl.toString();
}
function getComfyExecutionNodeIds(workflowJson = {}, selectedOutputs = []) {
const availableNodeIds = Object.keys(workflowJson || {});
if (availableNodeIds.length === 0) {
return new Set();
}
const preferredNodeIds = selectedOutputs
.map(output => String(output?.nodeId || output?.id || ''))
.filter(nodeId => nodeId && workflowJson?.[nodeId]);
const reachableNodeIds = new Set();
const queue = preferredNodeIds.length > 0 ? [...preferredNodeIds] : [...availableNodeIds];
while (queue.length > 0) {
const nodeId = String(queue.pop());
if (!nodeId || reachableNodeIds.has(nodeId) || !workflowJson?.[nodeId]) {
continue;
}
reachableNodeIds.add(nodeId);
for (const inputValue of Object.values(workflowJson[nodeId]?.inputs || {})) {
if (Array.isArray(inputValue) && inputValue.length > 0 && workflowJson?.[String(inputValue[0])]) {
queue.push(String(inputValue[0]));
}
}
}
return reachableNodeIds.size > 0 ? reachableNodeIds : new Set(availableNodeIds);
}
function getComfyExecutionNodeLabel(workflowJson, nodeId) {
const node = workflowJson?.[String(nodeId)];
return node?._meta?.title || node?.title || node?.class_type || `Node ${nodeId}`;
}
function getComfyExecutionProgressPercent(completedNodeCount, totalNodeCount, nodeProgress = 0, isComplete = false) {
if (isComplete) {
return 100;
}
const safeTotalNodeCount = Math.max(1, Number(totalNodeCount) || 1);
const safeNodeProgress = Number.isFinite(nodeProgress) ? Math.min(Math.max(nodeProgress, 0), 1) : 0;
const rawPercent = ((completedNodeCount + safeNodeProgress) / safeTotalNodeCount) * 100;
return Math.max(0, Math.min(99, Math.round(rawPercent)));
}
function getComfyProgressSubscribers(promptId) {
const key = String(promptId || '');
if (!comfyProgressSubscribers.has(key)) {
comfyProgressSubscribers.set(key, new Set());
}
return comfyProgressSubscribers.get(key);
}
function publishComfyProgress(promptId, payload) {
const key = String(promptId || '');
const message = {
promptId: key,
timestamp: Date.now(),
...payload
};
comfyProgressSnapshots.set(key, message);
for (const response of getComfyProgressSubscribers(key)) {
response.write(`data: ${JSON.stringify(message)}\n\n`);
}
if (message.status === 'completed' || message.status === 'error') {
setTimeout(() => {
if ((comfyProgressSubscribers.get(key)?.size || 0) === 0) {
comfyProgressSubscribers.delete(key);
comfyProgressSnapshots.delete(key);
}
}, 60000);
}
}
function subscribeToComfyProgress(promptId, req, res) {
const key = String(promptId || '');
const subscribers = getComfyProgressSubscribers(key);
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
res.flushHeaders?.();
res.write('retry: 1000\n\n');
subscribers.add(res);
const snapshot = comfyProgressSnapshots.get(key);
if (snapshot) {
res.write(`data: ${JSON.stringify(snapshot)}\n\n`);
}
const heartbeat = setInterval(() => {
res.write(': keep-alive\n\n');
}, 15000);
req.on('close', () => {
clearInterval(heartbeat);
subscribers.delete(res);
if (subscribers.size === 0 && !comfyProgressSnapshots.has(key)) {
comfyProgressSubscribers.delete(key);
}
});
}
function createComfyExecutionMonitor(baseUrl, { clientId, promptId, workflowJson, selectedOutputs = [], timeout = null, onProgress = null }) {
const trackedNodeIds = getComfyExecutionNodeIds(workflowJson, selectedOutputs);
const totalNodeCount = Math.max(1, trackedNodeIds.size || Object.keys(workflowJson || {}).length || 1);
const wsUrl = buildComfyUiWebSocketUrl(baseUrl, clientId);
const completedNodes = new Set();
let currentNodeId = null;
let currentNodeProgress = 0;
let socket = null;
let timer = null;
let isReady = false;
let isSettled = false;
let rejectCompletion = null;
const normalizeNodeId = (nodeId) => String(nodeId || '');
const isTrackedNode = (nodeId) => trackedNodeIds.size === 0 || trackedNodeIds.has(normalizeNodeId(nodeId));
const getCompletedNodeCount = () => completedNodes.size;
const getProgressPercent = (isComplete = false) => {
const runningNodeBonus = currentNodeId && !completedNodes.has(currentNodeId) && isTrackedNode(currentNodeId)
? currentNodeProgress
: 0;
return getComfyExecutionProgressPercent(getCompletedNodeCount(), totalNodeCount, runningNodeBonus, isComplete);
};
const markNodeCompleted = (nodeId) => {
const normalizedNodeId = normalizeNodeId(nodeId);
if (!normalizedNodeId || !isTrackedNode(normalizedNodeId)) {
return false;
}
completedNodes.add(normalizedNodeId);
if (currentNodeId === normalizedNodeId) {
currentNodeProgress = 0;
}
return true;
};
const publishState = (payload) => {
const nextPayload = {
totalNodeCount,
completedNodeCount: getCompletedNodeCount(),
progressPercent: getProgressPercent(payload?.status === 'completed'),
...payload
};
publishComfyProgress(promptId, nextPayload);
onProgress?.(nextPayload);
};
const ready = new Promise((resolve, reject) => {
socket = new WebSocket(wsUrl);
if (Number.isFinite(timeout) && timeout > 0) {
timer = setTimeout(() => {
isSettled = true;
publishState({
status: 'error',
detail: `Job did not complete within ${Math.round(timeout / 1000)}s`,
currentNodeLabel: 'Timed out'
});
socket.close();
rejectCompletion?.(new Error(`Job did not complete within ${Math.round(timeout / 1000)}s`));
reject(new Error(`Job did not complete within ${Math.round(timeout / 1000)}s`));
}, timeout);
}
socket.onopen = () => {
isReady = true;
publishState({
status: 'connected',
detail: `Connected to ComfyUI • ${totalNodeCount} workflow nodes`,
currentNodeLabel: 'Waiting for execution to start'
});
resolve();
};
socket.onerror = (error) => {
if (isSettled) {
return;
}
isSettled = true;
publishState({
status: 'error',
detail: 'Failed to connect to ComfyUI progress stream',
currentNodeLabel: 'Connection failed'
});
rejectCompletion?.(error instanceof Error ? error : new Error('Failed to connect to ComfyUI progress stream'));
reject(error instanceof Error ? error : new Error('Failed to connect to ComfyUI progress stream'));
};
});
const completion = new Promise((resolve, reject) => {
rejectCompletion = reject;
socket.onmessage = (event) => {
if (typeof event.data !== 'string') {
return;
}
let payload;
try {
payload = JSON.parse(event.data);
} catch {
return;
}
const messageType = payload?.type;
const messageData = payload?.data || {};
if (messageData.prompt_id && String(messageData.prompt_id) !== String(promptId)) {
return;
}
if (messageType === 'execution_cached') {
for (const nodeId of messageData.nodes || []) {
markNodeCompleted(nodeId);
}