-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
1332 lines (1188 loc) · 53.4 KB
/
App.tsx
File metadata and controls
1332 lines (1188 loc) · 53.4 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, useEffect, useMemo, useCallback, useRef } from 'react';
import { useLocalStorage } from './hooks/useLocalStorage';
import { starterPresets } from './data/presets';
import type { Tag, Category, SelectedTag, Preset, Conflict, Taxonomy, AppSettings, AiStatus, HistoryEntry, UdioParams, Toast, UpdateInfo } from './types';
import { Header } from './components/Header';
import { CategoryList } from './components/CategoryList';
import { TagPicker } from './components/TagPicker';
import { PromptPreview } from './components/PromptPreview';
import { ConflictResolutionModal } from './components/ConflictResolutionModal';
import { CommandPalette } from './components/CommandPalette';
import { ResizablePanels } from './components/ResizablePanels';
import { SettingsPage } from './components/SettingsPage';
import { logger } from './utils/logger';
import { LogPanel } from './components/LogPanel';
import { ResizableVerticalPanel } from './components/ResizableVerticalPanel';
import { InfoPage } from './components/InfoPage';
import { StatusBar } from './components/StatusBar';
import { SavePresetModal } from './components/SavePresetModal';
import { PromptHistoryModal } from './components/PromptHistoryModal';
import { DeconstructPromptModal } from './components/DeconstructPromptModal';
import { ThematicRandomizerModal } from './components/ThematicRandomizerModal';
import { SettingsContext } from './index';
import { AlertModal } from './components/AlertModal';
import { ToastContainer } from './components/ToastContainer';
import { PresetsGalleryPanel } from './components/PresetsGalleryPanel';
import { produce } from 'immer';
import { TitleBar } from './components/TitleBar';
import { useDebounce } from './hooks/useDebounce';
interface ConflictState {
newlySelectedTag: Tag;
conflictingTags: Tag[];
}
interface ActivePresetState {
preset: Preset;
isDirty: boolean;
}
type PresetSnapshot = {
selectedTags: Preset['selectedTags'];
textCategoryValues: Record<string, string>;
udioParams: UdioParams;
categoryOrder: string[];
};
const sortObjectKeys = (obj: Record<string, any>): Record<string, any> => {
return Object.keys(obj || {})
.sort()
.reduce((acc, key) => {
const value = obj[key];
acc[key] = value && typeof value === 'object' && !Array.isArray(value)
? sortObjectKeys(value)
: value;
return acc;
}, {} as Record<string, any>);
};
const normalizeSnapshot = (snapshot: PresetSnapshot) => {
const normalizedSelectedTags = Object.keys(snapshot.selectedTags)
.sort()
.reduce((acc, key) => {
const entry = snapshot.selectedTags[key];
const normalizedEntry: { categoryId: string; isLocked?: boolean } = {
categoryId: entry.categoryId,
};
if (entry.isLocked) {
normalizedEntry.isLocked = entry.isLocked;
}
acc[key] = normalizedEntry;
return acc;
}, {} as Preset['selectedTags']);
const normalizedTextValues = Object.keys(snapshot.textCategoryValues || {})
.sort()
.reduce((acc, key) => {
acc[key] = snapshot.textCategoryValues[key];
return acc;
}, {} as Record<string, string>);
return {
selectedTags: normalizedSelectedTags,
textCategoryValues: normalizedTextValues,
udioParams: sortObjectKeys({ instrumental: false, ...snapshot.udioParams }),
categoryOrder: [...snapshot.categoryOrder],
};
};
const snapshotsAreEqual = (a: PresetSnapshot, b: PresetSnapshot) => {
const normalizedA = normalizeSnapshot(a);
const normalizedB = normalizeSnapshot(b);
if (
normalizedA.categoryOrder.length !== normalizedB.categoryOrder.length ||
normalizedA.categoryOrder.some((id, index) => id !== normalizedB.categoryOrder[index])
) {
return false;
}
return (
JSON.stringify(normalizedA.selectedTags) === JSON.stringify(normalizedB.selectedTags) &&
JSON.stringify(normalizedA.textCategoryValues) === JSON.stringify(normalizedB.textCategoryValues) &&
JSON.stringify(normalizedA.udioParams) === JSON.stringify(normalizedB.udioParams)
);
};
const isElectron = !!window.electronAPI;
const App: React.FC = () => {
const [theme, setTheme] = useLocalStorage<'light' | 'dark'>('theme', 'dark');
const [panelSizes, setPanelSizes] = useLocalStorage('panel-sizes', [20, 45, 35]);
const [logPanelHeight, setLogPanelHeight] = useLocalStorage('log-panel-height', 288);
const [history, setHistory] = useLocalStorage<HistoryEntry[]>('prompt-history', []);
const [appSettings, setAppSettings] = useState<AppSettings | null>(null);
const [taxonomy, setTaxonomy] = useState<Taxonomy | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [categories, setCategories] = useState<Category[]>([]);
const [activeCategoryId, setActiveCategoryId] = useState<string>('');
const [selectedTags, setSelectedTags] = useState<Record<string, SelectedTag>>({});
const [textCategoryValues, setTextCategoryValues] = useState<Record<string, string>>({});
const [udioParams, setUdioParams] = useState<UdioParams>({ instrumental: false });
const [conflictState, setConflictState] = useState<ConflictState | null>(null);
const [commandSearchTerm, setCommandSearchTerm] = useState('');
const debouncedCommandSearchTerm = useDebounce(commandSearchTerm, 100);
const [isCommandPaletteOpen, setIsCommandPaletteOpen] = useState(false);
const [paletteStyle, setPaletteStyle] = useState({});
const [isLogPanelOpen, setIsLogPanelOpen] = useState(false);
const [activeView, setActiveView] = useState<'crafter' | 'settings' | 'info' | 'presets'>('crafter');
const [isSavePresetModalOpen, setIsSavePresetModalOpen] = useState(false);
const [activePresetState, setActivePresetState] = useState<ActivePresetState | null>(null);
const [presetModalInitialValues, setPresetModalInitialValues] = useState<{ name?: string; description?: string } | null>(null);
const [isHistoryModalOpen, setIsHistoryModalOpen] = useState(false);
const [isDeconstructModalOpen, setIsDeconstructModalOpen] = useState(false);
const [isThematicRandomizerModalOpen, setIsThematicRandomizerModalOpen] = useState(false);
const [alert, setAlert] = useState<{ title: string; message: string; variant: 'info' | 'warning' | 'error' } | null>(null);
const commandInputRef = useRef<HTMLInputElement>(null);
const commandPaletteRef = useRef<HTMLDivElement>(null);
// State for global features
const [appVersion, setAppVersion] = useState('');
const [aiStatus, setAiStatus] = useState<AiStatus>('checking');
const [detectedProviders, setDetectedProviders] = useState<('ollama' | 'lmstudio')[]>([]);
const [availableModels, setAvailableModels] = useState<{ ollama: string[]; lmstudio: string[] }>({ ollama: [], lmstudio: [] });
const [isDetecting, setIsDetecting] = useState(false);
const [toasts, setToasts] = useState<Toast[]>([]);
const updateToastIdRef = useRef<number | null>(null);
const initialUpdateCheckHandled = useRef(false);
const addToast = (toast: Omit<Toast, 'id'>) => {
const id = Date.now();
setToasts(prev => [...prev, { ...toast, id }]);
return id;
};
const removeToast = (id: number) => {
setToasts(prev => prev.filter(t => t.id !== id));
};
const updateToast = (id: number, updates: Partial<Omit<Toast, 'id'>>) => {
setToasts(prev => prev.map(t => t.id === id ? { ...t, ...updates } : t));
}
const buildCurrentPresetSnapshot = useCallback((): PresetSnapshot => {
const selectedTagsForPreset: Preset['selectedTags'] = {};
Object.entries(selectedTags).forEach(([id, tag]) => {
const selected = tag as SelectedTag;
const entry: { categoryId: string; isLocked?: boolean } = {
categoryId: selected.categoryId,
};
if (selected.isLocked) {
entry.isLocked = selected.isLocked;
}
selectedTagsForPreset[id] = entry;
});
return {
selectedTags: selectedTagsForPreset,
textCategoryValues: { ...textCategoryValues },
udioParams: { instrumental: false, ...udioParams },
categoryOrder: categories.map(c => c.id),
};
}, [selectedTags, textCategoryValues, udioParams, categories]);
const getSnapshotFromPreset = useCallback((preset: Preset): PresetSnapshot => {
const selectedTagsFromPreset: Preset['selectedTags'] = {};
Object.entries(preset.selectedTags || {}).forEach(([id, data]) => {
const entry: { categoryId: string; isLocked?: boolean } = {
categoryId: data.categoryId,
};
if (data.isLocked) {
entry.isLocked = data.isLocked;
}
selectedTagsFromPreset[id] = entry;
});
return {
selectedTags: selectedTagsFromPreset,
textCategoryValues: { ...(preset.textCategoryValues || {}) },
udioParams: { instrumental: false, ...(preset.udioParams || {}) },
categoryOrder: [...preset.categoryOrder],
};
}, []);
const detectServicesAndFetchModels = useCallback(async () => {
logger.info("Detecting local LLM services...");
setAiStatus('checking');
setIsDetecting(true);
const newDetected: ('ollama' | 'lmstudio')[] = [];
const newModels: { ollama: string[]; lmstudio: string[] } = { ollama: [], lmstudio: [] };
try {
const res = await fetch('http://localhost:11434/api/tags', { signal: AbortSignal.timeout(2000) });
if (res.ok) {
const data = await res.json();
newDetected.push('ollama');
if (data.models) newModels.ollama = data.models.map((m: any) => m.name).sort();
}
} catch (e) { /* ignore */ }
try {
const res = await fetch('http://127.0.0.1:1234/v1/models', { signal: AbortSignal.timeout(2000) });
if (res.ok) {
const data = await res.json();
newDetected.push('lmstudio');
if (data.data) newModels.lmstudio = data.data.map((m: any) => m.id).sort();
}
} catch (e) { /* ignore */ }
setDetectedProviders(newDetected);
setAvailableModels(newModels);
setIsDetecting(false);
setAiStatus(newDetected.length > 0 ? 'connected' : 'disconnected');
logger.info(`Service detection complete. Found: ${newDetected.join(', ') || 'None'}`);
setAppSettings(currentSettings => {
if (!currentSettings) return null;
if (newDetected.length > 0 && !newDetected.includes(currentSettings.aiSettings.provider)) {
const newProvider = newDetected[0];
logger.info(`Current AI provider not detected, switching to ${newProvider}.`);
return {
...currentSettings,
aiSettings: {
provider: newProvider,
baseUrl: newProvider === 'ollama' ? 'http://localhost:11434' : 'http://127.0.0.1:1234/v1',
model: newModels[newProvider][0] || '',
}
};
}
return currentSettings;
});
}, [setAppSettings]);
useEffect(() => {
if (!activePresetState) return;
const currentSnapshot = buildCurrentPresetSnapshot();
const originalSnapshot = getSnapshotFromPreset(activePresetState.preset);
const isDirty = !snapshotsAreEqual(currentSnapshot, originalSnapshot);
setActivePresetState(prev => {
if (!prev || prev.isDirty === isDirty) {
return prev;
}
return { ...prev, isDirty };
});
}, [activePresetState, buildCurrentPresetSnapshot, getSnapshotFromPreset]);
const handleClear = useCallback(() => {
logger.info('Clearing all selected tags and text.');
setSelectedTags({});
setTextCategoryValues({});
setUdioParams({ instrumental: false });
setActivePresetState(null);
}, []);
const handleTaxonomyChange = useCallback(async (newTaxonomy: Taxonomy, reset: boolean = false) => {
logger.info(reset ? "Resetting taxonomy to default." : "Saving custom taxonomy.");
let taxonomyToSaveAndSet: Taxonomy;
if (reset) {
if (isElectron) {
await window.electronAPI.resetCustomTaxonomy();
const defaultData = await window.electronAPI.readDefaultTaxonomy();
taxonomyToSaveAndSet = defaultData.taxonomy;
} else {
localStorage.removeItem('custom-taxonomy');
const res = await fetch('./taxonomy.json');
const data = await res.json();
taxonomyToSaveAndSet = data.taxonomy;
}
} else {
taxonomyToSaveAndSet = newTaxonomy;
if (isElectron) {
await window.electronAPI.writeCustomTaxonomy(taxonomyToSaveAndSet);
} else {
localStorage.setItem('custom-taxonomy', JSON.stringify(taxonomyToSaveAndSet));
}
}
setTaxonomy(taxonomyToSaveAndSet);
setCategories(taxonomyToSaveAndSet);
// If the currently selected category was deleted, select the first one.
if (taxonomyToSaveAndSet.length > 0 && !taxonomyToSaveAndSet.some(c => c.id === activeCategoryId)) {
setActiveCategoryId(taxonomyToSaveAndSet[0].id);
} else if (taxonomyToSaveAndSet.length === 0) {
setActiveCategoryId('');
}
handleClear();
logger.info("Taxonomy has been updated. The application state has been reset.");
}, [activeCategoryId, handleClear]);
useEffect(() => {
logger.info("Application starting up...");
if (isElectron) {
window.electronAPI.getAppVersion().then(version => {
setAppVersion(version);
logger.info(`App version: ${version}`);
});
}
const loadAppSettings = async () => {
if (isElectron) {
try {
const settings = await window.electronAPI.readSettings();
logger.info("Application settings loaded from file.");
setAppSettings(settings);
} catch (e: any) {
logger.error("Failed to read settings file.", { error: e.message });
setError("Could not read the application settings file.");
}
} else {
logger.info("Running in web mode, loading settings from localStorage.");
const storedPresets = localStorage.getItem('user-presets');
const storedAiSettings = localStorage.getItem('ai-settings');
const storedPromptRatio = localStorage.getItem('prompt-panel-ratio');
const storedIconSet = localStorage.getItem('icon-set');
const storedUiScale = localStorage.getItem('ui-scale');
setAppSettings({
presets: storedPresets ? JSON.parse(storedPresets) : starterPresets,
aiSettings: storedAiSettings ? JSON.parse(storedAiSettings) : {
provider: 'ollama',
baseUrl: 'http://localhost:11434',
model: 'llama3',
},
promptPanelRatio: storedPromptRatio ? JSON.parse(storedPromptRatio) : 50,
iconSet: storedIconSet ? JSON.parse(storedIconSet) : 'feather',
uiScale: storedUiScale ? JSON.parse(storedUiScale) : 100,
});
}
};
const loadTaxonomy = async () => {
try {
let loadedTaxonomy: Taxonomy | null = null;
if (isElectron) {
loadedTaxonomy = await window.electronAPI.readCustomTaxonomy();
if (!loadedTaxonomy) {
const defaultTaxonomyData = await window.electronAPI.readDefaultTaxonomy();
loadedTaxonomy = defaultTaxonomyData.taxonomy;
}
} else {
const storedTaxonomy = localStorage.getItem('custom-taxonomy');
if (storedTaxonomy) {
loadedTaxonomy = JSON.parse(storedTaxonomy);
} else {
const res = await fetch('./taxonomy.json');
if (!res.ok) throw new Error(`Failed to load taxonomy. Status: ${res.status}`);
const data = await res.json();
loadedTaxonomy = data.taxonomy;
}
}
if (loadedTaxonomy) {
logger.info("Taxonomy loaded successfully.");
setTaxonomy(loadedTaxonomy);
setCategories(loadedTaxonomy);
if (loadedTaxonomy.length > 0) {
setActiveCategoryId(loadedTaxonomy[0].id);
}
} else {
throw new Error("Taxonomy data is null or invalid.");
}
} catch (e: any) {
console.error("Failed to load taxonomy:", e);
const errorMessage = "Could not load the core taxonomy configuration. The application cannot start.";
logger.error(errorMessage, { error: e.message });
setError(errorMessage);
}
};
Promise.all([loadAppSettings(), loadTaxonomy()]).then(() => {
detectServicesAndFetchModels();
}).finally(() => {
setIsLoading(false);
});
}, [detectServicesAndFetchModels]);
useEffect(() => {
if (!appSettings) return;
if (isElectron) {
window.electronAPI.writeSettings(appSettings);
} else {
localStorage.setItem('user-presets', JSON.stringify(appSettings.presets));
localStorage.setItem('ai-settings', JSON.stringify(appSettings.aiSettings));
if (appSettings.promptPanelRatio) {
localStorage.setItem('prompt-panel-ratio', JSON.stringify(appSettings.promptPanelRatio));
}
if (appSettings.iconSet) {
localStorage.setItem('icon-set', JSON.stringify(appSettings.iconSet));
}
if (appSettings.uiScale) {
localStorage.setItem('ui-scale', JSON.stringify(appSettings.uiScale));
}
}
}, [appSettings]);
const { taxonomyMap, allTags } = useMemo(() => {
if (!taxonomy) {
return { taxonomyMap: new Map(), allTags: [] };
}
const newTaxonomyMap = new Map<string, Tag & { categoryId: string }>();
const allT: Tag[] = [];
taxonomy.forEach(cat => {
cat.tags.forEach(tag => {
newTaxonomyMap.set(tag.id, { ...tag, categoryId: cat.id });
allT.push(tag);
});
});
logger.debug('Taxonomy map and tag list created.', { tagCount: allT.length });
return { taxonomyMap: newTaxonomyMap, allTags: allT };
}, [taxonomy]);
useEffect(() => {
document.documentElement.classList.toggle('dark', theme === 'dark');
}, [theme]);
useEffect(() => {
const scale = appSettings?.uiScale || 100;
// FIX: The 'zoom' property is non-standard and causes a TypeScript error.
// Casting to 'any' allows setting it for UI scaling functionality.
(document.documentElement.style as any).zoom = `${scale / 100}`;
}, [appSettings?.uiScale]);
const handleCommandPaletteClose = useCallback(() => {
setIsCommandPaletteOpen(false);
}, []);
const handleTitleBarFocus = useCallback(() => {
if (commandInputRef.current) {
const rect = commandInputRef.current.getBoundingClientRect();
setPaletteStyle({
position: 'fixed',
top: `${rect.bottom + 4}px`,
left: `${rect.left}px`,
width: `${rect.width}px`,
});
}
setIsCommandPaletteOpen(true);
}, []);
const handleTitleBarBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
// If focus is moving to an element within the command palette, don't close it.
if (commandPaletteRef.current?.contains(e.relatedTarget as Node)) {
return;
}
handleCommandPaletteClose();
}, [handleCommandPaletteClose]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
handleCommandPaletteClose();
}
if ((event.ctrlKey || event.metaKey) && event.key === ';') {
event.preventDefault();
if (isCommandPaletteOpen) {
handleCommandPaletteClose();
} else {
commandInputRef.current?.focus();
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, [isCommandPaletteOpen, handleCommandPaletteClose]);
useEffect(() => {
if (!isElectron) return;
const unsubscribe = window.electronAPI.onUpdateEvent((event, data) => {
logger.info(`Received update event: ${event}`, data);
const currentToastId = updateToastIdRef.current;
switch(event) {
case 'update-available': {
if (currentToastId) removeToast(currentToastId);
const info = data as UpdateInfo;
const id = addToast({
type: 'info',
title: `Update Available: v${info.version}`,
message: 'A new version is ready. Would you like to download it now?',
actions: [{
label: 'Download',
onClick: () => {
window.electronAPI.downloadUpdate();
updateToast(id, {
type: 'loading',
title: `Downloading v${info.version}`,
message: 'Preparing to download...',
progress: 0,
actions: undefined
});
}
}]
});
updateToastIdRef.current = id;
initialUpdateCheckHandled.current = true;
break;
}
case 'download-progress': {
if (currentToastId) {
updateToast(currentToastId, {
message: `Download in progress...`,
progress: Math.round(data as number)
});
}
break;
}
case 'update-downloaded': {
const downloadedInfo = data as UpdateInfo;
const commonProps = {
type: 'success' as const,
title: `Update Ready: v${downloadedInfo.version}`,
message: 'Restart the application to install the latest version.',
progress: undefined,
actions: [{ label: 'Restart Now', onClick: () => window.electronAPI.restartAndInstall() }]
};
if (currentToastId) {
updateToast(currentToastId, commonProps);
} else {
const newId = addToast(commonProps);
updateToastIdRef.current = newId;
}
initialUpdateCheckHandled.current = true;
break;
}
case 'update-not-available':
if (initialUpdateCheckHandled.current) {
addToast({ type: 'success', title: 'Up to Date', message: 'You are running the latest version.', duration: 3000 });
}
initialUpdateCheckHandled.current = true;
break;
case 'error':
addToast({ type: 'error', title: 'Update Error', message: data as string, duration: 8000 });
initialUpdateCheckHandled.current = true;
break;
}
});
return unsubscribe;
}, []);
const callLlm = useCallback(async (systemPrompt: string, userPrompt: string, isResponseTextFreeform = false): Promise<any> => {
if (!appSettings?.aiSettings.baseUrl || !appSettings?.aiSettings.model) {
const errorMsg = "AI settings are not configured. Please configure them in the settings menu.";
logger.error(errorMsg);
throw new Error(errorMsg);
}
const { provider, baseUrl, model } = appSettings.aiSettings;
let endpoint = '';
let body: any = {};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 90000); // Deprecated but good fallback
if (provider === 'ollama') {
endpoint = `${baseUrl.replace(/\/$/, '')}/api/chat`;
body = { model, messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: userPrompt }], stream: false };
if (!isResponseTextFreeform) body.format = 'json';
} else { // lmstudio (openai-compatible)
endpoint = `${baseUrl.replace(/\/$/, '')}/chat/completions`;
body = { model, messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: userPrompt }], stream: false };
}
logger.info(`Calling LLM at ${endpoint}`, { provider, model });
logger.debug('LLM request body:', body);
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(90000) // Modern timeout
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = await response.text();
const errorMsg = `AI API request failed: ${response.status} ${response.statusText}. Response: ${errorText}`;
logger.error(errorMsg);
throw new Error(errorMsg);
}
const data = await response.json();
logger.debug('LLM response data received.');
const contentString: string = provider === 'ollama' ? data.message.content : data.choices[0].message.content;
if (isResponseTextFreeform) {
logger.info('Successfully received freeform LLM response.');
return contentString;
}
let textToParse = contentString.trim();
const markdownMatch = textToParse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
if (markdownMatch && markdownMatch[1]) {
logger.debug('Extracted JSON from markdown code block.');
textToParse = markdownMatch[1].trim();
}
try {
const parsedJson = JSON.parse(textToParse);
logger.info('Successfully received and parsed LLM response.');
return parsedJson;
} catch (error: any) {
logger.error('Failed to parse JSON from AI response', { errorMessage: error.message, content: textToParse });
throw new Error(`The AI returned invalid JSON. Response snippet: ${textToParse.substring(0, 150)}...`);
}
} catch (error: any) {
clearTimeout(timeoutId);
if (error.name === 'AbortError' || error.name === 'TimeoutError') {
const timeoutMessage = "AI API request timed out after 90 seconds. Please check if the service is running and the model is loaded.";
logger.error(timeoutMessage);
throw new Error(timeoutMessage);
}
const errorMessage = error.message || 'An unknown network error occurred.';
logger.error("Error calling LLM:", { message: errorMessage });
throw new Error(errorMessage);
}
}, [appSettings]);
const toggleTheme = () => setTheme(theme === 'light' ? 'dark' : 'light');
const handleCategoryOrderChange = (newCategories: Category[]) => {
setCategories(newCategories);
};
const handleToggleTag = useCallback((tag: Tag) => {
const isCurrentlySelected = !!selectedTags[tag.id];
if (!isCurrentlySelected) {
// FIX: Cast tag to Tag to access conflictsWith property.
const conflicts = (tag as Tag).conflictsWith
?.map(id => selectedTags[id])
.filter((t): t is SelectedTag => !!t);
if (conflicts && conflicts.length > 0) {
logger.warn('Tag conflict detected.', { newTag: tag.label, existingTags: conflicts.map(t => t.label) });
setConflictState({ newlySelectedTag: tag, conflictingTags: conflicts });
return;
}
}
logger.debug(`Toggling tag: ${tag.label}`, { selected: !isCurrentlySelected });
setSelectedTags(prev => {
const newSelected = { ...prev };
if (newSelected[tag.id]) {
delete newSelected[tag.id];
} else {
const categoryId = taxonomyMap.get(tag.id)?.categoryId;
if (categoryId) {
newSelected[tag.id] = { ...tag, categoryId, isLocked: false };
}
}
return newSelected;
});
}, [selectedTags, taxonomyMap]);
const handleToggleTagLock = useCallback((tagId: string) => {
logger.debug(`Toggling lock for tag: ${tagId}`);
setSelectedTags(prev => produce(prev, draft => {
if (draft[tagId]) {
draft[tagId].isLocked = !draft[tagId].isLocked;
}
}));
}, []);
const handleResolveConflict = (resolution: 'keep_new' | 'cancel' | 'keep_both') => {
if (!conflictState) return;
logger.info('Resolving tag conflict.', {
resolution,
newTag: conflictState.newlySelectedTag.label,
oldTags: conflictState.conflictingTags.map(t => t.label)
});
const { newlySelectedTag, conflictingTags } = conflictState;
switch (resolution) {
case 'keep_new':
setSelectedTags(prev => {
const newSelected = { ...prev };
conflictingTags.forEach(tag => {
delete newSelected[tag.id];
});
const categoryId = taxonomyMap.get(newlySelectedTag.id)?.categoryId;
if (categoryId) newSelected[newlySelectedTag.id] = { ...newlySelectedTag, categoryId, isLocked: false };
return newSelected;
});
break;
case 'keep_both':
setSelectedTags(prev => {
const newSelected = { ...prev };
const categoryId = taxonomyMap.get(newlySelectedTag.id)?.categoryId;
if (categoryId) newSelected[newlySelectedTag.id] = { ...newlySelectedTag, categoryId, isLocked: false };
return newSelected;
});
break;
case 'cancel':
// Do nothing.
break;
}
setConflictState(null);
};
const handleTextCategoryChange = (categoryId: string, value: string) => {
setTextCategoryValues(prev => ({ ...prev, [categoryId]: value }));
};
const handleLoadPreset = useCallback((preset: Preset) => {
logger.info(`Loading preset: ${preset.name}`);
const newSelectedTags: Record<string, SelectedTag> = {};
Object.entries(preset.selectedTags).forEach(([tagId, data]) => {
const fullTag = taxonomyMap.get(tagId);
if (fullTag) newSelectedTags[tagId] = { ...fullTag, ...data };
else logger.warn('Tag from preset not found.', { tagId });
});
setSelectedTags(newSelectedTags);
setTextCategoryValues(preset.textCategoryValues || {});
setUdioParams(preset.udioParams || { instrumental: false });
setCategories(prevCategories => {
const presetCategoryMap = new Map(prevCategories.map(c => [c.id, c]));
const ordered = preset.categoryOrder.map(id => presetCategoryMap.get(id)).filter((c): c is Category => !!c);
const remaining = prevCategories.filter(c => !preset.categoryOrder.includes(c.id));
return [...ordered, ...remaining];
});
const presetCopy: Preset = {
...preset,
selectedTags: Object.entries(preset.selectedTags).reduce((acc, [key, value]) => {
acc[key] = { categoryId: value.categoryId, ...(value.isLocked ? { isLocked: value.isLocked } : {}) };
return acc;
}, {} as Preset['selectedTags']),
categoryOrder: [...preset.categoryOrder],
udioParams: preset.udioParams ? { ...preset.udioParams } : undefined,
textCategoryValues: preset.textCategoryValues ? { ...preset.textCategoryValues } : undefined,
};
setActivePresetState({ preset: presetCopy, isDirty: false });
}, [taxonomyMap]);
const handleUdioParamsChange = useCallback((params: UdioParams) => {
setUdioParams(params);
}, []);
const handleSavePreset = (name: string, description: string): boolean => {
if (!name || !appSettings) return false;
if (appSettings.presets.some(p => p.name.toLowerCase() === name.toLowerCase())) {
logger.error(`A preset with the name "${name}" already exists.`);
setAlert({
title: "Duplicate Preset Name",
message: `A preset with the name "${name}" already exists. Please choose a different name.`,
variant: 'error',
});
return false;
}
logger.info(`Saving new preset: ${name}`);
const snapshot = buildCurrentPresetSnapshot();
const now = new Date().toISOString();
const newPreset: Preset = {
name,
description: description || undefined,
isFavorite: false,
createdAt: now,
updatedAt: now,
selectedTags: snapshot.selectedTags,
categoryOrder: snapshot.categoryOrder,
udioParams: snapshot.udioParams,
textCategoryValues: Object.keys(snapshot.textCategoryValues).length ? snapshot.textCategoryValues : undefined,
};
setAppSettings(prev => prev ? { ...prev, presets: [...prev.presets, newPreset] } : null);
setActivePresetState({ preset: newPreset, isDirty: false });
addToast({ type: 'success', title: 'Preset Saved', message: `Saved "${name}"`, duration: 3000 });
return true;
};
const handleUpdateActivePreset = (): boolean => {
if (!appSettings || !activePresetState) return false;
const targetName = activePresetState.preset.name;
const existingPreset = appSettings.presets.find(p => p.name === targetName);
if (!existingPreset) {
addToast({ type: 'error', title: 'Preset Missing', message: `The preset "${targetName}" could not be found.`, duration: 5000 });
setActivePresetState(null);
return false;
}
const snapshot = buildCurrentPresetSnapshot();
const now = new Date().toISOString();
const updatedPreset: Preset = {
...existingPreset,
description: activePresetState.preset.description ?? existingPreset.description,
selectedTags: snapshot.selectedTags,
categoryOrder: snapshot.categoryOrder,
udioParams: snapshot.udioParams,
textCategoryValues: Object.keys(snapshot.textCategoryValues).length ? snapshot.textCategoryValues : undefined,
updatedAt: now,
};
setAppSettings(prev => {
if (!prev) return null;
return {
...prev,
presets: prev.presets.map(p => (p.name === targetName ? updatedPreset : p)),
};
});
setActivePresetState({ preset: updatedPreset, isDirty: false });
addToast({ type: 'success', title: 'Preset Updated', message: `Updated "${targetName}"`, duration: 3000 });
return true;
};
const getDuplicateNameSuggestion = (originalName: string) => {
const baseSuggestion = `${originalName} Copy`;
if (!appSettings) return baseSuggestion;
const existingNames = new Set(appSettings.presets.map(p => p.name.toLowerCase()));
if (!existingNames.has(baseSuggestion.toLowerCase())) {
return baseSuggestion;
}
let counter = 2;
let suggestion = `${originalName} Copy ${counter}`;
while (existingNames.has(suggestion.toLowerCase())) {
counter += 1;
suggestion = `${originalName} Copy ${counter}`;
}
return suggestion;
};
const handleSaveActivePresetAsNew = () => {
if (!activePresetState) return;
const suggestedName = getDuplicateNameSuggestion(activePresetState.preset.name);
setPresetModalInitialValues({
name: suggestedName,
description: activePresetState.preset.description ?? '',
});
setIsSavePresetModalOpen(true);
};
const handleSimpleRandomize = useCallback(() => {
logger.info('Randomizing tags, respecting locks.');
// FIX: Cast Object.values to SelectedTag[] to fix type inference issue.
const lockedTags = (Object.values(selectedTags) as SelectedTag[]).filter(tag => tag.isLocked);
const newSelected: Record<string, SelectedTag> = {};
lockedTags.forEach(tag => {
newSelected[tag.id] = tag;
});
const lockedCategoryIds = new Set(lockedTags.map(tag => tag.categoryId));
categories.forEach(category => {
if (lockedCategoryIds.has(category.id)) {
return;
}
if (category.tags.length > 0 && category.type !== 'text') {
const randomTag = category.tags[Math.floor(Math.random() * category.tags.length)];
const fullTag = taxonomyMap.get(randomTag.id);
if (fullTag) {
// FIX: Cast fullTag to SelectedTag to satisfy newSelected type.
newSelected[randomTag.id] = { ...(fullTag as SelectedTag), isLocked: false };
}
}
});
setSelectedTags(newSelected);
setTextCategoryValues({});
setUdioParams({ instrumental: false });
setActivePresetState(null);
}, [selectedTags, categories, taxonomyMap]);
const handleClearCategoryTags = useCallback((categoryId: string) => {
logger.info(`Clearing tags for category: ${categoryId}`);
setSelectedTags(prev => {
const newSelected = { ...prev };
Object.keys(newSelected).forEach(tagId => {
if (newSelected[tagId].categoryId === categoryId) delete newSelected[tagId];
});
return newSelected;
});
}, []);
const handlePromptPanelResize = (ratio: number) => {
setAppSettings(prev => prev ? ({ ...prev, promptPanelRatio: ratio }) : null);
};
const handlePromptGenerated = useCallback((data: Omit<HistoryEntry, 'timestamp'>) => {
setHistory(prevHistory => {
const lastEntry = prevHistory[0];
// Avoid adding duplicate entries if nothing significant has changed
if (lastEntry &&
lastEntry.promptString === data.promptString &&
JSON.stringify(lastEntry.selectedTags) === JSON.stringify(data.selectedTags) &&
JSON.stringify(lastEntry.textCategoryValues) === JSON.stringify(data.textCategoryValues) &&
JSON.stringify(lastEntry.udioParams) === JSON.stringify(data.udioParams)
) {
return prevHistory;
}
const newEntry: HistoryEntry = {
...data,
timestamp: new Date().toISOString(),
};
const newHistory = [newEntry, ...prevHistory].slice(0, 50);
return newHistory;
});
}, [setHistory]);
const handleLoadFromHistory = useCallback((entry: HistoryEntry) => {
logger.info(`Loading prompt from history (timestamp: ${entry.timestamp})`);
const newSelectedTags: Record<string, SelectedTag> = {};
Object.entries(entry.selectedTags).forEach(([tagId, data]) => {
const fullTag = taxonomyMap.get(tagId);
if (fullTag) newSelectedTags[tagId] = { ...fullTag, ...data };
});
setSelectedTags(newSelectedTags);
setTextCategoryValues(entry.textCategoryValues);
setUdioParams(entry.udioParams || { instrumental: false });
setActivePresetState(null);
setCategories(prevCategories => {
const historyCategoryMap = new Map(prevCategories.map(c => [c.id, c]));
const ordered = entry.categoryOrder.map(id => historyCategoryMap.get(id)).filter((c): c is Category => !!c);
const remaining = prevCategories.filter(c => !entry.categoryOrder.includes(c.id));
return [...ordered, ...remaining];
});
setIsHistoryModalOpen(false);
}, [taxonomyMap]);
const handleClearHistory = () => {
logger.info('Clearing prompt history.');
setHistory([]);
};
const handleDeconstruct = useCallback(async (prompt: string): Promise<boolean> => {
logger.info("Deconstructing prompt with AI...", { prompt });
const systemPrompt = `You are an expert at analyzing music descriptions and mapping them to a predefined taxonomy of tags. Your task is to identify which tags from the provided list best represent the user's prompt.
- You will be given the user's prompt and a complete list of available tags.
- Each tag in the list has a unique 'id' and a descriptive 'label'.
- Your response MUST be a valid JSON object.
- The JSON object must have a single key: "tag_ids".
- The value of "tag_ids" must be an array of strings, where each string is the 'id' of a matched tag from the provided list.
- Only include IDs of tags that are explicitly mentioned or strongly implied in the prompt. Do not infer tags that are not present.
- Do not include any text, explanations, or markdown formatting outside of the JSON object itself.
Example: If the prompt is "a dreamy synthwave track" and the tag list contains { id: 'g_synthwave', label: 'Synthwave' } and { id: 'm_dreamy', label: 'Dreamy' }, your response should be:
{
"tag_ids": ["g_synthwave", "m_dreamy"]
}`;
const userPrompt = `User Prompt: "${prompt}"
Available Tags:
${JSON.stringify(allTags.map(({ id, label, description }) => ({ id, label, description })), null, 2)}`;