forked from Coneja-Chibi/TunnelVision
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui-controller.js
More file actions
2106 lines (1825 loc) · 87.4 KB
/
ui-controller.js
File metadata and controls
2106 lines (1825 loc) · 87.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
/**
* TunnelVision UI Controller
* Handles tree editor rendering, drag-and-drop, settings panel, and all user interactions.
*/
import { saveSettingsDebounced } from '../../../../script.js';
import { getContext } from '../../../st-context.js';
import { world_names, loadWorldInfo, saveWorldInfo } from '../../../world-info.js';
import { getAutoSummaryCount, resetAutoSummaryCount } from './auto-summary.js';
import { getActiveTunnelVisionBooks } from './tool-registry.js';
import {
getTree,
saveTree,
deleteTree,
isLorebookEnabled,
setLorebookEnabled,
createTreeNode,
addEntryToNode,
removeNode,
removeEntryFromTree,
getAllEntryUids,
getSettings,
getBookDescription,
setBookDescription,
getSelectedLorebook,
setSelectedLorebook,
isTrackerUid,
isTrackerTitle,
setTrackerUid,
syncTrackerUidsForLorebook,
getConnectionProfileId,
setConnectionProfileId,
listConnectionProfiles,
getBookPermission,
setBookPermission,
SETTING_DEFAULTS,
} from './tree-store.js';
import { buildTreeFromMetadata, buildTreeWithLLM, generateSummariesForTree, ingestChatMessages } from './tree-builder.js';
import { registerTools, unregisterTools, getDefaultToolDescriptions, stripDynamicContent } from './tool-registry.js';
import { runDiagnostics } from './diagnostics.js';
import { applyRecurseLimit } from './index.js';
import { refreshHiddenToolCallMessages } from './activity-feed.js';
import { separateConditions, isEvaluableCondition, formatCondition, EVALUABLE_TYPES, CONDITION_LABELS, getKeywordProbability, setKeywordProbability } from './conditions.js';
import { callGenericPopup, POPUP_TYPE } from '../../../popup.js';
let currentLorebook = null;
function selectCurrentLorebook(bookName) {
currentLorebook = bookName || null;
setSelectedLorebook(currentLorebook);
}
function syncSelectedLorebook() {
if (currentLorebook && world_names?.includes(currentLorebook)) {
return;
}
const preferredLorebook = getSelectedLorebook();
if (preferredLorebook && world_names?.includes(preferredLorebook)) {
currentLorebook = preferredLorebook;
return;
}
currentLorebook = null;
}
// ─── Event Bindings ──────────────────────────────────────────────
export function bindUIEvents() {
// Main collapsible header
$('#tv_header_toggle').on('click', function () {
$(this).toggleClass('expanded');
$(this).closest('.tv-container').find('.tv-settings-body').slideToggle(200);
});
$('#tv_global_enabled').on('change', onGlobalToggle);
$('#tv_conditional_triggers_master').on('change', function () {
const settings = getSettings();
settings.conditionalTriggersEnabled = $(this).prop('checked');
$('#tv_conditional_triggers').prop('checked', settings.conditionalTriggersEnabled);
saveSettingsDebounced();
});
$('#tv_lorebook_select').on('change', onLorebookSelect);
$('#tv_lorebook_enabled').on('change', onLorebookToggle);
$('#tv_book_description').on('input', onBookDescriptionChange);
$('#tv_build_metadata').on('click', onBuildFromMetadata);
$('#tv_build_llm').on('click', onBuildWithLLM);
$('#tv_open_tree_editor').on('click', onOpenTreeEditor);
$('#tv_import_file').on('change', onImportTree);
$('#tv_bulk_export').on('click', onBulkExport);
$('#tv_bulk_import_file').on('change', onBulkImport);
$('#tv_bulk_import').on('click', () => $('#tv_bulk_import_file').trigger('click'));
$('#tv_run_diagnostics').on('click', onRunDiagnostics);
// Lorebook filter
$('#tv_lorebook_filter').on('input', onLorebookFilter);
// Advanced Settings collapsible header
$('#tv_advanced_header').on('click', function () {
$(this).toggleClass('expanded');
$(this).next('.tv-advanced-body').slideToggle(200);
});
// Auto-detect pattern
$('#tv_auto_detect_pattern').on('input', function () {
const settings = getSettings();
settings.autoDetectPattern = $(this).val();
saveSettingsDebounced();
});
// Per-tool toggles
$(document).on('change', '.tv_tool_enabled', onToolToggle);
// Per-tool confirmation toggles
$('.tv_tool_confirm').on('change', onToolConfirmToggle);
// Tool prompt overrides
$('#tv_tool_prompt_overrides').on('input', '.tv-tool-prompt-textarea', onToolPromptChange);
$('#tv_tool_prompt_overrides').on('click', '.tv-tool-prompt-reset', onToolPromptReset);
// Search mode radio
$('input[name="tv_search_mode"]').on('change', onSearchModeChange);
// Collapsed tree depth
$('#tv_collapsed_depth').on('change', onCollapsedDepthChange);
// Selective retrieval
$('#tv_selective_retrieval').on('change', onSelectiveRetrievalToggle);
// Recurse limit
$('#tv_recurse_limit').on('change', onRecurseLimitChange);
// LLM build detail level
$('#tv_llm_detail').on('change', onLlmDetailChange);
// Tree granularity
$('#tv_tree_granularity').on('change', onTreeGranularityChange);
// LLM chunk size
$('#tv_chunk_tokens').on('change', onChunkTokensChange);
// Vector dedup toggle + threshold
$('#tv_vector_dedup').on('change', onVectorDedupToggle);
$('#tv_dedup_threshold').on('change', onDedupThresholdChange);
// Chat ingest
$('#tv_ingest_chat').on('click', onIngestChat);
// Mandatory tool calls & prompt injection settings
$('#tv_mandatory_tools').on('change', onMandatoryToolsToggle);
$('#tv_mandatory_position').on('change', onPromptInjectionChange);
$('#tv_mandatory_depth').on('change', onPromptInjectionChange);
$('#tv_mandatory_role').on('change', onPromptInjectionChange);
$('#tv_mandatory_prompt_text').on('change', onMandatoryPromptTextChange);
$('#tv_mandatory_prompt_reset').on('click', onMandatoryPromptReset);
$('#tv_notebook_position').on('change', onPromptInjectionChange);
$('#tv_notebook_depth').on('change', onPromptInjectionChange);
$('#tv_notebook_role').on('change', onPromptInjectionChange);
$('#tv_stealth_mode').on('change', onStealthModeToggle);
$('#tv_ephemeral_results').on('change', onEphemeralResultsToggle);
$('.tv_ephemeral_tool').on('change', onEphemeralToolFilterChange);
// Slash commands context setting
$('#tv_command_context').on('change', onCommandContextChange);
// Auto-summary settings
$('#tv_auto_summary_enabled').on('change', onAutoSummaryToggle);
$('#tv_auto_summary_interval').on('change', onAutoSummaryIntervalChange);
$('#tv_auto_hide_summarized').on('change', onAutoHideSummarizedToggle);
$('#tv_passthrough_constant').on('change', onPassthroughConstantToggle);
$('#tv_allow_keyword_triggers').on('change', onAllowKeywordTriggersToggle);
// Multi-book mode
$('input[name="tv_multi_book_mode"]').on('change', onMultiBookModeChange);
// Sidecar LLM (connection profile + sampler overrides)
$('#tv_connection_profile').on('change', onConnectionProfileChange);
$('#tv_sidecar_temperature').on('input', onSidecarTemperatureChange);
$('#tv_sidecar_max_tokens').on('input', onSidecarMaxTokensChange);
// Sidecar auto-retrieval
$('#tv_sidecar_auto_retrieval').on('change', onSidecarAutoRetrievalToggle);
$('#tv_sidecar_context_messages').on('input', onSidecarContextMessagesChange);
$('#tv_sidecar_max_injection').on('input', onSidecarMaxInjectionChange);
$('#tv_conditional_triggers').on('change', function () {
const settings = getSettings();
settings.conditionalTriggersEnabled = $(this).prop('checked');
$('#tv_conditional_triggers_master').prop('checked', settings.conditionalTriggersEnabled);
saveSettingsDebounced();
});
// Sidecar post-gen writer
$('#tv_sidecar_post_gen_writer').on('change', onSidecarPostGenWriterToggle);
$('#tv_sidecar_writer_context').on('input', onSidecarWriterContextChange);
$('#tv_sidecar_writer_max_ops').on('input', onSidecarWriterMaxOpsChange);
// Compact tool prompts
$('#tv_compact_tool_prompts').on('change', onCompactToolPromptsToggle);
// Per-lorebook permissions
$('#tv_book_permission').on('change', onBookPermissionChange);
// Backup & Restore collapsible header
$('#tv_backup_header').on('click', function () {
$(this).toggleClass('expanded');
$(this).next('.tv-card-body').slideToggle(200);
});
// Diagnostics collapsible header
$('#tv_diagnostics_header').on('click', function () {
$(this).toggleClass('expanded');
$(this).next('.tv-diagnostics-body').slideToggle(200);
});
}
// ─── Refresh / Init ──────────────────────────────────────────────
export function refreshUI() {
const settings = getSettings();
const globalEnabled = settings.globalEnabled !== false;
syncSelectedLorebook();
$('#tv_global_enabled').prop('checked', globalEnabled);
$('#tv_main_controls').toggle(globalEnabled);
$('#tv_conditional_master_row').toggle(globalEnabled);
$('#tv_conditional_triggers_master').prop('checked', settings.conditionalTriggersEnabled !== false);
// Sync tool toggles from settings
const disabledTools = settings.disabledTools || {};
$('.tv_tool_enabled').each(function () {
const toolName = $(this).data('tool');
$(this).prop('checked', !disabledTools[toolName]);
});
// Sync tool confirmation toggles
const confirmTools = settings.confirmTools || {};
$('.tv_tool_confirm').each(function () {
const toolName = $(this).data('tool');
$(this).prop('checked', !!confirmTools[toolName]);
});
// Render tool prompt overrides
renderToolPromptOverrides();
// Sync search mode radio
$(`input[name="tv_search_mode"][value="${settings.searchMode || 'traversal'}"]`).prop('checked', true);
// Sync collapsed depth
$('#tv_collapsed_depth').val(settings.collapsedDepth ?? 2);
$('#tv_collapsed_depth_section').toggle((settings.searchMode || 'traversal') === 'collapsed');
// Sync auto-detect pattern
$('#tv_auto_detect_pattern').val(settings.autoDetectPattern || '');
// Sync selective retrieval
$('#tv_selective_retrieval').prop('checked', settings.selectiveRetrieval === true);
// Sync recurse limit
const recurseLimit = settings.recurseLimit ?? 5;
$('#tv_recurse_limit').val(recurseLimit);
$('#tv_recurse_warn').toggle(recurseLimit > 10);
// Sync LLM detail level
$('#tv_llm_detail').val(settings.llmBuildDetail || 'full');
// Sync tree granularity
$('#tv_tree_granularity').val(settings.treeGranularity ?? 0);
// Sync LLM chunk size
$('#tv_chunk_tokens').val(settings.llmChunkTokens ?? 30000);
// Sync vector dedup
const dedupEnabled = settings.enableVectorDedup === true;
$('#tv_vector_dedup').prop('checked', dedupEnabled);
$('#tv_dedup_threshold_row').toggle(dedupEnabled);
$('#tv_dedup_threshold').val(settings.vectorDedupThreshold ?? 0.85);
updateDedupStatus(dedupEnabled);
// Sync mandatory tool calls & prompt injection
$('#tv_mandatory_tools').prop('checked', settings.mandatoryTools === true);
$('#tv_mandatory_prompt_options').toggle(settings.mandatoryTools === true);
$('#tv_mandatory_position').val(settings.mandatoryPromptPosition || 'in_chat');
$('#tv_mandatory_depth').val(settings.mandatoryPromptDepth ?? 1);
$('#tv_mandatory_role').val(settings.mandatoryPromptRole || 'system');
$('#tv_mandatory_prompt_text').val(settings.mandatoryPromptText || '');
$('#tv_mandatory_depth_row').toggle((settings.mandatoryPromptPosition || 'in_chat') === 'in_chat');
// Sync notebook injection settings
$('#tv_notebook_position').val(settings.notebookPromptPosition || 'in_chat');
$('#tv_notebook_depth').val(settings.notebookPromptDepth ?? 1);
$('#tv_notebook_role').val(settings.notebookPromptRole || 'system');
$('#tv_notebook_depth_row').toggle((settings.notebookPromptPosition || 'in_chat') === 'in_chat');
$('#tv_stealth_mode').prop('checked', settings.stealthMode === true);
$('#tv_ephemeral_results').prop('checked', settings.ephemeralResults === true);
$('#tv_ephemeral_filter_options').toggle(settings.ephemeralResults === true);
const filterList = settings.ephemeralToolFilter || [];
$('.tv_ephemeral_tool').each(function () {
$(this).prop('checked', filterList.includes($(this).val()));
});
// Sync slash command context setting
$('#tv_command_context').val(settings.commandContextMessages ?? 50);
// Sync auto-summary settings
const autoEnabled = settings.autoSummaryEnabled === true;
$('#tv_auto_summary_enabled').prop('checked', autoEnabled);
$('#tv_auto_summary_options').toggle(autoEnabled);
$('#tv_auto_summary_interval').val(settings.autoSummaryInterval ?? 20);
$('#tv_auto_summary_count').text(getAutoSummaryCount());
$('#tv_auto_hide_summarized').prop('checked', settings.autoHideSummarized !== false);
$('#tv_passthrough_constant').prop('checked', settings.passthroughConstant !== false);
$('#tv_allow_keyword_triggers').prop('checked', settings.allowKeywordTriggers === true);
// Sync multi-book mode
$(`input[name="tv_multi_book_mode"][value="${settings.multiBookMode || 'unified'}"]`).prop('checked', true);
// Sync connection profile + sidecar sampler controls
populateConnectionProfiles();
populateLorebookDropdown();
$('#tv_lorebook_controls').toggle(!!currentLorebook);
if (currentLorebook) {
loadLorebookUI(currentLorebook);
}
}
function onLorebookFilter() {
const query = $('#tv_lorebook_filter').val().toLowerCase().trim();
$('#tv_lorebook_list .tv-lorebook-card').each(function () {
const bookName = $(this).attr('data-book')?.toLowerCase() || '';
$(this).toggle(!query || bookName.includes(query));
});
}
function populateLorebookDropdown() {
syncSelectedLorebook();
const $list = $('#tv_lorebook_list');
$list.empty();
if (!world_names?.length) {
$list.append('<div class="tv-help-text" style="text-align:center; padding: 12px;">No lorebooks found.</div>');
return;
}
// Sort: TV-enabled first, then active in chat, then alphabetical
const activeBooks = getActiveTunnelVisionBooks();
const sorted = [...world_names].sort((a, b) => {
const aTV = isLorebookEnabled(a) ? 1 : 0;
const bTV = isLorebookEnabled(b) ? 1 : 0;
if (aTV !== bTV) return bTV - aTV;
const aActive = activeBooks.includes(a) ? 1 : 0;
const bActive = activeBooks.includes(b) ? 1 : 0;
if (aActive !== bActive) return bActive - aActive;
return a.localeCompare(b);
});
for (const name of sorted) {
const isActive = activeBooks.includes(name);
const tvEnabled = isLorebookEnabled(name);
const tree = getTree(name);
const hasTree = !!tree?.root?.children?.length;
const $card = $('<div class="tv-lorebook-card"></div>')
.toggleClass('tv-lorebook-active', isActive)
.toggleClass('tv-lorebook-selected', name === currentLorebook)
.attr('data-book', name);
const $info = $('<div class="tv-lorebook-card-info"></div>');
const $name = $('<span class="tv-lorebook-card-name"></span>').text(name);
$info.append($name);
// Status badges
const $badges = $('<div class="tv-lorebook-card-badges"></div>');
if (!isActive) {
$badges.append('<span class="tv-badge-inactive">inactive</span>');
}
if (tvEnabled) {
$badges.append('<span class="tv-badge-tv-on"><i class="fa-solid fa-eye"></i> TV On</span>');
}
if (hasTree) {
const count = (tree.root.children || []).length;
$badges.append(`<span class="tv-badge-tree">${count} cat</span>`);
}
$info.append($badges);
// Status indicator dot
const dotClass = tvEnabled ? 'tv-dot-on' : (hasTree ? 'tv-dot-ready' : 'tv-dot-off');
const $dot = $(`<span class="tv-lorebook-dot ${dotClass}"></span>`);
$card.append($dot, $info);
$card.on('click', () => {
selectCurrentLorebook(name);
$('.tv-lorebook-card').removeClass('tv-lorebook-selected');
$card.addClass('tv-lorebook-selected');
$('#tv_lorebook_controls').show();
loadLorebookUI(name);
});
$list.append($card);
}
}
// ─── Lorebook & Toggle Handlers ──────────────────────────────────
function onGlobalToggle() {
const enabled = $(this).prop('checked');
const settings = getSettings();
settings.globalEnabled = enabled;
saveSettingsDebounced();
$('#tv_main_controls').toggle(enabled);
$('#tv_conditional_master_row').toggle(enabled);
enabled ? registerTools() : unregisterTools();
}
function onLorebookSelect() {
// Legacy handler for hidden select (kept for compatibility)
const bookName = $(this).val();
selectCurrentLorebook(bookName || null);
$('#tv_lorebook_controls').toggle(!!bookName);
if (bookName) loadLorebookUI(bookName);
}
async function loadLorebookUI(bookName) {
const bookData = await loadWorldInfo(bookName);
if (bookData?.entries) {
await syncTrackerUidsForLorebook(bookName, bookData.entries);
}
$('#tv_lorebook_enabled').prop('checked', isLorebookEnabled(bookName));
$('#tv_book_description').val(getBookDescription(bookName) || '');
$('#tv_book_permission').val(getBookPermission(bookName));
const tree = getTree(bookName);
updateTreeStatus(bookName, tree);
await renderTreeEditor(bookName, tree);
await renderUnassignedEntries(bookName, tree, bookData);
updateIngestUI();
}
function updateIngestUI() {
const context = getContext();
const hasChat = !!(context.chatId && context.chat?.length > 0);
const hasBook = !!currentLorebook && isLorebookEnabled(currentLorebook);
$('#tv_ingest_container').toggle(hasBook);
if (hasChat) {
const maxIdx = context.chat.length - 1;
$('#tv_ingest_to').attr('max', maxIdx).val(maxIdx);
$('#tv_ingest_from').attr('max', maxIdx);
$('#tv_ingest_chat_info').text(`Chat has ${context.chat.length} messages (0-${maxIdx})`);
$('#tv_ingest_chat').prop('disabled', false);
} else {
$('#tv_ingest_chat_info').text('No chat open. Open a chat to ingest messages.');
$('#tv_ingest_chat').prop('disabled', true);
}
}
function onLorebookToggle() {
if (!currentLorebook) return;
setLorebookEnabled(currentLorebook, $(this).prop('checked'));
registerTools();
populateLorebookDropdown(); // refresh badges
}
function onBookDescriptionChange() {
if (!currentLorebook) return;
const desc = $(this).val().trim();
setBookDescription(currentLorebook, desc);
saveSettingsDebounced();
}
function onToolToggle() {
const toolName = $(this).data('tool');
const enabled = $(this).prop('checked');
const settings = getSettings();
const disabledTools = settings.disabledTools || {};
if (enabled) {
delete disabledTools[toolName];
} else {
disabledTools[toolName] = true;
}
settings.disabledTools = disabledTools;
// Sync notebook injection setting with tool toggle
if (toolName === 'TunnelVision_Notebook') {
settings.notebookEnabled = enabled;
}
saveSettingsDebounced();
registerTools();
}
// ─── Tool Confirmation Toggles ───────────────────────────────────
function onToolConfirmToggle() {
const toolName = $(this).data('tool');
const settings = getSettings();
if (!settings.confirmTools) settings.confirmTools = {};
settings.confirmTools[toolName] = $(this).prop('checked');
saveSettingsDebounced();
registerTools();
}
// ─── Tool Prompt Overrides ───────────────────────────────────────
function renderToolPromptOverrides() {
const $container = $('#tv_tool_prompt_overrides');
$container.empty();
const settings = getSettings();
const overrides = settings.toolPromptOverrides || {};
const defaults = getDefaultToolDescriptions();
for (const [toolName, defaultDesc] of Object.entries(defaults)) {
const rawOverride = overrides[toolName] ? stripDynamicContent(overrides[toolName]) : null;
const currentValue = rawOverride || defaultDesc;
const isModified = !!rawOverride && rawOverride !== defaultDesc;
const shortName = toolName.replace('TunnelVision_', '');
const $block = $(`<div class="tv-tool-prompt-block ${isModified ? 'tv-tool-prompt-modified' : ''}"></div>`);
const $header = $('<div class="tv-tool-prompt-header"></div>');
$header.append(`<span class="tv-tool-prompt-label">${shortName}</span>`);
$header.append(`<button class="tv-tool-prompt-reset" data-tool="${toolName}" title="Reset to default">Reset</button>`);
$block.append($header);
const $textarea = $(`<textarea class="tv-tool-prompt-textarea" data-tool="${toolName}" rows="4"></textarea>`);
$textarea.val(currentValue);
$block.append($textarea);
$container.append($block);
}
}
function onToolPromptChange() {
const toolName = $(this).data('tool');
const value = stripDynamicContent($(this).val());
const settings = getSettings();
if (!settings.toolPromptOverrides) settings.toolPromptOverrides = {};
const defaults = getDefaultToolDescriptions();
if (value === defaults[toolName]) {
// Value matches default — remove override
delete settings.toolPromptOverrides[toolName];
$(this).closest('.tv-tool-prompt-block').removeClass('tv-tool-prompt-modified');
} else {
settings.toolPromptOverrides[toolName] = value;
$(this).closest('.tv-tool-prompt-block').addClass('tv-tool-prompt-modified');
}
saveSettingsDebounced();
}
function onToolPromptReset() {
const toolName = $(this).data('tool');
const settings = getSettings();
if (settings.toolPromptOverrides) {
delete settings.toolPromptOverrides[toolName];
}
saveSettingsDebounced();
const defaults = getDefaultToolDescriptions();
const $block = $(this).closest('.tv-tool-prompt-block');
$block.find('.tv-tool-prompt-textarea').val(defaults[toolName] || '');
$block.removeClass('tv-tool-prompt-modified');
}
function onSearchModeChange() {
const mode = $('input[name="tv_search_mode"]:checked').val();
const settings = getSettings();
settings.searchMode = mode;
saveSettingsDebounced();
$('#tv_collapsed_depth_section').toggle(mode === 'collapsed');
// Re-register to rebuild tool description with new mode
registerTools();
}
function onCollapsedDepthChange() {
const raw = Number($('#tv_collapsed_depth').val());
const clamped = Math.min(4, Math.max(1, Math.round(raw) || 2));
$('#tv_collapsed_depth').val(clamped);
const settings = getSettings();
settings.collapsedDepth = clamped;
saveSettingsDebounced();
registerTools();
}
async function onSelectiveRetrievalToggle() {
const settings = getSettings();
settings.selectiveRetrieval = $(this).prop('checked');
saveSettingsDebounced();
await registerTools();
}
function onRecurseLimitChange() {
const raw = Number($('#tv_recurse_limit').val());
const clamped = Math.min(Math.max(Math.round(raw) || 5, 1), 50);
$('#tv_recurse_limit').val(clamped);
$('#tv_recurse_warn').toggle(clamped > 10);
const settings = getSettings();
settings.recurseLimit = clamped;
saveSettingsDebounced();
applyRecurseLimit(settings);
}
function onLlmDetailChange() {
const settings = getSettings();
settings.llmBuildDetail = $('#tv_llm_detail').val();
saveSettingsDebounced();
}
function onTreeGranularityChange() {
const settings = getSettings();
settings.treeGranularity = Number($('#tv_tree_granularity').val()) || 0;
saveSettingsDebounced();
}
function onChunkTokensChange() {
const raw = Number($('#tv_chunk_tokens').val());
const clamped = Math.min(Math.max(Math.round(raw / 1000) * 1000 || 30000, 5000), 500000);
$('#tv_chunk_tokens').val(clamped);
const settings = getSettings();
settings.llmChunkTokens = clamped;
saveSettingsDebounced();
}
function onVectorDedupToggle() {
const enabled = $(this).prop('checked');
const settings = getSettings();
settings.enableVectorDedup = enabled;
saveSettingsDebounced();
$('#tv_dedup_threshold_row').toggle(enabled);
updateDedupStatus(enabled);
}
function onDedupThresholdChange() {
const raw = Number($('#tv_dedup_threshold').val());
const clamped = Math.min(Math.max(raw, 0.5), 0.99);
$('#tv_dedup_threshold').val(clamped);
const settings = getSettings();
settings.vectorDedupThreshold = clamped;
saveSettingsDebounced();
}
/**
* Update the dedup status indicator.
* @param {boolean} enabled
*/
function updateDedupStatus(enabled) {
const $status = $('#tv_dedup_status');
const $text = $('#tv_dedup_method_text');
if (!enabled) {
$status.hide();
return;
}
$status.show();
$text.text('Using trigram similarity — fast character n-gram matching that catches near-duplicates and morphological variants.');
}
// ─── Tree Building ───────────────────────────────────────────────
async function onBuildFromMetadata() {
if (!currentLorebook) return;
const $btn = $('#tv_build_metadata');
try {
$btn.prop('disabled', true).html('<span class="tv_loading"></span> Building...');
const tree = await buildTreeFromMetadata(currentLorebook);
toastr.success(`Built tree with ${(tree.root.children || []).length} categories`, 'TunnelVision');
loadLorebookUI(currentLorebook);
populateLorebookDropdown();
registerTools();
} catch (e) {
toastr.error(e.message, 'TunnelVision');
console.error('[TunnelVision]', e);
} finally {
$btn.prop('disabled', false).html('<i class="fa-solid fa-sitemap"></i> From Metadata');
}
}
async function onBuildWithLLM() {
if (!currentLorebook) return;
const $btn = $('#tv_build_llm');
const $progress = $('#tv_build_progress');
const $progressText = $('#tv_build_progress_text');
const $progressFill = $('#tv_build_progress_fill');
const $progressDetail = $('#tv_build_progress_detail');
try {
$btn.prop('disabled', true).html('<span class="tv_loading"></span> Building...');
$('#tv_build_metadata').prop('disabled', true);
$progress.slideDown(200);
$progressFill.css('width', '0%');
$progressDetail.text('');
const tree = await buildTreeWithLLM(currentLorebook, {
onProgress: (msg, pct) => {
$progressText.text(msg);
if (typeof pct === 'number') {
$progressFill.css('width', `${Math.min(pct, 100)}%`);
}
},
onDetail: (msg) => $progressDetail.text(msg),
});
$progressFill.css('width', '100%');
$progressText.text('Done!');
toastr.success(`LLM built tree with ${(tree.root.children || []).length} categories`, 'TunnelVision');
loadLorebookUI(currentLorebook);
populateLorebookDropdown();
registerTools();
} catch (e) {
toastr.error(e.message, 'TunnelVision');
console.error('[TunnelVision]', e);
} finally {
$btn.prop('disabled', false).html('<i class="fa-solid fa-brain"></i> With LLM');
$('#tv_build_metadata').prop('disabled', false);
setTimeout(() => $progress.slideUp(300), 2000);
}
}
// ─── Chat Ingest ─────────────────────────────────────────────────
async function onIngestChat() {
if (!currentLorebook) return;
const context = getContext();
if (!context.chatId || !context.chat?.length) {
toastr.error('No chat is open. Open a chat first.', 'TunnelVision');
return;
}
const from = parseInt($('#tv_ingest_from').val(), 10) || 0;
const to = parseInt($('#tv_ingest_to').val(), 10) || 0;
if (from > to) {
toastr.warning('"From" must be less than or equal to "To".', 'TunnelVision');
return;
}
const $btn = $('#tv_ingest_chat');
const $progress = $('#tv_ingest_progress');
const $progressText = $('#tv_ingest_progress_text');
const $progressFill = $('#tv_ingest_progress_fill');
const $progressDetail = $('#tv_ingest_progress_detail');
try {
$btn.prop('disabled', true).html('<span class="tv_loading"></span> Ingesting...');
$progress.slideDown(200);
$progressFill.css('width', '0%');
$progressDetail.text('');
const result = await ingestChatMessages(currentLorebook, {
from,
to,
progress: (msg, pct) => {
$progressText.text(msg);
if (typeof pct === 'number') {
$progressFill.css('width', `${Math.min(pct, 100)}%`);
}
},
detail: (msg) => $progressDetail.text(msg),
});
$progressFill.css('width', '100%');
$progressText.text('Done!');
toastr.success(`Created ${result.created} entries from chat (${result.errors} errors)`, 'TunnelVision');
loadLorebookUI(currentLorebook);
registerTools();
} catch (e) {
toastr.error(e.message, 'TunnelVision');
console.error('[TunnelVision] Ingest error:', e);
} finally {
$btn.prop('disabled', false).html('<i class="fa-solid fa-download"></i> Ingest Messages');
setTimeout(() => $progress.slideUp(300), 2000);
}
}
function onMandatoryToolsToggle() {
const settings = getSettings();
settings.mandatoryTools = $(this).prop('checked');
saveSettingsDebounced();
$('#tv_mandatory_prompt_options').toggle(settings.mandatoryTools);
}
function onPromptInjectionChange() {
const settings = getSettings();
const $el = $(this);
const id = $el.attr('id') || '';
if (id.startsWith('tv_mandatory_')) {
const field = id.replace('tv_mandatory_', '');
if (field === 'position') {
settings.mandatoryPromptPosition = $el.val();
$('#tv_mandatory_depth_row').toggle($el.val() === 'in_chat');
} else if (field === 'depth') {
settings.mandatoryPromptDepth = Math.max(1, Math.round(Number($el.val()) || 1));
$el.val(settings.mandatoryPromptDepth);
} else if (field === 'role') {
settings.mandatoryPromptRole = $el.val();
}
} else if (id.startsWith('tv_notebook_')) {
const field = id.replace('tv_notebook_', '');
if (field === 'position') {
settings.notebookPromptPosition = $el.val();
$('#tv_notebook_depth_row').toggle($el.val() === 'in_chat');
} else if (field === 'depth') {
settings.notebookPromptDepth = Math.max(1, Math.round(Number($el.val()) || 1));
$el.val(settings.notebookPromptDepth);
} else if (field === 'role') {
settings.notebookPromptRole = $el.val();
}
}
saveSettingsDebounced();
}
function onMandatoryPromptTextChange() {
const settings = getSettings();
settings.mandatoryPromptText = $(this).val() || '';
saveSettingsDebounced();
}
function onMandatoryPromptReset() {
const settings = getSettings();
settings.mandatoryPromptText = SETTING_DEFAULTS.mandatoryPromptText;
$('#tv_mandatory_prompt_text').val(settings.mandatoryPromptText);
saveSettingsDebounced();
}
function onStealthModeToggle() {
const settings = getSettings();
settings.stealthMode = $(this).prop('checked');
saveSettingsDebounced();
void refreshHiddenToolCallMessages({ syncFlags: true });
}
function onEphemeralResultsToggle() {
const settings = getSettings();
settings.ephemeralResults = $(this).prop('checked');
$('#tv_ephemeral_filter_options').toggle(settings.ephemeralResults);
saveSettingsDebounced();
}
function onEphemeralToolFilterChange() {
const settings = getSettings();
const selected = [];
$('.tv_ephemeral_tool:checked').each(function () {
selected.push($(this).val());
});
settings.ephemeralToolFilter = selected;
saveSettingsDebounced();
}
// ─── Slash Commands Settings ─────────────────────────────────────
function onCommandContextChange() {
const raw = Number($('#tv_command_context').val());
const clamped = Math.min(Math.max(Math.round(raw) || 50, 5), 500);
$('#tv_command_context').val(clamped);
const settings = getSettings();
settings.commandContextMessages = clamped;
saveSettingsDebounced();
}
// ─── Auto-Summary Settings ──────────────────────────────────────
function onAutoSummaryToggle() {
const enabled = $(this).prop('checked');
const settings = getSettings();
settings.autoSummaryEnabled = enabled;
saveSettingsDebounced();
$('#tv_auto_summary_options').toggle(enabled);
}
function onAutoSummaryIntervalChange() {
const raw = Number($('#tv_auto_summary_interval').val());
const clamped = Math.min(Math.max(Math.round(raw) || 20, 5), 200);
$('#tv_auto_summary_interval').val(clamped);
const settings = getSettings();
settings.autoSummaryInterval = clamped;
saveSettingsDebounced();
}
function onAutoHideSummarizedToggle() {
const enabled = $(this).prop('checked');
const settings = getSettings();
settings.autoHideSummarized = enabled;
saveSettingsDebounced();
}
function onPassthroughConstantToggle() {
const enabled = $(this).prop('checked');
const settings = getSettings();
settings.passthroughConstant = enabled;
saveSettingsDebounced();
}
function onAllowKeywordTriggersToggle() {
const enabled = $(this).prop('checked');
const settings = getSettings();
settings.allowKeywordTriggers = enabled;
saveSettingsDebounced();
}
// ─── Multi-Book Mode ─────────────────────────────────────────────
function onMultiBookModeChange() {
const mode = $('input[name="tv_multi_book_mode"]:checked').val();
const settings = getSettings();
settings.multiBookMode = mode;
saveSettingsDebounced();
registerTools();
}
// ─── Sidecar LLM (Connection Profile + Sampler Overrides) ───────
function onConnectionProfileChange() {
setConnectionProfileId($(this).val() || null);
// Show/hide sampler controls when a profile is selected
$('#tv_sidecar_sampler_fields').toggle(!!$(this).val());
}
function onSidecarTemperatureChange() {
const val = parseFloat($(this).val());
const settings = getSettings();
settings.sidecarTemperature = val;
$('#tv_sidecar_temp_val').text(val.toFixed(2));
saveSettingsDebounced();
}
function onSidecarMaxTokensChange() {
const settings = getSettings();
settings.sidecarMaxTokens = Number($(this).val()) || 2048;
saveSettingsDebounced();
}
function onSidecarAutoRetrievalToggle() {
const settings = getSettings();
settings.sidecarAutoRetrieval = $(this).prop('checked');
$('#tv_sidecar_retrieval_fields').toggle(settings.sidecarAutoRetrieval);
saveSettingsDebounced();
}
function onSidecarContextMessagesChange() {
const settings = getSettings();
settings.sidecarContextMessages = Number($(this).val()) || 10;
saveSettingsDebounced();
}
function onSidecarMaxInjectionChange() {
const settings = getSettings();
settings.sidecarMaxInjectionTokens = Number($(this).val()) || 4000;
saveSettingsDebounced();
}
function onSidecarPostGenWriterToggle() {
const settings = getSettings();
settings.sidecarPostGenWriter = $(this).prop('checked');
$('#tv_sidecar_writer_fields').toggle(settings.sidecarPostGenWriter);
saveSettingsDebounced();
}
function onCompactToolPromptsToggle() {
const settings = getSettings();
settings.compactToolPrompts = $(this).prop('checked');
saveSettingsDebounced();
registerTools();
}
function onSidecarWriterContextChange() {
const settings = getSettings();
settings.sidecarWriterContextMessages = Number($(this).val()) || 15;
saveSettingsDebounced();
}
function onSidecarWriterMaxOpsChange() {
const settings = getSettings();
settings.sidecarWriterMaxOps = Number($(this).val()) || 5;
saveSettingsDebounced();
}
// ─── Per-Lorebook Permissions ────────────────────────────────────
function onBookPermissionChange() {
if (!currentLorebook) return;
setBookPermission(currentLorebook, $(this).val() || 'read_write');
registerTools();
}
function populateConnectionProfiles() {
const $select = $('#tv_connection_profile');
const currentVal = getConnectionProfileId() || '';
// Keep the first option (default)