-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathApp.tsx.bak
More file actions
1546 lines (1413 loc) · 67.3 KB
/
Copy pathApp.tsx.bak
File metadata and controls
1546 lines (1413 loc) · 67.3 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 React, { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import {
Plus, Play, Pause, Save, Trash2, Search, Settings,
Layers, ChevronRight, AlertCircle, CheckCircle2,
X, Type, Image as ImageIcon, Volume2, Video as VideoIcon,
Cpu, Sparkles, AlignLeft, Download, RefreshCw,
Terminal, MousePointer2, Wand2, Globe, Palette, Clapperboard, UserCircle, UserCog,
Maximize, ZoomIn, ZoomOut, Zap, MessageSquare, PenTool, FileText, Star, Edit3, Boxes,
Camera, Mic, Wand, ListPlus, Hash, Info, PlayCircle, FastForward, ArrowUpRight,
Target, Activity, History, Clock, Maximize2, DownloadCloud, BookOpen, ChevronLeft, ChevronDown, ChevronUp,
Calendar, LayoutGrid, Sparkle, ToggleLeft, ToggleRight, Timer, PlayCircle as PlayIcon,
Key, Globe2, Upload, Languages, ShieldCheck, TriangleAlert, SaveAll, Eraser
} from 'lucide-react';
import { TOOLS } from './constants';
import {
WorkflowNode, Connection, WorkflowState,
NodeStatus, DataType, Port, ToolDefinition, GenerationRun
} from './types';
import { geminiText, geminiImage, geminiSpeech, geminiVideo, lightX2VTask, lightX2VTTS, lightX2VVoiceClone, lightX2VVoiceCloneTTS, lightX2VGetVoiceList, lightX2VGetCloneVoiceList, deepseekText, doubaoText, ppchatGeminiText } from './services/geminiService';
import { removeGeminiWatermark } from './services/watermarkRemover';
import { PRESET_WORKFLOWS } from './preset_workflow';
import { Editor } from './src/components/editor/Editor';
import { Dashboard } from './src/components/dashboard/Dashboard';
import { ExpandedOutputModal } from './src/components/modals/ExpandedOutputModal';
import { AIGenerateModal } from './src/components/modals/AIGenerateModal';
import { CloneVoiceModal } from './src/components/modals/CloneVoiceModal';
import { AudioEditorModal } from './src/components/modals/AudioEditorModal';
import { useWorkflow } from './src/hooks/useWorkflow';
import { useCanvas } from './src/hooks/useCanvas';
import { useVoiceList } from './src/hooks/useVoiceList';
import { useTranslation } from './src/i18n/useTranslation';
import { useNodeManagement } from './src/hooks/useNodeManagement';
import { useConnectionManagement } from './src/hooks/useConnectionManagement';
import { useModalState } from './src/hooks/useModalState';
import { useResultManagement } from './src/hooks/useResultManagement';
import { useAIGenerateWorkflow } from './src/hooks/useAIGenerateWorkflow';
import { useWorkflowExecution } from './src/hooks/useWorkflowExecution';
// --- Main App ---
const App: React.FC = () => {
const [lang, setLang] = useState<'en' | 'zh'>(() => {
const saved = localStorage.getItem('omniflow_lang');
return (saved as any) || 'zh';
});
const [currentView, setCurrentView] = useState<'DASHBOARD' | 'EDITOR'>('DASHBOARD');
const [activeTab, setActiveTab] = useState<'MY' | 'PRESET'>('MY');
// Use useWorkflow Hook
const {
myWorkflows,
workflow,
setWorkflow,
setMyWorkflows,
saveWorkflowToLocal,
deleteWorkflow: deleteWorkflowFromHook
} = useWorkflow();
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
const [selectedConnectionId, setSelectedConnectionId] = useState<string | null>(null);
const [selectedRunId, setSelectedRunId] = useState<string | null>(null);
const [activeOutputs, setActiveOutputs] = useState<Record<string, any>>({});
// Canvas ref
const canvasRef = useRef<HTMLDivElement>(null);
const nodeHeightsRef = useRef<Map<string, number>>(new Map());
// Use useCanvas Hook
const {
view,
setView,
isPanning,
isOverNode,
setIsOverNode,
draggingNode,
connecting,
setConnecting,
mousePos,
zoomIn,
zoomOut,
resetView,
handleMouseMove: canvasHandleMouseMove,
handleMouseDown: canvasHandleMouseDown,
handleMouseUp: canvasHandleMouseUp,
handleMouseLeave: canvasHandleMouseLeave,
handleWheel: canvasHandleWheel,
handleNodeDragStart: canvasHandleNodeDragStart,
handleNodeDrag: canvasHandleNodeDrag,
handleNodeDragEnd: canvasHandleNodeDragEnd,
screenToWorldCoords
} = useCanvas(workflow, canvasRef);
// Use useModalState Hook
const modalState = useModalState();
const [ticker, setTicker] = useState(0);
const [validationErrors, setValidationErrors] = useState<{ message: string; type: 'ENV' | 'INPUT' }[]>([]);
const [globalError, setGlobalError] = useState<{ message: string; details?: string } | null>(null);
const [aiWorkflowDescription, setAIWorkflowDescription] = useState('');
const [isGeneratingWorkflow, setIsGeneratingWorkflow] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const isPausedRef = useRef(false);
const runningTaskIdsRef = useRef<Map<string, string>>(new Map()); // Map<nodeId, taskId> for tracking LightX2V tasks
const abortControllerRef = useRef<AbortController | null>(null); // AbortController for cancelling tasks
// Use translation hook from components
const { t } = useTranslation(lang);
// Helper function to get LightX2V config from env vars only
const getLightX2VConfig = useCallback((workflow: WorkflowState | null) => {
return {
url: (process.env.LIGHTX2V_URL || 'https://x2v.light-ai.top').trim(),
token: (process.env.LIGHTX2V_TOKEN || '').trim()
};
}, []);
// Use useVoiceList Hook (after getLightX2VConfig is defined)
const voiceList = useVoiceList(workflow, selectedNodeId, getLightX2VConfig);
// Helper function to get node outputs (needed by hooks)
const getNodeOutputs = (node: WorkflowNode): Port[] => {
const tool = TOOLS.find(t => t.id === node.toolId);
if (node.toolId === 'gemini-text' && node.data.customOutputs) return node.data.customOutputs.map((o: any) => ({ ...o, type: DataType.TEXT }));
return tool?.outputs || [];
};
// Use useNodeManagement Hook
const nodeManagement = useNodeManagement({
workflow,
setWorkflow,
selectedNodeId,
setSelectedNodeId,
selectedRunId,
setValidationErrors,
setActiveOutputs,
canvasRef,
screenToWorldCoords,
view,
getNodeOutputs,
lang
});
// Use useConnectionManagement Hook
const connectionManagement = useConnectionManagement({
workflow,
setWorkflow,
selectedConnectionId,
setSelectedConnectionId,
selectedRunId,
setConnecting
});
// Use useResultManagement Hook
const resultManagement = useResultManagement({
workflow,
selectedRunId,
activeOutputs,
expandedOutput: modalState.expandedOutput,
tempEditValue: modalState.tempEditValue,
setActiveOutputs,
setWorkflow,
setExpandedOutput: modalState.setExpandedOutput,
setIsEditingResult: modalState.setIsEditingResult,
lang
});
// Use useAIGenerateWorkflow Hook
const aiGenerateWorkflow = useAIGenerateWorkflow({
workflow,
setWorkflow,
setCurrentView,
getLightX2VConfig,
resetView,
lang
});
// Wrapper for generateWorkflowWithAI with loading state
const generateWorkflowWithAI = useCallback(async (description: string) => {
setIsGeneratingWorkflow(true);
try {
await aiGenerateWorkflow.generateWorkflowWithAI(description);
modalState.setShowAIGenerateModal(false);
setAIWorkflowDescription('');
} catch (error: any) {
console.error('[AI Workflow] Generation failed:', error);
setGlobalError({
message: t('execution_failed'),
details: error.message || String(error)
});
} finally {
setIsGeneratingWorkflow(false);
}
}, [aiGenerateWorkflow, modalState, setAIWorkflowDescription, setGlobalError, t]);
// Use useWorkflowExecution Hook
const workflowExecution = useWorkflowExecution({
workflow,
setWorkflow,
activeOutputs,
setActiveOutputs,
isPausedRef,
setIsPaused,
runningTaskIdsRef,
abortControllerRef,
getLightX2VConfig,
setValidationErrors,
setSelectedRunId,
setGlobalError,
updateNodeData,
voiceList,
lang
});
// runWorkflow, validateWorkflow, and getDescendants are now provided by useWorkflowExecution Hook
const runWorkflow = workflowExecution.runWorkflow;
const validateWorkflow = workflowExecution.validateWorkflow;
const getDescendants = workflowExecution.getDescendants;
// Helper functions for voice selection
const getLanguageDisplayName = useCallback((langCode: string) => {
const languageMap: Record<string, string> = {
'chinese': '中文',
'en_us': '美式英语',
'en_gb': '英式英语',
'en_au': '澳洲英语',
'es': '西语',
'ja': '日语'
};
return languageMap[langCode] || langCode;
}, []);
// filteredVoices, isFemaleVoice are provided by useVoiceList Hook
const toggleLang = () => {
const next = lang === 'en' ? 'zh' : 'en';
setLang(next);
localStorage.setItem('omniflow_lang', next);
};
// Workflow loading is handled by useWorkflow Hook
useEffect(() => {
let interval: any;
if (workflow?.isRunning) {
interval = setInterval(() => setTicker(t => t + 1), 100);
}
return () => clearInterval(interval);
}, [workflow?.isRunning]);
// Voice list loading is handled by useVoiceList Hook
// Auto-match resource_id when voice list is loaded
useEffect(() => {
if (!voiceList.lightX2VVoiceList?.voices || !workflow) return;
const voiceData = voiceList.lightX2VVoiceList;
if (voiceData.voices && voiceData.voices.length > 0) {
workflow.nodes.forEach(node => {
const isLightX2V = node.data.model === 'lightx2v' || node.data.model?.startsWith('lightx2v');
if (node.toolId === 'tts' && isLightX2V && node.data.voiceType) {
const matchingVoice = voiceData.voices.find((v: any) => v.voice_type === node.data.voiceType);
if (matchingVoice?.resource_id) {
// Only update if resourceId is empty, wrong, or missing
if (!node.data.resourceId || node.data.resourceId !== matchingVoice.resource_id) {
updateNodeData(node.id, 'resourceId', matchingVoice.resource_id);
console.log(`[LightX2V] Auto-matched resource_id: ${matchingVoice.resource_id} for voice: ${node.data.voiceType}`);
}
}
}
});
}
}, [voiceList.lightX2VVoiceList, workflow]);
// saveWorkflowToLocal and deleteWorkflow are provided by useWorkflow Hook
const deleteWorkflow = useCallback((id: string, e: React.MouseEvent) => {
e.stopPropagation();
if (!window.confirm(t('confirm_delete'))) return;
deleteWorkflowFromHook(id);
}, [t, deleteWorkflowFromHook]);
const openWorkflow = (w: WorkflowState) => {
setSelectedRunId(null);
setSelectedNodeId(null);
setSelectedConnectionId(null);
setValidationErrors([]);
setActiveOutputs({});
voiceList.resetVoiceList(); // Reset voice list when switching workflows
voiceList.resetCloneVoiceList(); // Reset clone voice list
setWorkflow({ ...w, isDirty: false, isRunning: false, env: w.env || { lightx2v_url: '', lightx2v_token: '' } });
setCurrentView('EDITOR');
};
const createNewWorkflow = () => {
setSelectedRunId(null);
setSelectedNodeId(null);
setSelectedConnectionId(null);
setValidationErrors([]);
setActiveOutputs({});
voiceList.resetVoiceList(); // Reset voice list when creating new workflow
voiceList.resetCloneVoiceList(); // Reset clone voice list
const newFlow: WorkflowState = {
id: `flow-${Date.now()}`,
name: t('untitled'),
nodes: [],
connections: [],
isDirty: true,
isRunning: false,
globalInputs: {},
env: {
lightx2v_url: "https://x2v.light-ai.top",
lightx2v_token: ""
},
history: [],
updatedAt: Date.now(),
showIntermediateResults: true
};
setWorkflow(newFlow);
setCurrentView('EDITOR');
};
const selectedNode = useMemo(() => workflow?.nodes.find(n => n.id === selectedNodeId), [workflow, selectedNodeId]);
// updateNodeData is now provided by useNodeManagement Hook
const updateNodeData = nodeManagement.updateNodeData;
// expandedResultData, activeResultsList, and handleManualResultEdit are now provided by useResultManagement Hook
const expandedResultData = resultManagement.expandedResultData;
const activeResultsList = resultManagement.activeResultsList;
const handleManualResultEdit = resultManagement.handleManualResultEdit;
const handleGlobalInputChange = useCallback((nodeId: string, portId: string, value: any) => {
if (selectedRunId) setSelectedRunId(null);
setValidationErrors([]);
setWorkflow(prev => prev ? ({ ...prev, globalInputs: { ...prev.globalInputs, [`${nodeId}-${portId}`]: value }, isDirty: true }) : null);
}, [selectedRunId]);
// addNode and pinOutputToCanvas are now provided by useNodeManagement Hook
const addNode = nodeManagement.addNode;
const pinOutputToCanvas = nodeManagement.pinOutputToCanvas;
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.key === 'Delete' || e.key === 'Backspace') && !['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName || '')) {
if (selectedNodeId) nodeManagement.deleteNode(selectedNodeId);
if (selectedConnectionId) connectionManagement.deleteConnection(selectedConnectionId);
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectedNodeId, selectedConnectionId, nodeManagement, connectionManagement]);
// Close replace menu, output quick add menu, model select, and voice select when clicking outside
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
const target = e.target as HTMLElement;
if (modalState.showReplaceMenu && !target.closest('.replace-menu-container')) {
modalState.setShowReplaceMenu(null);
}
if (modalState.showOutputQuickAdd && !target.closest('.output-quick-add-menu')) {
modalState.setShowOutputQuickAdd(null);
}
if (modalState.showModelSelect && !target.closest('.model-select-container')) {
modalState.setShowModelSelect(null);
}
if (modalState.showVoiceSelect && !target.closest('.voice-select-container')) {
modalState.setShowVoiceSelect(null);
}
};
window.addEventListener('click', handleClickOutside);
return () => window.removeEventListener('click', handleClickOutside);
}, [modalState.showReplaceMenu, modalState.showOutputQuickAdd, modalState.showModelSelect, modalState.showVoiceSelect]);
// deleteSelectedNode is now provided by useNodeManagement Hook
const deleteSelectedNode = useCallback(() => {
if (!selectedNodeId) return;
nodeManagement.deleteNode(selectedNodeId);
}, [selectedNodeId, nodeManagement]);
// getReplaceableTools is now provided by useNodeManagement Hook
const getReplaceableTools = nodeManagement.getReplaceableTools;
// Replace a node with another compatible tool (complex logic with connection mapping)
const replaceNode = useCallback((nodeId: string, newToolId: string) => {
if (!workflow) return;
const node = workflow.nodes.find(n => n.id === nodeId);
if (!node) return;
const newTool = TOOLS.find(t => t.id === newToolId);
if (!newTool) return;
// Get current node outputs
const currentNodeOutputs = getNodeOutputs(node);
// Handle gemini-text special case (dynamic outputs)
let newToolOutputs: Port[] = [];
let newCustomOutputs: any[] | undefined = undefined;
if (newToolId === 'gemini-text') {
// If replacing with gemini-text, preserve customOutputs if they exist
if (node.toolId === 'gemini-text' && node.data.customOutputs) {
newToolOutputs = node.data.customOutputs.map((o: any) => ({ ...o, type: DataType.TEXT }));
newCustomOutputs = node.data.customOutputs;
} else {
// When replacing another node with gemini-text, create customOutputs based on current node outputs
// This allows replacement of nodes with outputs
newCustomOutputs = currentNodeOutputs.map((out, idx) => ({
id: `out-${idx + 1}`,
label: out.label || `Output ${idx + 1}`,
description: out.label || `Output ${idx + 1}`
}));
newToolOutputs = newCustomOutputs.map((o: any) => ({ ...o, type: DataType.TEXT }));
}
} else {
newToolOutputs = newTool.outputs;
}
// Check if outputs are compatible (for gemini-text, we've already created matching outputs)
if (currentNodeOutputs.length !== newToolOutputs.length) return;
const isCompatible = currentNodeOutputs.every((out, idx) => {
if (idx >= newToolOutputs.length) return false;
return out.type === newToolOutputs[idx].type;
});
if (!isCompatible) return;
// Create a mapping of old output port IDs to new ones
const outputPortMap: Record<string, string> = {};
currentNodeOutputs.forEach((oldOut, idx) => {
if (idx < newToolOutputs.length) {
outputPortMap[oldOut.id] = newToolOutputs[idx].id;
}
});
// Update the node
setWorkflow(prev => {
if (!prev) return null;
// Create new node with new tool
const newNode: WorkflowNode = {
...node,
toolId: newToolId,
data: {
...node.data,
// Reset model if the new tool doesn't have models
model: newTool.models && newTool.models.length > 0 ? (newTool.models[0].id || node.data.model) : undefined,
// Preserve customOutputs if replacing with gemini-text and current node has them
customOutputs: newToolId === 'gemini-text' ? (newCustomOutputs || node.data.customOutputs) : (newToolId !== 'gemini-text' ? node.data.customOutputs : undefined)
},
status: NodeStatus.IDLE,
error: undefined,
executionTime: undefined,
startTime: undefined
};
// Update connections: map old output port IDs to new ones
// Special handling for TTS -> Voice Clone replacement
const isTTSToVoiceClone = node.toolId === 'tts' && newToolId === 'lightx2v-voice-clone';
const updatedConnections = prev.connections.map(conn => {
// Handle output connections (source is the replaced node)
if (conn.sourceNodeId === nodeId) {
const newSourcePortId = outputPortMap[conn.sourcePortId];
if (newSourcePortId) {
return { ...conn, sourcePortId: newSourcePortId };
}
// If no mapping found, remove the connection
return null;
}
// Handle input connections (target is the replaced node)
if (conn.targetNodeId === nodeId) {
// Special case: TTS -> Voice Clone
if (isTTSToVoiceClone) {
// Map in-text to in-tts-text
if (conn.targetPortId === 'in-text') {
return { ...conn, targetPortId: 'in-tts-text' };
}
// Remove in-context-tone connection
if (conn.targetPortId === 'in-context-tone') {
return null;
}
}
// For other replacements, try to map input ports
const oldTool = TOOLS.find(t => t.id === node.toolId);
const oldInputs = oldTool?.inputs || [];
const newInputs = newTool.inputs || [];
// Try to find matching input port by type and position
const oldInputIndex = oldInputs.findIndex(inp => inp.id === conn.targetPortId);
if (oldInputIndex >= 0 && oldInputIndex < newInputs.length) {
const oldInput = oldInputs[oldInputIndex];
const newInput = newInputs[oldInputIndex];
// Only map if types match
if (oldInput.type === newInput.type) {
return { ...conn, targetPortId: newInput.id };
}
}
// If no mapping found, check if port ID exists in new tool
const portExists = newInputs.some(inp => inp.id === conn.targetPortId);
if (portExists) {
return conn; // Keep connection if port exists
}
// Remove connection if port doesn't exist
return null;
}
return conn;
}).filter((c): c is Connection => c !== null);
return {
...prev,
nodes: prev.nodes.map(n => n.id === nodeId ? newNode : n),
connections: updatedConnections,
isDirty: true
};
});
modalState.setShowReplaceMenu(null);
}, [workflow]);
// deleteSelectedConnection and addConnection are now provided by useConnectionManagement Hook
const deleteSelectedConnection = useCallback(() => {
if (!selectedConnectionId) return;
connectionManagement.deleteConnection(selectedConnectionId);
}, [selectedConnectionId, connectionManagement]);
const addConnection = connectionManagement.addConnection;
// quickAddInput is now provided by useNodeManagement Hook
const quickAddInput = nodeManagement.quickAddInput;
// Get tools that can accept a specific output type
const getCompatibleToolsForOutput = useCallback((outputType: DataType): ToolDefinition[] => {
return TOOLS.filter(tool => {
// Skip input nodes
if (tool.category === 'Input') return false;
// Find tools that have at least one input port matching the output type
return tool.inputs.some(input => input.type === outputType);
});
}, []);
// quickAddOutput is now provided by useNodeManagement Hook
const quickAddOutput = nodeManagement.quickAddOutput;
const disconnectedInputs = useMemo(() => {
if (!workflow) return [];
const list: { nodeId: string; port: Port; toolName: string; isSourceNode?: boolean; dataType: DataType }[] = [];
workflow.nodes.forEach(node => {
const tool = TOOLS.find(t => t.id === node.toolId);
if (!tool || tool.category === 'Input') return;
tool.inputs.forEach(port => {
const isConnected = workflow.connections.some(c => c.targetNodeId === node.id && c.targetPortId === port.id);
if (!isConnected) {
list.push({ nodeId: node.id, port, toolName: (lang === 'zh' ? tool.name_zh : tool.name), dataType: port.type });
}
});
});
workflow.nodes.forEach(node => {
const tool = TOOLS.find(t => t.id === node.toolId);
if (!tool || tool.category !== 'Input') return;
const val = node.data.value;
const isEmpty = (Array.isArray(val) && val.length === 0) || !val;
if (isEmpty) {
list.push({
nodeId: node.id,
port: tool.outputs[0],
toolName: (lang === 'zh' ? tool.name_zh : tool.name),
isSourceNode: true,
dataType: tool.outputs[0].type
});
}
});
return list;
}, [workflow?.nodes, workflow?.connections, lang]);
// validateWorkflow and runWorkflow are now provided by useWorkflowExecution Hook
if (!workflow || workflow.isRunning) return;
// Reset pause state when starting a new workflow
setIsPaused(false);
isPausedRef.current = false;
setSelectedRunId(null);
const runStartTime = performance.now();
let nodesToRunIds: Set<string>;
if (startNodeId) {
if (onlyOne) nodesToRunIds = new Set([startNodeId]);
else {
nodesToRunIds = getDescendants(startNodeId, workflow.connections);
nodesToRunIds.add(startNodeId);
}
} else {
nodesToRunIds = new Set(workflow.nodes.map(n => n.id));
}
const errors = validateWorkflow(nodesToRunIds);
if (errors.length > 0) {
setValidationErrors(errors);
return;
}
setValidationErrors([]);
const requiresUserApiKey = workflow.nodes
.filter(n => nodesToRunIds.has(n.id))
.some(n =>
n.toolId.includes('video') ||
n.toolId === 'avatar-gen' ||
n.data.model === 'gemini-3-pro-image-preview' ||
n.data.model === 'gemini-2.5-flash-image'
);
if (requiresUserApiKey) {
try {
if (!(await (window as any).aistudio.hasSelectedApiKey())) {
await (window as any).aistudio.openSelectKey();
}
} catch (err) {}
}
setWorkflow(prev => prev ? ({
...prev,
isRunning: true,
nodes: prev.nodes.map(n => nodesToRunIds.has(n.id) ? { ...n, status: NodeStatus.IDLE, error: undefined, executionTime: undefined, startTime: undefined } : n)
}) : null);
const executedInSession = new Set<string>();
const sessionOutputs: Record<string, any> = {};
// If running from a specific node, preserve outputs from nodes that won't be re-run
// Otherwise, clear all outputs for a fresh start
if (startNodeId) {
Object.entries(activeOutputs).forEach(([nodeId, val]) => {
if (!nodesToRunIds.has(nodeId)) sessionOutputs[nodeId] = val;
});
setActiveOutputs(prev => {
const next = { ...prev };
nodesToRunIds.forEach(id => delete next[id]);
return next;
});
} else {
// Full workflow run: clear all outputs to prevent memory accumulation
setActiveOutputs({});
}
// Get LightX2V config once at the start of workflow execution
const lightX2VConfig = getLightX2VConfig(workflow);
try {
// Execute nodes in parallel by layer, with max 3 concurrent executions
const MAX_CONCURRENT = 3;
while (executedInSession.size < workflow.nodes.filter(n => nodesToRunIds.has(n.id)).length) {
// Check if workflow is paused, wait until resumed
while (isPausedRef.current) {
await new Promise(resolve => setTimeout(resolve, 100));
// Check if workflow is still running (might have been stopped)
const currentWorkflow = workflow;
if (!currentWorkflow?.isRunning) {
return;
}
}
// Find all nodes ready to execute (all inputs are ready)
const readyNodes: typeof workflow.nodes = [];
for (const node of workflow.nodes) {
if (!nodesToRunIds.has(node.id) || executedInSession.has(node.id)) continue;
const tool = TOOLS.find(t => t.id === node.toolId)!;
const incomingConns = workflow.connections.filter(c => c.targetNodeId === node.id);
const inputsReady = incomingConns.every(c => !nodesToRunIds.has(c.sourceNodeId) || executedInSession.has(c.sourceNodeId));
if (inputsReady) {
readyNodes.push(node);
}
}
// If no nodes are ready, break to avoid infinite loop
if (readyNodes.length === 0) break;
// Execute ready nodes in batches of MAX_CONCURRENT
for (let i = 0; i < readyNodes.length; i += MAX_CONCURRENT) {
// Check pause state before starting each batch
while (isPausedRef.current) {
await new Promise(resolve => setTimeout(resolve, 100));
const currentWorkflow = workflow;
if (!currentWorkflow?.isRunning) {
return;
}
}
const batch = readyNodes.slice(i, i + MAX_CONCURRENT);
// Execute batch in parallel
const executionPromises = batch.map(async (node) => {
const tool = TOOLS.find(t => t.id === node.toolId)!;
const incomingConns = workflow.connections.filter(c => c.targetNodeId === node.id);
const nodeStart = performance.now();
// Update node status to RUNNING
setWorkflow(prev => prev ? ({ ...prev, nodes: prev.nodes.map(n => n.id === node.id ? { ...n, status: NodeStatus.RUNNING, startTime: nodeStart } : n) }) : null);
try {
const nodeInputs: Record<string, any> = {};
await Promise.all(tool.inputs.map(async (port) => {
// Check if there's an override value for this port
if (node.data.inputOverrides && node.data.inputOverrides[port.id] !== undefined) {
nodeInputs[port.id] = node.data.inputOverrides[port.id];
return;
}
const conns = incomingConns.filter(c => c.targetPortId === port.id);
if (conns.length > 0) {
const values = (await Promise.all(conns.map(async (c) => {
// First check if source node has executed and has output in sessionOutputs
if (sessionOutputs[c.sourceNodeId] !== undefined) {
const sourceRes = sessionOutputs[c.sourceNodeId];
return (typeof sourceRes === 'object' && sourceRes !== null && c.sourcePortId in sourceRes) ? sourceRes[c.sourcePortId] : sourceRes;
}
// If not executed yet, check if it's an input node and read from node.data.value
// This handles the case where input nodes haven't been executed but their values are needed
const sourceNode = workflow.nodes.find(n => n.id === c.sourceNodeId);
if (sourceNode) {
const sourceTool = TOOLS.find(t => t.id === sourceNode.toolId);
if (sourceTool?.category === 'Input') {
// For input nodes, read directly from node.data.value
let inputValue = sourceNode.data.value;
// Convert file paths to base64 data URLs for image and audio inputs
if (sourceNode.toolId === 'image-input' && Array.isArray(inputValue) && inputValue.length > 0) {
inputValue = await Promise.all(inputValue.map(async (img: string) => {
// If it's already a data URL or base64, return as is
if (img.startsWith('data:') || (!img.startsWith('http') && img.includes(','))) {
return img;
}
// If it's a file path (starts with /), load and convert to base64
if (img.startsWith('/')) {
try {
const response = await fetch(img);
const blob = await response.blob();
return await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (e) {
console.error(`Failed to load image ${img}:`, e);
return img; // Return original path if loading fails
}
}
return img;
}));
} else if (sourceNode.toolId === 'audio-input' && inputValue && typeof inputValue === 'string' && inputValue.startsWith('/')) {
// Convert audio file path to base64 data URL
try {
const response = await fetch(inputValue);
const blob = await response.blob();
inputValue = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (e) {
console.error(`Failed to load audio ${inputValue}:`, e);
// Keep original path if loading fails
}
}
// Check if this is a multi-output node (like gemini-text with customOutputs)
if (sourceNode.toolId === 'gemini-text' && sourceNode.data.customOutputs && typeof inputValue === 'object' && inputValue !== null) {
return c.sourcePortId in inputValue ? inputValue[c.sourcePortId] : inputValue;
}
return inputValue;
}
// For other nodes that haven't executed, try to read from previously executed outputs
// This handles nodes that were executed in previous runs
const prevOutput = activeOutputs[c.sourceNodeId];
if (prevOutput !== undefined) {
return (typeof prevOutput === 'object' && prevOutput !== null && c.sourcePortId in prevOutput) ? prevOutput[c.sourcePortId] : prevOutput;
}
}
return undefined;
}))).filter(v => v !== undefined).flat();
nodeInputs[port.id] = values.length === 1 ? values[0] : values.length > 0 ? values : undefined;
} else nodeInputs[port.id] = workflow.globalInputs[`${node.id}-${port.id}`];
}));
let result: any;
const model = node.data.model;
switch (node.toolId) {
case 'text-input': result = node.data.value || ""; break;
case 'image-input':
const imageValue = node.data.value || [];
// Convert file paths to base64 data URLs if needed
if (Array.isArray(imageValue) && imageValue.length > 0) {
const convertedImages = await Promise.all(imageValue.map(async (img: string) => {
// If it's already a data URL or base64, return as is
if (img.startsWith('data:') || (!img.startsWith('http') && img.includes(','))) {
return img;
}
// If it's a file path (starts with /), load and convert to base64
if (img.startsWith('/')) {
try {
const response = await fetch(img);
const blob = await response.blob();
return await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (e) {
console.error(`Failed to load image ${img}:`, e);
return img; // Return original path if loading fails
}
}
// If it's a URL, return as is (will be handled by the service)
return img;
}));
result = convertedImages;
} else {
result = imageValue;
}
break;
case 'audio-input':
const audioValue = node.data.value;
// Convert file path to base64 data URL if needed
if (audioValue && typeof audioValue === 'string') {
// If it's already a data URL or base64, return as is
if (audioValue.startsWith('data:') || (!audioValue.startsWith('http') && audioValue.includes(','))) {
result = audioValue;
} else if (audioValue.startsWith('/')) {
// If it's a file path (starts with /), load and convert to base64
try {
const response = await fetch(audioValue);
const blob = await response.blob();
result = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (e) {
console.error(`Failed to load audio ${audioValue}:`, e);
result = audioValue; // Return original path if loading fails
}
} else {
// If it's a URL or other format, return as is
result = audioValue;
}
} else {
result = audioValue;
}
break;
case 'video-input': result = node.data.value; break;
case 'web-search': result = await geminiText(nodeInputs['in-text'] || "Search query", true, 'basic', undefined, model); break;
case 'gemini-text':
const outputFields = (node.data.customOutputs || []).map((o: any) => ({ id: o.id, description: o.description || o.label }));
// Use DeepSeek for deepseek models, Doubao for doubao models, PP Chat for ppchat models, otherwise use Gemini
if (model && model.startsWith('deepseek-')) {
result = await deepseekText(nodeInputs['in-text'] || "...", node.data.mode, node.data.customInstruction, model, outputFields);
} else if (model && model.startsWith('doubao-')) {
const imageInput = nodeInputs['in-image'];
result = await doubaoText(nodeInputs['in-text'] || "...", node.data.mode, node.data.customInstruction, model, outputFields, imageInput);
} else if (model && model.startsWith('ppchat-')) {
const imageInput = nodeInputs['in-image'];
result = await ppchatGeminiText(nodeInputs['in-text'] || "...", node.data.mode, node.data.customInstruction, model.replace('ppchat-', ''), outputFields, imageInput);
} else {
result = await geminiText(nodeInputs['in-text'] || "...", false, node.data.mode, node.data.customInstruction, model, outputFields);
}
break;
case 'text-to-image':
if (model === 'gemini-2.5-flash-image') {
result = await geminiImage(nodeInputs['in-text'] || "Artistic portrait", undefined, node.data.aspectRatio, model);
} else {
result = await lightX2VTask(
lightX2VConfig.url,
lightX2VConfig.token,
't2i',
model || 'Qwen-Image-2512',
nodeInputs['in-text'] || "",
undefined, undefined, undefined,
'output_image',
node.data.aspectRatio,
undefined,
(taskId) => runningTaskIdsRef.current.set(node.id, taskId),
abortControllerRef.current?.signal
);
}
break;
case 'image-to-image':
if (model === 'gemini-2.5-flash-image') {
// For Gemini, if multiple images are provided, combine them intelligently
const geminiImgs = Array.isArray(nodeInputs['in-image']) ? nodeInputs['in-image'] : (nodeInputs['in-image'] ? [nodeInputs['in-image']] : []);
result = await geminiImage(nodeInputs['in-text'] || "Transform", geminiImgs.length > 0 ? geminiImgs : undefined, node.data.aspectRatio || "1:1", model);
} else {
// For LightX2V i2i, handle multiple images:
// - Server supports multiple images via array input
// - If multiple images provided, pass all of them to the server
// - Server will handle them as input_image_1, input_image_2, etc.
const i2iImgs = Array.isArray(nodeInputs['in-image']) ? nodeInputs['in-image'] : (nodeInputs['in-image'] ? [nodeInputs['in-image']] : []);
// Pass all images to the server (single image or array of images)
const imageInput = i2iImgs.length === 0 ? undefined : (i2iImgs.length === 1 ? i2iImgs[0] : i2iImgs);
result = await lightX2VTask(
lightX2VConfig.url,
lightX2VConfig.token,
'i2i',
model || 'Qwen-Image-Edit-2511',
nodeInputs['in-text'] || "",
imageInput,
undefined,
undefined,
'output_image',
node.data.aspectRatio,
undefined,
(taskId) => runningTaskIdsRef.current.set(node.id, taskId),
abortControllerRef.current?.signal
);
}
break;
case 'gemini-watermark-remover':
const watermarkImg = Array.isArray(nodeInputs['in-image']) ? nodeInputs['in-image'][0] : nodeInputs['in-image'];
if (!watermarkImg) throw new Error("Image input is required for watermark removal");
result = await removeGeminiWatermark(watermarkImg);
break;
case 'tts':
// Determine which service to use based on model
const isLightX2V = model === 'lightx2v' || model?.startsWith('lightx2v');
if (isLightX2V) {
// Use LightX2V TTS
const voiceTypeToUse = node.data.voiceType || 'zh_female_vv_uranus_bigtts';
let resourceIdToUse = node.data.resourceId;
// Always try to match resource_id from voice list to ensure correctness
if (voiceList.lightX2VVoiceList?.voices && voiceList.lightX2VVoiceList.voices.length > 0) {
const matchingVoice = voiceList.lightX2VVoiceList.voices.find((v: any) => v.voice_type === voiceTypeToUse);
if (matchingVoice?.resource_id) {
resourceIdToUse = matchingVoice.resource_id;
// Update node data with correct resource_id for future use
if (!node.data.resourceId || node.data.resourceId !== resourceIdToUse) {
updateNodeData(node.id, 'resourceId', resourceIdToUse);
console.log(`[LightX2V] Matched resource_id: ${resourceIdToUse} for voice: ${voiceTypeToUse}`);
}
} else {
console.warn(`[LightX2V] No matching voice found for voice_type: ${voiceTypeToUse}`);
}
} else {
console.warn(`[LightX2V] Voice list not loaded, using stored resourceId: ${resourceIdToUse || 'none'}`);
}
// Fallback to default if still not found
if (!resourceIdToUse) {
resourceIdToUse = "seed-tts-1.0";
console.warn(`[LightX2V] Using fallback resourceId: ${resourceIdToUse}`);
}
const contextTone = nodeInputs['in-context-tone'] || "";
result = await lightX2VTTS(
lightX2VConfig.url,
lightX2VConfig.token,
nodeInputs['in-text'] || "",
voiceTypeToUse,
contextTone,
node.data.emotion || "",
node.data.emotionScale || 3,
node.data.speechRate || 0,
node.data.pitch || 0,
node.data.loudnessRate || 0,
resourceIdToUse
);
} else {
// Use Gemini TTS
const contextTone = nodeInputs['in-context-tone'] || "";
result = await geminiSpeech(
nodeInputs['in-text'] || "Script",
node.data.voice || "Kore",
model || 'gemini-2.5-flash-preview-tts',
contextTone
);
}
break;
case 'lightx2v-voice-clone':
// Use selected speaker_id from node data
const speakerId = node.data.speakerId;
if (!speakerId) {
throw new Error("Please select a cloned voice. Use the node settings to choose or create a new cloned voice.");
}
// Generate TTS with cloned voice
const ttsText = nodeInputs['in-tts-text'] || nodeInputs['in-text'] || "";
if (!ttsText) throw new Error("TTS text is required");