agentgui 1.0.1121 → 1.0.1123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,9 @@
1
1
  import { h, mount, installStyles, components as C } from 'anentrypoint-design';
2
2
  import * as B from './backend.js';
3
- import { createChatPersistence } from './chat-persistence.js';
3
+ import { createChatPersistence, CHAT_KEY } from './chat-persistence.js';
4
+ import { installShortcuts } from './shortcuts.js';
5
+ import { readHash as readHashRouting, buildHash as buildHashRouting, writeHash as writeHashRouting } from './hash-routing.js';
6
+ import { createHistory } from './history.js';
4
7
 
5
8
  installStyles().catch(() => {});
6
9
 
@@ -68,59 +71,12 @@ const ARM_RESET_MS = 4000;
68
71
 
69
72
  // Full routable param set. Every view-defining piece of state round-trips
70
73
  // through the hash so reload and Back/forward restore the exact view.
71
- const HASH_KEYS = ['tab', 'sid', 'dir', 'file', 'q', 'project', 'section', 'filter', 'lsort', 'lfilter', 'lerr', 'ets'];
72
- function readHash() {
73
- const hash = location.hash || '';
74
- const out = {};
75
- for (const k of HASH_KEYS) {
76
- const m = hash.match(new RegExp('(?:^#|&)' + k + '=([^&]*)'));
77
- out[k] = m ? decodeURIComponent(m[1]) : null;
78
- }
79
- return out;
80
- }
81
- function buildHash() {
82
- const parts = [];
83
- const tab = state.tab || 'chat';
84
- // tab is omitted for the default chat tab, EXCEPT when a session id rides
85
- // along - a bare #sid= historically meant history, so chat+sid must name its
86
- // tab explicitly or the deep-link restores the wrong surface.
87
- if (tab !== 'chat') parts.push('tab=' + encodeURIComponent(tab));
88
- else if (state.selectedSid) parts.push('tab=chat');
89
- // Keep sid whenever set (regardless of tab) so Back restores the selection.
90
- if (state.selectedSid) parts.push('sid=' + encodeURIComponent(state.selectedSid));
91
- if (tab === 'files' && state.files) {
92
- if (state.files.path) parts.push('dir=' + encodeURIComponent(state.files.path));
93
- if (state.files.preview && state.files.preview.path) parts.push('file=' + encodeURIComponent(state.files.preview.path));
94
- if (state.files.filter) parts.push('filter=' + encodeURIComponent(state.files.filter));
95
- }
96
- if (tab === 'history') {
97
- const q = (state.searchQ || '').trim();
98
- if (q.length >= 2) parts.push('q=' + encodeURIComponent(q));
99
- if (state.projectFilter) parts.push('project=' + encodeURIComponent(state.projectFilter));
100
- // A session opened from a search hit carries the matched event's
101
- // timestamp so reload/Back reproduces the same scrolled+flashed position
102
- // a live click gives - without this, the anchor only existed in memory
103
- // and a search-hit URL degraded to just the bare session on reload.
104
- if (state._focusEventTs != null) parts.push('ets=' + encodeURIComponent(state._focusEventTs));
105
- }
106
- if (tab === 'settings' && state.settingsSection) parts.push('section=' + encodeURIComponent(state.settingsSection));
107
- if (tab === 'live') {
108
- const lv = state.live || {};
109
- if (lv.sort && lv.sort !== 'status') parts.push('lsort=' + encodeURIComponent(lv.sort));
110
- if (lv.filter) parts.push('lfilter=' + encodeURIComponent(lv.filter));
111
- if (lv.errorsOnly) parts.push('lerr=1');
112
- }
113
- return parts.length ? '#' + parts.join('&') : '';
114
- }
115
- function writeHash({ push = false } = {}) {
116
- const h = buildHash();
117
- const url = location.pathname + location.search + h;
118
- if (location.hash === h || (!location.hash && !h)) return;
119
- // pushState for user navigation steps (tab visits, session selection,
120
- // directory walks, preview opens) so Back retraces them; replaceState for
121
- // passive state sync (search text, filter resets).
122
- (push ? history.pushState : history.replaceState).call(history, null, '', url);
123
- }
74
+ // Hash-based deep-link state - extracted to hash-routing.js. Local names kept
75
+ // identical to every existing call site (readHash/buildHash/writeHash), bound
76
+ // against the module's shared `state` object.
77
+ function readHash() { return readHashRouting(); }
78
+ function buildHash() { return buildHashRouting(state); }
79
+ function writeHash(opts) { return writeHashRouting(state, opts); }
124
80
  const plural = (n, w) => n + ' ' + w + (n === 1 ? '' : 's');
125
81
  function fmtRelTime(ts) {
126
82
  if (!ts) return '';
@@ -3277,249 +3233,16 @@ function eventMatchesFilter(e, f) {
3277
3233
 
3278
3234
  // Scroll to + flash the first error event, widening the render window (and
3279
3235
  // clearing the type filter) so the row is actually rendered.
3280
- function jumpToEvent(idx) {
3281
- if (idx < 0) return;
3282
- state.eventFilter = 'all';
3283
- state._errorNavIdx = idx;
3284
- const fromEnd = state.events.length - idx;
3285
- if (fromEnd > state.eventsLimit) state.eventsLimit = Math.ceil(fromEnd / 300) * 300;
3286
- render();
3287
- const sliceStart = Math.max(0, state.events.length - state.eventsLimit);
3288
- const rowPos = idx - sliceStart;
3289
- requestAnimationFrame(() => {
3290
- const rows = document.querySelectorAll('.ds-event-list .row');
3291
- const row = rows[rowPos];
3292
- if (row) { row.scrollIntoView({ block: 'center' }); row.classList.add('event-flash'); setTimeout(() => row.classList.remove('event-flash'), 2000); }
3293
- });
3294
- }
3295
- function jumpToFirstError() {
3296
- const idx = state.events.findIndex(e => e.isError);
3297
- jumpToEvent(idx);
3298
- }
3299
- // Persistent next/prev navigation between error events - jumpToFirstError
3300
- // alone only reaches the FIRST error once; a session with multiple errors had
3301
- // no way to step through them without manually scanning the event list.
3302
- function jumpToNextError(dir) {
3303
- const errIdxs = state.events.reduce((acc, e, i) => { if (e.isError) acc.push(i); return acc; }, []);
3304
- if (!errIdxs.length) return;
3305
- const cur = state._errorNavIdx;
3306
- let pos = errIdxs.indexOf(cur);
3307
- pos = pos < 0 ? (dir > 0 ? 0 : errIdxs.length - 1) : (pos + dir + errIdxs.length) % errIdxs.length;
3308
- jumpToEvent(errIdxs[pos]);
3309
- }
3310
-
3311
- function historyMain() {
3312
- if (!state.selectedSid) {
3313
- const count = (Array.isArray(state.sessions) ? state.sessions : []).length;
3314
- return [
3315
- reconnectAlert(),
3316
- PageHeader({
3317
- compact: true,
3318
- dense: true,
3319
- title: 'History',
3320
- lede: 'Pick a conversation to inspect its events as they happen.',
3321
- }),
3322
- h('div', { key: 'histempty', class: 'history-empty', role: 'status' },
3323
- h('p', { key: 'gt', class: 'history-empty-title' },
3324
- count ? 'Select a conversation to view its events' : 'No conversations yet'),
3325
- h('p', { key: 'gs', class: 'history-empty-sub' },
3326
- count
3327
- ? count + ' conversation' + (count === 1 ? '' : 's') + ' available · use the search box or press / to filter'
3328
- : 'Start a chat or run a local coding agent - its conversation will appear here live.'),
3329
- count ? h('div', { key: 'gh', class: 'history-empty-hints' },
3330
- ShortcutList({ shortcuts: SHORTCUTS.slice(0, 4) })) : null),
3331
- ].filter(Boolean);
3332
- }
3333
-
3334
- const sess = (Array.isArray(state.sessions) ? state.sessions : []).find(s => s.sid === state.selectedSid);
3335
- // sess.model is the raw ccsniff-sourced field (41st-run fix); ccsniff only
3336
- // reads Claude Code's own JSONL so the agent is always constant. The
3337
- // History detail header previously never surfaced either, reading
3338
- // identity-thin next to the same session's Running-panel/Live-dashboard
3339
- // rows which both show an agent+model badge.
3340
- const agentModelBit = sess?.model ? ((agentById('claude-code')?.name || 'Claude Code') + ' · ' + sess.model) : null;
3341
- const lede = sess
3342
- ? (projectLabel(sess.project) || pathBasename(sess.cwd) || 'unknown location') + (agentModelBit ? ' · ' + agentModelBit : '') + ' · ' + plural(sess.events || 0, 'event') + ' · ' + plural(sess.userTurns || 0, 'turn') + ' · ' + fmtRelTime(sess.last)
3343
- : UNTITLED_CONVERSATION;
3344
-
3345
- const head = PageHeader({
3346
- compact: true,
3347
- dense: true,
3348
- title: truncate(projectLabel(sess?.title) || projectLabel(sess?.project) || pathBasename(sess?.cwd) || state.selectedSid || UNTITLED_CONVERSATION, 40, 80),
3349
- lede,
3350
- });
3351
-
3352
- const hasErrors = state.events.some(e => e.isError);
3353
- const actions = h('div', { key: 'acts', class: 'history-actions' }, [
3354
- Btn({ key: 'resume', primary: true, onClick: () => resumeInChat(sess || { sid: state.selectedSid }), children: 'open in chat' }),
3355
- Btn({ key: 'copy', onClick: copySid, children: copyToast || 'copy conversation id' }),
3356
- Btn({ key: 'exportsess', disabled: !state.eventsLoaded, title: 'Download this session\'s events as JSON',
3357
- onClick: () => downloadBlob(JSON.stringify(state.events, null, 2), (projectLabel(sess?.project) || 'session') + '-' + state.selectedSid + '.json', 'application/json'),
3358
- children: 'export' }),
3359
- hasErrors ? Btn({ key: 'jumperr', onClick: jumpToFirstError, children: 'jump to first error' }) : null,
3360
- // Persistent next/prev stepping between errors - jump-to-first alone only
3361
- // ever reaches the FIRST one; a session with several errors had no way to
3362
- // step through the rest without manually scrolling/scanning.
3363
- hasErrors ? Btn({ key: 'errprev', title: 'previous error', 'aria-label': 'previous error', onClick: () => jumpToNextError(-1), children: 'prev error' }) : null,
3364
- hasErrors ? Btn({ key: 'errnext', title: 'next error', 'aria-label': 'next error', onClick: () => jumpToNextError(1), children: 'next error' }) : null,
3365
- ].filter(Boolean));
3366
-
3367
- if (state.events.length === 0) {
3368
- // Distinguish "still loading" from "genuinely empty" so a 0-event session
3369
- // doesn't spin forever. After 5s of an unresolved first fetch, swap to the
3370
- // indexing copy (ccsniff's first JSONL walk can take a minute).
3371
- const body = state.eventsLoaded
3372
- ? h('div', { key: 'noev', class: 'lede empty-state', role: 'status' },
3373
- h('span', { key: 'noevtxt' }, 'no events in this conversation'),
3374
- Btn({ key: 'reload', onClick: () => loadSession(state.selectedSid), children: 'reload' }))
3375
- // Shape-matched skeleton rows (kit EventList loading state) instead of a
3376
- // lone spinner collapsing the slowest pane in the product.
3377
- : h('div', { key: 'loading' }, EventList({ items: [], loading: true,
3378
- loadingText: state.eventsSlow ? 'Indexing your Claude history — the first load can take a minute…' : 'loading events…' }));
3379
- return [reconnectAlert(), head, actions, Panel({ title: 'events', kind: 'wide', children: body })].filter(Boolean);
3380
- }
3381
-
3382
- if (!state.expandedEvents) state.expandedEvents = new Set();
3383
- // Event-type filter applies BEFORE the render-window slice so "errors" shows
3384
- // every error in the session, not only errors among the most-recent 300.
3385
- const ef = state.eventFilter || 'all';
3386
- const filteredEvents = ef === 'all' ? state.events : state.events.filter(e => eventMatchesFilter(e, ef));
3387
- const filterPills = FilterPills({
3388
- options: [
3389
- { id: 'all', label: 'all' },
3390
- { id: 'text', label: 'text' },
3391
- { id: 'tool', label: 'tools' },
3392
- { id: 'errors', label: 'errors' },
3393
- { id: 'thinking', label: 'thinking' },
3394
- ],
3395
- selected: ef,
3396
- onSelect: (id) => { state.eventFilter = id && id.id ? id.id : id; render(); },
3397
- label: 'Filter events by type',
3398
- });
3399
- // Single pass over state.events for all three counters (replaces three separate .filter() calls).
3400
- const evCounters = state.events.reduce((c, e) => {
3401
- if (e.role === 'user') c.turns++;
3402
- if (e.type === 'tool_use') c.tools++;
3403
- if (e.isError) c.errors++;
3404
- return c;
3405
- }, { turns: 0, tools: 0, errors: 0 });
3406
- const meta = SessionMeta({
3407
- items: [
3408
- sess && sess.cwd ? { label: 'directory', value: sess.cwd, title: sess.cwd,
3409
- actionLabel: 'use as chat cwd',
3410
- onAction: () => { state.chatCwd = sess.cwd; lsSet('agentgui.cwd', sess.cwd); pushRecentCwd(sess.cwd); announce('working directory set to ' + sess.cwd); render(); } } : null,
3411
- (() => { const dur = sessionDuration(); return dur ? { label: 'duration', value: dur } : null; })(),
3412
- { label: 'session id', value: state.selectedSid.slice(0, 8) + '…', title: state.selectedSid, onCopy: () => copyText(state.selectedSid, 'session id copied') },
3413
- // Spelled counter vocabulary in the detail strip (events/turns/tools/
3414
- // errors); the abbreviated 'ev/tools/err' triple stays compact-row-only.
3415
- { label: 'events', value: String(state.events.length) },
3416
- { label: 'turns', value: String(sess?.userTurns ?? evCounters.turns) },
3417
- { label: 'tools', value: String(evCounters.tools) },
3418
- { label: 'errors', value: String(evCounters.errors) },
3419
- sess && sess.cost != null ? { label: 'cost', value: '$' + Number(sess.cost).toFixed(4) } : null,
3420
- ].filter(Boolean),
3421
- });
3422
- if (filteredEvents.length === 0) {
3423
- return [reconnectAlert(), head, actions, Panel({ title: 'events', kind: 'wide', children: [
3424
- h('div', { key: 'evmeta' }, meta),
3425
- h('div', { key: 'evfp' }, filterPills),
3426
- h('div', { key: 'nofilt', class: 'lede empty-state', role: 'status' },
3427
- h('span', { key: 'noftxt' }, 'no events match this filter'),
3428
- Btn({ key: 'clearf', onClick: () => { state.eventFilter = 'all'; render(); }, children: 'clear filter' })),
3429
- ] })].filter(Boolean);
3430
- }
3431
- const total = filteredEvents.length;
3432
- const limit = state.eventsLimit;
3433
- const shown = filteredEvents.slice(-limit);
3434
- const hiddenCount = total - shown.length;
3435
- // Keys of the currently-shown rows, so expand-all toggles only what's rendered.
3436
- const shownKeys = shown.map((e, i) => e.i != null ? 'ev' + e.i : 'ev-' + (e.ts || 0) + '-' + (e.type || '') + '-' + (e._idx ?? (total - shown.length + i)));
3437
- const allExpanded = shownKeys.length > 0 && shownKeys.every(k => state.expandedEvents.has(k));
3438
- const eventControls = h('div', { key: 'evctrl', class: 'history-actions', role: 'group', 'aria-label': 'event controls' },
3439
- Btn({ key: 'expall', onClick: () => {
3440
- if (allExpanded) { shownKeys.forEach(k => state.expandedEvents.delete(k)); }
3441
- else { shownKeys.forEach(k => state.expandedEvents.add(k)); }
3442
- render();
3443
- }, children: allExpanded ? 'collapse shown' : 'expand shown' }),
3444
- hiddenCount > 0
3445
- ? Btn({ key: 'older', onClick: () => { const added = Math.min(300, hiddenCount); state.eventsLimit += 300; announce('loaded ' + added + ' more events'); render(); }, children: 'load ' + Math.min(300, hiddenCount) + ' older (' + hiddenCount + ' hidden)' })
3446
- : null,
3447
- // A per-click 300-event step is fine for casual scanning, but a huge
3448
- // session (thousands hidden) makes that a lot of repeat clicks - a
3449
- // secondary "load all" jumps straight to the full transcript.
3450
- hiddenCount > 1000
3451
- ? Btn({ key: 'loadall', onClick: () => { state.eventsLimit = total; announce('loaded all ' + total + ' events'); render(); }, children: 'load all (' + hiddenCount + ' hidden)' })
3452
- : null,
3453
- );
3454
- return [
3455
- reconnectAlert(),
3456
- head,
3457
- actions,
3458
- Panel({
3459
- title: plural(total, 'event') + (ef !== 'all' ? ' (' + ef + ' filter)' : '') + (hiddenCount > 0 ? ' (showing last ' + shown.length + '; ' + hiddenCount + ' older)' : ''),
3460
- kind: 'wide',
3461
- children: [h('div', { key: 'evmeta' }, meta), h('div', { key: 'evfp' }, filterPills), eventControls, EventList({
3462
- items: shown.map((e, i) => {
3463
- // Stable key: prefer the server-assigned event index, else the
3464
- // event timestamp + position, never a bare array index (which
3465
- // collides between loaded and live-pushed events).
3466
- // Stable key: server event index when present, else ts + the event's
3467
- // ABSOLUTE position in state.events (not the sliced-view index, which
3468
- // shifts when live events append and would collide loaded vs live rows).
3469
- const key = e.i != null ? 'ev' + e.i : 'ev-' + (e.ts || 0) + '-' + (e.type || '') + '-' + (e._idx ?? (total - shown.length + i));
3470
- const role = e.role || '?';
3471
- const type = e.type || '?';
3472
- const tool = e.tool ? ' · tool: ' + e.tool : '';
3473
- const errMark = e.isError ? ' · error' : '';
3474
- const raw = e.text || '';
3475
- const text = raw.replace(/\s+/g, ' ').trim() || (e.type === 'tool_use' && e.toolInput ? toolLabel(e.toolInput) : '');
3476
- const toolNamePrefix = (e.type === 'tool_use' && e.tool) ? e.tool + ': ' : '';
3477
- const typePrefix = e.type === 'tool_result' ? '(result) ' : (e.type === 'tool_use' ? ('(tool call) ' + toolNamePrefix) : '');
3478
- const expanded = state.expandedEvents.has(key);
3479
- // Only build the expanded body (JSON.stringify tool input) when the row is
3480
- // expanded - doing it for all ~300 rows every frame wastes work mid-stream.
3481
- const full = expanded ? (e.toolInput ? (text + '\n\n' + JSON.stringify(e.toolInput, null, 2)) : raw) : '';
3482
- // Rail tone matches the session/agents rail semantics so an event's
3483
- // kind is visible at a glance, consistent across the GUI:
3484
- // flame = error, purple = tool activity, green = normal turn.
3485
- const rail = e.isError ? 'flame' : (e.type === 'tool_use' || e.type === 'tool_result' ? 'purple' : 'green');
3486
- // When the session was opened from a search hit, window the collapsed
3487
- // title AROUND the first query match (a match at char 5000 would
3488
- // otherwise be invisible behind the 0-220 slice).
3489
- let collapsedTitle = typePrefix + text.slice(0, 220);
3490
- const q = state.sessionSearchQ;
3491
- if (q && !expanded) {
3492
- const qi = text.toLowerCase().indexOf(q.toLowerCase());
3493
- if (qi > 60) collapsedTitle = '…' + text.slice(qi - 60, qi - 60 + 220);
3494
- }
3495
- return {
3496
- key,
3497
- code: String(total - shown.length + i + 1).padStart(4, '0'),
3498
- rail,
3499
- expanded, // disclosure state -> kit Row sets aria-expanded
3500
- highlight: q || undefined,
3501
- // Copy is available whether or not the row is expanded - a user
3502
- // scanning collapsed rows for a specific payload shouldn't have
3503
- // to expand every row first just to copy one.
3504
- actions: [{
3505
- label: 'copy', title: 'copy event',
3506
- onClick: () => copyText(full || raw || ('(' + type + ')'), 'event copied'),
3507
- }],
3508
- title: expanded ? (typePrefix + (text || '(' + type + ')')) : (collapsedTitle || typePrefix + '(' + type + ')'),
3509
- detail: expanded && e.toolInput ? JSON.stringify(e.toolInput, null, 2) : undefined,
3510
- // Guard ts: a missing/zero timestamp renders "Invalid Date" otherwise.
3511
- // Every row is click-to-expand, so always show the affordance word
3512
- // (not only when text overflows 220 chars).
3513
- // Relative time matches every other surface; the absolute stamp
3514
- // appears when the row is expanded (forensic precision preserved).
3515
- sub: (e.ts ? (expanded ? new Date(e.ts).toLocaleString() : fmtRelTime(e.ts)) : 'no time') + ' · ' + role + ' · ' + type + tool + errMark + ' · ' + (expanded ? 'collapse' : 'expand'),
3516
- onClick: () => { expanded ? state.expandedEvents.delete(key) : state.expandedEvents.add(key); render(); },
3517
- };
3518
- }),
3519
- })],
3520
- }),
3521
- ].filter(Boolean);
3522
- }
3236
+ // History tab (session list, event viewer, search) - extracted to
3237
+ // history.js. Local names kept identical to every existing call site.
3238
+ const { jumpToEvent, jumpToFirstError, jumpToNextError, historyMain, refreshHistory: _refreshHistory, runSearch: _runSearch, loadSession } = createHistory(state, () => render(), B, {
3239
+ h, PageHeader, ShortcutList, Btn, Panel, EventList, FilterPills, SessionMeta,
3240
+ SHORTCUTS, UNTITLED_CONVERSATION,
3241
+ reconnectAlert, agentById, projectLabel, pathBasename, plural, fmtRelTime, truncate,
3242
+ eventMatchesFilter, sessionDuration, resumeInChat, downloadBlob, toolLabel, copyText,
3243
+ pushRecentCwd, announce, lsSet, errText, writeHash,
3244
+ getCopyToast: () => copyToast, copySid: (...args) => copySid(...args),
3245
+ });
3523
3246
 
3524
3247
  let copyToast = null;
3525
3248
  // Hold the toast long enough to read (2.5s); the copy button label is inside a
@@ -4148,184 +3871,18 @@ function agentsPanel() {
4148
3871
  }
4149
3872
 
4150
3873
  // --- data ---
4151
- async function refreshHistory() {
4152
- // Guard against concurrent calls: a slow first fetch followed by a polling
4153
- // trigger would otherwise stack two in-flight requests; the second would
4154
- // overwrite state mid-render with a stale response.
4155
- if (state._historyFetching) return;
4156
- state._historyFetching = true;
4157
- // Warmup copy: the FIRST sessions fetch can sit behind ccsniff's 30-90s
4158
- // JSONL walk; after 5s swap the loading copy to indexing language.
4159
- const firstLoad = !state._historyLoadedOnce;
4160
- const slowTimer = firstLoad
4161
- ? setTimeout(() => { if (!state._historyLoadedOnce) { state.historySlow = true; render(); } }, 5000)
4162
- : null;
4163
- try {
4164
- state.sessions = await B.listSessions(state.backend);
4165
- state._historyLoadedOnce = true;
4166
- state._historyLoadedAt = Date.now();
4167
- state.historySlow = false;
4168
- // Index by sid so each live SSE event is an O(1) lookup, not an O(sessions)
4169
- // linear scan per event during a burst load.
4170
- state.sessionsBySid = new Map((state.sessions || []).map(s => [s.sid, s]));
4171
- state._sessionGroupsCache = null;
4172
- // Bound the live tally: drop entries with no activity in 24h and cap the
4173
- // Map at ~200 most-recent sids (a long-lived tab otherwise accumulates
4174
- // every sid ever seen, and dead entries could resurrect wrong externals).
4175
- if (state.live.tally) {
4176
- const cutoff = Date.now() - 24 * 3600 * 1000;
4177
- for (const [sid, t] of [...state.live.tally]) {
4178
- if (!t.last || t.last < cutoff) state.live.tally.delete(sid);
4179
- }
4180
- if (state.live.tally.size > 200) {
4181
- state.live.tally = new Map([...state.live.tally.entries()]
4182
- .sort((a, b) => (b[1].last || 0) - (a[1].last || 0))
4183
- .slice(0, 200));
4184
- }
4185
- }
4186
- // If the selected session vanished from the list (deleted/aged out server-side),
4187
- // drop the selection so the main pane doesn't sit on stale events that can no
4188
- // longer be reloaded; fall back to the no-selection empty state.
4189
- if (state.selectedSid && !state.sessionsBySid.has(state.selectedSid)) {
4190
- state.selectedSid = null;
4191
- state.events = [];
4192
- state.eventsLoaded = false;
4193
- writeHash();
4194
- }
4195
- state.historyError = null;
4196
- } catch (e) {
4197
- // Only a genuine fetch/list failure is a history error. A render exception
4198
- // must not masquerade as one (it would poison the sessions panel with a
4199
- // render-stack string and never clear), so render() lives outside this try.
4200
- state.historyError = errText(e);
4201
- console.warn('history fetch failed:', e.message);
4202
- } finally {
4203
- state._historyFetching = false;
4204
- if (slowTimer) clearTimeout(slowTimer);
4205
- render();
4206
- }
4207
- }
3874
+ // refreshHistory/runSearch/loadSession - extracted to history.js, bound to
3875
+ // the local names _refreshHistory/_runSearch above (loadSession keeps its
3876
+ // name directly since nothing else in app.js shadows it).
3877
+ const refreshHistory = _refreshHistory;
4208
3878
  const debouncedRefreshHistory = debounce(refreshHistory, 500);
4209
3879
  // Debounced files filter: toLowerCase() on every entry runs on every keystroke;
4210
3880
  // 150ms coalesces rapid typing into one filter pass (perf-003).
4211
3881
  const debouncedFilesFilter = debounce((v) => { state.files.filter = v; state.files.shown = null; if (state.tab === 'files') writeHash(); render(); }, 150);
4212
3882
 
4213
- async function runSearch() {
4214
- const q = state.searchQ.trim();
4215
- if (!q) { state.searchHits = null; state.searchBusy = false; writeHash(); render(); return; }
4216
- if (q.length < 2) { state.searchHits = null; state.searchBusy = false; writeHash(); render(); return; }
4217
- // The project-filter pills are hidden while searching; clear the filter so it
4218
- // doesn't silently re-apply (and surprise the user) when they later clear the
4219
- // search and the now-visible session list is unexpectedly narrowed.
4220
- state.projectFilter = '';
4221
- // The debounced search keeps the URL's q=/project= in sync via replaceState
4222
- // so a reload (or share) restores the search, without flooding history.
4223
- writeHash();
4224
- state.searchBusy = true;
4225
- render();
4226
- try {
4227
- state.searchHits = await B.searchHistory(state.backend, q, 60);
4228
- // Announce the settled count for AT - the sessions-column count is only
4229
- // rendered visually (the history actions row is the only aria-live region).
4230
- const n = (state.searchHits.results || []).length;
4231
- announce((n || 'no') + ' matches for ' + q);
4232
- } catch (e) {
4233
- state.searchHits = { query: q, results: [], error: errText(e) };
4234
- } finally {
4235
- state.searchBusy = false;
4236
- render();
4237
- }
4238
- }
3883
+ const runSearch = _runSearch;
4239
3884
  const debouncedSearch = debounce(runSearch, 300);
4240
3885
 
4241
- async function loadSession(sid, { focusEventI = null, focusEventTs = null, fromHash = false } = {}) {
4242
- // Guard against a bad sid from a malformed hash (e.g. "?sid=undefined").
4243
- if (!sid || sid === 'undefined' || sid === 'null') { state.selectedSid = null; render(); return; }
4244
- if (sid === state.selectedSid && state.eventsLoaded && !fromHash && focusEventI == null && focusEventTs == null) {
4245
- render();
4246
- requestAnimationFrame(() => { document.querySelector('.app-side .row.active')?.scrollIntoView({ block: 'nearest' }); });
4247
- return;
4248
- }
4249
- state.selectedSid = sid;
4250
- // A plain (non-search-hit) session open must not carry a stale event
4251
- // anchor forward into the URL - only reset it when this call ISN'T itself
4252
- // the one supplying a fresh focusEventTs.
4253
- if (focusEventTs == null) state._focusEventTs = null;
4254
- state.events = [];
4255
- state.events._seen = new Set(); // O(1) dedupe by event index
4256
- state.eventsLoaded = false;
4257
- state.eventsSlow = false;
4258
- state.eventsLimit = 300; // reset the render window per session
4259
- state.eventFilter = 'all'; // don't carry the type filter across sessions
4260
- state.expandedEvents = new Set(); // don't carry expansion to the new session
4261
- // Remember the query this session was opened FROM (search hit) so the event
4262
- // rows can highlight + window around the match; a plain selection clears it.
4263
- state.sessionSearchQ = (focusEventI != null || focusEventTs != null) && state.searchQ.trim().length >= 2
4264
- ? state.searchQ.trim() : null;
4265
- // The live "live · N" crumb counter reads as the selected session's activity,
4266
- // so reset it per selection rather than letting it accrue across all sessions.
4267
- state.live.eventCount = 0;
4268
- writeHash({ push: !fromHash });
4269
- // Warmup copy: a first events fetch can sit behind ccsniff's JSONL walk.
4270
- const slowTimer = setTimeout(() => { if (!state.eventsLoaded && state.selectedSid === sid) { state.eventsSlow = true; render(); } }, 5000);
4271
- // Close the mobile sidebar drawer on selection. The DS only auto-closes when
4272
- // the clicked element is an <a>; agentgui's session rows are onClick divs, so
4273
- // we close it explicitly here.
4274
- // Close the WorkspaceShell mobile sessions drawer on session selection.
4275
- if (state.wsSessions) { state.wsSessions = false; }
4276
- document.querySelector('[data-ws-sessions-open]')?.removeAttribute('data-ws-sessions-open');
4277
- render();
4278
- // Bring the now-active sidebar row into view (deep-link / back-forward may
4279
- // select a row that's scrolled out of the session list).
4280
- requestAnimationFrame(() => {
4281
- document.querySelector('.app-side .row.active')?.scrollIntoView({ block: 'nearest' });
4282
- });
4283
- try {
4284
- state.events = await B.getSessionEvents(state.backend, sid);
4285
- // ccsniff's events route has no ?limit= (checked: router.js returns the
4286
- // whole session) - cap in-memory state at the most-recent 5000 so a
4287
- // monster session can't pin the tab; the render window stays 300+load-older.
4288
- if (state.events.length > 5000) state.events = state.events.slice(-5000);
4289
- // Stamp stable _idx so EventList keys are stable regardless of slice/cap.
4290
- state.events.forEach((e, i) => { if (e._idx == null) e._idx = i; });
4291
- clearTimeout(slowTimer);
4292
- state.eventsSlow = false;
4293
- state.eventsLoaded = true;
4294
- // If we arrived from a search hit, make sure the matched event is within the
4295
- // render window, then scroll to + flash it so the match isn't lost.
4296
- if (focusEventI != null || focusEventTs != null) {
4297
- const idx = state.events.findIndex(e => (focusEventI != null && e.i === focusEventI) || (focusEventTs != null && e.ts === focusEventTs));
4298
- if (idx >= 0) {
4299
- const fromEnd = state.events.length - idx;
4300
- if (fromEnd > state.eventsLimit) state.eventsLimit = Math.ceil(fromEnd / 300) * 300;
4301
- render();
4302
- // The rendered EventList shows the last eventsLimit events in order, so
4303
- // the matched event's row is at (idx - sliceStart) among .ds-event-list rows.
4304
- const sliceStart = Math.max(0, state.events.length - state.eventsLimit);
4305
- const rowPos = idx - sliceStart;
4306
- requestAnimationFrame(() => {
4307
- const rows = document.querySelectorAll('.ds-event-list .row');
4308
- const row = rows[rowPos];
4309
- if (row) { row.scrollIntoView({ block: 'center' }); row.classList.add('event-flash'); setTimeout(() => row.classList.remove('event-flash'), 2000); }
4310
- });
4311
- return;
4312
- }
4313
- }
4314
- render();
4315
- } catch (e) {
4316
- state.events = [{
4317
- ts: Date.now(),
4318
- role: 'error',
4319
- type: 'fetch',
4320
- text: 'Failed to load session: ' + errText(e) + ' - retry via the rail',
4321
- }];
4322
- clearTimeout(slowTimer);
4323
- state.eventsSlow = false;
4324
- state.eventsLoaded = true;
4325
- render();
4326
- }
4327
- }
4328
-
4329
3886
  // Fetch agents + pick the active one. Reusable: boot, backend save, and the
4330
3887
  // reconnect path all re-run it. Returns true on success; failure lands in
4331
3888
  // state.agentsError so the chat tab can surface it with a retry control.
@@ -4646,115 +4203,16 @@ window.__agentgui = { state, render };
4646
4203
 
4647
4204
  // Keyboard shortcuts. 'g' then c/h/s switches tabs; 'n' new chat; '/' focuses
4648
4205
  // search (history) or composer (chat). Ignored while typing in a field.
4649
- let gPending = false;
4650
- function focusComposer() {
4651
- const el = document.querySelector('#agentgui-main textarea, #agentgui-main [contenteditable="true"], #agentgui-main input[type="text"]');
4652
- el?.focus();
4653
- }
4654
- function focusSearch() {
4655
- const el = document.querySelector('#app input[type="search"]');
4656
- el?.focus();
4657
- }
4658
- // Focus the active surface's filter input (Files grid filter / Live dashboard
4659
- // filter) - both are search-type inputs inside the main region.
4660
- function focusFilter() {
4661
- const el = document.querySelector('#agentgui-main input[type="search"]')
4662
- || document.querySelector('#agentgui-main .ds-file-filter-input')
4663
- || document.querySelector('#agentgui-main input[type="text"]');
4664
- el?.focus();
4665
- return !!el;
4666
- }
4667
- window.addEventListener('keydown', (e) => {
4668
- const t = e.target;
4669
- const typing = t && (t.tagName === 'TEXTAREA' || t.tagName === 'INPUT' || t.isContentEditable);
4670
- // One explicit chord BEFORE the modifier early-return: Mod+Shift+L focuses
4671
- // the composer from anywhere, even while typing in another field.
4672
- if ((e.metaKey || e.ctrlKey) && e.shiftKey && (e.key === 'L' || e.key === 'l')) {
4673
- e.preventDefault();
4674
- navTo('chat');
4675
- requestAnimationFrame(() => focusComposer());
4676
- announce('composer focused');
4677
- return;
4678
- }
4679
- if (e.metaKey || e.ctrlKey || e.altKey) return;
4680
- if (typing) {
4681
- // The cwd editor's own text input is the one exception: Escape there must
4682
- // close the editor in a single press (matching every other Escape-
4683
- // closeable surface in the app), not blur-then-require-a-second-press.
4684
- if (e.key === 'Escape' && t.classList && t.classList.contains('agentchat-cwd-input')) {
4685
- t.blur();
4686
- // Fall through to the ladder below instead of returning early.
4687
- } else {
4688
- if (e.key === 'Escape') t.blur();
4689
- return;
4690
- }
4691
- }
4692
- if (e.key === 'Escape') {
4693
- // Priority ladder for transient state (modals/drawers are kit-handled):
4694
- // shortcuts overlay > armed confirms > stop a streaming generation.
4695
- if (state.showShortcuts) { state.showShortcuts = false; render(); announce('shortcuts closed'); return; }
4696
- // File-mutation dialog: close on Escape wherever focus sits (the kit's
4697
- // backdrop listener covers in-dialog focus; this covers everything else).
4698
- if (state.files.dialog) { if (!state.files.dialog.busy) closeFileDialog(); return; }
4699
- if (state.chat.confirmingEdit) { state.chat.confirmingEdit = null; render(); announce('edit cancelled'); return; }
4700
- // cwd editor: the browse popover is a nested layer within it - Escape
4701
- // closes the popover first (one level of the nesting) before falling
4702
- // through to closing the whole editor on a second press, matching the
4703
- // dialog-then-page Escape convention used elsewhere in the app.
4704
- if (state.cwdEditing) {
4705
- if (state.cwdBrowse) { state.cwdBrowse = null; render(); announce('folder browser closed'); return; }
4706
- state.cwdEditing = false; state.cwdDraft = undefined; state.cwdError = null; state.cwdChecking = false;
4707
- render(); announce('cwd edit cancelled');
4708
- requestAnimationFrame(() => { const btn = document.querySelector('.agentchat-cwd-btn'); if (btn) btn.focus(); });
4709
- return;
4710
- }
4711
- if (state.confirmingClearData) { state.confirmingClearData = false; render(); announce('clear cancelled'); return; }
4712
- if (state.confirmingNewChat) { clearTimeout(_newChatArmTimer); state.confirmingNewChat = false; render(); announce('new chat cancelled'); return; }
4713
- if (state.live.confirmingStopAll || state.live.confirmingStopSelected) {
4714
- state.live.confirmingStopAll = false; state.live.confirmingStopSelected = false;
4715
- clearTimeout(_stopAllArmTimer); clearTimeout(_stopSelArmTimer);
4716
- render(); announce('stop cancelled'); return;
4717
- }
4718
- // A live file multi-select is transient state too: Escape drops it before
4719
- // falling through to stop-generation.
4720
- if (state.tab === 'files' && filesMarked().size) { clearFileSelection(); return; }
4721
- if (state.chat.busy && state.tab === 'chat') { cancelChat(); announce('generation stopped'); return; }
4722
- return;
4723
- }
4724
- if (gPending) {
4725
- gPending = false;
4726
- if (e.key === 'c') { navTo('chat'); return; }
4727
- if (e.key === 'h') { navTo('history'); return; }
4728
- if (e.key === 'f') { navTo('files'); return; }
4729
- if (e.key === 'l') { navTo('live'); return; }
4730
- if (e.key === 's') { navTo('settings'); return; }
4731
- return;
4732
- }
4733
- if (e.key === 'g') { gPending = true; setTimeout(() => { gPending = false; }, 1000); return; }
4734
- if (e.key === 'n' && state.tab === 'chat') { e.preventDefault(); newChat(); return; }
4735
- if (e.key === '/') {
4736
- // / targets the active surface's find affordance: search on history,
4737
- // composer on chat, the filter inputs on files/live. Settings has no
4738
- // field - the only documented no-op.
4739
- if (state.tab === 'history') { e.preventDefault(); focusSearch(); announce('search focused'); }
4740
- else if (state.tab === 'chat') { e.preventDefault(); focusComposer(); announce('composer focused'); }
4741
- else if (state.tab === 'files' || state.tab === 'live') { e.preventDefault(); if (focusFilter()) announce('filter focused'); }
4742
- return;
4743
- }
4744
- if (e.key === '?') { state.showShortcuts = !state.showShortcuts; render(); return; }
4745
- // Left/Right: step through file previews (documented in SHORTCUTS).
4746
- if ((e.key === 'ArrowLeft' || e.key === 'ArrowRight') && state.tab === 'files' && state.files.preview) {
4747
- const { prev, next } = previewNeighbours();
4748
- const target = e.key === 'ArrowLeft' ? prev : next;
4749
- if (target) { e.preventDefault(); openPreview(target); }
4750
- return;
4751
- }
4752
- });
4753
-
4754
- // A file dropped anywhere outside a DropZone must never navigate the browser
4755
- // away (destroying the live session view). DropZones handle their own events.
4756
- window.addEventListener('dragover', (e) => {
4757
- if (!(e.target instanceof Element) || !e.target.closest('.ds-dropzone')) e.preventDefault();
4206
+ // Keyboard shortcuts - extracted to shortcuts.js (vertical slice per
4207
+ // AGENTS.md SOLID/Clean-Architecture preferences). The factory takes every
4208
+ // app.js dependency explicitly (state, render, and the helpers object below)
4209
+ // rather than closing over app.js's module scope.
4210
+ const { focusComposer } = installShortcuts(state, render, {
4211
+ navTo, announce, closeFileDialog, filesMarked, clearFileSelection,
4212
+ cancelChat, newChat, previewNeighbours, openPreview,
4213
+ clearNewChatArmTimer: () => clearTimeout(_newChatArmTimer),
4214
+ clearStopAllArmTimer: () => clearTimeout(_stopAllArmTimer),
4215
+ clearStopSelArmTimer: () => clearTimeout(_stopSelArmTimer),
4758
4216
  });
4759
4217
  window.addEventListener('drop', (e) => {
4760
4218
  if (!(e.target instanceof Element) || !e.target.closest('.ds-dropzone')) e.preventDefault();