coding-agent-search 0.6.2

Unified TUI search over local coding agent histories
Documentation
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
/**
 * cass Archive Viewer - Main Application Module
 *
 * Ties together search, conversation viewer, and database modules.
 * Manages application state and view transitions with hash-based routing.
 *
 * Routes:
 *   #/                      -> home / search
 *   #/search?q=auth+bug     -> search query
 *   #/c/12345               -> conversation 12345
 *   #/c/12345/m/67          -> message 67 in conversation 12345
 *   #/settings              -> settings panel
 *   #/stats                 -> analytics dashboard
 */

import { isDatabaseReady, getStatistics, closeDatabase } from './database.js';
import { initSearch, clearSearch, getSearchState, setSearchRoute } from './search.js';
import {
    initConversationViewer,
    loadConversation,
    clearViewer,
    cleanupConversationViewer,
    getCurrentConversation,
} from './conversation.js';
import { createRouter, getRouter, parseSearchParams, buildConversationPath, buildSearchPath } from './router.js';
import { getConversationLink, copyConversationLink, isWebShareAvailable, shareConversation } from './share.js';
import { initStats, renderStatsDashboard, clearStatsCache } from './stats.js';
import { initStorage, StorageKeys } from './storage.js';
import { initSettings, render as renderSettings, cleanupSettings } from './settings.js';

// Application state
const state = {
    view: 'search', // 'search' | 'conversation' | 'settings' | 'stats' | 'not-found'
    conversationId: null,
    messageId: null,
    searchQuery: '',
    searchFilters: {
        agent: null,
        since: null,
        until: null,
        timePreset: null,
    },
    initialized: false,
};

// Router instance
let router = null;
let storageReady = null;
let settingsReady = false;
let waitingForDatabaseReady = false;
let viewerLifecycleEpoch = 0;

// DOM element references
let elements = {
    appContent: null,
    searchView: null,
    conversationView: null,
    settingsView: null,
    statsView: null,
    notFoundView: null,
    statsDisplay: null,
    navBar: null,
};

/**
 * Initialize the viewer application
 */
export function init() {
    console.log('[Viewer] Initializing...');

    // Get the app content container
    elements.appContent = document.getElementById('app-content');

    if (!elements.appContent) {
        console.error('[Viewer] App content container not found');
        return;
    }

    if (state.initialized) {
        if (!isDatabaseReady()) {
            console.log('[Viewer] Waiting for database re-open...');
            ensureDatabaseReadyListener();
            return;
        }

        refreshAfterDatabaseReady();
        return;
    }

    if (!isDatabaseReady()) {
        console.log('[Viewer] Waiting for database...');
        ensureDatabaseReadyListener();
        return;
    }

    initializeViews();
}

function ensureDatabaseReadyListener() {
    if (waitingForDatabaseReady) {
        return;
    }

    waitingForDatabaseReady = true;
    window.addEventListener('cass:db-ready', handleDatabaseReady);
}

/**
 * Handle database ready event
 */
function handleDatabaseReady(event) {
    console.log('[Viewer] Database ready:', event.detail);
    window.removeEventListener('cass:db-ready', handleDatabaseReady);
    waitingForDatabaseReady = false;

    if (state.initialized) {
        refreshAfterDatabaseReady();
        return;
    }

    initializeViews();
}

/**
 * Initialize views after database is ready
 */
function initializeViews() {
    const lifecycleEpoch = ++viewerLifecycleEpoch;

    // Clear loading state
    elements.appContent.innerHTML = '';

    // Create view containers
    createViewContainers();

    // Expose notifications to settings module
    window.showNotification = showNotification;

    // Apply stored theme early
    applyStoredTheme();

    // Initialize storage and settings
    storageReady = initStorage().then(() => ({ ok: true })).catch((error) => {
        console.warn('[Viewer] Storage init failed:', error);
        return { ok: false, error };
    });
    storageReady.then((result) => {
        void initializeSettingsAfterStorageReady(result, lifecycleEpoch);
    });

    // Initialize search view
    initSearch(elements.searchView, handleResultSelect);

    // Initialize conversation viewer
    initConversationViewer(elements.conversationView, handleBackToSearch);

    // Initialize stats module
    initStats(elements.statsView);

    // Create router with navigation handler
    router = createRouter({
        onNavigate: handleRouteChange,
    });

    window.addEventListener('cass:lock', handleGlobalLock);

    // Mark as initialized
    state.initialized = true;

    console.log('[Viewer] Initialized with hash-based routing');
}

function refreshAfterDatabaseReady() {
    if (!state.initialized) {
        initializeViews();
        return;
    }

    switch (state.view) {
        case 'conversation':
            if (state.conversationId) {
                handleConversationRoute(state.conversationId, state.messageId);
                return;
            }
            break;
        case 'settings':
            handleSettingsRoute();
            return;
        case 'stats':
            handleStatsRoute();
            return;
        case 'not-found':
            handleNotFoundRoute(window.location.hash || '/');
            return;
        default:
            break;
    }

    handleSearchRoute({
        query: {
            q: state.searchQuery,
            agent: state.searchFilters.agent,
            since: state.searchFilters.since,
            until: state.searchFilters.until,
            time: state.searchFilters.timePreset && state.searchFilters.timePreset !== 'custom'
                ? state.searchFilters.timePreset
                : null,
        },
    });
}

/**
 * Create view containers
 */
function createViewContainers() {
    elements.appContent.innerHTML = `
        <nav id="nav-bar" class="nav-bar">
            <div class="nav-brand">
                <a href="#/" class="nav-logo">cass Archive</a>
            </div>
            <div class="nav-links">
                <a href="#/" class="nav-link" data-view="search">Search</a>
                <a href="#/stats" class="nav-link" data-view="stats">Stats</a>
                <a href="#/settings" class="nav-link" data-view="settings">Settings</a>
            </div>
        </nav>
        <div id="stats-display" class="stats-display"></div>
        <div id="search-view" class="view-container"></div>
        <div id="conversation-view" class="view-container hidden"></div>
        <div id="settings-view" class="view-container hidden"></div>
        <div id="stats-view" class="view-container hidden"></div>
        <div id="not-found-view" class="view-container hidden"></div>
    `;

    elements.navBar = document.getElementById('nav-bar');
    elements.searchView = document.getElementById('search-view');
    elements.conversationView = document.getElementById('conversation-view');
    elements.settingsView = document.getElementById('settings-view');
    elements.statsView = document.getElementById('stats-view');
    elements.notFoundView = document.getElementById('not-found-view');
    elements.statsDisplay = document.getElementById('stats-display');

    // Set up nav link highlighting
    setupNavLinks();
}

/**
 * Set up navigation link click handling
 */
function setupNavLinks() {
    const navLinks = elements.navBar.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            // Update active state (router handles actual navigation)
            updateActiveNavLink(link.dataset.view);
        });
    });
}

/**
 * Update active navigation link
 */
function updateActiveNavLink(activeView) {
    const navLinks = elements.navBar.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        if (link.dataset.view === activeView) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });
}

/**
 * Handle route changes from the router
 */
function handleRouteChange(route) {
    console.debug('[Viewer] Route change:', route);

    const { view, params, query } = route;
    const leavingConversation = state.view === 'conversation' && view !== 'conversation';
    const leavingSearch = state.view === 'search' && view !== 'search';
    const leavingStats = state.view === 'stats' && view !== 'stats';

    if (leavingConversation) {
        clearViewer();
    }
    if (leavingSearch) {
        clearSearch({ reloadRecent: false });
    }
    if (leavingStats) {
        clearStatsCache();
    }

    switch (view) {
        case 'search':
            handleSearchRoute(route);
            break;

        case 'conversation':
            handleConversationRoute(params.conversationId, params.messageId);
            break;

        case 'settings':
            handleSettingsRoute();
            break;

        case 'stats':
            handleStatsRoute();
            break;

        case 'not-found':
        default:
            handleNotFoundRoute(params.path || route.raw);
            break;
    }
}

/**
 * Handle search route
 */
function handleSearchRoute(route = { query: {} }) {
    const searchParams = parseSearchParams(route);

    state.view = 'search';
    state.conversationId = null;
    state.messageId = null;
    state.searchQuery = searchParams.query;
    state.searchFilters = {
        agent: searchParams.agent,
        since: searchParams.since,
        until: searchParams.until,
        timePreset: searchParams.timePreset,
    };

    // Show search view
    showViewContainer('search');

    // Display stats header
    displayStats();

    // Update nav
    updateActiveNavLink('search');

    if (state.searchQuery || state.searchFilters.agent || state.searchFilters.since || state.searchFilters.until || state.searchFilters.timePreset) {
        console.debug('[Viewer] Search route from URL:', searchParams);
        setSearchRoute(searchParams).catch((error) => {
            console.warn('[Viewer] Failed to run search route from URL:', error);
        });
        return;
    }

    clearSearch({ reloadRecent: true });
}

/**
 * Handle conversation route
 */
function handleConversationRoute(conversationId, messageId = null) {
    if (!conversationId) {
        handleNotFoundRoute('/c/');
        return;
    }

    state.view = 'conversation';
    state.conversationId = conversationId;
    state.messageId = messageId;

    // Show conversation view
    showViewContainer('conversation');

    // Load conversation
    loadConversation(conversationId, messageId);

    // Hide stats header
    if (elements.statsDisplay) {
        elements.statsDisplay.classList.add('hidden');
    }

    // Update nav (no specific nav for conversation)
    updateActiveNavLink(null);
}

/**
 * Handle settings route
 */
function handleSettingsRoute() {
    state.view = 'settings';
    state.conversationId = null;
    state.messageId = null;

    // Show settings view
    showViewContainer('settings');

    // Render settings panel
    renderSettingsPanel();

    // Hide stats header
    if (elements.statsDisplay) {
        elements.statsDisplay.classList.add('hidden');
    }

    // Update nav
    updateActiveNavLink('settings');
}

/**
 * Handle stats route
 */
function handleStatsRoute() {
    state.view = 'stats';
    state.conversationId = null;
    state.messageId = null;

    // Show stats view
    showViewContainer('stats');

    // Render stats panel
    renderStatsPanel();

    // Hide stats header
    if (elements.statsDisplay) {
        elements.statsDisplay.classList.add('hidden');
    }

    // Update nav
    updateActiveNavLink('stats');
}

/**
 * Handle not-found route
 */
function handleNotFoundRoute(path) {
    state.view = 'not-found';

    // Show not found view
    showViewContainer('not-found');

    // Render 404 content
    renderNotFoundPanel(path);

    // Hide stats header
    if (elements.statsDisplay) {
        elements.statsDisplay.classList.add('hidden');
    }

    // Update nav
    updateActiveNavLink(null);
}

/**
 * Show a specific view container
 */
function showViewContainer(viewName) {
    // Hide all views
    elements.searchView.classList.add('hidden');
    elements.conversationView.classList.add('hidden');
    elements.settingsView.classList.add('hidden');
    elements.statsView.classList.add('hidden');
    elements.notFoundView.classList.add('hidden');

    // Show requested view
    switch (viewName) {
        case 'search':
            elements.searchView.classList.remove('hidden');
            elements.statsDisplay.classList.remove('hidden');
            break;
        case 'conversation':
            elements.conversationView.classList.remove('hidden');
            break;
        case 'settings':
            elements.settingsView.classList.remove('hidden');
            break;
        case 'stats':
            elements.statsView.classList.remove('hidden');
            break;
        case 'not-found':
            elements.notFoundView.classList.remove('hidden');
            break;
    }
}

/**
 * Display archive statistics (header bar)
 */
function displayStats() {
    try {
        const stats = getStatistics();

        elements.statsDisplay.innerHTML = `
            <div class="stats-container">
                <div class="stat-item">
                    <span class="stat-value">${stats.conversations}</span>
                    <span class="stat-label">Conversations</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${stats.messages}</span>
                    <span class="stat-label">Messages</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${stats.agents.length}</span>
                    <span class="stat-label">Agents</span>
                </div>
            </div>
        `;
        elements.statsDisplay.classList.remove('hidden');
    } catch (error) {
        console.error('[Viewer] Failed to display stats:', error);
        elements.statsDisplay.innerHTML = '';
    }
}

/**
 * Render settings panel
 */
function renderSettingsPanel() {
    if (storageReady) {
        storageReady.then((result) => {
            void renderSettingsPanelAfterStorageReady(result);
        });
        return;
    }

    if (settingsReady) {
        void renderSettingsPanelNow();
    }
}

async function initializeSettingsAfterStorageReady(result, lifecycleEpoch) {
    if (lifecycleEpoch !== viewerLifecycleEpoch) {
        return;
    }

    if (!result?.ok) {
        settingsReady = false;
        return;
    }

    try {
        await initSettings(elements.settingsView, {
            onSessionReset: handleSessionReset,
        });
        if (lifecycleEpoch !== viewerLifecycleEpoch) {
            return;
        }
        settingsReady = true;
    } catch (error) {
        console.error('[Viewer] Failed to initialize settings:', error);
        settingsReady = false;
        if (state.initialized && state.view === 'settings') {
            renderSettingsErrorPanel('Settings could not be initialized for this archive.');
        }
    }
}

async function renderSettingsPanelAfterStorageReady(result) {
    if (!result?.ok) {
        if (state.initialized && state.view === 'settings') {
            renderSettingsErrorPanel('Settings are unavailable because browser storage failed to initialize.');
        }
        return;
    }

    if (!settingsReady || !state.initialized || state.view !== 'settings') {
        return;
    }

    await renderSettingsPanelNow();
}

async function renderSettingsPanelNow() {
    try {
        await renderSettings();
    } catch (error) {
        console.error('[Viewer] Failed to render settings panel:', error);
        renderSettingsErrorPanel('Settings could not be rendered for this archive.');
    }
}

/**
 * Apply theme
 */
function applyTheme(theme) {
    const root = document.documentElement;

    if (theme === 'auto') {
        root.removeAttribute('data-theme');
    } else {
        root.setAttribute('data-theme', theme);
    }
}

function applyStoredTheme() {
    try {
        const theme = localStorage.getItem(StorageKeys.THEME) || 'auto';
        applyTheme(theme);
    } catch (error) {
        // Ignore storage errors
    }
}

/**
 * Render stats panel (full analytics view)
 * Delegates to the stats module for precomputed analytics
 */
function renderStatsPanel() {
    // Use the stats module for rendering
    renderStatsDashboard();
}

/**
 * Render 404 not found panel
 */
function renderNotFoundPanel(path) {
    elements.notFoundView.innerHTML = `
        <div class="panel not-found-panel">
            <div class="not-found-content">
                <div class="not-found-icon">404</div>
                <h2>Page Not Found</h2>
                <p>The requested page <code>${escapeHtml(path || 'unknown')}</code> could not be found.</p>
                <a href="#/" class="btn btn-primary">Go to Search</a>
            </div>
        </div>
    `;
}

function renderSettingsErrorPanel(message) {
    if (!elements.settingsView) {
        return;
    }

    elements.settingsView.innerHTML = `
        <div class="panel settings-panel">
            <header class="panel-header">
                <h2>Settings</h2>
            </header>
            <div class="panel-content">
                <p>${escapeHtml(message)}</p>
            </div>
        </div>
    `;
}

/**
 * Handle search result selection
 */
function handleResultSelect(conversationId, messageId = null) {
    // Navigate using router
    if (router) {
        router.goToConversation(conversationId, messageId);
    }
}

/**
 * Handle back to search
 */
function handleBackToSearch() {
    clearViewer();

    // Navigate using router
    if (router) {
        const searchState = getSearchState();
        router.navigate(buildSearchPath(searchState.query, searchState.filters));
    }
}

function syncLockedViewerState() {
    state.view = 'search';
    state.conversationId = null;
    state.messageId = null;
    state.searchQuery = '';
    state.searchFilters = {
        agent: null,
        since: null,
        until: null,
        timePreset: null,
    };

    if (window?.location?.href) {
        const url = new URL(window.location.href);
        url.hash = '/';
        if (window.history?.replaceState) {
            window.history.replaceState(null, '', url.toString());
        } else {
            window.location.replace(url.toString());
        }
    }
}

function handleSessionReset(action) {
    syncLockedViewerState();
    cleanup();
    window.dispatchEvent(new CustomEvent('cass:lock', {
        detail: { action, source: 'viewer' },
    }));
}

function handleGlobalLock(event) {
    if (event?.detail?.source === 'viewer') {
        return;
    }

    syncLockedViewerState();
    cleanup();
}

/**
 * Navigate to a conversation (public API)
 */
export function navigateToConversation(conversationId, messageId = null) {
    if (router) {
        router.goToConversation(conversationId, messageId);
    }
}

/**
 * Navigate to search (public API)
 */
export function navigateToSearch(query = null, filters = {}) {
    if (router) {
        router.navigate(buildSearchPath(query || '', filters));
    }
}

/**
 * Get share link for current conversation
 */
export function getCurrentShareLink() {
    if (state.view === 'conversation' && state.conversationId) {
        return getConversationLink(state.conversationId, state.messageId);
    }
    return null;
}

/**
 * Copy current conversation link to clipboard
 */
export async function copyCurrentLink() {
    if (state.view === 'conversation' && state.conversationId) {
        const result = await copyConversationLink(state.conversationId, state.messageId);
        if (result.success) {
            showNotification('Link copied to clipboard', 'success');
        } else {
            showNotification('Failed to copy link', 'error');
        }
        return result;
    }
    return { success: false, link: null };
}

/**
 * Share current conversation (using Web Share API)
 */
export async function shareCurrentConversation() {
    if (state.view === 'conversation' && state.conversationId) {
        const conv = getCurrentConversation();
        const title = conv?.title || 'Conversation';
        const success = await shareConversation(state.conversationId, title, state.messageId);
        return success;
    }
    return false;
}

/**
 * Show a notification toast
 */
function showNotification(message, type = 'info') {
    // Check if toast container exists
    let toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.className = 'toast-container';
        document.body.appendChild(toastContainer);
    }

    // Create toast
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;

    toastContainer.appendChild(toast);

    // Auto-remove after delay
    setTimeout(() => {
        toast.classList.add('toast-fade-out');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 3000);
}

/**
 * Format agent name for display
 */
function formatAgentName(agent) {
    if (agent === undefined || agent === null || agent === '') return 'Unknown';
    const value = String(agent);
    // Capitalize first letter
    return value.charAt(0).toUpperCase() + value.slice(1).replace(/_/g, ' ');
}

/**
 * Format date for display
 */
function formatDate(timestamp) {
    if (!timestamp) return 'Unknown';

    const date = new Date(timestamp);
    return date.toLocaleDateString(undefined, {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    });
}

/**
 * Escape HTML special characters
 */
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * Clean up resources
 */
export function cleanup() {
    viewerLifecycleEpoch += 1;

    // Destroy router
    if (router) {
        router.destroy();
        router = null;
    }

    window.removeEventListener('cass:db-ready', handleDatabaseReady);
    window.removeEventListener('cass:lock', handleGlobalLock);
    waitingForDatabaseReady = false;
    storageReady = null;
    settingsReady = false;
    state.initialized = false;

    cleanupSettings();
    closeDatabase();
    clearSearch({ reloadRecent: false });
    cleanupConversationViewer();
    clearStatsCache();
    console.log('[Viewer] Cleaned up');
}

/**
 * Get current application state
 */
export function getState() {
    return { ...state };
}

/**
 * Get router instance
 */
export function getViewerRouter() {
    return router;
}

// Export default
export default {
    init,
    cleanup,
    getState,
    getViewerRouter,
    navigateToConversation,
    navigateToSearch,
    getCurrentShareLink,
    copyCurrentLink,
    shareCurrentConversation,
};