-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavascript.h
More file actions
5140 lines (4901 loc) · 239 KB
/
javascript.h
File metadata and controls
5140 lines (4901 loc) · 239 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
#pragma once
// NOTE: This file defines a member function of FrontendServer.
// It must be included AFTER the full class definition in frontend.cpp.
// It is not self-contained and cannot be used as a standalone header.
#include <string>
inline std::string FrontendServer::build_ui_js() {
std::string port_str = std::to_string(http_port_);
std::string tsp_port_str = std::to_string(TEST_SIP_PROVIDER_PORT);
std::string js = R"JS(
let currentPage='dashboard',currentSvc=null;
let logSSE=null,svcLogSSE=null;
const TSP_PORT=)JS" + tsp_port_str + R"JS(;
// JS named constants — all setInterval/setTimeout delays and limits.
// POLL_* = recurring poll intervals. DELAY_* = one-shot timeouts.
// COUNTUP_* = animation timing. SIP_MAX_LINES = grid size limit.
const POLL_STATUS_MS=3000,POLL_TESTS_MS=3000,POLL_SERVICES_MS=5000;
const POLL_SIP_STATS_MS=2000;
const POLL_TEST_RESULTS_MS=5000,POLL_CALL_LINE_MAP_MS=5000;
const DELAY_SERVICE_REFRESH_MS=1000,DELAY_TEST_REFRESH_MS=500;
const DELAY_SIP_LINE_MS=200,TOAST_DURATION_MS=3000;
const POLL_BENCHMARK_MS=2000,POLL_ACCURACY_MS=3000;
const POLL_STRESS_MS=2000,POLL_PIPELINE_HEALTH_MS=10000;
const SIP_MAX_LINES=20,SSE_RECONNECT_MS=3000;
const LOG_LEVEL_ORDER={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4};
const DELAY_RESTART_MS=2000,DELAY_SIP_REFRESH_MS=300;
const POLL_SHUTUP_MS=1500,POLL_LLAMA_QUALITY_MS=2000;
const POLL_LLAMA_SHUTUP_MS=1000,POLL_KOKORO_QUALITY_MS=2000;
const POLL_KOKORO_BENCH_MS=2000,POLL_TTS_ROUNDTRIP_MS=3000;
const POLL_FULL_LOOP_MS=3000,DELAY_SAVE_FEEDBACK_MS=1500;
const DELAY_MODEL_SELECT_MS=500,DELAY_SIP_ADD_REFRESH_MS=500;
const STATUS_CLEAR_MS=5000,POLL_LLAMA_BENCH_MS=2000;
const POLL_PIPELINE_STRESS_MS=2000,POLL_DOWNLOAD_MS=1000;
const TOAST_FADE_MS=300,DELAY_DEBOUNCE_MS=300;
const COUNTUP_STEP_MS=20,COUNTUP_DURATION_MS=400;
const TEST_SETUP_POLL_MS=1000,TEST_TIMEOUT_MS=1800000;
let _ttsPreference='auto';
let _testSetupActive=false;
function loadTtsPreference(){
fetch('/api/tests/tts_preference').then(r=>r.json()).then(d=>{
_ttsPreference=d.preference||'auto';
document.querySelectorAll('.tts-pref-select').forEach(sel=>{sel.value=_ttsPreference;});
}).catch(()=>{});
}
function setTtsPreference(val){
_ttsPreference=val;
document.querySelectorAll('.tts-pref-select').forEach(sel=>{sel.value=val;});
fetch('/api/tests/tts_preference',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({preference:val})}).catch(()=>{});
}
// runWithTestSetup(testFn, opts) — Universal test setup wrapper.
// opts: { statusEl (DOM element for progress), btnEl (button to disable), ttsOverride }
// Returns a Promise that resolves when both runs complete (or rejects on setup failure).
async function runWithTestSetup(testFn,opts){
opts=opts||{};
const statusEl=opts.statusEl||null;
const btnEl=opts.btnEl||null;
const ttsOverride=opts.ttsOverride||null;
function setStatus(html){if(statusEl)statusEl.innerHTML=html;}
if(_testSetupActive){
const _activeTts=['neutts','vits2','matcha'].includes(_ttsPreference)?_ttsPreference:'kokoro';
try{return await testFn({tts:_activeTts,runIndex:0});}finally{}
}
if(btnEl){btnEl.disabled=true;btnEl._origText=btnEl.textContent;btnEl.textContent='Setting up...';}
const ttsOrder=ttsOverride?[ttsOverride]:
(['kokoro','neutts','vits2','matcha'].includes(_ttsPreference)?[_ttsPreference]:
['kokoro','neutts']);
const runResults=[];
try{
for(let ri=0;ri<ttsOrder.length;ri++){
const tts=ttsOrder[ri];
const _engineLabels={kokoro:'Kokoro',neutts:'NeuTTS',vits2:'VITS2',matcha:'Matcha'};
const runLabel=ttsOrder.length>1?`Run ${ri+1}/${ttsOrder.length} (${_engineLabels[tts]||tts})`:'';
// --- Setup ---
setStatus(`<span style="color:var(--wt-accent)">⏳ ${runLabel?runLabel+' — ':''}Setting up pipeline...</span>`);
let setupResp;
try{
setupResp=await fetch('/api/tests/setup/start',{method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({tts})});
}catch(e){
setStatus(`<span style="color:var(--wt-danger)">Setup network error: ${escapeHtml(String(e))}</span>`);
throw e;
}
if(!setupResp.ok){
const err=await setupResp.json().catch(()=>({error:'Setup failed'}));
setStatus(`<span style="color:var(--wt-danger)">Setup failed: ${escapeHtml(err.error||'unknown')}</span>`);
throw new Error(err.error||'setup failed');
}
const {task_id}=await setupResp.json();
// --- Poll setup progress ---
await new Promise((res,rej)=>{
const iv=setInterval(async()=>{
try{
const d=await fetch(`/api/async/status?task_id=${task_id}`).then(r=>r.json());
if(d.status==='running'){
const stepLabel=d.step?`[Step ${d.step}] `:'';
setStatus(`<span style="color:var(--wt-accent)">⏳ ${runLabel?runLabel+' — ':''}${stepLabel}${escapeHtml(d.detail||'Setting up...')}</span>`);
return;
}
clearInterval(iv);
if(d.error){
setStatus(`<span style="color:var(--wt-danger)">Setup error: ${escapeHtml(d.error)}</span>`);
rej(new Error(d.error));
}else{
setStatus(`<span style="color:var(--wt-success)">✓ Setup complete${runLabel?' ('+runLabel+')':''} — running test...</span>`);
res(d);
}
}catch(e){clearInterval(iv);rej(e);}
},TEST_SETUP_POLL_MS);
});
// --- Run test with 10-min timeout ---
let teardownCalled=false;
async function doTeardown(){
if(teardownCalled)return;teardownCalled=true;
await fetch('/api/tests/teardown',{method:'POST'}).catch(()=>{});
}
const timeoutHandle=setTimeout(async()=>{
setStatus(`<span style="color:var(--wt-danger)">⏰ Test timed out after 30 minutes — tearing down</span>`);
await doTeardown();
},TEST_TIMEOUT_MS);
let testResult=null,testError=null;
_testSetupActive=true;
try{
testResult=await testFn({tts,runIndex:ri});
}catch(e){
testError=e;
}finally{
_testSetupActive=false;
clearTimeout(timeoutHandle);
await doTeardown();
}
if(testError&&ttsOrder.length===1)throw testError;
runResults.push({tts,result:testResult,error:testError?String(testError):null});
}
// --- Show comparison if auto (both runs) ---
if(ttsOrder.length>1&&statusEl){
const r0=runResults[0],r1=runResults[1];
let cmp=`<div style="display:flex;gap:12px;margin-top:8px">`;
cmp+=`<div style="flex:1;padding:8px;border:1px solid var(--wt-border);border-radius:4px">`;
cmp+=`<strong>Kokoro</strong><br>`;
cmp+=r0.error?`<span style="color:var(--wt-danger)">${escapeHtml(r0.error)}</span>`
:`<span style="color:var(--wt-success)">Completed</span>`;
cmp+=`</div>`;
cmp+=`<div style="flex:1;padding:8px;border:1px solid var(--wt-border);border-radius:4px">`;
cmp+=`<strong>NeuTTS</strong><br>`;
cmp+=r1.error?`<span style="color:var(--wt-danger)">${escapeHtml(r1.error)}</span>`
:`<span style="color:var(--wt-success)">Completed</span>`;
cmp+=`</div></div>`;
statusEl.innerHTML=`<span style="color:var(--wt-success)">Both runs complete</span>${cmp}`;
}
return runResults;
}finally{
if(btnEl){btnEl.disabled=false;btnEl.textContent=btnEl._origText||'Run Test';}
}
}
// _waitForTask(taskId, intervalMs) — polls /api/async/status until the task
// is no longer running and returns a Promise with the final result object.
function _waitForTask(taskId,intervalMs){
return new Promise((resolve,reject)=>{
const iv=setInterval(()=>{
fetch(`/api/async/status?task_id=${taskId}`).then(r=>r.json()).then(d=>{
if(d.status==='running')return;
clearInterval(iv);
if(d.error)reject(new Error(d.error));else resolve(d);
}).catch(e=>{clearInterval(iv);reject(e);});
},intervalMs||2000);
});
}
// showPage(p) — Navigation/page-transition controller.
//
// Page switching uses CSS visibility+opacity (not display:none) via the .wt-page
// class. The .active class sets opacity:1, visibility:visible, pointer-events:auto
// with position:relative; inactive pages get opacity:0, visibility:hidden,
// pointer-events:none with position:absolute so they overlay without affecting layout.
//
// Critical ordering: add .active to the new page BEFORE removing from the old
// page, so the container always has at least one position:relative child and
// never collapses to zero height during the transition frame.
//
// Note: .hidden (display:none!important) is a separate mechanism used for ~50
// inline element toggles (service config panels, test detail/overview, schema
// views, etc.) — it is NOT used for page-level transitions.
//
// Each page activation may trigger data fetches and start/stop polling timers.
function showPage(p){
const newPage=document.getElementById('page-'+p);
if(newPage)newPage.classList.add('active');
document.querySelectorAll('.wt-page').forEach(e=>{if(e.id!==`page-${p}`)e.classList.remove('active');});
document.querySelectorAll('.wt-nav-item').forEach(e=>{
e.classList.toggle('active',e.dataset.page===p);
});
currentPage=p;
if(p!=='dashboard')stopDashboardPoll();
if(p!=='beta-testing')stopTestResultsPoll();
if(p==='dashboard'){fetchDashboard();fetchRagHealthDash();startDashboardPoll();dashLoadPipelineLanguage();}
if(p==='services'){showServicesOverview();fetchServices();}
if(p==='beta-testing'){
try{buildSipLinesGrid();}catch(e){console.error('buildSipLinesGrid:',e);}
try{refreshTestFiles();}catch(e){console.error('refreshTestFiles:',e);}
try{loadVadConfig();}catch(e){}
try{loadLlamaPrompts();}catch(e){}
try{refreshInjectLegs();}catch(e){}
try{updateBetaSummaryDots();}catch(e){}
const resTab=document.getElementById('tab-beta-results');
if(resTab&&resTab.classList.contains('active')){fetchTestResultsPage();startTestResultsPoll();}
startPrereqPoll();
}else{stopPrereqPoll();}
if(p==='models'){loadModels();loadModelComparison();loadHfAuthStatus();}
if(p==='logs'){reconnectLogSSE();}
if(p==='database'){}
if(p==='credentials'){loadCredentials();}
if(p==='certificates'){fetchCerts();}
if(p==='login'){fetchLoginConfig();}
}
function fetchStatus(){
fetch('/api/status').then(r=>r.json()).then(d=>{
document.getElementById('statusText').textContent=
`${d.services_online} services \u2022 ${d.running_tests} tests \u2022 ${d.sse_connections} SSE`;
document.getElementById('svcBadge').textContent=`${d.services_online}/${d.services_total||6}`;
}).catch(()=>{document.getElementById('statusText').textContent='Disconnected';});
}
let dashPollTimer=null;
function startDashboardPoll(){
stopDashboardPoll();
dashPollTimer=setInterval(()=>{fetchDashboard();fetchRagHealthDash();},POLL_STATUS_MS);
}
function stopDashboardPoll(){
if(dashPollTimer){clearInterval(dashPollTimer);dashPollTimer=null;}
}
function animateCountUp(el,newVal){
if(!el)return;
const text=String(newVal);
if(el.textContent===text)return;
const start=parseInt(el.textContent)||0;
const end=parseInt(newVal);
if(isNaN(end)||isNaN(start)){el.textContent=text;return;}
const steps=Math.max(1,Math.floor(COUNTUP_DURATION_MS/COUNTUP_STEP_MS));
const diff=end-start;
let step=0;
if(el._countTimer)clearInterval(el._countTimer);
el._countTimer=setInterval(()=>{
step++;
if(step>=steps){
el.textContent=String(end);
clearInterval(el._countTimer);el._countTimer=null;
el.classList.remove('metric-updated');
void el.offsetWidth;
el.classList.add('metric-updated');
}
else{el.textContent=String(Math.round(start+diff*(step/steps)));}
},COUNTUP_STEP_MS);
}
function formatUptime(s){
if(s<60)return s+'s';
if(s<3600)return Math.floor(s/60)+'m';
if(s<86400)return Math.floor(s/3600)+'h '+Math.floor((s%3600)/60)+'m';
return Math.floor(s/86400)+'d '+Math.floor((s%86400)/3600)+'h';
}
function fetchDashboard(){
fetch('/api/dashboard').then(r=>r.json()).then(d=>{
animateCountUp(document.getElementById('dashMetricServicesOnline'),d.services_online);
animateCountUp(document.getElementById('dashMetricRunningTests'),d.running_tests);
animateCountUp(document.getElementById('dashMetricTestPass'),d.test_pass);
const failEl=document.getElementById('dashMetricTestFail');
if(d.test_fail>0){failEl.textContent=`${d.test_fail} failed`;failEl.className='metric-delta negative';}
else{failEl.textContent='';failEl.className='metric-delta';}
document.getElementById('dashMetricUptime').textContent=formatUptime(d.uptime_seconds);
const badge=document.getElementById('dashHealthBadge');
const ratio=d.services_total>0?d.services_online/d.services_total:0;
if(ratio>=1){badge.textContent='Healthy';badge.style.background='rgba(52,199,89,0.4)';}
else if(ratio>=0.5){badge.textContent='Degraded';badge.style.background='rgba(255,159,10,0.4)';}
else{badge.textContent='Offline';badge.style.background='rgba(255,59,48,0.4)';}
if(d.services){
const svcMap={};
d.services.forEach(s=>{svcMap[s.name]=s.online;});
d.services.forEach(s=>{
const dot=document.getElementById(`pipeline-status-${s.name}`);
if(dot)dot.className=`node-status ${s.online?'online':'offline'}`;
});
}
fetch('/api/tts/status').then(r=>r.ok?r.json():null).then(ts=>{
const lbl=document.getElementById('pipeline-tts-engine');
if(!lbl)return;
if(ts&&ts.engine){lbl.textContent=ts.engine;lbl.style.color='var(--wt-success,#34c759)';}
else{lbl.textContent='no engine';lbl.style.color='rgba(255,255,255,0.5)';}
}).catch(()=>{
const lbl=document.getElementById('pipeline-tts-engine');
if(lbl){lbl.textContent='no engine';lbl.style.color='rgba(255,255,255,0.5)';}
});
const ollamaDot=document.getElementById('pipeline-status-OLLAMA');
if(ollamaDot)ollamaDot.className=`node-status ${d.ollama_running?'online':'offline'}`;
if(d.ollama_installed===false&&!sessionStorage.getItem('ollamaAlertDismissed')){
const ov=document.getElementById('ollamaAlertOverlay');
if(ov)ov.style.display='flex';
}
const feed=document.getElementById('dashActivityFeed');
if(d.recent_logs&&d.recent_logs.length>0){
let html='';
d.recent_logs.forEach(log=>{
const lvlClass=`log-lvl-${/^[A-Z]+$/.test(log.level)?log.level:'INFO'}`;
html+=`<div class="wt-log-entry" style="animation:slideIn 0.3s ease">`
+`<span class="log-ts">${escapeHtml(log.timestamp)}</span> `
+`<span class="log-svc">${escapeHtml(log.service)}</span> `
+`<span class="${lvlClass}">${escapeHtml(log.level)}</span> `
+`${escapeHtml(log.message)}</div>`;
});
const changed=feed.innerHTML!==html;
feed.innerHTML=html;
if(changed){
const pulse=document.getElementById('dashFeedPulse');
if(pulse){pulse.style.animation='none';pulse.offsetHeight;pulse.style.animation='neonPulse 0.4s ease 3';}
}
} else {
feed.innerHTML='<div style="color:var(--wt-text-secondary);padding:16px;text-align:center">No recent activity</div>';
}
}).catch(()=>{});
}
function dashStartAll(){
fetch('/api/services').then(r=>r.json()).then(d=>{
d.services.forEach(s=>{
if(!s.online)fetch('/api/services/start',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({service:s.name})});
});
setTimeout(fetchDashboard,DELAY_SERVICE_REFRESH_MS);
});
}
function dashStopAll(){
fetch('/api/services').then(r=>r.json()).then(d=>{
d.services.forEach(s=>{
if(s.online)fetch('/api/services/stop',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({service:s.name})});
});
setTimeout(fetchDashboard,DELAY_SERVICE_REFRESH_MS);
});
}
function dashLoadPipelineLanguage(){
fetch('/api/settings').then(r=>r.json()).then(d=>{
const v=(d.settings&&d.settings.pipeline_language)||'de';
const sel=document.getElementById('dashLanguageSelect');
if(sel)sel.value=v;
}).catch(()=>{});
}
function dashSetPipelineLanguage(v){
fetch('/api/settings',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({key:'pipeline_language',value:v})})
.then(()=>{
const h=document.getElementById('dashLanguageHint');
if(h)h.textContent='Saved. Restart services to apply ('+v+').';
});
}
function dashRestartFailed(){
fetch('/api/services').then(r=>r.json()).then(d=>{
d.services.forEach(s=>{
if(!s.online&&s.managed)fetch('/api/services/start',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({service:s.name})});
});
setTimeout(fetchDashboard,DELAY_SERVICE_REFRESH_MS);
});
}
function fetchServices(){
fetch('/api/services').then(r=>r.json()).then(d=>{
const online=d.services.filter(s=>s.online).length;
document.getElementById('svcBadge').textContent=`${online}/${d.services.length}`;
const c=document.getElementById('servicesContainer');
c.innerHTML=d.services.map(s=>{
const status=s.online?'<span class="wt-badge wt-badge-success"><span class="wt-status-dot online"></span>Online</span>'
:'<span class="wt-badge wt-badge-secondary"><span class="wt-status-dot offline"></span>Offline</span>';
const desc={'SIP_CLIENT':'SIP/RTP Gateway','INBOUND_AUDIO_PROCESSOR':'G.711 Decode & Resample',
'VAD_SERVICE':'Voice Activity Detection','WHISPER_SERVICE':'Whisper ASR','LLAMA_SERVICE':'LLaMA LLM',
'TTS_SERVICE':'TTS Stage (generic dock, hot-plug engines)',
'KOKORO_ENGINE':'Kokoro TTS Engine','NEUTTS_ENGINE':'NeuTTS Nano German Engine',
'OUTBOUND_AUDIO_PROCESSOR':'Audio Encode & RTP',
'TOMEDO_CRAWL_SERVICE':'Tomedo RAG — Patient Context','TEST_SIP_PROVIDER':'SIP B2BUA Test Provider',
'MOSHI_SERVICE':'Moshi Full-Duplex Neural Voice'};
const eName=escapeHtml(s.name),eDesc=escapeHtml(desc[s.name]||s.description),ePath=escapeHtml(s.binary_path);
const svcAttr=escapeHtml(s.name);
let btns='<div style="margin-top:6px;display:flex;gap:6px;align-items:center" onclick="event.stopPropagation()">';
if(!s.online) btns+=`<button class="wt-btn wt-btn-primary" style="font-size:11px;padding:2px 8px" data-svc="${svcAttr}" onclick="quickSvcStart(this.dataset.svc)">▶ Start</button>`;
if(s.managed&&s.online) btns+=`<button class="wt-btn wt-btn-danger" style="font-size:11px;padding:2px 8px" data-svc="${svcAttr}" onclick="quickSvcStop(this.dataset.svc)">■ Stop</button>`;
if(s.managed&&s.online) btns+=`<button class="wt-btn wt-btn-secondary" style="font-size:11px;padding:2px 8px" data-svc="${svcAttr}" onclick="quickSvcRestart(this.dataset.svc)">↻ Restart</button>`;
btns+=`<button class="wt-btn wt-btn-secondary" style="font-size:11px;padding:2px 8px" data-svc="${svcAttr}" onclick="showSvcDetail(this.dataset.svc)">⚙ Config</button>`;
btns+='</div>';
return `<div class="wt-card" style="cursor:pointer" data-svc="${svcAttr}" onclick="showSvcDetail(this.dataset.svc)">`
+`<div class="wt-card-header"><span class="wt-card-title">`
+`<span class="wt-status-dot ${s.online?'online':'offline'}"></span>`
+`${eName}</span>${status}</div>`
+`<div style="font-size:12px;color:var(--wt-text-secondary)">${eDesc}</div>`
+`<div style="font-size:11px;color:var(--wt-text-secondary);margin-top:4px;font-family:var(--wt-mono)">${ePath}</div>`
+(s.managed?'<div style="font-size:11px;margin-top:4px"><span class="wt-badge wt-badge-warning">Managed by Frontend</span></div>':'')
+(s.name==='SIP_CLIENT'?'<div id="sipOverviewLines" style="font-size:11px;margin-top:4px;color:var(--wt-text-secondary)"></div>':'')
+btns+'</div>';
}).join('');
if(currentSvc){
const s=d.services.find(x=>x.name===currentSvc);
if(s)updateSvcDetail(s);
}
const sipSvc=d.services.find(x=>x.name==='SIP_CLIENT');
if(sipSvc&&sipSvc.online){
fetch('/api/sip/lines').then(r=>r.json()).then(ld=>{
const el=document.getElementById('sipOverviewLines');
if(!el)return;
const lines=ld.lines||[];
if(lines.length===0){el.innerHTML='No active lines';return;}
const reg=lines.filter(l=>l.registered).length;
el.innerHTML=`${lines.length} line(s) (${reg} connected): `+lines.map(l=>`${escapeHtml(l.user)}@${escapeHtml(l.server)}:${escapeHtml(String(l.port))}`).join(', ');
}).catch(()=>{});
}
});
}
function showSvcDetail(name){
currentSvc=name;
document.getElementById('services-overview').classList.add('hidden');
document.getElementById('services-detail').classList.remove('hidden');
document.getElementById('svcDetailName').textContent=name;
fetch('/api/services').then(r=>r.json()).then(d=>{
const s=d.services.find(x=>x.name===name);
if(s)updateSvcDetail(s);
});
connectSvcSSE(name);
}
function updateSvcDetail(s){
document.getElementById('svcDetailPath').textContent=s.binary_path;
if(s.name!=='MOSHI_SERVICE') document.getElementById('svcDetailArgs').value=s.default_args||'';
const online=s.online;
document.getElementById('svcDetailStatus').innerHTML=online
?'<span class="wt-badge wt-badge-success">Online</span>'
:'<span class="wt-badge wt-badge-secondary">Offline</span>';
document.getElementById('svcStartBtn').style.display=online?'none':'';
document.getElementById('svcStopBtn').style.display=(s.managed&&online)?'':'none';
document.getElementById('svcRestartBtn').style.display=(s.managed&&online)?'':'none';
const wc=document.getElementById('whisperConfig');
if(s.name==='WHISPER_SERVICE'){
wc.classList.remove('hidden');
loadWhisperConfig(s.default_args||'');
loadHallucinationFilterState();
} else {
wc.classList.add('hidden');
}
const sc=document.getElementById('sipClientConfig');
const slc=document.getElementById('sipActiveLinesCard');
if(s.name==='SIP_CLIENT'){
sc.classList.remove('hidden');
slc.classList.remove('hidden');
sipRefreshActiveLines();
} else {
sc.classList.add('hidden');
slc.classList.add('hidden');
}
const spc=document.getElementById('sipProviderConfig');
if(s.name==='TEST_SIP_PROVIDER'){
spc.classList.remove('hidden');
loadSipProviderWavConfig();
} else {
spc.classList.add('hidden');
}
const oc=document.getElementById('oapConfig');
if(s.name==='OUTBOUND_AUDIO_PROCESSOR'){
oc.classList.remove('hidden');
loadOapWavConfig();
} else {
oc.classList.add('hidden');
}
const tc=document.getElementById('tomedoCrawlConfig');
if(s.name==='TOMEDO_CRAWL_SERVICE'){
tc.classList.remove('hidden');
loadRagConfig();
fetchRagHealth();
setTimeout(parseRagArgsToControls,100);
} else {
tc.classList.add('hidden');
}
const lc=document.getElementById('llamaConfig');
if(lc){
if(s.name==='LLAMA_SERVICE'){
lc.classList.remove('hidden');
loadLlamaConfig(s.default_args||'');
} else {
lc.classList.add('hidden');
}
}
const kc=document.getElementById('kokoroConfig');
if(kc){
if(s.name==='KOKORO_ENGINE'){
kc.classList.remove('hidden');
loadKokoroConfig(s.default_args||'');
} else {
kc.classList.add('hidden');
}
}
const nc=document.getElementById('neuttsConfig');
if(nc){
if(s.name==='NEUTTS_ENGINE'){
nc.classList.remove('hidden');
loadNeuTTSStatus();
} else {
nc.classList.add('hidden');
}
}
const v2c=document.getElementById('vits2Config');
if(v2c){
if(s.name==='VITS2_ENGINE'){
v2c.classList.remove('hidden');
loadVITS2Config();
} else {
v2c.classList.add('hidden');
}
}
const mc=document.getElementById('matchaConfig');
if(mc){
if(s.name==='MATCHA_ENGINE'){
mc.classList.remove('hidden');
loadMatchaConfig();
} else {
mc.classList.add('hidden');
}
}
const moshic=document.getElementById('moshiConfig');
if(moshic){
if(s.name==='MOSHI_SERVICE'){
moshic.classList.remove('hidden');
if(!_moshiDirty) loadMoshiConfig();
} else {
moshic.classList.add('hidden');
}
}
}
function loadWhisperConfig(args){
fetch('/api/whisper/models').then(r=>r.json()).then(d=>{
const langSel=document.getElementById('whisperLang');
const modelSel=document.getElementById('whisperModel');
langSel.innerHTML=d.languages.map(l=>`<option value="${escapeHtml(l)}">${escapeHtml(l)}</option>`).join('');
modelSel.innerHTML=d.models.map(m=>`<option value="${escapeHtml(m)}">${escapeHtml(m)}</option>`).join('');
let curLang='de',curModel='';
const parts=args.split(/\s+/);
for(let i=0;i<parts.length;i++){
if((parts[i]==='--language'||parts[i]==='-l')&&i+1<parts.length){curLang=parts[i+1];i++;}
else if((parts[i]==='--model'||parts[i]==='-m')&&i+1<parts.length){curModel=parts[i+1];i++;}
else if(parts[i].indexOf('.bin')!==-1){curModel=parts[i];}
}
langSel.value=curLang;
window._cachedWhisperLang=curLang;
if(curModel)modelSel.value=curModel;
});
}
function updateWhisperArgs(){
const lang=document.getElementById('whisperLang').value;
const model=document.getElementById('whisperModel').value;
document.getElementById('svcDetailArgs').value=`--language ${lang} --model ${model}`;
}
function loadLlamaConfig(args){
fetch('/api/models/llama').then(r=>r.json()).then(d=>{
const sel=document.getElementById('llamaModel');
if(!sel)return;
const models=(d&&d.models)||[];
sel.innerHTML=models.map(m=>`<option value="${escapeHtml(m.path)}">${escapeHtml(m.filename)}</option>`).join('');
const parts=(args||'').trim().split(/\s+/);
const curModel=parts.find(p=>p.endsWith('.gguf'))||'';
if(curModel)sel.value=curModel;
}).catch(()=>{});
}
function updateLlamaArgs(){
const sel=document.getElementById('llamaModel');
if(!sel)return;
const model=sel.value;
const cur=document.getElementById('svcDetailArgs').value;
const stripped=cur.replace(/--model\s+\S+\.gguf(\s|$)/g,'').replace(/\S+\.gguf(\s|$)/g,'').replace(/\s+/g,' ').trim();
document.getElementById('svcDetailArgs').value=(stripped+' '+model).trim();
}
function loadKokoroConfig(args){
fetch('/api/models/kokoro').then(r=>r.json()).then(d=>{
const varSel=document.getElementById('kokoroVariant');
if(!varSel)return;
const variants=(d&&d.variants)||[];
varSel.innerHTML=variants.map(v=>`<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)}</option>`).join('');
let curVariant='',curVoice='';
const parts=(args||'').split(/\s+/);
for(let i=0;i<parts.length;i++){
if(parts[i]==='--variant'&&i+1<parts.length){curVariant=parts[++i];}
else if(parts[i]==='--voice'&&i+1<parts.length){curVoice=parts[++i];}
}
if(curVariant)varSel.value=curVariant;
window._kokoroData=variants;
updateKokoroVoices(curVoice);
}).catch(()=>{});
}
function updateKokoroVoices(preselect){
const varSel=document.getElementById('kokoroVariant');
const voiceSel=document.getElementById('kokoroVoice');
if(!varSel||!voiceSel)return;
const varName=varSel.value;
const variant=(window._kokoroData||[]).find(v=>v.name===varName);
const voices=variant?(variant.voices||[]):[];
voiceSel.innerHTML=voices.map(v=>`<option value="${escapeHtml(v)}">${escapeHtml(v)}</option>`).join('');
if(preselect&&typeof preselect==='string')voiceSel.value=preselect;
}
function updateKokoroArgs(){
const varSel=document.getElementById('kokoroVariant');
const voiceSel=document.getElementById('kokoroVoice');
if(!varSel||!voiceSel)return;
const variant=varSel.value;
const voice=voiceSel.value;
document.getElementById('svcDetailArgs').value=`--variant ${variant} --voice ${voice}`;
}
function loadNeuTTSStatus(){
fetch('/api/models/neutts').then(r=>r.json()).then(d=>{
const el=document.getElementById('neuttsModelStatus');
if(!el)return;
if(!d||!d.exists){
el.innerHTML='<span style="color:var(--wt-danger)">Model directory not found: bin/models/neutts-nano-german/. Download and convert the model via the Models page.</span>';
} else if(!d.coreml){
el.innerHTML='<span style="color:var(--wt-warning)">Model found but CoreML package missing. <button class="wt-btn wt-btn-sm wt-btn-secondary" onclick="triggerNeuTTSConvert()">Convert to CoreML</button></span>';
} else {
el.innerHTML='<span style="color:var(--wt-success)">Model ready (CoreML)</span>';
}
}).catch(()=>{
const el=document.getElementById('neuttsModelStatus');
if(el)el.innerHTML='<span style="color:var(--wt-text-secondary)">(offline)</span>';
});
}
function loadVITS2Config(){
fetch('/api/tts/engine_config?engine=vits2').then(r=>r.json()).then(d=>{
const langSel=document.getElementById('vits2Lang');
const g2pSel=document.getElementById('vits2G2P');
if(langSel&&d.language)langSel.value=d.language;
if(g2pSel&&d.g2p_backend)g2pSel.value=d.g2p_backend;
fetch('/api/tts/available_voices?engine=vits2').then(r=>r.json()).then(vd=>{
const voiceSel=document.getElementById('vits2Voice');
if(!voiceSel)return;
const voices=(vd&&vd.voices)||[];
voiceSel.innerHTML=voices.map(v=>`<option value="${escapeHtml(v)}">${escapeHtml(v)}</option>`).join('')||'<option value="default">default</option>';
if(d.voice)voiceSel.value=d.voice;
}).catch(()=>{});
}).catch(()=>{});
}
function updateVITS2Args(){
const voice=(document.getElementById('vits2Voice')||{}).value||'';
const g2p=(document.getElementById('vits2G2P')||{}).value||'';
const argsEl=document.getElementById('svcDetailArgs');
if(argsEl)argsEl.value=[voice?`--voice ${voice}`:'',g2p?`--g2p ${g2p}`:''].filter(Boolean).join(' ');
}
function saveVITS2Config(){
const voice=(document.getElementById('vits2Voice')||{}).value||'';
const g2p=(document.getElementById('vits2G2P')||{}).value||'';
const lang=(document.getElementById('vits2Lang')||{}).value||'de';
const statusEl=document.getElementById('vits2SaveStatus');
if(statusEl)statusEl.textContent='Saving...';
fetch('/api/tts/engine_config',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({engine:'vits2',voice,g2p_backend:g2p,language:lang})})
.then(r=>r.json()).then(d=>{
if(statusEl)statusEl.textContent='Saved';
setTimeout(()=>{if(statusEl)statusEl.textContent='';},2000);
}).catch(()=>{if(statusEl)statusEl.textContent='Error';setTimeout(()=>{if(statusEl)statusEl.textContent='';},3000);});
updateVITS2Args();
}
function loadMatchaConfig(){
fetch('/api/tts/engine_config?engine=matcha').then(r=>r.json()).then(d=>{
const langSel=document.getElementById('matchaLang');
const g2pSel=document.getElementById('matchaG2P');
if(langSel&&d.language)langSel.value=d.language;
if(g2pSel&&d.g2p_backend)g2pSel.value=d.g2p_backend;
fetch('/api/tts/available_voices?engine=matcha').then(r=>r.json()).then(vd=>{
const voiceSel=document.getElementById('matchaVoice');
if(!voiceSel)return;
const voices=(vd&&vd.voices)||[];
voiceSel.innerHTML=voices.map(v=>`<option value="${escapeHtml(v)}">${escapeHtml(v)}</option>`).join('')||'<option value="default">default</option>';
if(d.voice)voiceSel.value=d.voice;
}).catch(()=>{});
}).catch(()=>{});
}
function updateMatchaArgs(){
const voice=(document.getElementById('matchaVoice')||{}).value||'';
const g2p=(document.getElementById('matchaG2P')||{}).value||'';
const argsEl=document.getElementById('svcDetailArgs');
if(argsEl)argsEl.value=[voice?`--voice ${voice}`:'',g2p?`--g2p ${g2p}`:''].filter(Boolean).join(' ');
}
function saveMatchaConfig(){
const voice=(document.getElementById('matchaVoice')||{}).value||'';
const g2p=(document.getElementById('matchaG2P')||{}).value||'';
const lang=(document.getElementById('matchaLang')||{}).value||'de';
const statusEl=document.getElementById('matchaSaveStatus');
if(statusEl)statusEl.textContent='Saving...';
fetch('/api/tts/engine_config',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({engine:'matcha',voice,g2p_backend:g2p,language:lang})})
.then(r=>r.json()).then(d=>{
if(statusEl)statusEl.textContent='Saved';
setTimeout(()=>{if(statusEl)statusEl.textContent='';},2000);
}).catch(()=>{if(statusEl)statusEl.textContent='Error';setTimeout(()=>{if(statusEl)statusEl.textContent='';},3000);});
updateMatchaArgs();
}
let _moshiBackends=[];
let _moshiTriggers=[];
let _moshiDirty=false;
function loadMoshiConfig(){
fetch('/api/moshi/config').then(r=>r.json()).then(d=>{
_moshiBackends=d.backends||[];
_moshiTriggers=d.triggers||[];
const dl=document.getElementById('moshiDefaultLang');
if(dl)dl.value=d.default_language||'en';
const bu=document.getElementById('moshiBackendUrl');
if(bu)bu.value=d.backend_url||'http://127.0.0.1:8090';
const tcu=document.getElementById('moshiTomedoCrawlUrl');
if(tcu)tcu.value=d.tomedo_crawl_url||'http://127.0.0.1:13181';
const arc=document.getElementById('moshiArcMode');
if(arc){arc.checked=!!d.arc_mode_enabled;moshiToggleArcFields();}
const llm=document.getElementById('moshiLlmMode');
if(llm){llm.checked=!!d.llm_mode_enabled;moshiToggleLlmFields();}
const amf=document.getElementById('moshiArcModelFile');
if(amf)amf.value=d.arc_model_file||'';
const atp=document.getElementById('moshiArcTokenizerPath');
if(atp)atp.value=d.arc_tokenizer_path||'';
const lau=document.getElementById('moshiLlmApiUrl');
if(lau)lau.value=d.llm_api_url||'';
const lak=document.getElementById('moshiLlmApiKey');
if(lak)lak.value=d.llm_api_key||'';
const ra=document.getElementById('moshiRetAction');
if(ra)ra.value=d.ret_action||'tomedo-crawl-query';
renderMoshiBackendList();
renderMoshiTriggerList();
buildMoshiArgs();
moshiTriggerActionTypeChanged();
}).catch(()=>{});
}
function moshiToggleArcFields(){
const f=document.getElementById('moshiArcFields');
const c=document.getElementById('moshiArcMode');
if(f&&c){if(c.checked)f.classList.remove('hidden');else f.classList.add('hidden');}
}
function moshiToggleLlmFields(){
const f=document.getElementById('moshiLlmFields');
const c=document.getElementById('moshiLlmMode');
if(f&&c){if(c.checked)f.classList.remove('hidden');else f.classList.add('hidden');}
}
function moshiTriggerActionTypeChanged(){
const sel=document.getElementById('moshiNewTriggerActionType');
const wrap=document.getElementById('moshiNewTriggerActionUrlWrap');
if(!sel||!wrap)return;
const v=sel.value;
if(v==='tomedo-crawl-query'||v==='llm-retrieval')wrap.style.opacity='0.4';
else wrap.style.opacity='1';
}
function renderMoshiBackendList(){
const el=document.getElementById('moshiBackendList');
if(!el)return;
if(_moshiBackends.length===0){el.innerHTML='<div style="font-size:11px;color:var(--wt-text-secondary);margin-bottom:4px">No backends configured.</div>';return;}
let h='<table style="width:100%;border-collapse:collapse;font-size:11px;margin-bottom:4px">'
+'<tr style="color:var(--wt-text-secondary)"><th style="text-align:left;padding:2px 4px">Lang</th><th style="text-align:left;padding:2px 4px">Config JSON</th><th style="text-align:left;padding:2px 4px">Binary</th><th></th></tr>';
_moshiBackends.forEach(function(b,i){
h+=`<tr><td style="padding:2px 4px">${escapeHtml(b.lang)}</td>`
+`<td style="padding:2px 4px;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${escapeHtml(b.config)}">${escapeHtml(b.config)}</td>`
+`<td style="padding:2px 4px;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escapeHtml(b.binary||'')}</td>`
+`<td style="padding:2px 4px"><button class="wt-btn wt-btn-sm wt-btn-danger" style="font-size:10px;padding:1px 6px" onclick="moshiRemoveBackend(${i})">✕</button></td></tr>`;
});
el.innerHTML=h+'</table>';
}
function renderMoshiTriggerList(){
const el=document.getElementById('moshiTriggerList');
if(!el)return;
if(_moshiTriggers.length===0){el.innerHTML='<div style="font-size:11px;color:var(--wt-text-secondary);margin-bottom:4px">No triggers configured.</div>';return;}
let h='<table style="width:100%;border-collapse:collapse;font-size:11px;margin-bottom:4px">'
+'<tr style="color:var(--wt-text-secondary)"><th style="text-align:left;padding:2px 4px">Type</th><th style="text-align:left;padding:2px 4px">Match</th><th style="text-align:left;padding:2px 4px">Action Type</th><th style="text-align:left;padding:2px 4px">Action URL</th><th style="text-align:left;padding:2px 4px">Label</th><th style="text-align:left;padding:2px 4px">CD(s)</th><th style="text-align:left;padding:2px 4px">Inj</th><th></th></tr>';
_moshiTriggers.forEach(function(t,i){
h+=`<tr><td style="padding:2px 4px">${escapeHtml(t.type)}</td>`
+`<td style="padding:2px 4px;max-width:100px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${escapeHtml(t.match)}">${escapeHtml(t.match||'')}</td>`
+`<td style="padding:2px 4px">${escapeHtml(t.action_type||'tomedo-crawl-query')}</td>`
+`<td style="padding:2px 4px;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${escapeHtml(t.action_url||'')}">${escapeHtml(t.action_url||'')}</td>`
+`<td style="padding:2px 4px">${escapeHtml(t.label||'')}</td>`
+`<td style="padding:2px 4px">${escapeHtml(t.cooldown_secs!=null?t.cooldown_secs:30)}</td>`
+`<td style="padding:2px 4px">${t.inject_result!==false?'✓':'—'}</td>`
+`<td style="padding:2px 4px"><button class="wt-btn wt-btn-sm wt-btn-danger" style="font-size:10px;padding:1px 6px" onclick="moshiRemoveTrigger(${i})">✕</button></td></tr>`;
});
el.innerHTML=h+'</table>';
}
function moshiAddBackend(){
const lang=(document.getElementById('moshiNewLang')||{}).value||'';
const config=(document.getElementById('moshiNewConfig')||{}).value||'';
const binary=(document.getElementById('moshiNewBinary')||{}).value||'';
if(!lang||!config){alert('Language code and config path are required.');return;}
_moshiBackends.push({lang,config,binary});
_moshiDirty=true;
renderMoshiBackendList();
buildMoshiArgs();
document.getElementById('moshiNewLang').value='';
document.getElementById('moshiNewConfig').value='';
document.getElementById('moshiNewBinary').value='';
}
function moshiRemoveBackend(i){
_moshiBackends.splice(i,1);
_moshiDirty=true;
renderMoshiBackendList();
buildMoshiArgs();
}
function moshiAddTrigger(){
const type=(document.getElementById('moshiNewTriggerType')||{}).value||'keyword';
const match=(document.getElementById('moshiNewTriggerMatch')||{}).value||'';
const action_type=(document.getElementById('moshiNewTriggerActionType')||{}).value||'tomedo-crawl-query';
const action_url=(document.getElementById('moshiNewTriggerActionUrl')||{}).value||'';
const label=(document.getElementById('moshiNewTriggerLabel')||{}).value||'';
const _rawCooldown=parseInt((document.getElementById('moshiNewTriggerCooldown')||{}).value);
const cooldown_secs=isNaN(_rawCooldown)?30:_rawCooldown;
const inject_result=!!(document.getElementById('moshiNewTriggerInject')||{}).checked;
if((type==='keyword'||type==='regex')&&!match){alert('Match pattern is required for keyword and regex trigger types.');return;}
if(action_type==='webhook'||action_type==='calendar'||action_type==='script'||action_type==='retrieval_and_webhook'){
if(!action_url){alert('Action URL / path is required for this action type.');return;}
}
const id=crypto.randomUUID?crypto.randomUUID():('t-'+Date.now()+'-'+Math.random().toString(36).slice(2,8));
_moshiTriggers.push({id,type,match,action_type,action_url,label,cooldown_secs,inject_result});
_moshiDirty=true;
renderMoshiTriggerList();
document.getElementById('moshiNewTriggerType').value='keyword';
document.getElementById('moshiNewTriggerMatch').value='';
document.getElementById('moshiNewTriggerActionType').value='tomedo-crawl-query';
document.getElementById('moshiNewTriggerActionUrl').value='';
document.getElementById('moshiNewTriggerLabel').value='';
document.getElementById('moshiNewTriggerCooldown').value='30';
document.getElementById('moshiNewTriggerInject').checked=true;
moshiTriggerActionTypeChanged();
}
function moshiRemoveTrigger(i){
_moshiTriggers.splice(i,1);
_moshiDirty=true;
renderMoshiTriggerList();
}
function buildMoshiArgs(){
const dl=(document.getElementById('moshiDefaultLang')||{}).value||'en';
const f=document.getElementById('svcDetailArgs');
if(!f)return;
let existing=f.value||'';
let kept=[];
let tokens=existing.match(/(?:[^\s"]+|"[^"]*")+/g)||[];
for(let i=0;i<tokens.length;i++){
if(tokens[i]==='--backend-config'||tokens[i]==='-B'){i++;continue;}
if(tokens[i].startsWith('--backend-config='))continue;
if(tokens[i]==='--default-language'||tokens[i]==='-d'){i++;continue;}
if(tokens[i].startsWith('--default-language='))continue;
kept.push(tokens[i]);
}
let args='';
_moshiBackends.forEach(function(b){
let spec=b.lang+':'+b.config;
if(b.binary)spec+=':'+b.binary;
args+='--backend-config '+spec+' ';
});
args+='--default-language '+dl;
if(kept.length>0)args+=' '+kept.join(' ');
f.value=args.trim();
}
function saveMoshiConfig(){
const dl=(document.getElementById('moshiDefaultLang')||{}).value||'en';
const st=document.getElementById('moshiConfigStatus');
if(st)st.textContent='Saving...';
buildMoshiArgs();
const payload={
backends:_moshiBackends,
triggers:_moshiTriggers,
default_language:dl,
backend_url:(document.getElementById('moshiBackendUrl')||{}).value||'http://127.0.0.1:8090',
tomedo_crawl_url:(document.getElementById('moshiTomedoCrawlUrl')||{}).value||'http://127.0.0.1:13181',
arc_mode_enabled:!!(document.getElementById('moshiArcMode')||{}).checked,
llm_mode_enabled:!!(document.getElementById('moshiLlmMode')||{}).checked,
arc_model_file:(document.getElementById('moshiArcModelFile')||{}).value||'',
arc_tokenizer_path:(document.getElementById('moshiArcTokenizerPath')||{}).value||'',
llm_api_url:(document.getElementById('moshiLlmApiUrl')||{}).value||'',
llm_api_key:(document.getElementById('moshiLlmApiKey')||{}).value||'',
ret_action:(document.getElementById('moshiRetAction')||{}).value||'tomedo-crawl-query'
};
fetch('/api/moshi/config',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify(payload)
}).then(r=>r.json()).then(d=>{
_moshiDirty=false;
if(st)st.textContent='Saved';
setTimeout(()=>{if(st)st.textContent='';},2000);
saveSvcConfig();
}).catch(()=>{if(st)st.textContent='Error';setTimeout(()=>{if(st)st.textContent='';},3000);});
}
function toggleHallucinationFilter(enabled){
const statusEl=document.getElementById('whisperHalluFilterStatus');
statusEl.textContent='...';
fetch('/api/whisper/hallucination_filter',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({enabled:enabled?'true':'false'})})
.then(r=>r.json()).then(d=>{
if(d.error){statusEl.textContent='(offline)';document.getElementById('whisperHallucinationFilter').checked=false;return;}
statusEl.textContent=d.enabled?'ON':'OFF';
}).catch(()=>{statusEl.textContent='(error)';});
}
function loadHallucinationFilterState(){
const cb=document.getElementById('whisperHallucinationFilter');
const statusEl=document.getElementById('whisperHalluFilterStatus');
fetch('/api/whisper/hallucination_filter').then(r=>r.json()).then(d=>{
if(d.error){cb.checked=false;statusEl.textContent='(offline)';return;}
cb.checked=d.enabled;statusEl.textContent=d.enabled?'ON':'OFF';
}).catch(()=>{cb.checked=false;statusEl.textContent='(offline)';});
}
function loadSipProviderWavConfig(){
const cb=document.getElementById('sipProviderSaveWav');
const dirEl=document.getElementById('sipProviderWavDir');
const statusEl=document.getElementById('sipProviderWavStatus');
fetch(`http://localhost:${TSP_PORT}/wav_recording`).then(r=>r.json()).then(d=>{
cb.checked=d.enabled;
dirEl.value=d.dir||'';
statusEl.textContent=d.enabled?'ON':'OFF';
}).catch(()=>{cb.checked=false;statusEl.textContent='(offline)';});
}
function saveSipProviderWavConfig(){
const cb=document.getElementById('sipProviderSaveWav');
const dirEl=document.getElementById('sipProviderWavDir');
const statusEl=document.getElementById('sipProviderWavStatus');
statusEl.textContent='...';
fetch(`http://localhost:${TSP_PORT}/wav_recording`,{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({enabled:cb.checked,dir:dirEl.value})
}).then(()=>loadSipProviderWavConfig()).catch(()=>{statusEl.textContent='(error)';});
}
function loadOapWavConfig(){
const cb=document.getElementById('oapSaveWav');
const dirEl=document.getElementById('oapWavDir');
const statusEl=document.getElementById('oapWavStatus');
fetch('/api/oap/wav_recording').then(r=>r.json()).then(d=>{
if(d.error){cb.checked=false;statusEl.textContent='(offline)';return;}
cb.checked=d.enabled;
dirEl.value=d.dir||'';
statusEl.textContent=d.enabled?'ON':'OFF';
}).catch(()=>{cb.checked=false;statusEl.textContent='(offline)';});
}
function saveOapWavConfig(){
const cb=document.getElementById('oapSaveWav');
const dirEl=document.getElementById('oapWavDir');
const statusEl=document.getElementById('oapWavStatus');
statusEl.textContent='...';
fetch('/api/oap/wav_recording',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({enabled:cb.checked?'true':'false',dir:dirEl.value})
}).then(()=>loadOapWavConfig()).catch(()=>{statusEl.textContent='(error)';});
}
var _ragSavedModel=null;
function loadRagConfig(){
fetch('/api/rag/config').then(r=>r.json()).then(d=>{
const h=document.getElementById('ragTomedoHost');
const p=document.getElementById('ragTomedoPort');
const ou=document.getElementById('ragOllamaUrl');
const ct=document.getElementById('ragCrawlTime');
const cr=document.getElementById('ragCrawlRepeatMin');
const cs=document.getElementById('ragCertStatus');
if(h)h.value=d.tomedo_host||'';
if(p)p.value=d.tomedo_port||'';
if(ou)ou.value=d.ollama_url||'';
if(ct)ct.value=d.crawl_time||'02:00';
const rMin=parseInt(d.crawl_repeat_minutes||'0',10);
if(cr)cr.value=rMin>0?rMin:60;
const modeRadio=document.querySelector('input[name="ragCrawlMode"][value="'+(rMin>0?'interval':'daily')+'"]');
if(modeRadio){modeRadio.checked=true;toggleCrawlMode();}
if(cs)cs.textContent=d.cert_uploaded?'Certificate uploaded':'No certificate';
_ragSavedModel=d.ollama_model||'embeddinggemma:300m';
loadOllamaModels(_ragSavedModel);
checkOllamaStatus();
}).catch(()=>{});
}
function loadOllamaModels(activeModel){
fetch('/api/ollama/models').then(r=>r.json()).then(d=>{
const sel=document.getElementById('ragOllamaModel');
if(!sel)return;
sel.innerHTML='';
if(d.models&&d.models.length>0){
d.models.forEach(m=>{
const opt=document.createElement('option');
opt.value=m.name;opt.textContent=m.name;
if(m.name===activeModel||m.active)opt.selected=true;
sel.appendChild(opt);
});
if(!Array.from(sel.options).some(o=>o.value===activeModel)){
const opt=document.createElement('option');
opt.value=activeModel;opt.textContent=activeModel+' (not installed)';
opt.selected=true;sel.appendChild(opt);
}
} else {
const opt=document.createElement('option');
opt.value=activeModel;opt.textContent=activeModel;
opt.selected=true;sel.appendChild(opt);