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
/**
 * cass Archive Hash-based Router
 *
 * Provides hash-based routing for static hosting compatibility.
 * Supports deep linking to conversations, messages, search queries, and panels.
 *
 * URL Schema:
 *   #/                      -> 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
 */

// Route definitions
const ROUTES = {
    HOME: '/',
    SEARCH: '/search',
    CONVERSATION: '/c/:id',
    CONVERSATION_MESSAGE: '/c/:id/m/:msgId',
    SETTINGS: '/settings',
    STATS: '/stats',
};

// Route handlers registry
const routeHandlers = new Map();

// Current route state
let currentRoute = {
    path: '/',
    params: {},
    query: {},
    raw: '',
};

// Router instance
let routerInstance = null;

export function parseRouteIdSegment(segment) {
    if (typeof segment !== 'string' || !/^[1-9]\d*$/.test(segment)) {
        return null;
    }

    const value = Number.parseInt(segment, 10);
    return Number.isSafeInteger(value) ? value : null;
}

export function parseConversationRouteParts(parts) {
    if (!Array.isArray(parts) || parts[0] !== 'c') {
        return null;
    }

    if (parts.length !== 2 && !(parts.length === 4 && parts[2] === 'm' && parts[3])) {
        return null;
    }

    const conversationId = parseRouteIdSegment(parts[1]);
    if (conversationId === null) {
        return null;
    }

    const messageId = parts.length === 4 ? parseRouteIdSegment(parts[3]) : null;
    if (parts.length === 4 && messageId === null) {
        return null;
    }

    return {
        conversationId,
        messageId,
    };
}

export function splitRouteQuery(route) {
    const queryStart = route.indexOf('?');
    if (queryStart === -1) {
        return [route, ''];
    }

    return [
        route.slice(0, queryStart),
        route.slice(queryStart + 1),
    ];
}

/**
 * Hash-based Router class
 */
class Router {
    /**
     * Create a router instance
     * @param {Object} options - Router options
     * @param {Function} options.onNavigate - Callback when route changes
     * @param {boolean} options.autoInit - Auto-initialize on creation (default: true)
     */
    constructor(options = {}) {
        this.onNavigate = options.onNavigate || (() => {});
        this.autoInit = options.autoInit !== false;
        this._boundHashHandler = this._handleHashChange.bind(this);

        if (this.autoInit) {
            this.init();
        }
    }

    /**
     * Initialize the router
     */
    init() {
        // Listen for hash changes
        window.addEventListener('hashchange', this._boundHashHandler);

        // Handle initial route
        this._handleHashChange();

        console.debug('[Router] Initialized');
    }

    /**
     * Clean up router
     */
    destroy() {
        window.removeEventListener('hashchange', this._boundHashHandler);
        console.debug('[Router] Destroyed');
    }

    /**
     * Navigate to a path
     * @param {string} path - Path to navigate to
     * @param {Object} options - Navigation options
     * @param {boolean} options.replace - Replace current history entry
     */
    navigate(path, options = {}) {
        const normalizedPath = path.startsWith('/') ? path : `/${path}`;
        const newHash = `#${normalizedPath}`;

        if (options.replace) {
            window.location.replace(newHash);
        } else {
            window.location.hash = normalizedPath;
        }
    }

    /**
     * Navigate to home/search
     * @param {string} query - Optional search query
     */
    goHome(query = null) {
        if (query) {
            this.navigate(`/search?q=${encodeURIComponent(query)}`);
        } else {
            this.navigate('/');
        }
    }

    /**
     * Navigate to a conversation
     * @param {number|string} conversationId - Conversation ID
     * @param {number|string|null} messageId - Optional message ID to scroll to
     */
    goToConversation(conversationId, messageId = null) {
        if (messageId) {
            this.navigate(`/c/${conversationId}/m/${messageId}`);
        } else {
            this.navigate(`/c/${conversationId}`);
        }
    }

    /**
     * Navigate to settings
     */
    goToSettings() {
        this.navigate('/settings');
    }

    /**
     * Navigate to stats
     */
    goToStats() {
        this.navigate('/stats');
    }

    /**
     * Go back in history
     */
    back() {
        window.history.back();
    }

    /**
     * Get current route state
     * @returns {Object} Current route
     */
    getCurrentRoute() {
        return { ...currentRoute };
    }

    /**
     * Handle hash change events
     * @private
     */
    _handleHashChange() {
        const hash = (window.location.hash || '').slice(1) || '/';
        const parsed = this._parseHash(hash);

        currentRoute = parsed;

        // Call navigation handler
        this.onNavigate(parsed);

        // Dispatch custom event for other listeners
        window.dispatchEvent(new CustomEvent('cass:route-change', {
            detail: parsed,
        }));
    }

    /**
     * Parse a hash string into route components
     * @param {string} hash - Hash string (without #)
     * @returns {Object} Parsed route
     * @private
     */
    _parseHash(hash) {
        // Split path and query
        const [pathPart, queryPart] = splitRouteQuery(hash);
        const path = pathPart || '/';

        // Parse query parameters
        const query = {};
        if (queryPart) {
            const searchParams = new URLSearchParams(queryPart);
            for (const [key, value] of searchParams) {
                query[key] = value;
            }
        }

        // Parse path and extract parameters
        const { view, params } = this._matchRoute(path);

        return {
            path,
            view,
            params,
            query,
            raw: hash,
        };
    }

    /**
     * Match path to route and extract parameters
     * @param {string} path - Path to match
     * @returns {Object} Matched view and params
     * @private
     */
    _matchRoute(path) {
        const parts = path.split('/').filter(Boolean);

        // Empty path or just '/' -> home/search
        if (parts.length === 0) {
            return { view: 'search', params: {} };
        }

        // /search -> search view
        if (parts[0] === 'search' && parts.length === 1) {
            return { view: 'search', params: {} };
        }

        // /c/:id -> conversation view
        if (parts[0] === 'c') {
            const conversationParams = parseConversationRouteParts(parts);
            if (conversationParams) {
                return {
                    view: 'conversation',
                    params: conversationParams,
                };
            }

            return { view: 'not-found', params: { path } };
        }

        // /settings -> settings panel
        if (parts[0] === 'settings' && parts.length === 1) {
            return { view: 'settings', params: {} };
        }

        // /stats -> stats panel
        if (parts[0] === 'stats' && parts.length === 1) {
            return { view: 'stats', params: {} };
        }

        // Unknown route -> 404 view
        return { view: 'not-found', params: { path } };
    }
}

/**
 * Create and initialize the global router
 * @param {Object} options - Router options
 * @returns {Router} Router instance
 */
export function createRouter(options = {}) {
    if (routerInstance) {
        console.warn('[Router] Router already exists, destroying old instance');
        routerInstance.destroy();
    }

    routerInstance = new Router(options);
    return routerInstance;
}

/**
 * Get the current router instance
 * @returns {Router|null} Router instance or null
 */
export function getRouter() {
    return routerInstance;
}

/**
 * Navigate to a path (convenience function)
 * @param {string} path - Path to navigate to
 * @param {Object} options - Navigation options
 */
export function navigate(path, options = {}) {
    if (!routerInstance) {
        console.error('[Router] Router not initialized');
        return;
    }
    routerInstance.navigate(path, options);
}

/**
 * Get current route (convenience function)
 * @returns {Object} Current route
 */
export function getCurrentRoute() {
    return { ...currentRoute };
}

/**
 * Build a path for a conversation
 * @param {number|string} conversationId - Conversation ID
 * @param {number|string|null} messageId - Optional message ID
 * @returns {string} Path string
 */
export function buildConversationPath(conversationId, messageId = null) {
    if (messageId) {
        return `/c/${conversationId}/m/${messageId}`;
    }
    return `/c/${conversationId}`;
}

/**
 * Build a path for search
 * @param {string} query - Search query
 * @param {Object} filters - Optional filters
 * @returns {string} Path string
 */
export function buildSearchPath(query = '', filters = {}) {
    const params = new URLSearchParams();
    const hasExplicitFilterValue = (value) => value !== undefined && value !== null && value !== '';

    if (query) {
        params.set('q', query);
    }

    if (hasExplicitFilterValue(filters.agent)) {
        params.set('agent', filters.agent);
    }

    if (hasExplicitFilterValue(filters.timePreset) && filters.timePreset !== 'custom') {
        params.set('time', filters.timePreset);
    } else {
        if (hasExplicitFilterValue(filters.since)) {
            params.set('since', filters.since);
        }

        if (hasExplicitFilterValue(filters.until)) {
            params.set('until', filters.until);
        }
    }

    const queryString = params.toString();
    return queryString ? `/search?${queryString}` : '/search';
}

/**
 * Parse search parameters from route
 * @param {Object} route - Route object
 * @returns {Object} Search parameters
 */
export function parseSearchParams(route) {
    return {
        query: route.query.q || '',
        agent: route.query.agent || null,
        timePreset: route.query.time || null,
        since: route.query.since || null,
        until: route.query.until || null,
    };
}

// Export route constants
export { ROUTES };

// Export Router class for advanced usage
export { Router };

// Export default
export default {
    createRouter,
    getRouter,
    navigate,
    getCurrentRoute,
    parseConversationRouteParts,
    parseRouteIdSegment,
    buildConversationPath,
    buildSearchPath,
    parseSearchParams,
    ROUTES,
    Router,
};