Repository navigation
Expand file tree
/
Copy pathui.js
More file actions
1924 lines (1728 loc) · 75.5 KB
/
Copy pathui.js
File metadata and controls
1924 lines (1728 loc) · 75.5 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
/**
* Smart Memory - SillyTavern Extension
* Copyright (C) 2026 Senjin the Dragon
* https://github.com/senjinthedragon/Smart-Memory
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Pure display layer: all functions that read state and write to the DOM.
* Zero coupling to index.js state variables - safe to import from anywhere.
*
* TOKEN_TIERS - metadata for each injection tier (key, label, colour)
* PERSONAL_TIERS - per-character tiers shown in group-chat rows
* getGroupMembers - ordered list of character names in the current group
* estimateCharPersonalTokens - stored token footprint for one character's personal tiers
* updateTokenDisplay - refreshes the token usage bar chart
* setStatusMessage - updates the status bar text in the settings panel header
* setContinuityBadge - updates the contradiction count badge in the header
* showSearchResults - renders a dismissible modal with /sm-search results
* initTooltips - wires up the floating tooltip on .sm-info elements
* updateShortTermUI - syncs the short-term summary textarea
* updateCanonUI - populates the canon display and status line
* updateLongTermUI - re-renders the long-term memories list and entity panel
* updateRelationshipHistoryUI - re-renders the relationship history panel with edit/delete/add controls
* buildTypePicker - builds a custom type-picker widget
* initTypePickers - registers the document-level close handler for type pickers
* updateEmbeddingNotice - shows/hides the embedding inactive notice
* updateFreshStartUI - syncs the fresh-start checkbox and body class
* updateSessionUI - re-renders the session memory list
* updateScenesUI - re-renders the scene history list
* updateArcsUI - re-renders the story arcs list
* updateProfilesUI - renders the profiles display panel
* updateEntityPanel - renders the entity registry panel
* showEntityTimeline - shows an inline timeline for a single entity
* renderMemoriesList - renders the long-term memories list with edit/delete controls
* updateEpistemicUI - re-renders the Perspectives & Secrets entry list with add/edit/delete controls
*/
import { extension_prompts, saveSettingsDebounced } from '../../../../script.js';
import { getContext, extension_settings } from '../../../extensions.js';
import {
estimateTokens,
MODULE_NAME,
META_KEY,
MEMORY_TYPES,
SESSION_TYPES,
PROMPT_KEY_LONG,
PROMPT_KEY_SESSION,
PROMPT_KEY_SHORT,
PROMPT_KEY_CANON,
PROMPT_KEY_SCENES,
PROMPT_KEY_ARCS,
PROMPT_KEY_PROFILES,
PROMPT_KEY_RELATIONSHIPS,
PROMPT_KEY_EPISTEMIC,
PROMPT_KEY_STATE_LEDGER,
} from './constants.js';
import {
loadCharacterMemories,
saveCharacterMemories,
injectMemories,
loadRelationshipHistory,
saveRelationshipHistory,
injectRelationshipHistory,
} from './longterm.js';
import { loadSessionMemories, saveSessionMemories, injectSessionMemories } from './session.js';
import { loadSceneHistory } from './scenes.js';
import {
loadArcs,
saveArcs,
deleteArc,
resolveArcWithSummary,
injectArcs,
promoteArc,
demoteArc,
reopenArc,
loadArcSummaries,
loadPersistentArcs,
savePersistentArcs,
loadGroupPersistentArcs,
saveGroupPersistentArcs,
} from './arcs.js';
import { loadCanon } from './canon.js';
import { loadProfiles } from './profiles.js';
import {
loadCharacterEntityRegistry,
loadSessionEntityRegistry,
saveCharacterEntityRegistry,
saveSessionEntityRegistry,
setEntityType,
deleteEntityById,
mergeEntitiesById,
} from './graph-migration.js';
import { getUnifiedTierBreakdown } from './unified-inject.js';
import { hasEmbeddingFailed } from './embeddings.js';
import {
getTierTrimStats,
hasAnyTrimmedTier,
hasTrimToastFired,
markTrimToastFired,
isChatLoadComplete,
} from './trim-stats.js';
import {
loadEpistemicKnowledge,
saveEpistemicKnowledge,
injectEpistemicKnowledge,
shrinkEpistemicBudgetIfPossible,
} from './epistemic.js';
import {
getStateCard,
setStateCard,
deleteStateCard,
migrateStateLedgerKey,
isStateLedgerEnabled,
injectStateLedger,
STATE_CARD_FIELDS,
STATE_CARD_TYPES,
} from './state-ledger.js';
// ---- Local helpers (not exported) ----------------------------------------
function getSettings() {
return extension_settings[MODULE_NAME];
}
/** Returns the active character name, or null if no character is loaded. */
function getCurrentCharacterName() {
const context = getContext();
return context.name2 || context.characterName || null;
}
/**
* Returns the character name the settings panel should operate on.
* Reads from the DOM selector which is always in sync with the index.js
* selectedGroupCharacter variable, so no state import is needed here.
* @returns {string|null}
*/
function getSelectedCharacterName() {
if (getContext().groupId) {
return $('#sm_group_char_select').val() || null;
}
return getCurrentCharacterName();
}
// ---- Constants -----------------------------------------------------------
// Tier colours use OKLCH for perceptual uniformity: 10 hues at 36-degree
// intervals (360/10) with fixed lightness and chroma give maximum perceptual
// separation regardless of the display. oklch(62% 0.14 H).
const TIER_COLORS = {
relationships: 'oklch(62% 0.14 0)',
scenes: 'oklch(62% 0.14 36)',
state: 'oklch(62% 0.14 72)',
epistemic: 'oklch(62% 0.14 108)',
shortterm: 'oklch(62% 0.14 144)',
profiles: 'oklch(62% 0.14 180)',
canon: 'oklch(62% 0.14 216)',
longterm: 'oklch(62% 0.14 252)',
session: 'oklch(62% 0.14 288)',
arcs: 'oklch(62% 0.14 324)',
};
/**
* Metadata for each injection tier used by the token usage display.
* Order determines the visual stacking order in the bar chart.
*/
export const TOKEN_TIERS = [
{ key: PROMPT_KEY_LONG, label: 'Long-term', color: TIER_COLORS.longterm },
{ key: PROMPT_KEY_SESSION, label: 'Session', color: TIER_COLORS.session },
{ key: PROMPT_KEY_SHORT, label: 'Short-term', color: TIER_COLORS.shortterm },
{ key: PROMPT_KEY_CANON, label: 'Canon', color: TIER_COLORS.canon },
{ key: PROMPT_KEY_SCENES, label: 'Scenes', color: TIER_COLORS.scenes },
{ key: PROMPT_KEY_ARCS, label: 'Arcs', color: TIER_COLORS.arcs },
{ key: PROMPT_KEY_PROFILES, label: 'Profiles', color: TIER_COLORS.profiles },
{ key: PROMPT_KEY_RELATIONSHIPS, label: 'Relationships', color: TIER_COLORS.relationships },
{ key: PROMPT_KEY_EPISTEMIC, label: 'Perspectives', color: TIER_COLORS.epistemic },
{ key: PROMPT_KEY_STATE_LEDGER, label: 'State', color: TIER_COLORS.state },
];
// Personal tiers shown in per-character group rows. Shared tiers (session,
// scenes, arcs, short-term) are omitted - they are identical across all group
// members and already represented in the top bar.
export const PERSONAL_TIERS = [
{ key: 'longterm', label: 'Long-term', color: TIER_COLORS.longterm },
{ key: 'canon', label: 'Canon', color: TIER_COLORS.canon },
{ key: 'profiles', label: 'Profiles', color: TIER_COLORS.profiles },
];
// ---- Display functions ---------------------------------------------------
/**
* Returns the ordered list of character names in the current group chat,
* or null when not in a group chat.
* @returns {string[]|null}
*/
export function getGroupMembers() {
const context = getContext();
if (!context.groupId) return null;
const group = context.groups?.find((g) => g.id === context.groupId);
if (!group) return null;
return (group.members ?? [])
.map((avatarId) => context.characters.find((c) => c.avatar === avatarId)?.name)
.filter(Boolean);
}
/**
* Estimates the stored token footprint of a character's personal memory tiers:
* long-term memories, canon, and profiles. Does not include shared tiers
* (session, scenes, arcs, short-term) which are identical for all group members.
*
* Reads from stored data rather than injected content, so values reflect the
* full memory footprint before budget trimming.
*
* @param {string} charName
* @returns {{ longterm: number, canon: number, profiles: number, total: number }}
*/
export function estimateCharPersonalTokens(charName) {
const memories = loadCharacterMemories(charName).filter((m) => !m.superseded_by);
const longtermTokens =
memories.length > 0 ? estimateTokens(memories.map((m) => `- ${m.content}`).join('\n')) : 0;
const canon = loadCanon(charName);
const canonTokens = canon ? estimateTokens(canon) : 0;
const profiles = loadProfiles(charName);
const profileTokens = profiles
? estimateTokens(
[profiles.character_state, profiles.world_state, profiles.relationship_matrix]
.filter(Boolean)
.join('\n'),
)
: 0;
return {
longterm: longtermTokens,
canon: canonTokens,
profiles: profileTokens,
total: longtermTokens + canonTokens + profileTokens,
};
}
/**
* Reads the currently injected content for each tier from extension_prompts
* and updates the token usage bar chart and totals line. In group chats,
* also renders a compact per-character row for each group member showing their
* stored personal memory footprint (long-term, canon, profiles).
*
* Called after any injection or chat change so the display stays current.
* Uses the estimateTokens heuristic (~4 chars/token) - fast, synchronous,
* accurate enough for budget tuning.
*/
export function updateTokenDisplay() {
const bar = document.getElementById('sm_token_bar');
if (!bar) return;
// ---- Top bar: actual injected content for the active character ----------
// In unified mode the individual slots are empty - use the breakdown saved
// by the last injectUnified call so tier colours are still visible.
const settings = getSettings();
const tiers = (
settings.unified_injection
? getUnifiedTierBreakdown()
: TOKEN_TIERS.map((t) => ({
...t,
tokens: estimateTokens(extension_prompts[t.key]?.value ?? ''),
}))
).filter((t) => t.tokens > 0);
const total = tiers.reduce((sum, t) => sum + t.tokens, 0);
const maxContext = getContext().maxContext || 0;
// Each segment's width is its share of total SM tokens. The title tooltip
// carries the detail breakdown that the old legend used to show inline.
bar.innerHTML = '';
for (const tier of tiers) {
const widthPct = total > 0 ? ((tier.tokens / total) * 100).toFixed(1) : 0;
const sharePct = total > 0 ? ((tier.tokens / total) * 100).toFixed(0) : 0;
const seg = document.createElement('div');
seg.style.width = `${widthPct}%`;
seg.style.background = tier.color;
const trimStats = getTierTrimStats(tier.key);
const isTrimmed = trimStats && trimStats.full > trimStats.injected;
seg.className = isTrimmed ? 'sm-token-segment sm-token-trimmed' : 'sm-token-segment';
if (isTrimmed) {
const dropped = trimStats.full - trimStats.injected;
seg.title =
`${tier.label}: ~${tier.tokens.toLocaleString()} tokens injected (${sharePct}%)\n` +
`~${dropped.toLocaleString()} tokens trimmed to fit budget`;
} else {
seg.title = `${tier.label}: ~${tier.tokens.toLocaleString()} tokens (${sharePct}%)`;
}
bar.appendChild(seg);
}
const contextPct = maxContext && total ? ((total / maxContext) * 100).toFixed(1) : '0';
const usedEl = document.getElementById('sm_token_used');
const maxEl = document.getElementById('sm_token_max');
const pctEl = document.getElementById('sm_token_pct');
if (usedEl) usedEl.textContent = `~${total.toLocaleString()}`;
if (maxEl) maxEl.textContent = maxContext ? maxContext.toLocaleString() : '?';
if (pctEl) pctEl.textContent = contextPct;
// Fire a one-time notification the first time any tier is found to be trimming
// content. Users who never open the settings panel will still see this once,
// prompting them to check the token bar. Subsequent calls are silent.
if (isChatLoadComplete() && hasAnyTrimmedTier() && !hasTrimToastFired()) {
markTrimToastFired();
toastr.warning(
'One or more memory tiers are trimming content to stay within budget. Check the token bar in Smart Memory settings.',
'Smart Memory',
{ timeOut: 8000, extendedTimeOut: 4000, closeButton: true },
);
}
// ---- Per-character rows (group chats only) ------------------------------
const groupRowsEl = document.getElementById('sm_token_group_rows');
if (!groupRowsEl) return;
const members = getGroupMembers();
if (!members || members.length === 0) {
groupRowsEl.style.display = 'none';
return;
}
groupRowsEl.style.display = '';
groupRowsEl.innerHTML = '';
const activeChar = getSelectedCharacterName();
for (const member of members) {
const personal = estimateCharPersonalTokens(member);
const isActive = member === activeChar;
const row = document.createElement('div');
row.className = 'sm-token-group-row' + (isActive ? ' sm-token-active' : '');
row.title = `Click to view ${member}'s memories`;
row.addEventListener('click', () => {
$('#sm_group_char_select').val(member).trigger('change');
});
const nameEl = document.createElement('span');
nameEl.className = 'sm-token-group-name';
nameEl.textContent = member;
row.appendChild(nameEl);
const barWrap = document.createElement('div');
barWrap.className = 'sm-token-mini-bar-wrap';
const miniBar = document.createElement('div');
miniBar.className = 'sm-token-mini-bar';
if (personal.total > 0) {
for (const tier of PERSONAL_TIERS) {
const tierTokens = personal[tier.key];
if (tierTokens === 0) continue;
const widthPct = ((tierTokens / personal.total) * 100).toFixed(1);
const seg = document.createElement('div');
seg.className = 'sm-token-segment';
seg.style.width = `${widthPct}%`;
seg.style.background = tier.color;
seg.title = `${tier.label}: ~${tierTokens.toLocaleString()} tokens (stored)`;
miniBar.appendChild(seg);
}
}
barWrap.appendChild(miniBar);
row.appendChild(barWrap);
const countEl = document.createElement('span');
countEl.className = 'sm-token-group-count';
if (personal.total > 0) {
countEl.textContent = `~${personal.total.toLocaleString()}`;
countEl.title = 'Stored memory size before budget trimming';
} else {
countEl.textContent = 'no data';
}
row.appendChild(countEl);
groupRowsEl.appendChild(row);
}
}
/** Updates the status bar text shown at the top of the settings panel. */
export function setStatusMessage(msg) {
$('#sm_status').text(msg);
}
/**
* Updates the continuity badge shown in the settings panel header.
* Called after the Profile B auto-check completes each AI turn.
* @param {number|null} count - Contradiction count from checkContinuity, or null to clear.
*/
export function setContinuityBadge(count) {
const $badge = $('#sm_continuity_badge');
$badge.removeClass('sm_continuity_badge_clean sm_continuity_badge_warn');
if (count === null) {
$badge.hide();
return;
}
if (count === 0) {
$badge.addClass('sm_continuity_badge_clean').text('clean').show();
// Positive state is transient - hide after 4 s so it doesn't linger.
setTimeout(() => $badge.hide(), 4000);
} else {
$badge
.addClass('sm_continuity_badge_warn')
.text(`${count} conflict${count === 1 ? '' : 's'}`)
.show();
}
}
/**
* Displays memory search results in a dismissible modal overlay.
* Called by the /sm-search slash command.
* @param {string} query - The original search query.
* @param {Array<{mem: Object, score: number}>} results - Top-K scored memories, sorted descending.
*/
export function showSearchResults(query, results) {
$('#sm_search_overlay').remove();
// Use a <dialog> element so it renders in the browser's top layer, immune
// to ST's transformed ancestors that trap position:fixed divs on mobile.
const dialog = document.createElement('dialog');
dialog.id = 'sm_search_overlay';
const card = $('<div class="sm_search_card">');
card.append($('<h3>Memory Search Results</h3>'));
card.append(
$('<p class="sm_search_query_label">').text(
`Query: "${query}" - ${results.length} result${results.length === 1 ? '' : 's'}`,
),
);
if (results.length === 0) {
card.append($('<p>').text('No matching memories found.'));
} else {
const $list = $('<ul class="sm_search_list">');
for (const { mem, score } of results) {
const $item = $('<li class="sm_search_item">');
$item.append(
$('<span class="sm_search_badge sm_search_badge_tier">').text(mem._tier),
$('<span>').addClass(`sm_search_badge sm_type_${mem.type}`).text(mem.type),
$('<span class="sm_search_content">').text(String(mem.content || '')),
$('<span class="sm_search_score">').text(`${Math.round(score * 100)}%`),
);
$list.append($item);
}
card.append($list);
}
const $footer = $('<div class="sm_search_footer">');
const $dismiss = $('<button>Dismiss</button>').addClass('menu_button');
const dismiss = () => {
dialog.close();
dialog.remove();
};
$dismiss.on('click', dismiss);
$(dialog).on('click', (e) => {
if (e.target === dialog) dismiss();
});
$footer.append($dismiss);
card.append($footer);
$(dialog).append(card);
document.body.appendChild(dialog);
dialog.showModal();
}
/**
* Injects a single #sm-tooltip div into <body> and wires up hover/focus
* events on all .sm-info elements inside the settings panel.
*
* Using position:fixed on the tooltip div means it escapes ST's
* overflow:hidden extensions panel and is never clipped at the edge.
*/
export function initTooltips() {
// Remove any previous tooltip element before creating a new one.
// Guards against the settings panel being re-rendered (e.g. on extension
// reload) which would otherwise append a second tooltip div to the body.
document.getElementById('sm-tooltip')?.remove();
const tooltip = document.createElement('div');
tooltip.id = 'sm-tooltip';
document.body.appendChild(tooltip);
const panel = document.getElementById('smart_memory_settings');
if (!panel) return;
panel.addEventListener('mouseover', (e) => {
const target = e.target.closest('.sm-info');
if (!target?.dataset.tooltip) return;
tooltip.textContent = target.dataset.tooltip;
const rect = target.getBoundingClientRect();
// Prefer showing below the icon; flip above if too close to the bottom.
const spaceBelow = window.innerHeight - rect.bottom;
// Use the tooltip's actual rendered width to clamp the left position,
// falling back to 260 before the first render when offsetWidth is 0.
const tooltipWidth = tooltip.offsetWidth || 260;
tooltip.style.left = `${Math.min(rect.left, window.innerWidth - tooltipWidth - 8)}px`;
tooltip.style.top =
spaceBelow > 80 ? `${rect.bottom + 6}px` : `${rect.top - tooltip.offsetHeight - 6}px`;
tooltip.classList.add('sm-tooltip-visible');
});
panel.addEventListener('mouseout', (e) => {
if (!e.target.closest('.sm-info')) return;
tooltip.classList.remove('sm-tooltip-visible');
});
}
/** Syncs the short-term summary textarea with the current summary text. */
export function updateShortTermUI(summary) {
$('#sm_current_summary').val(summary || '');
}
/**
* Updates the Canon section UI to reflect the currently stored canon for the
* given character. Populates the display textarea and status line.
* @param {string|null} characterName
*/
export function updateCanonUI(characterName) {
const canon = characterName ? loadCanon(characterName) : null;
$('#sm_canon_display').val(canon?.text || '');
if (canon) {
const arcCount = loadArcSummaries().length;
$('#sm_canon_status').text(
`Canon: ${estimateTokens(canon.text)} tokens, sourced from ${arcCount} arc summar${arcCount === 1 ? 'y' : 'ies'}.`,
);
} else {
$('#sm_canon_status').text('');
}
}
/** Re-renders the long-term memories list and entity panel for the given character. */
export function updateLongTermUI(characterName) {
const memories = characterName ? loadCharacterMemories(characterName) : [];
renderMemoriesList(memories, characterName);
updateEntityPanel(characterName);
}
/**
* Renders the relationship history panel for the given character.
* Each pair is shown as an editable row with subject, arrow, target,
* descriptors, magnitude, and delete/edit controls.
* @param {string|null} characterName
*/
export function updateRelationshipHistoryUI(characterName) {
const $list = $('#sm_relationships_list');
$list.empty();
const history = characterName ? loadRelationshipHistory(characterName) : {};
const pairs = Object.entries(history);
if (pairs.length === 0) {
$list.append('<div class="sm_no_char">No relationship history yet.</div>');
return;
}
for (const [key, state] of pairs) {
const [subject, target] = key.split('→').map((s) => s.trim());
const descriptors = state.descriptors ?? [];
// Display as "word(magnitude), word(magnitude)" for per-descriptor magnitudes.
const descriptorStr = descriptors.map((d) => `${d.word}(${d.magnitude})`).join(', ');
// For the edit form, serialize as "word(magnitude), ..." so it round-trips cleanly.
const descriptorFieldVal = descriptorStr;
const $row = $('<div class="sm_memory_item">');
const $content = $('<div class="sm_memory_content">').text(
`${subject} → ${target}: ${descriptorStr}`,
);
const $editBtn = $('<button class="sm_memory_action menu_button" title="Edit">')
.append('<i class="fa-solid fa-pencil"></i>')
.on('click', () => {
// Populate the add form for editing this pair.
$('#sm_rel_subject').val(subject);
$('#sm_rel_target').val(target);
$('#sm_rel_descriptors').val(descriptorFieldVal);
$('#sm_relationship_add_form').show();
// Store the key being edited so save can delete the old one.
$('#sm_relationship_add_form').data('editing', key);
$('#sm_rel_subject').focus();
});
const $deleteBtn = $(
'<button class="sm_memory_action sm_memory_delete menu_button" title="Delete">',
)
.append('<i class="fa-solid fa-trash-can"></i>')
.on('click', async () => {
const h = loadRelationshipHistory(characterName);
delete h[key];
saveRelationshipHistory(characterName, h);
saveSettingsDebounced();
injectRelationshipHistory(characterName);
updateRelationshipHistoryUI(characterName);
updateTokenDisplay();
});
$row.append($content, $editBtn, $deleteBtn);
$list.append($row);
}
}
/**
* Builds a custom type-picker widget to replace the native <select>.
* Native selects don't allow reliable per-option background styling in
* Chromium/Electron because the select's own background bleeds into the
* open dropdown, overriding option colors inconsistently.
*
* The returned element exposes its current value via $(el).data('value').
* Clicking outside any open picker collapses it - register the document
* handler once at init via initTypePickers().
*
* @param {string[]} types - ordered list of type values
* @returns {jQuery} div.sm-type-picker
*/
export function buildTypePicker(types) {
const initial = types[0];
const $picker = $('<div class="sm-type-picker">').attr('data-value', initial);
const $current = $('<div class="sm-type-picker-current">')
.attr('data-value', initial)
.text(initial);
const $list = $('<div class="sm-type-picker-list">');
types.forEach((t) => {
$list.append($('<div class="sm-type-option">').attr('data-value', t).text(t));
});
$picker.append($current, $list);
$current.on('click', (e) => {
e.stopPropagation();
// Close any other open pickers first.
$('.sm-type-picker').not($picker).removeClass('open');
$picker.toggleClass('open');
});
$list.on('click', '.sm-type-option', function () {
const val = $(this).data('value');
$picker.attr('data-value', val).removeClass('open');
$current.attr('data-value', val).text(val);
});
return $picker;
}
/**
* Registers a single document-level click handler that closes all open
* type pickers when the user clicks outside them. Called once at init.
*/
export function initTypePickers() {
$(document).on('click.smTypePicker', (e) => {
if (!$(e.target).closest('.sm-type-picker').length) {
$('.sm-type-picker').removeClass('open');
}
});
}
/**
* Shows or hides the embedding inactive notice at the top of the settings panel.
* Visible when embeddings are disabled in settings OR when an API call has
* failed this session (meaning the model is enabled but unreachable).
*/
export function updateEmbeddingNotice() {
const settings = getSettings();
const inactive = !settings.embedding_enabled || hasEmbeddingFailed();
$('#sm_embedding_notice').toggle(inactive);
}
/** Syncs the Fresh Start checkbox state. */
export function updateFreshStartUI(freshStart) {
$('#sm_read_only').prop('checked', !!freshStart);
$('body').toggleClass('sm-read-only', !!freshStart);
}
/**
* Re-renders the session memory list with per-entry edit and delete buttons.
* Shows a placeholder when no session memories exist yet.
*/
export function updateSessionUI() {
const memories = loadSessionMemories();
const $list = $('#sm_session_list');
$list.empty();
if (memories.length === 0) {
$list.append('<div class="sm_no_char">No session memories yet.</div>');
}
const sortedSession = [...memories].sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0));
const hasRetiredSession = sortedSession.some((m) => m.superseded_by);
if (hasRetiredSession) {
const $toggle = $(
'<button class="sm_toggle_retired menu_button" style="margin-bottom:6px;font-size:0.8em;">' +
'<i class="fa-solid fa-eye-slash"></i> Show retired memories</button>',
);
$list.append($toggle);
$toggle.on('click', function () {
const showing = $list.find('.sm_memory_item.sm_memory_retired').first().is(':visible');
$list.find('.sm_memory_item.sm_memory_retired').toggle(!showing);
$(this).html(
`<i class="fa-solid ${showing ? 'fa-eye-slash' : 'fa-eye'}"></i> ${showing ? 'Show' : 'Hide'} retired memories`,
);
});
}
sortedSession.forEach((mem) => {
// Display order is sorted by ts, but edit/delete index into the stored
// (unsorted) array, so use the position in that array, not the sorted one.
const idx = memories.indexOf(mem);
const isRetired = Boolean(mem.superseded_by);
const hasConflict = Array.isArray(mem.contradicts) && mem.contradicts.length > 0;
const retiredClass = isRetired ? ' sm_memory_retired' : '';
const retiredBadge = isRetired
? '<span class="sm_memory_retired_badge" title="This memory was superseded by a newer fact">retired</span>'
: '';
const supersededByLink = isRetired
? `<button class="sm_superseded_by_link menu_button" data-superseded-by="${mem.superseded_by}" title="Jump to the memory that replaced this one">→ superseded by</button>`
: '';
const conflictBadge = hasConflict
? `<span class="sm_memory_conflict_badge" title="This memory conflicts with ${mem.contradicts.length} other ${mem.contradicts.length === 1 ? 'memory' : 'memories'} - run the continuity checker to review"><i class="fa-solid fa-triangle-exclamation"></i></span>`
: '';
const importanceDots = '●'.repeat(mem.importance ?? 1);
const expiration = mem.expiration ?? 'session';
const $item = $(`
<div class="sm_memory_item${retiredClass}" data-index="${idx}" data-memory-id="${mem.id || ''}" ${isRetired ? 'style="display:none"' : ''}>
<span class="sm_memory_type sm_type_${mem.type}">${mem.type}</span>
<span class="sm_memory_importance sm_importance_${mem.importance ?? 1}" title="Importance ${mem.importance ?? 1}/3">${importanceDots}</span>
<span class="sm_memory_expiration sm_expiration_${expiration}" title="Expires: ${expiration}">${expiration}</span>
${retiredBadge}${supersededByLink}${conflictBadge}
<span class="sm_memory_text">${$('<div>').text(mem.content).html()}</span>
${Array.isArray(mem.source_messages) && mem.source_messages.length > 0 ? `<button class="sm_jump_source menu_button" data-source-start="${mem.source_messages[mem.source_messages.length - 1][0]}" data-source-end="${mem.source_messages[mem.source_messages.length - 1][1]}" title="Jump to source message"><i class="fa-solid fa-arrow-up-right-from-square"></i></button>` : ''}
<button class="sm_edit_session_memory menu_button" data-index="${idx}" title="Edit this memory" ${isRetired ? 'style="display:none"' : ''}>
<i class="fa-solid fa-pencil"></i>
</button>
<button class="sm_delete_session_memory menu_button" data-index="${idx}" title="Delete this memory">
<i class="fa-solid fa-trash-can"></i>
</button>
</div>
`);
$list.append($item);
});
// Jump-to-replacement handler for "→ superseded by" links.
$list.find('.sm_superseded_by_link').on('click', function () {
const targetId = $(this).data('superseded-by');
if (!targetId) return;
const $target = $list.find(`.sm_memory_item[data-memory-id="${targetId}"]`);
if (!$target.length) return;
// Ensure the target is visible - if it is also retired, make sure retired items are shown.
if (!$target.is(':visible')) {
$list.find('.sm_memory_item.sm_memory_retired').show();
$list
.find('.sm_toggle_retired')
.html('<i class="fa-solid fa-eye"></i> Hide retired memories');
}
$target[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
$target.addClass('sm_memory_highlight');
setTimeout(() => $target.removeClass('sm_memory_highlight'), 1500);
});
$list.find('.sm_jump_source').on('click', function () {
const startIdx = parseInt($(this).data('source-start'), 10);
const endIdx = parseInt($(this).data('source-end'), 10);
const $startMsg = $(`#chat .mes[mesid="${startIdx}"]`);
if (!$startMsg.length) return;
// Close the extensions panel so the chat is visible when the scroll lands.
if ($('#rm_extensions_block').hasClass('openDrawer')) {
$('#extensions-settings-button .drawer-toggle').trigger('click');
}
// Scroll to the first message in the source range.
setTimeout(() => {
const $chat = $('#chat');
const scrollTarget = $startMsg.offset().top - $chat.offset().top + $chat.scrollTop();
$chat.animate({ scrollTop: scrollTarget }, 400);
// Flash all messages in the range so the user can see what produced this memory.
const FLASH_DURATION_MS = 2400; // 3 pulses × 0.8 s each
for (let i = startIdx; i <= endIdx; i++) {
const $m = $(`#chat .mes[mesid="${i}"]`);
if ($m.length) {
$m.addClass('sm_source_flash');
setTimeout(() => $m.removeClass('sm_source_flash'), FLASH_DURATION_MS);
}
}
}, 300);
});
$list.find('.sm_edit_session_memory').on('click', async function () {
const idx = parseInt($(this).data('index'), 10);
const $item = $(this).closest('.sm_memory_item');
const $textSpan = $item.find('.sm_memory_text');
const current = loadSessionMemories();
if (!current[idx]) return;
// Replace text span with an inline textarea for editing.
const $textarea = $('<textarea class="sm_memory_edit_input">').val(current[idx].content);
$textSpan.replaceWith($textarea);
$textarea.trigger('focus');
// Swap edit/delete buttons with save/cancel.
$(this).hide();
$item.find('.sm_delete_session_memory').hide();
const $save = $(
'<button class="sm_save_session_memory menu_button" title="Save">Save</button>',
);
const $cancel = $(
'<button class="sm_cancel_session_memory menu_button" title="Cancel">Cancel</button>',
);
$item.append($save, $cancel);
$save.on('click', async () => {
const newContent = $textarea.val().trim();
if (!newContent) return;
const memories = loadSessionMemories();
if (!memories[idx]) return;
memories[idx].content = newContent;
await saveSessionMemories(memories);
await injectSessionMemories();
updateSessionUI();
});
$cancel.on('click', () => updateSessionUI());
});
$list.find('.sm_delete_session_memory').on('click', async function () {
const idx = parseInt($(this).data('index'), 10);
const context = getContext();
const meta = context.chatMetadata?.[META_KEY];
if (!meta?.sessionMemories) return;
meta.sessionMemories.splice(idx, 1);
await context.saveMetadata();
injectSessionMemories();
updateSessionUI();
});
// Add memory form at the bottom of the list.
$list.next('.sm_add_memory_form').remove();
const $addForm = $(`
<div class="sm_add_memory_form">
<input type="text" class="sm_add_memory_input" placeholder="New session memory...">
<button class="sm_add_memory_btn menu_button" title="Add memory">Add</button>
</div>
`);
$addForm.prepend(buildTypePicker(SESSION_TYPES));
$list.after($addForm);
$addForm.find('.sm_add_memory_btn').on('click', async () => {
const type = $addForm.find('.sm-type-picker').data('value');
const content = $addForm.find('.sm_add_memory_input').val().trim();
if (!content) return;
const memories = loadSessionMemories();
memories.push({
type,
content,
importance: 2,
expiration: 'session',
ts: Date.now(),
consolidated: true,
confidence: 1.0,
persona_relevance: 1,
intimacy_relevance: 1,
retrieval_count: 0,
last_confirmed_ts: Date.now(),
});
await saveSessionMemories(memories);
await injectSessionMemories();
updateSessionUI();
});
}
/** Re-renders the scene history list. */
export function updateScenesUI() {
const history = loadSceneHistory();
const $list = $('#sm_scenes_list');
$list.empty();
if (history.length === 0) {
$list.append('<div class="sm_no_char">No scenes recorded yet.</div>');
return;
}
history.forEach((s, i) => {
$list.append(
`<div class="sm_scene_item"><b>Scene ${i + 1}:</b> ${$('<div>').text(s.summary).html()}</div>`,
);
});
}
/** Re-renders the story arcs list with per-arc edit, resolve, and add buttons. */
export function updateArcsUI() {
const arcs = loadArcs();
const $list = $('#sm_arcs_list');
const $resolvedList = $('#sm_resolved_arcs_list');
const $resolvedSection = $('#sm_resolved_arcs_section');
$list.empty();
$resolvedList.empty();
const ctx = getContext();
const groupId = ctx.groupId ?? null;
const charName = groupId ? null : getCurrentCharacterName();
const canPin = !!(charName || groupId);
const activeArcs = arcs.filter((a) => !a.resolved);
const resolvedArcs = arcs.filter((a) => a.resolved);
if (activeArcs.length === 0) {
$list.append('<div class="sm_no_char">No open story threads.</div>');
}
arcs.forEach((arc, idx) => {
const isPersistent = !!arc.persistent;
const isResolved = !!arc.resolved;
if (isResolved) {
const $item = $(`
<div class="sm_arc_item sm_arc_persistent sm_arc_resolved" data-index="${idx}">
<span class="sm_arc_text">${$('<div>').text(arc.content).html()}</span>
<button class="sm_reopen_arc menu_button" data-index="${idx}" title="Re-open this thread"><i class="fa-solid fa-rotate-left"></i></button>
<button class="sm_remove_resolved_arc menu_button" data-index="${idx}" title="Remove"><i class="fa-solid fa-xmark"></i></button>
</div>
`);
$resolvedList.append($item);
} else {
const pinTitle = isPersistent
? 'Unpin - keep only in this chat'
: 'Pin - carry this thread into future chats';
const $item = $(`
<div class="sm_arc_item${isPersistent ? ' sm_arc_persistent' : ''}" data-index="${idx}">
<span class="sm_arc_text">${$('<div>').text(arc.content).html()}</span>
${canPin ? `<button class="sm_pin_arc menu_button${isPersistent ? ' sm_pin_active' : ''}" data-index="${idx}" title="${pinTitle}"><i class="fa-solid fa-thumbtack"></i></button>` : ''}
<button class="sm_edit_arc menu_button" data-index="${idx}" title="Edit this arc">
<i class="fa-solid fa-pencil"></i>
</button>
<button class="sm_resolve_arc menu_button" data-index="${idx}" title="Resolve this thread and generate an arc summary. Best used right after the thread concludes in the story - the summary is built from recent scene context, so resolving old threads may produce vague results.">
<i class="fa-solid fa-check"></i>
</button>
<button class="sm_delete_arc menu_button" data-index="${idx}" title="Delete this thread without summarising">
<i class="fa-solid fa-trash-can"></i>
</button>
</div>
`);
$list.append($item);
}
});
// Show the resolved section only when there are resolved arcs.
$resolvedSection.toggle(resolvedArcs.length > 0);
$resolvedList.find('.sm_reopen_arc').on('click', async function () {
const idx = parseInt($(this).data('index'), 10);
await reopenArc(idx, charName, groupId);
injectArcs();
updateArcsUI();
});
$resolvedList.find('.sm_remove_resolved_arc').on('click', async function () {
const idx = parseInt($(this).data('index'), 10);
const arc = loadArcs()[idx];
if (!arc) return;
await deleteArc(idx, charName);
if (groupId) {
const gP = loadGroupPersistentArcs(groupId);
saveGroupPersistentArcs(
groupId,
gP.filter((p) => p.content !== arc.content),
);
} else if (charName) {
const cP = loadPersistentArcs(charName);
savePersistentArcs(
charName,
cP.filter((p) => p.content !== arc.content),
);
}
injectArcs();
updateArcsUI();
});
$list.find('.sm_pin_arc').on('click', async function () {
const idx = parseInt($(this).data('index'), 10);
const arc = loadArcs()[idx];
if (!arc) return;
if (arc.persistent) {
await demoteArc(idx, charName, groupId);
} else {