File size: 42,493 Bytes
3d50167
 
 
 
 
0bc2a8a
 
 
 
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79fe2c6
 
 
 
3d50167
 
 
 
 
79fe2c6
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
79fe2c6
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a40f14d
 
 
 
 
 
 
 
0bc2a8a
 
 
a40f14d
 
 
 
 
 
 
 
 
 
 
3d50167
 
0bc2a8a
 
 
 
 
 
 
 
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b7272b
 
 
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
0bc2a8a
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bc2a8a
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
798bcc6
 
 
 
3d50167
 
 
 
a40f14d
3d50167
 
 
0bc2a8a
3d50167
798bcc6
3d50167
 
a40f14d
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
a40f14d
3d50167
 
 
 
 
a40f14d
 
 
798bcc6
3d50167
 
 
 
a40f14d
3d50167
 
 
a40f14d
 
3d50167
 
a40f14d
 
 
 
 
 
 
 
 
0bc2a8a
 
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
0bc2a8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a40f14d
 
 
 
 
3d50167
 
798bcc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d50167
a40f14d
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
a40f14d
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a40f14d
3d50167
 
 
 
a40f14d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a40f14d
3d50167
a40f14d
 
 
 
 
 
 
 
3d50167
a40f14d
3d50167
a40f14d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d50167
 
 
a40f14d
 
 
 
 
 
3d50167
 
a40f14d
 
3d50167
 
a40f14d
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
a40f14d
3d50167
 
 
 
a40f14d
 
 
 
3d50167
 
 
a40f14d
 
3d50167
 
a40f14d
3d50167
a40f14d
3d50167
a40f14d
 
3d50167
 
a40f14d
3d50167
 
a40f14d
3d50167
 
a40f14d
3d50167
 
 
a40f14d
 
3d50167
a40f14d
 
 
 
 
 
 
3d50167
 
 
a40f14d
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bc2a8a
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bc2a8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a40f14d
3d50167
a40f14d
3d50167
 
a40f14d
3d50167
 
a40f14d
3d50167
 
 
a40f14d
3d50167
 
a40f14d
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79fe2c6
 
 
 
 
 
 
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
// ===== KIMI MEMORY UI MANAGER =====
class KimiMemoryUI {
    constructor() {
        this.memorySystem = null;
        this.isInitialized = false;
        // Debounce helpers for UI refresh to coalesce multiple DB reads
        this._debounceTimers = {};
    }

    debounce(key, fn, wait = 350) {
        if (this._debounceTimers[key]) clearTimeout(this._debounceTimers[key]);
        this._debounceTimers[key] = setTimeout(() => {
            fn();
            delete this._debounceTimers[key];
        }, wait);
    }

    async init() {
        if (!window.kimiMemorySystem) {
            console.warn("Memory system not available");
            return;
        }

        this.memorySystem = window.kimiMemorySystem;
        this.setupEventListeners();
        await this.updateMemoryStats();
        this.isInitialized = true;
    }

    setupEventListeners() {
        // Memory toggle
        const memoryToggle = document.getElementById("memory-toggle");
        if (memoryToggle) {
            memoryToggle.addEventListener("click", () => this.toggleMemorySystem());
        }

        // View memories button
        const viewMemoriesBtn = document.getElementById("view-memories");
        if (viewMemoriesBtn) {
            viewMemoriesBtn.addEventListener("click", () => this.openMemoryModal());
        }

        // Add memory button
        const addMemoryBtn = document.getElementById("add-memory");
        if (addMemoryBtn) {
            addMemoryBtn.addEventListener("click", () => {
                this.addManualMemory();
                ensureVideoNeutralOnUIChange();
            });
        }

        // Memory modal close
        const memoryClose = document.getElementById("memory-close");
        if (memoryClose) {
            memoryClose.addEventListener("click", () => {
                this.closeMemoryModal();
                ensureVideoNeutralOnUIChange();
            });
        }

        // Memory export
        const memoryExport = document.getElementById("memory-export");
        if (memoryExport) {
            memoryExport.addEventListener("click", () => this.exportMemories());
        }

        // Memory filter
        const memoryFilter = document.getElementById("memory-filter-category");
        if (memoryFilter) {
            memoryFilter.addEventListener("change", () => {
                this.filterMemories();
                ensureVideoNeutralOnUIChange();
            });
        }

        // Memory search
        const memorySearch = document.getElementById("memory-search");
        if (memorySearch) {
            memorySearch.addEventListener("input", () => this.filterMemories());
        }

        // Close modal on overlay click
        const memoryOverlay = document.getElementById("memory-overlay");
        if (memoryOverlay) {
            memoryOverlay.addEventListener("click", e => {
                if (e.target === memoryOverlay) {
                    this.closeMemoryModal();
                }
            });
        }

        // Delegated handler for memory-source clicks / touch / keyboard
        const memoryList = document.getElementById("memory-list");
        if (memoryList) {
            // Click and touch
            memoryList.addEventListener("click", e => this.handleMemorySourceToggle(e));
            memoryList.addEventListener("touchstart", e => this.handleMemorySourceToggle(e));

            // General delegated click handler for memory actions (summarize, etc.)
            memoryList.addEventListener("click", e => this.handleMemoryListClick(e));

            // Keyboard accessibility: Enter / Space when focused on .memory-source
            memoryList.addEventListener("keydown", e => {
                const target = e.target;
                if (target && target.classList && target.classList.contains("memory-source")) {
                    if (e.key === "Enter" || e.key === " ") {
                        e.preventDefault();
                        this.toggleSourceContentForElement(target);
                    }
                }
            });
        }
    }

    // Delegated click handler for actions inside the memory list
    async handleMemoryListClick(e) {
        try {
            const summarizeBtn = e.target.closest && e.target.closest("#memory-summarize-btn");
            if (summarizeBtn) {
                e.stopPropagation();
                await this.handleSummarizeAction();
                return;
            }
        } catch (err) {
            console.error("Error handling memory list click", err);
        }
    }

    async toggleMemorySystem() {
        if (!this.memorySystem) return;

        const toggle = document.getElementById("memory-toggle");
        const enabled = !this.memorySystem.memoryEnabled;

        await this.memorySystem.toggleMemorySystem(enabled);

        if (toggle) {
            toggle.setAttribute("aria-checked", enabled.toString());
            toggle.classList.toggle("active", enabled);
        }

        // Show feedback
        this.showFeedback(enabled ? "Memory system enabled" : "Memory system disabled");
    }

    async addManualMemory() {
        const categorySelect = document.getElementById("memory-category");
        const contentInput = document.getElementById("memory-content");

        if (!categorySelect || !contentInput) return;

        const category = categorySelect.value;
        const content = contentInput.value.trim();

        if (!content) {
            this.showFeedback("Please enter memory content", "error");
            return;
        }

        try {
            await this.memorySystem.addMemory({
                category: category,
                content: content,
                type: "manual",
                confidence: 1.0
            });

            contentInput.value = "";
            await this.updateMemoryStats();
            this.showFeedback("Memory added successfully");
        } catch (error) {
            console.error("Error adding memory:", error);
            this.showFeedback("Error adding memory", "error");
        }
    }

    async openMemoryModal() {
        const overlay = document.getElementById("memory-overlay");
        if (!overlay) return;

        overlay.style.display = "flex";
        await this.loadMemories();
    }

    closeMemoryModal() {
        const overlay = document.getElementById("memory-overlay");
        if (overlay) {
            overlay.style.display = "none";
            // Ensure background video resumes after closing memory modal
            const kv = window.kimiVideo;
            if (kv && kv.activeVideo) {
                try {
                    const v = kv.activeVideo;
                    if (v.ended) {
                        if (typeof kv.returnToNeutral === "function") kv.returnToNeutral();
                    } else if (v.paused) {
                        // Use centralized video utility for play
                        window.KimiVideoManager.getVideoElement(v)
                            .play()
                            .catch(() => {
                                if (typeof kv.returnToNeutral === "function") kv.returnToNeutral();
                            });
                    }
                } catch {}
            }
        }
    }

    async loadMemories() {
        if (!this.memorySystem) return;

        try {
            // Use debounce to avoid multiple rapid DB reads
            this.debounce("loadMemories", async () => {
                const memories = await this.memorySystem.getAllMemories();
                console.log("Loading memories into UI:", memories.length);
                this.renderMemories(memories);
            });
        } catch (error) {
            console.error("Error loading memories:", error);
        }
    }

    async filterMemories() {
        const filterSelect = document.getElementById("memory-filter-category");
        const searchInput = document.getElementById("memory-search");
        if (!this.memorySystem) return;

        try {
            const category = filterSelect?.value;
            const searchTerm = searchInput?.value.toLowerCase().trim();
            let memories;

            if (category) {
                memories = await this.memorySystem.getMemoriesByCategory(category);
            } else {
                memories = await this.memorySystem.getAllMemories();
            }

            // Apply search filter if search term exists
            if (searchTerm) {
                memories = memories.filter(
                    memory =>
                        memory.content.toLowerCase().includes(searchTerm) ||
                        memory.category.toLowerCase().includes(searchTerm) ||
                        (memory.sourceText && memory.sourceText.toLowerCase().includes(searchTerm))
                );
            }

            this.renderMemories(memories);
        } catch (error) {
            console.error("Error filtering memories:", error);
        }
    }

    renderMemories(memories) {
        const memoryList = document.getElementById("memory-list");
        if (!memoryList) return;

        console.log("Rendering memories:", memories); // Debug logging

        if (memories.length === 0) {
            memoryList.innerHTML = `

                <div class="memory-empty">

                    <i class="fas fa-brain"></i>

                    <p>No memories found. Start chatting to build memories automatically, or add them manually.</p>

                </div>

            `;
            return;
        }

        // Group memories by category for better organization
        const groupedMemories = memories.reduce((groups, memory) => {
            const category = memory.category || "other";
            if (!groups[category]) groups[category] = [];
            groups[category].push(memory);
            return groups;
        }, {});

        let html = "";

        // Toolbar with summarize action
        html += `

            <div class="memory-toolbar" style="display:flex; gap:8px; align-items:center; margin-bottom:12px;">

                <button id="memory-summarize-btn" class="kimi-button" title="Summarize recent memories">πŸ“ Summarize last 7 days</button>

            </div>

        `;
        Object.entries(groupedMemories).forEach(([category, categoryMemories]) => {
            html += `

                <div class="memory-category-group">

                    <h4 class="memory-category-header">

                        ${this.getCategoryIcon(category)} ${this.formatCategoryName(category)}

                        <span class="memory-category-count">(${categoryMemories.length})</span>

                    </h4>

                    <div class="memory-category-items">

            `;

            categoryMemories.forEach(memory => {
                const confidence = Math.round(memory.confidence * 100);
                const isAutomatic = memory.type === "auto_extracted";
                const previewLength = 120;
                const isLongContent = memory.content.length > previewLength;
                const previewText = isLongContent ? memory.content.substring(0, previewLength) + "..." : memory.content;
                const wordCount = memory.content.split(/\s+/).length;
                const importance = typeof memory.importance === "number" ? memory.importance : 0.5;
                const importanceLevel = this.getImportanceLevelFromValue(importance);
                const importancePct = Math.round(importance * 100);
                const tagsHtml = this.renderTags(memory.tags || []);

                html += `

                    <div class="memory-item ${isAutomatic ? "memory-auto" : "memory-manual"}" data-memory-id="${memory.id}">

                        <div class="memory-header">

                            <div class="memory-item-title">${window.KimiValidationUtils && window.KimiValidationUtils.escapeHtml ? window.KimiValidationUtils.escapeHtml(memory.title || "") : memory.title || ""}${!memory.title ? "" : ""}</div>

                            <div class="memory-badges">

                                <span class="memory-type ${memory.type}">${memory.type === "auto_extracted" ? "πŸ€– Auto" : "βœ‹ Manual"}</span>

                                <span class="memory-confidence confidence-${this.getConfidenceLevel(confidence)}">${confidence}%</span>

                                ${memory.type === "summary" || (memory.tags && memory.tags.includes("summary")) ? `<span class="memory-summary-badge" style="background:var(--accent-color);color:white;padding:2px 6px;border-radius:12px;margin-left:8px;font-size:0.8em;">Summary</span>` : ""}

                                ${isLongContent ? `<span class="memory-length">${wordCount} mots</span>` : ""}

                <span class="memory-importance importance-${importanceLevel}" title="Importance: ${importancePct}% (${importanceLevel})">${importanceLevel.charAt(0).toUpperCase() + importanceLevel.slice(1)}</span>

                            </div>

                        </div>

                        ${

                            !memory.title

                                ? `

                        <div class="memory-preview">

                            <div class="memory-preview-text ${isLongContent ? "memory-preview-short" : ""}" id="preview-${memory.id}">

                                ${this.highlightMemoryContent(previewText)}

                            </div>

                            ${

                                isLongContent

                                    ? `

                                <div class="memory-preview-full" id="full-${memory.id}" style="display: none;">

                                    ${this.highlightMemoryContent(memory.content)}

                                </div>

                                <button class="memory-expand-btn" onclick="kimiMemoryUI.toggleMemoryContent('${memory.id}')">

                                    <i class="fas fa-chevron-down" id="icon-${memory.id}"></i> <span data-i18n="view_more"></span>

                                </button>

                            `

                                    : ""

                            }

                        </div>

                        `

                                : ""

                        }

            ${tagsHtml}

                        <div class="memory-meta">

                            <span class="memory-date">${this.formatDate(memory.timestamp)}</span>

                            ${

                                memory.sourceText

                                    ? `<span class="memory-source" data-i18n="memory_source_label" title="${

                                          window.KimiValidationUtils && window.KimiValidationUtils.escapeHtml

                                              ? window.KimiValidationUtils.escapeHtml(memory.sourceText)

                                              : memory.sourceText

                                      }"></span>`

                                    : `<span data-i18n="memory_manually_added"></span>`

                            }

                        </div>

                            ${

                                memory.sourceText

                                    ? `<div class="memory-source-content" id="source-content-${memory.id}" style="display:none;">${

                                          window.KimiValidationUtils && window.KimiValidationUtils.escapeHtml

                                              ? window.KimiValidationUtils.escapeHtml(memory.sourceText)

                                              : memory.sourceText

                                      }</div>`

                                    : ""

                            }

                                <div class="memory-actions">

                                    <button class="memory-edit-btn" onclick="kimiMemoryUI.editMemory('${memory.id}')" data-i18n-title="edit_memory_button_title">

                                        <i class="fas fa-edit"></i>

                                    </button>

                                    <button class="memory-delete-btn" onclick="kimiMemoryUI.deleteMemory('${memory.id}')" data-i18n-title="delete_memory_button_title">

                                        <i class="fas fa-trash"></i>

                                    </button>

                                </div>

                    </div>

                `;
            });

            html += `

                    </div>

                </div>

            `;
        });

        // Minimal runtime guard: block accidental <script> tags in generated HTML
        // This is a non-intrusive safety check that prevents XSS when the
        // assembled `html` somehow contains script tags. In normal operation
        // the content is escaped via KimiValidationUtils and highlightMemoryContent(),
        // so this will not run; it only activates on suspicious input.
        try {
            if (/\<\s*script\b/i.test(html)) {
                console.warn("Blocked suspicious <script> tag in memory HTML rendering");
                // Fallback: render as safe text to avoid executing injected scripts
                memoryList.textContent = html;
            } else {
                memoryList.innerHTML = html;
            }
        } catch (e) {
            // On any unexpected error, fallback to safe text rendering
            console.error("Error while rendering memories, falling back to safe text:", e);
            memoryList.textContent = html;
        }

        // Apply translations to dynamic content
        if (window.applyTranslations && typeof window.applyTranslations === "function") {
            window.applyTranslations();
        }
    }

    // Map importance value [0..1] to level string
    getImportanceLevelFromValue(value) {
        if (value >= 0.8) return "high";
        if (value >= 0.6) return "medium";
        return "low";
    }

    // Render tags as compact chips; show up to 4 then "+N"
    renderTags(tags) {
        if (!Array.isArray(tags) || tags.length === 0) return "";
        const maxVisible = 4;
        const visible = tags.slice(0, maxVisible);
        const moreCount = tags.length - visible.length;

        const escape = txt =>
            window.KimiValidationUtils && window.KimiValidationUtils.escapeHtml
                ? window.KimiValidationUtils.escapeHtml(String(txt))
                : String(txt);

        const classify = tag => {
            if (tag.startsWith("relationship:")) return "tag-relationship";
            if (tag.startsWith("boundary:")) return "tag-boundary";
            if (tag.startsWith("time:")) return "tag-time";
            if (tag.startsWith("type:")) return "tag-type";
            return "tag-generic";
        };

        const chips = visible
            .map(tag => `<span class="memory-tag ${classify(tag)}" title="${escape(tag)}">${escape(tag)}</span>`)
            .join("");

        const moreChip = moreCount > 0 ? `<span class="memory-tag tag-more" title="${moreCount} more">+${moreCount}</span>` : "";

        return `<div class="memory-tags">${chips}${moreChip}</div>`;
    }

    formatCategoryName(category) {
        // Try to resolve via i18n keys first, fallback to hardcoded English
        const i18nKey = `memory_category_${category}`;
        if (window.kimiI18nManager && typeof window.kimiI18nManager.t === "function") {
            const val = window.kimiI18nManager.t(i18nKey);
            if (val && val !== i18nKey) return val;
        }

        const names = {
            personal: "Personal Information",
            preferences: "Likes & Dislikes",
            relationships: "Relationships & People",
            activities: "Activities & Hobbies",
            goals: "Goals & Aspirations",
            experiences: "Shared Experiences",
            important: "Important Events"
        };

        return names[category] || category.charAt(0).toUpperCase() + category.slice(1);
    }

    getConfidenceLevel(confidence) {
        if (confidence >= 80) return "high";
        if (confidence >= 60) return "medium";
        return "low";
    }

    formatDate(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diffTime = now - date;
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

        if (diffDays === 0) return "Today";
        if (diffDays === 1) return "Yesterday";
        if (diffDays < 7) return `${diffDays} days ago`;
        return date.toLocaleDateString();
    }

    highlightMemoryContent(content) {
        // Escape HTML first using centralized util
        const escapedContent =
            window.KimiValidationUtils && window.KimiValidationUtils.escapeHtml
                ? window.KimiValidationUtils.escapeHtml(content)
                : content;

        // Simple highlighting for search terms if there's a search active
        const searchInput = document.getElementById("memory-search");
        if (searchInput && searchInput.value.trim()) {
            const searchTerm = searchInput.value.trim();
            const regex = new RegExp(`(${searchTerm})`, "gi");
            return escapedContent.replace(
                regex,
                '<mark style="background: var(--primary-color); color: white; padding: 1px 3px; border-radius: 2px;">$1</mark>'
            );
        }

        return escapedContent;
    }

    getCategoryIcon(category) {
        const icons = {
            personal: "πŸ‘€",
            preferences: "❀️",
            relationships: "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦",
            activities: "🎯",
            goals: "🎯",
            experiences: "⭐",
            important: "πŸ“Œ"
        };
        return icons[category] || "πŸ“";
    }

    toggleMemoryContent(memoryId) {
        const previewShort = document.getElementById(`preview-${memoryId}`);
        const previewFull = document.getElementById(`full-${memoryId}`);
        const icon = document.getElementById(`icon-${memoryId}`);
        const expandBtn = icon?.closest(".memory-expand-btn");

        if (!previewShort || !previewFull || !icon || !expandBtn) return;

        const isExpanded = previewFull.style.display !== "none";

        if (isExpanded) {
            previewShort.style.display = "block";
            previewFull.style.display = "none";
            icon.className = "fas fa-chevron-down";
            expandBtn.innerHTML = '<i class="fas fa-chevron-down"></i> <span data-i18n="view_more"></span>';
        } else {
            previewShort.style.display = "none";
            previewFull.style.display = "block";
            icon.className = "fas fa-chevron-up";
            expandBtn.innerHTML = '<i class="fas fa-chevron-up"></i> <span data-i18n="view_less"></span>';
        }

        // Re-apply translations for the new button label
        if (window.applyTranslations && typeof window.applyTranslations === "function") {
            window.applyTranslations();
        }
    }

    // Handle delegated click/touch events for .memory-source
    handleMemorySourceToggle(e) {
        try {
            const el = e.target.closest && e.target.closest(".memory-source");
            if (!el) return;
            // Prevent triggering parent handlers
            e.stopPropagation();
            e.preventDefault();
            this.toggleSourceContentForElement(el);
        } catch (err) {
            console.error("Error handling memory-source toggle", err);
        }
    }

    // Toggle the adjacent .memory-source-content for a given .memory-source element
    toggleSourceContentForElement(sourceEl) {
        if (!sourceEl) return;
        // The memory id is present on the nearest .memory-item
        const item = sourceEl.closest(".memory-item");
        if (!item) return;
        const id = item.getAttribute("data-memory-id");
        if (!id) return;

        const contentEl = document.getElementById(`source-content-${id}`);
        if (!contentEl) return;

        const isVisible = contentEl.style.display !== "none" && contentEl.style.display !== "";

        // Close any other open source contents
        document.querySelectorAll(".memory-source-content").forEach(el => {
            if (el !== contentEl) el.style.display = "none";
        });

        if (isVisible) {
            contentEl.style.display = "none";
            sourceEl.setAttribute("aria-expanded", "false");
        } else {
            // simple sliding animation via max-height for smoother appearance
            contentEl.style.display = "block";
            sourceEl.setAttribute("aria-expanded", "true");
        }
    }

    async editMemory(memoryId) {
        if (!this.memorySystem) return;

        try {
            // Get the memory to edit
            const memories = await this.memorySystem.getAllMemories();
            const memory = memories.find(m => m.id == memoryId);
            if (!memory) {
                this.showFeedback("Memory not found", "error");
                return;
            }

            // Create edit dialog
            const overlay = document.createElement("div");
            overlay.className = "memory-edit-overlay";
            overlay.style.cssText = `

                position: fixed;

                top: 0;

                left: 0;

                width: 100%;

                height: 100%;

                background: rgba(0, 0, 0, 0.8);

                display: flex;

                justify-content: center;

                align-items: center;

                z-index: 10001;

            `;

            const dialog = document.createElement("div");
            dialog.className = "memory-edit-dialog";
            dialog.style.cssText = `

                background: var(--background-secondary);

                border-radius: 12px;

                padding: 24px;

                width: 90%;

                max-width: 500px;

                box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);

            `;

            dialog.innerHTML = `

                <h3 style="margin: 0 0 20px 0; color: var(--text-primary);">

                    <i class="fas fa-edit"></i> <span data-i18n="edit_memory_title"></span>

                </h3>

                <div style="margin-bottom: 12px;">

                    <label style="display: block; margin-bottom: 8px; font-weight: 500;" data-i18n="label_title"></label>

                    <input id="edit-memory-title" class="kimi-input" style="width:100%;" value="${

                        window.KimiValidationUtils && window.KimiValidationUtils.escapeHtml

                            ? window.KimiValidationUtils.escapeHtml(memory.title || "")

                            : memory.title || ""

                    }" placeholder="Optional title for this memory" />

                </div>

                <div style="margin-bottom: 16px;">

                    <label style="display: block; margin-bottom: 8px; font-weight: 500;" data-i18n="label_category"></label>

                    <select id="edit-memory-category" class="kimi-select" style="width: 100%;">

                        <option value="personal" ${memory.category === "personal" ? "selected" : ""}>${

                            window.kimiI18nManager && window.kimiI18nManager.t

                                ? window.kimiI18nManager.t("memory_category_personal")

                                : "Personal Info"

                        }</option>

                        <option value="preferences" ${memory.category === "preferences" ? "selected" : ""}>${

                            window.kimiI18nManager && window.kimiI18nManager.t

                                ? window.kimiI18nManager.t("memory_category_preferences")

                                : "Likes & Dislikes"

                        }</option>

                        <option value="relationships" ${memory.category === "relationships" ? "selected" : ""}>${

                            window.kimiI18nManager && window.kimiI18nManager.t

                                ? window.kimiI18nManager.t("memory_category_relationships")

                                : "Relationships"

                        }</option>

                        <option value="activities" ${memory.category === "activities" ? "selected" : ""}>${

                            window.kimiI18nManager && window.kimiI18nManager.t

                                ? window.kimiI18nManager.t("memory_category_activities")

                                : "Activities & Hobbies"

                        }</option>

                        <option value="goals" ${memory.category === "goals" ? "selected" : ""}>${

                            window.kimiI18nManager && window.kimiI18nManager.t

                                ? window.kimiI18nManager.t("memory_category_goals")

                                : "Goals & Plans"

                        }</option>

                        <option value="experiences" ${memory.category === "experiences" ? "selected" : ""}>${

                            window.kimiI18nManager && window.kimiI18nManager.t

                                ? window.kimiI18nManager.t("memory_category_experiences")

                                : "Experiences"

                        }</option>

                        <option value="important" ${memory.category === "important" ? "selected" : ""}>${

                            window.kimiI18nManager && window.kimiI18nManager.t

                                ? window.kimiI18nManager.t("memory_category_important")

                                : "Important Events"

                        }</option>

                    </select>

                </div>

                <div style="margin-bottom: 20px;">

                    <label style="display: block; margin-bottom: 8px; font-weight: 500;" data-i18n="label_content"></label>

                    <textarea id="edit-memory-content" class="kimi-input" style="width: 100%; height: 100px; resize: vertical;" placeholder="Memory content...">${

                        window.KimiValidationUtils && window.KimiValidationUtils.escapeHtml

                            ? window.KimiValidationUtils.escapeHtml(memory.sourceText || memory.content || "")

                            : memory.sourceText || memory.content || ""

                    }</textarea>

                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">

                    <button id="cancel-edit" class="kimi-button" style="background: #6c757d;" data-i18n="cancel">

                        <i class="fas fa-times"></i> <span data-i18n="cancel"></span>

                    </button>

                    <button id="save-edit" class="kimi-button">

                        <i class="fas fa-save"></i> <span data-i18n="save"></span>

                    </button>

                </div>

            `;

            overlay.appendChild(dialog);
            document.body.appendChild(overlay);

            // Handle buttons
            dialog.querySelector("#cancel-edit").addEventListener("click", () => {
                document.body.removeChild(overlay);
            });

            dialog.querySelector("#save-edit").addEventListener("click", async () => {
                const newTitle = dialog.querySelector("#edit-memory-title").value.trim();
                const newCategory = dialog.querySelector("#edit-memory-category").value;
                const newContent = dialog.querySelector("#edit-memory-content").value.trim();

                if (!newContent) {
                    this.showFeedback(
                        window.kimiI18nManager ? window.kimiI18nManager.t("validation_empty_message") : "Content cannot be empty",
                        "error"
                    );
                    return;
                }

                console.log(`πŸ”„ Attempting to update memory ID: ${memoryId}`);
                console.log("New data:", { category: newCategory, content: newContent });

                try {
                    // Also update sourceText so the "πŸ“ Memory of the conversation" shows edited content
                    const result = await this.memorySystem.updateMemory(memoryId, {
                        title: newTitle,
                        category: newCategory,
                        content: newContent,
                        sourceText: newContent
                    });

                    console.log("Update result:", result);

                    if (result === true) {
                        // Close the modal
                        document.body.removeChild(overlay);

                        // Force full reload
                        await this.loadMemories();
                        await this.updateMemoryStats();

                        this.showFeedback(window.kimiI18nManager ? window.kimiI18nManager.t("saved") : "Saved");
                        console.log("βœ… UI updated");
                    } else {
                        this.showFeedback(
                            window.kimiI18nManager
                                ? window.kimiI18nManager.t("fallback_general_error")
                                : "Error: unable to update memory",
                            "error"
                        );
                        console.error("❌ Update failed, result:", result);
                    }
                } catch (error) {
                    console.error("Error updating memory:", error);
                    this.showFeedback(
                        window.kimiI18nManager ? window.kimiI18nManager.t("fallback_general_error") : "Error updating memory",
                        "error"
                    );
                }
            });

            // Close on overlay click
            overlay.addEventListener("click", e => {
                if (e.target === overlay) {
                    document.body.removeChild(overlay);
                }
            });
        } catch (error) {
            console.error("Error editing memory:", error);
            this.showFeedback("Error loading memory for editing", "error");
        }
    }

    async deleteMemory(memoryId) {
        if (!confirm("Are you sure you want to delete this memory?")) return;

        try {
            await this.memorySystem.deleteMemory(memoryId);
            await this.loadMemories();
            // Debounced stats update
            this.debounce("updateStats", async () => await this.updateMemoryStats());
            this.showFeedback("Memory deleted");
        } catch (error) {
            console.error("Error deleting memory:", error);
            this.showFeedback("Error deleting memory", "error");
        }
    }

    async exportMemories() {
        if (!this.memorySystem) return;

        try {
            const exportData = await this.memorySystem.exportMemories();
            if (exportData) {
                const blob = new Blob([JSON.stringify(exportData, null, 2)], {
                    type: "application/json"
                });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url;
                a.download = `kimi-memories-${new Date().toISOString().split("T")[0]}.json`;
                a.click();
                URL.revokeObjectURL(url);
                this.showFeedback("Memories exported successfully");
            }
        } catch (error) {
            console.error("Error exporting memories:", error);
            this.showFeedback("Error exporting memories", "error");
        }
    }

    async handleSummarizeAction() {
        if (!this.memorySystem) return;
        try {
            // Destructive confirmation modal
            const confirmMsg = `This action will create a single summary memory for the last 7 days and permanently DELETE the source memories. This is irreversible. Do you want to continue?`;
            if (!confirm(confirmMsg)) {
                this.showFeedback("Summary canceled");
                return;
            }

            this.showFeedback("Creating summary and replacing sources...");
            const result = await this.memorySystem.summarizeAndReplace(7, {});
            if (result) {
                this.showFeedback("Summary created and sources deleted");
                await this.loadMemories();
                await this.updateMemoryStats();
            } else {
                this.showFeedback("No recent memories to summarize");
            }
        } catch (e) {
            console.error("Error creating destructive summary", e);
            this.showFeedback("Error creating summary", "error");
        }
    }

    async updateMemoryStats() {
        if (!this.memorySystem) return;

        try {
            const stats = await this.memorySystem.getMemoryStats();
            const memoryCount = document.getElementById("memory-count");
            const memoryToggle = document.getElementById("memory-toggle");

            if (memoryCount) {
                memoryCount.textContent = `${stats.total} memories`;
            }

            // Update toggle state
            if (memoryToggle) {
                const enabled = this.memorySystem.memoryEnabled;
                memoryToggle.setAttribute("aria-checked", enabled.toString());
                memoryToggle.classList.toggle("active", enabled);

                // Add visual indicator for memory status
                const indicator = memoryToggle.querySelector(".memory-indicator") || document.createElement("div");
                if (!memoryToggle.querySelector(".memory-indicator")) {
                    indicator.className = "memory-indicator";
                    memoryToggle.appendChild(indicator);
                }
                indicator.style.cssText = `

                    position: absolute;

                    top: -2px;

                    right: -2px;

                    width: 8px;

                    height: 8px;

                    border-radius: 50%;

                    background: ${enabled ? "#27ae60" : "#e74c3c"};

                    border: 2px solid white;

                `;
            }
        } catch (error) {
            console.error("Error updating memory stats:", error);
        }
    }

    // Force refresh of the memory UI (useful for debugging)
    async forceRefresh() {
        console.log("πŸ”„ Force refresh of memory UI...");
        try {
            if (this.memorySystem) {
                // Migrate IDs if necessary
                await this.memorySystem.migrateIncompatibleIDs();

                // Reload memories
                await this.loadMemories();
                await this.updateMemoryStats();

                console.log("βœ… Forced refresh completed");
            }
        } catch (error) {
            console.error("❌ Error during forced refresh:", error);
        }
    }

    showFeedback(message, type = "success") {
        // Create feedback element
        const feedback = document.createElement("div");
        feedback.className = `memory-feedback memory-feedback-${type}`;
        feedback.textContent = message;

        // Style the feedback based on type
        let backgroundColor;
        switch (type) {
            case "error":
                backgroundColor = "#e74c3c";
                break;
            case "info":
                backgroundColor = "#3498db";
                break;
            default:
                backgroundColor = "#27ae60";
        }

        // Style the feedback
        Object.assign(feedback.style, {
            position: "fixed",
            top: "20px",
            right: "20px",
            padding: "12px 20px",
            borderRadius: "6px",
            color: "white",
            backgroundColor: backgroundColor,
            boxShadow: "0 4px 12px rgba(0,0,0,0.2)",
            zIndex: "10000",
            fontSize: "14px",
            fontWeight: "500",
            opacity: "0",
            transform: "translateX(100%)",
            transition: "all 0.3s ease"
        });

        document.body.appendChild(feedback);

        // Animate in
        setTimeout(() => {
            feedback.style.opacity = "1";
            feedback.style.transform = "translateX(0)";
        }, 10);

        // Remove after delay (longer for info messages, shorter for others)
        const delay = type === "info" ? 2000 : 3000;
        setTimeout(() => {
            feedback.style.opacity = "0";
            feedback.style.transform = "translateX(100%)";
            setTimeout(() => {
                if (feedback.parentNode) {
                    feedback.parentNode.removeChild(feedback);
                }
            }, 300);
        }, delay);
    }
}

// Initialize memory UI when DOM is ready
document.addEventListener("DOMContentLoaded", async () => {
    window.kimiMemoryUI = new KimiMemoryUI();

    // Wait for memory system to be ready
    const waitForMemorySystem = () => {
        if (window.kimiMemorySystem) {
            window.kimiMemoryUI.init();
        } else {
            setTimeout(waitForMemorySystem, 100);
        }
    };

    setTimeout(waitForMemorySystem, 1000); // Give time for initialization
});

window.KimiMemoryUI = KimiMemoryUI;

function ensureVideoNeutralOnUIChange() {
    if (window.kimiVideo && window.kimiVideo.getCurrentVideoInfo) {
        const info = window.kimiVideo.getCurrentVideoInfo();
        if (info && info.ended) window.kimiVideo.returnToNeutral();
    }
}