@ucsandman/legcli 0.9.0 → 0.11.0

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +146 -0
  2. package/README.md +110 -11
  3. package/bin/leg.mjs +78 -15
  4. package/docs/ERRORS.md +187 -0
  5. package/docs/README.md +3 -1
  6. package/docs/ROADMAP-v2.md +24 -11
  7. package/docs/VOCABULARY.md +1 -0
  8. package/docs/adapters.md +93 -11
  9. package/docs/board-guide.md +20 -1
  10. package/docs/cli-contracts.md +50 -17
  11. package/docs/configuration.md +56 -5
  12. package/docs/history.md +172 -0
  13. package/docs/runtime-tap.md +156 -0
  14. package/fixtures/limits/grok/grok-balance-exhausted.json +11 -0
  15. package/fixtures/live/grok/cmd.txt +1 -1
  16. package/fixtures/live/grok/parsed.json +6 -3
  17. package/fixtures/live/grok/run.json +22 -10
  18. package/fixtures/verified.json +8 -1
  19. package/package.json +1 -1
  20. package/scripts/build-docs-site.mjs +11 -4
  21. package/scripts/probe.mjs +2 -1
  22. package/src/accounts.mjs +5 -2
  23. package/src/adapters/cli.mjs +130 -0
  24. package/src/adapters/custom.mjs +271 -0
  25. package/src/adapters/grok.mjs +51 -10
  26. package/src/adapters/index.mjs +34 -7
  27. package/src/attach.mjs +85 -13
  28. package/src/audit.mjs +118 -0
  29. package/src/board/audit.js +123 -0
  30. package/src/board/board.css +38 -1
  31. package/src/board/board.js +14 -2
  32. package/src/board/history.js +377 -0
  33. package/src/board/index.html +55 -0
  34. package/src/board/sessions.js +49 -7
  35. package/src/history/cli.mjs +159 -0
  36. package/src/history/common.mjs +119 -0
  37. package/src/history/index.mjs +429 -0
  38. package/src/history/providers/agy.mjs +91 -0
  39. package/src/history/providers/claude.mjs +161 -0
  40. package/src/history/providers/codex.mjs +133 -0
  41. package/src/history/providers/copilot.mjs +94 -0
  42. package/src/history/providers/grok.mjs +138 -0
  43. package/src/history/worktrees.mjs +116 -0
  44. package/src/redact.mjs +23 -5
  45. package/src/server.mjs +272 -28
  46. package/src/sessions.mjs +9 -0
  47. package/src/share.mjs +66 -6
  48. package/src/taps/claude.mjs +11 -4
  49. package/src/taps/grok.mjs +4 -0
  50. package/src/taps/mod.mjs +340 -0
  51. package/src/usage.mjs +21 -5
  52. package/src/worktree.mjs +1 -1
@@ -0,0 +1,377 @@
1
+ // History cell: every conversation on this machine, Leg's own and the ones
2
+ // Claude Code, Codex, Grok, Antigravity and Copilot keep in their own stores.
3
+ // Data: /api/history (a page at a time) and /api/history/<id> (one
4
+ // conversation's last messages, read only when a row is opened), plus
5
+ // /api/worktrees. Nothing here is pushed over SSE: the live terminals lane
6
+ // stays the only live region; this cell is a count that opens, like finished
7
+ // terminals and what landed (DESIGN.md rule 3).
8
+ //
9
+ // `el`, `api`, `getToken`, `ago` and `whenAgo` are copied from sessions.js,
10
+ // which cannot export from its IIFE. The time grammar is sessions.js's: a
11
+ // change to ago() there is a change here in the same commit.
12
+ (function () {
13
+ 'use strict'
14
+ const PAGE = 50
15
+ const IDS = ['claude', 'codex', 'agy', 'grok', 'copilot']
16
+
17
+ function getToken() { return localStorage.getItem('legToken') || localStorage.getItem('batonToken') || '' }
18
+ async function api(path, opts = {}) {
19
+ const headers = { 'Content-Type': 'application/json' }
20
+ const token = getToken()
21
+ if (token) headers.Authorization = `Bearer ${token}`
22
+ const r = await fetch(path, { method: opts.method || 'GET', headers, body: opts.body ? JSON.stringify(opts.body) : undefined })
23
+ const data = await r.json().catch(() => ({}))
24
+ if (!r.ok) throw new Error(data.error || `${r.status} ${r.statusText}`)
25
+ return data
26
+ }
27
+ function el(tag, attrs, children) {
28
+ const n = document.createElement(tag)
29
+ for (const [k, v] of Object.entries(attrs || {})) { if (v === null || v === undefined) continue; if (k === 'class') n.className = v; else n.setAttribute(k, v) }
30
+ for (const c of children || []) { if (c === null || c === undefined) continue; n.appendChild(typeof c === 'string' ? document.createTextNode(c) : c) }
31
+ return n
32
+ }
33
+ function ago(ms) {
34
+ const s = Math.max(0, Math.floor(ms / 1000))
35
+ if (s < 60) return `${s}s`
36
+ const m = Math.floor(s / 60)
37
+ if (m < 60) return `${m}m`
38
+ const h = Math.floor(m / 60)
39
+ if (h < 48) return `${h}h${m % 60 ? ` ${m % 60}m` : ''}`
40
+ const d = Math.floor(h / 24)
41
+ return `${d}d${h % 24 ? ` ${h % 24}h` : ''}`
42
+ }
43
+ function whenAgo(ts) {
44
+ const t = Date.parse(ts)
45
+ return Number.isFinite(t) ? `${ago(Date.now() - t)} ago` : ''
46
+ }
47
+ function sysMessage(text, tone) { const fn = window.legMessage || window.batonMessage; if (typeof fn === 'function') fn(text, tone) }
48
+
49
+ function fallbackCopy(text) {
50
+ const ta = document.createElement('textarea')
51
+ ta.value = text
52
+ ta.style.position = 'fixed'
53
+ ta.style.opacity = '0'
54
+ document.body.appendChild(ta)
55
+ ta.select()
56
+ let ok = false
57
+ try { ok = document.execCommand('copy') } catch { ok = false }
58
+ document.body.removeChild(ta)
59
+ return ok
60
+ }
61
+
62
+ function takeFocus(box) {
63
+ const node = document.activeElement
64
+ if (!box || !node || !box.contains(node)) return null
65
+ const key = typeof node.getAttribute === 'function' ? node.getAttribute('data-focus-key') : null
66
+ if (!key) return null
67
+ const at = { key }
68
+ if (typeof node.selectionStart === 'number') { at.start = node.selectionStart; at.end = node.selectionEnd }
69
+ return at
70
+ }
71
+
72
+ function putFocus(box, at) {
73
+ if (!box || !at) return
74
+ const key = at.key.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
75
+ let target = null
76
+ try { target = box.querySelector(`[data-focus-key="${key}"]`) } catch { return }
77
+ if (target && target.disabled) target = target.parentElement?.querySelector('[data-focus-key]:not([disabled])') || null
78
+ if (!target) return
79
+ target.focus({ preventScroll: true })
80
+ if (typeof at.start === 'number' && typeof target.setSelectionRange === 'function') {
81
+ try { target.setSelectionRange(at.start, at.end) } catch {}
82
+ }
83
+ }
84
+
85
+ function takeScroll(box) {
86
+ const at = new Map()
87
+ if (!box) return at
88
+ for (const node of box.querySelectorAll('[data-scroll-key]')) if (node.scrollTop) at.set(node.getAttribute('data-scroll-key'), node.scrollTop)
89
+ return at
90
+ }
91
+
92
+ function putScroll(box, at) {
93
+ if (!box || !at || !at.size) return
94
+ for (const node of box.querySelectorAll('[data-scroll-key]')) {
95
+ const was = at.get(node.getAttribute('data-scroll-key'))
96
+ if (was) node.scrollTop = was
97
+ }
98
+ }
99
+
100
+ const state = {
101
+ open: false, loaded: false, loading: false, error: '', guest: false,
102
+ total: 0, counts: {}, records: [], offset: 0, providers: [], refreshedAt: null,
103
+ filters: { provider: '', search: '', repo: '', managed: false },
104
+ detailId: null, detail: null, detailError: '',
105
+ worktrees: null, worktreesError: '',
106
+ }
107
+ let searchTimer = null
108
+ let loadSeq = 0 // a slower, older request never overwrites a newer filter's answer
109
+
110
+ function query({ more = false } = {}) {
111
+ const f = state.filters
112
+ const q = new URLSearchParams()
113
+ q.set('limit', String(PAGE))
114
+ if (more && state.records.length) {
115
+ const last = state.records[state.records.length - 1]
116
+ q.set('before', last.id)
117
+ } else {
118
+ q.set('offset', '0')
119
+ }
120
+ if (f.provider) q.set('provider', f.provider)
121
+ if (f.search) q.set('search', f.search)
122
+ if (f.repo) q.set('repo', f.repo)
123
+ if (f.managed) q.set('managed', '1')
124
+ return `/api/history?${q}`
125
+ }
126
+
127
+ async function load({ more = false } = {}) {
128
+ if (state.loading && more) return
129
+ state.loading = true
130
+ state.error = ''
131
+ const seq = ++loadSeq
132
+ try {
133
+ const r = await api(query({ more }))
134
+ if (seq !== loadSeq) return
135
+ // a page fetched after new conversations arrived can overlap the last one
136
+ const seen = new Set(more ? state.records.map((x) => x.id) : [])
137
+ state.records = more ? [...state.records, ...r.records.filter((x) => !seen.has(x.id))] : r.records
138
+ state.total = r.total
139
+ state.counts = r.counts || {}
140
+ state.providers = r.providers || []
141
+ state.refreshedAt = r.refreshed_at
142
+ state.loaded = true
143
+ if (r.refresh_error) state.error = `the index did not refresh: ${r.refresh_error}`
144
+ } catch (err) {
145
+ if (seq !== loadSeq) return
146
+ // a guest never gets this cell: the whole group is the owner's
147
+ if (/belongs to the owner/.test(err.message)) state.guest = true
148
+ state.error = err.message
149
+ }
150
+ state.loading = false
151
+ render()
152
+ }
153
+
154
+ async function loadWorktrees() {
155
+ try { state.worktrees = await api('/api/worktrees?dirty=0'); state.worktreesError = '' } catch (err) { state.worktreesError = err.message }
156
+ render()
157
+ }
158
+
159
+ async function openDetail(id) {
160
+ if (state.detailId === id) { state.detailId = null; state.detail = null; render(); return }
161
+ state.detailId = id
162
+ state.detail = null
163
+ state.detailError = ''
164
+ render()
165
+ try {
166
+ const d = await api(`/api/history/${encodeURIComponent(id)}?messages=8`)
167
+ if (state.detailId !== id) return
168
+ state.detail = d
169
+ } catch (err) { if (state.detailId === id) state.detailError = err.message }
170
+ render()
171
+ document.querySelector(`[data-focus-key="history-close:${CSS.escape(id)}"]`)?.focus({ preventScroll: true })
172
+ }
173
+
174
+ function copy(text, what) {
175
+ const done = () => sysMessage(`${what} copied`, 'ok')
176
+ const fail = () => {
177
+ if (fallbackCopy(text)) done()
178
+ else sysMessage(`could not copy the ${what}`, 'danger')
179
+ }
180
+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, fail)
181
+ else fail()
182
+ }
183
+
184
+ const short = (r) => `${r.provider}:${String(r.native_id || r.leg_session_id || '').slice(0, 8)}`
185
+ const agentChip = (name) => el('span', { class: `chip${IDS.includes(name) ? ` chip-id-${name}` : ''}` }, [name])
186
+
187
+ function row(r) {
188
+ const where = `${r.repo_name || r.cwd || 'no folder'}${r.branch ? ` on ${r.branch}` : ''}${r.worktree ? ' (worktree)' : ''}`
189
+ const open = state.detailId === r.id
190
+ const title = el('button', { type: 'button', class: 'history-title', 'aria-expanded': open ? 'true' : 'false', 'data-focus-key': `history:${r.id}` }, [r.title || `(untitled, ${short(r)})`])
191
+ title.addEventListener('click', () => openDetail(r.id))
192
+ return el('div', { class: 'history-row', 'data-history-id': r.id }, [
193
+ el('div', {}, [
194
+ title,
195
+ el('div', { class: 'history-register' }, [
196
+ agentChip(r.provider),
197
+ r.managed ? el('span', { class: 'chip' }, [r.live ? 'leg, live' : 'leg']) : el('span', { class: 'chip is-stale' }, [r.live ? 'external, live' : 'external']),
198
+ el('span', {}, [where]),
199
+ r.turns ? el('span', {}, [`${r.turns} prompt${r.turns === 1 ? '' : 's'}`]) : null,
200
+ el('span', { class: 'mono' }, [short(r)]),
201
+ ]),
202
+ ]),
203
+ el('span', { class: 'history-when' }, [whenAgo(r.updated_at || r.started_at)]),
204
+ ])
205
+ }
206
+
207
+ function messageRow(m, key) {
208
+ const isUser = m.role === 'user'
209
+ return el('div', { class: `turn drawer-msg ${isUser ? 'is-human' : 'is-agent'}` }, [
210
+ el('div', { class: 'drawer-msg-head' }, [
211
+ el('span', { class: `turn-role drawer-msg-role ${isUser ? '' : 'chip-state-ok'}` }, [isUser ? 'human' : 'agent']),
212
+ m.ts ? el('span', { class: 'turn-when drawer-msg-when' }, [whenAgo(m.ts)]) : null,
213
+ ]),
214
+ el('p', { 'data-scroll-key': `history-msg:${key}` }, [m.text]),
215
+ ])
216
+ }
217
+
218
+ function detail(r) {
219
+ const d = state.detail
220
+ const box = el('div', { class: 'history-detail', role: 'region', 'aria-label': `Conversation ${short(r)}` })
221
+ const close = el('button', { type: 'button', class: 'btn btn-secondary btn-sm', 'data-focus-key': `history-close:${r.id}` }, ['Close'])
222
+ close.addEventListener('click', () => openDetail(r.id))
223
+ box.appendChild(el('div', { class: 'detail-heading' }, [el('span', {}, [r.title || 'Untitled conversation']), close]))
224
+ if (state.detailError) { box.appendChild(el('p', { class: 'history-empty' }, [`could not read it: ${state.detailError}`])); return box }
225
+ if (!d) { box.appendChild(el('p', { class: 'history-empty' }, ['reading the conversation'])); return box }
226
+ const kv = el('div', { class: 'kv' })
227
+ const pair = (k, v) => { if (v === null || v === undefined || v === '') return; kv.appendChild(el('span', { class: 'kv-key' }, [k])); kv.appendChild(el('span', { class: 'kv-val' }, [typeof v === 'string' ? v : String(v)])) }
228
+ pair('agent', `${d.provider}${d.account && d.account !== 'default' ? ` (${d.account})` : ''}`)
229
+ pair('started by', d.managed ? `Leg, session ${d.leg_session_id} (${d.leg_status})` : 'the agent itself, outside Leg')
230
+ pair('folder', `${d.cwd || 'unknown'}${d.cwd_exists === false ? ' (gone)' : ''}`)
231
+ pair('repository', d.repo ? `${d.repo}${d.branch ? ` on ${d.branch}` : ''}` : null)
232
+ pair('worktree', d.worktree ? d.worktree.path : null)
233
+ pair('started', d.started_at ? `${new Date(d.started_at).toLocaleString()} (${whenAgo(d.started_at)})` : null)
234
+ pair('last activity', d.updated_at ? `${new Date(d.updated_at).toLocaleString()} (${whenAgo(d.updated_at)})` : null)
235
+ pair('prompts', d.turns)
236
+ pair('transcript', d.transcript === 'supported' ? d.transcript_path : `${d.transcript_path || 'kept by the agent'} (Leg cannot read this agent's transcript)`)
237
+ pair('id', d.id)
238
+ box.appendChild(kv)
239
+ const cmd = el('div', { class: 'history-command' })
240
+ if (d.resume && d.resume.supported) {
241
+ const text = `leg history continue ${d.id}`
242
+ const b = el('button', { type: 'button', class: 'btn btn-secondary btn-sm' }, ['Copy the continue command'])
243
+ b.addEventListener('click', () => copy(text, 'command'))
244
+ cmd.append(el('span', {}, ['Continue it in a terminal:']), el('code', { class: 'mono' }, [text]), b)
245
+ } else cmd.appendChild(el('span', { class: 'history-empty' }, [`Cannot continue it: ${d.resume ? d.resume.reason : 'unknown'}`]))
246
+ if (d.cwd) { const b = el('button', { type: 'button', class: 'btn btn-secondary btn-sm' }, ['Copy folder path']); b.addEventListener('click', () => copy(d.cwd, 'path')); cmd.appendChild(b) }
247
+ box.appendChild(cmd)
248
+ if (d.messages === null) box.appendChild(el('p', { class: 'history-empty' }, ['Leg has no reader for this agent\'s transcript; the agent itself can show it.']))
249
+ else if (!d.messages.length) box.appendChild(el('p', { class: 'history-empty' }, ['No messages could be read from the transcript.']))
250
+ else {
251
+ box.appendChild(el('p', { class: 'cap-line' }, [`the last ${d.messages.length} message${d.messages.length === 1 ? '' : 's'}, newest first`]))
252
+ const msgs = [...d.messages].reverse()
253
+ msgs.forEach((m, i) => box.appendChild(messageRow(m, `${r.id}:${i}`)))
254
+ }
255
+ return box
256
+ }
257
+
258
+ function worktreeRow(w) {
259
+ const owner = w.owner.kind === 'checkout' ? 'the checkout itself' : w.owner.kind === 'session' ? `Leg session ${w.owner.id}${w.owner.live ? ', live' : ''}` : w.owner.kind === 'card' ? `Leg card ${w.owner.id}` : 'not Leg\'s'
260
+ const flags = []
261
+ if (!w.exists) flags.push(el('span', { class: 'chip chip-state-warn' }, ['missing']))
262
+ if (w.orphaned) flags.push(el('span', { class: 'chip chip-state-warn' }, ['orphaned']))
263
+ if (w.stale) flags.push(el('span', { class: 'chip is-stale' }, ['stale']))
264
+ if (w.dirty !== null && w.dirty !== undefined) flags.push(el('span', { class: `chip ${w.dirty ? 'chip-state-warn' : 'chip-state-ok'}` }, [w.dirty ? `${w.dirty} uncommitted` : 'clean']))
265
+ return el('div', { class: 'history-row' }, [
266
+ el('div', {}, [
267
+ el('div', { class: 'mono' }, [w.path]),
268
+ el('div', { class: 'history-register' }, [
269
+ el('span', {}, [`${w.repo_name || 'repo'}${w.branch ? ` on ${w.branch}` : ' (detached)'}`]),
270
+ el('span', {}, [owner]),
271
+ el('span', {}, [`${w.conversations.count} conversation${w.conversations.count === 1 ? '' : 's'}`]),
272
+ ...flags,
273
+ ]),
274
+ ]),
275
+ el('span', { class: 'history-when' }, [w.last_activity_at ? whenAgo(w.last_activity_at) : '']),
276
+ ])
277
+ }
278
+
279
+ function render() {
280
+ const head = document.getElementById('history-head')
281
+ const region = document.querySelector('.region-history')
282
+ const meta = document.querySelector('.region-history .region-meta')
283
+ const slot = document.getElementById('history-actions')
284
+ const panel = document.getElementById('history-drawer')
285
+ const list = document.getElementById('history-list')
286
+ const listMeta = document.getElementById('history-list-meta')
287
+ const more = document.getElementById('history-more')
288
+ if (!head || !meta || !slot || !panel || !list || !listMeta || !more) return
289
+ const focusAt = takeFocus(panel) || takeFocus(region)
290
+ const scrollAt = takeScroll(panel)
291
+ slot.textContent = ''
292
+ if (state.guest) { head.textContent = 'Conversations'; meta.textContent = 'The owner of this machine sees them.'; panel.hidden = true; return }
293
+ if (!state.loaded) {
294
+ head.textContent = state.error ? 'Conversations unavailable' : 'Reading conversations'
295
+ meta.textContent = state.error || 'Looking through the agents\' own stores.'
296
+ panel.hidden = true
297
+ return
298
+ }
299
+ const filtered = state.filters.provider || state.filters.search || state.filters.repo || state.filters.managed
300
+ const all = Object.values(state.counts).reduce((a, b) => a + b, 0)
301
+ const byAgent = Object.entries(state.counts).sort((a, b) => b[1] - a[1]).map(([p, n]) => `${n} ${p}`).join(', ')
302
+ head.textContent = all ? `${all} conversation${all === 1 ? '' : 's'}` : 'No conversations found'
303
+ meta.textContent = all
304
+ ? `${byAgent}${filtered ? `; ${state.total} match the filters` : ''}${state.refreshedAt ? `; looked ${whenAgo(state.refreshedAt)}` : ''}`
305
+ : 'Leg looks in the Claude Code, Codex, Grok, Antigravity and Copilot homes on this machine, and its own sessions.'
306
+ const btn = el('button', { type: 'button', class: 'btn btn-secondary', 'aria-expanded': state.open ? 'true' : 'false', 'aria-controls': 'history-drawer', 'data-focus-key': 'history-toggle' },
307
+ [state.open ? 'Hide conversations' : (all ? `Browse ${all}` : 'Browse')])
308
+ btn.addEventListener('click', () => { state.open = !state.open; if (state.open && state.worktrees === null) loadWorktrees(); render() })
309
+ slot.appendChild(btn)
310
+ panel.hidden = !state.open
311
+ if (!state.open) {
312
+ putFocus(region, focusAt)
313
+ return
314
+ }
315
+ const headline = document.getElementById('history-drawer-head')
316
+ if (headline) headline.textContent = filtered ? `${state.total} of ${all} conversations` : `${all} conversation${all === 1 ? '' : 's'}`
317
+ // filters: the select is filled once from the providers the server names
318
+ const sel = document.getElementById('history-provider')
319
+ if (sel && sel.options.length <= 1 && state.providers.length) for (const p of state.providers) sel.appendChild(el('option', { value: p.name }, [p.label]))
320
+ listMeta.textContent = state.error ? state.error : (state.loading ? 'reading' : `${state.records.length} of ${state.total} shown, newest first`)
321
+ list.textContent = ''
322
+ if (!state.records.length && !state.loading) list.appendChild(el('p', { class: 'history-empty' }, [filtered ? 'Nothing matches these filters.' : 'No conversation has been found on this machine yet.']))
323
+ for (const r of state.records) {
324
+ list.appendChild(row(r))
325
+ if (state.detailId === r.id) list.appendChild(detail(r))
326
+ }
327
+ more.textContent = ''
328
+ if (state.records.length < state.total) {
329
+ const b = el('button', { type: 'button', class: 'btn btn-secondary', 'data-focus-key': 'history-more' }, [`Show ${Math.min(PAGE, state.total - state.records.length)} more`])
330
+ b.addEventListener('click', () => load({ more: true }))
331
+ more.appendChild(b)
332
+ }
333
+ // checkouts
334
+ const wtMeta = document.getElementById('worktrees-meta')
335
+ const wtList = document.getElementById('worktrees-list')
336
+ if (wtMeta && wtList) {
337
+ wtList.textContent = ''
338
+ if (state.worktreesError) wtMeta.textContent = `could not list them: ${state.worktreesError}`
339
+ else if (!state.worktrees) wtMeta.textContent = 'listing the checkouts'
340
+ else {
341
+ const w = state.worktrees.worktrees
342
+ const missing = w.filter((x) => !x.exists).length
343
+ const orphaned = w.filter((x) => x.orphaned).length
344
+ wtMeta.textContent = w.length ? `${w.length} checkout${w.length === 1 ? '' : 's'} across ${state.worktrees.repos} repositor${state.worktrees.repos === 1 ? 'y' : 'ies'}${missing ? `, ${missing} missing` : ''}${orphaned ? `, ${orphaned} orphaned` : ''}. Read only: Remove on a terminal or a card is what removes one.` : 'No repository is known yet.'
345
+ for (const x of w) wtList.appendChild(worktreeRow(x))
346
+ }
347
+ }
348
+ putScroll(panel, scrollAt)
349
+ putFocus(panel, focusAt) || putFocus(region, focusAt)
350
+ }
351
+
352
+ function wireFilters() {
353
+ const sel = document.getElementById('history-provider')
354
+ const search = document.getElementById('history-search')
355
+ const repo = document.getElementById('history-repo')
356
+ const only = document.getElementById('history-only')
357
+ const form = document.getElementById('history-filters')
358
+ if (form) form.addEventListener('submit', (e) => { e.preventDefault(); load() })
359
+ if (sel) sel.addEventListener('change', () => { state.filters.provider = sel.value; load() })
360
+ if (only) only.addEventListener('change', () => { state.filters.managed = only.checked; load() })
361
+ const debounce = (input, key) => input && input.addEventListener('input', () => {
362
+ state.filters[key] = input.value.trim()
363
+ clearTimeout(searchTimer)
364
+ searchTimer = setTimeout(() => load(), 300)
365
+ })
366
+ debounce(search, 'search')
367
+ debounce(repo, 'repo')
368
+ }
369
+
370
+ document.addEventListener('DOMContentLoaded', () => {
371
+ wireFilters()
372
+ render()
373
+ load()
374
+ // the count stays honest without pushing anything over the live stream
375
+ setInterval(() => { if (!document.hidden && !state.open) load() }, 60000)
376
+ })
377
+ })()
@@ -75,6 +75,15 @@
75
75
  <div class="ledger-actions" id="trunk-actions"></div>
76
76
  </div>
77
77
 
78
+ <!-- Every conversation on this machine, Leg's own and the ones the agents
79
+ keep in their own stores. A count that opens, like the other three:
80
+ history.js fills it from /api/history, only once the reader asks. -->
81
+ <div class="ledger-cell region-history">
82
+ <h3 id="history-head">Reading conversations</h3>
83
+ <p class="region-meta"></p>
84
+ <div class="ledger-actions" id="history-actions"></div>
85
+ </div>
86
+
78
87
  <div class="ledger-cell" id="board">
79
88
  <h3 id="cards-head">No background tasks</h3>
80
89
  <p class="region-meta"></p>
@@ -97,6 +106,29 @@
97
106
  <div class="trunk-list" id="trunk"></div>
98
107
  </div>
99
108
 
109
+ <div class="drawer" id="history-drawer" hidden>
110
+ <h3 class="drawer-head" id="history-drawer-head">Conversations</h3>
111
+ <!-- discovered conversations are read from the agents' own stores and
112
+ never moved; a row opens its last messages in place, and the only
113
+ way to continue one is a command in a terminal, shown on the row -->
114
+ <form class="history-filters" id="history-filters">
115
+ <label for="history-provider">Agent</label>
116
+ <select id="history-provider"><option value="">every agent</option></select>
117
+ <label for="history-search">Search</label>
118
+ <input type="text" id="history-search" autocomplete="off" spellcheck="false" placeholder="title, repo, branch or id">
119
+ <label for="history-repo">Repository</label>
120
+ <input type="text" id="history-repo" autocomplete="off" spellcheck="false" placeholder="name or path">
121
+ <label for="history-only"><input type="checkbox" id="history-only"> only conversations Leg started</label>
122
+ </form>
123
+ <p class="region-meta" id="history-list-meta" role="status" aria-atomic="true"></p>
124
+ <div class="history-list" id="history-list"></div>
125
+ <div class="ledger-actions" id="history-more"></div>
126
+ <p class="drawer-note">Read only: each agent keeps its own history where it always was. Leg lists it, opens it, and never moves or changes it. Sessions Leg started itself are marked <span class="chip">leg</span>; the rest are <span class="chip is-stale">external</span>.</p>
127
+ <h3 class="drawer-head" id="worktrees-head">Checkouts</h3>
128
+ <p class="region-meta" id="worktrees-meta" role="status" aria-atomic="true"></p>
129
+ <div class="history-list" id="worktrees-list"></div>
130
+ </div>
131
+
100
132
  <div class="drawer" id="cards-drawer" hidden>
101
133
  <h3 class="drawer-head">Background tasks</h3>
102
134
  <div class="card-list" id="columns"></div>
@@ -126,6 +158,27 @@
126
158
  <button type="button" class="btn btn-secondary" id="default-order-save">Save default</button>
127
159
  <span class="field-status" id="default-order-status" aria-live="polite"></span>
128
160
  </fieldset>
161
+ <!-- Who did what, across every terminal and every card. The owner's, like
162
+ the rest of this panel: the trail names repositories and people. It
163
+ loads when asked rather than on every board render. -->
164
+ <fieldset class="audit" id="audit" hidden>
165
+ <legend>Audit trail</legend>
166
+ <p class="field-help">Every hand-off, landing, approval, reassignment and kill on this board, newest first, with the person or the agent that did it.</p>
167
+ <div class="audit-filters">
168
+ <label for="audit-who">Who</label>
169
+ <select id="audit-who"><option value="">anyone</option></select>
170
+ <label for="audit-kind">Kind</label>
171
+ <select id="audit-kind">
172
+ <option value="">people and agents</option>
173
+ <option value="human">people</option>
174
+ <option value="agent">agents</option>
175
+ <option value="leg">Leg itself</option>
176
+ </select>
177
+ <button type="button" class="btn btn-secondary" id="audit-load">Load</button>
178
+ </div>
179
+ <p class="region-meta" id="audit-meta" role="status" aria-atomic="true"></p>
180
+ <div class="audit-list" id="audit-list"></div>
181
+ </fieldset>
129
182
  <div class="field board-facts"></div>
130
183
  </div>
131
184
  </section>
@@ -247,5 +300,7 @@
247
300
 
248
301
  <script src="board.js" defer></script>
249
302
  <script src="sessions.js" defer></script>
303
+ <script src="history.js" defer></script>
304
+ <script src="audit.js" defer></script>
250
305
  </body>
251
306
  </html>
@@ -661,7 +661,7 @@
661
661
  sysMessage('removed the Leg record; the worktree and the branch are kept', 'ok')
662
662
  } else {
663
663
  await api(`/api/sessions/${encodeURIComponent(id)}/${action}`, { method: 'POST', body })
664
- if (action === 'handoff') actionNotes.set(id, { at: Date.now(), tone: 'warn', text: 'hand-off requested; this terminal switches agents in a few seconds' })
664
+ if (action === 'handoff') actionNotes.set(id, { at: Date.now(), tone: 'warn', text: body && body.agent ? `hand-off to ${optionLabel(body)} requested; this terminal switches agents in a few seconds` : 'hand-off requested; this terminal switches agents in a few seconds' })
665
665
  else if (action === 'end') actionNotes.set(id, { at: Date.now(), tone: 'warn', text: 'end requested; the agent stops after its current turn' })
666
666
  else if (action === 'land/fix') actionNotes.set(id, { at: Date.now(), tone: 'ok', text: 'applied fix' })
667
667
  }
@@ -693,6 +693,34 @@
693
693
  else wrap.appendChild(el('p', { class: 'sentence tone-muted' }, [`first eligible now: ${eligible}`]))
694
694
  wrap.appendChild(el('p', { class: 'blocker' }, ['Used after a usage limit or Hand off now. A normal exit ends this terminal.']))
695
695
 
696
+ // The picker. The Hand off now button on the panel stays the one-click
697
+ // path (it takes the order); this names a destination instead. An option
698
+ // that cannot be picked carries the reason in its own label, so nothing is
699
+ // greyed out without saying why.
700
+ const targets = Array.isArray(s.handoff_targets) ? s.handoff_targets : []
701
+ if (s.active && targets.length) {
702
+ const pick = el('div', { class: 'form-row' })
703
+ const selectId = `handoff-to-${s.session_id}`
704
+ pick.appendChild(el('label', { for: selectId }, ['Hand off now to']))
705
+ const select = el('select', { id: selectId })
706
+ select.appendChild(el('option', { value: '' }, ['the next option in the order']))
707
+ targets.forEach((t, i) => {
708
+ const note = t.available ? '' : ` — ${t.reason}${Number.isFinite(t.resets_at) ? `, back ${until(t.resets_at)}` : ''}`
709
+ // the index is the value: an account name is not ours to parse
710
+ select.appendChild(el('option', { value: String(i), disabled: t.available ? null : 'disabled' }, [optionLabel(t) + note]))
711
+ })
712
+ const go = el('button', { type: 'button', class: 'btn btn-secondary' }, ['Hand off'])
713
+ go.addEventListener('click', () => {
714
+ const t = select.value === '' ? null : targets[Number(select.value)]
715
+ act(s.session_id, 'handoff', go, t ? { agent: t.agent, account: t.account } : null)
716
+ })
717
+ pick.appendChild(el('div', { class: 'chain-rail' }, [select, go]))
718
+ if (!targets.some((t) => t.available)) {
719
+ pick.appendChild(el('p', { class: 'field-help' }, ['Every destination is at its limit or not installed; a hand-off now waits for the first reset.']))
720
+ }
721
+ wrap.appendChild(pick)
722
+ }
723
+
696
724
  const editableNow = ['starting', 'running', 'warning', 'limit', 'waiting'].includes(s.status)
697
725
  if (!s.hidden && editableNow) {
698
726
  let state = sessionEditors.get(s.session_id)
@@ -836,8 +864,14 @@
836
864
  ]))
837
865
 
838
866
  if (pendingConfirm && pendingConfirm.id === s.session_id) {
867
+ // Snapshot it: confirmRow clears pendingConfirm before it calls back, so
868
+ // a callback that read the variable instead of this value dereferenced
869
+ // null and threw on the way to act(). That was every Yes on this page —
870
+ // Remove, Remove record, End and Land all did nothing, with the
871
+ // TypeError going only to the console.
872
+ const pending = pendingConfirm
839
873
  term.appendChild(row)
840
- term.appendChild(confirmRow(pendingConfirm.question, pendingConfirm.verb, (btn) => act(s.session_id, pendingConfirm.action, btn)))
874
+ term.appendChild(confirmRow(pending.question, pending.verb, (btn) => act(s.session_id, pending.action, btn)))
841
875
  return term
842
876
  }
843
877
  const actions = el('div', { class: 'term-actions' })
@@ -1563,7 +1597,13 @@
1563
1597
  }
1564
1598
  renderAccounts(v.accounts || [])
1565
1599
  renderDefaultOrder(v)
1566
- renderSessions(v)
1600
+ // A rebuild replaces every button in the grid. A confirm row is a question
1601
+ // the reader is answering right now, and a push landing between their
1602
+ // mousedown and their mouseup dropped the click: the browser fires `click`
1603
+ // only when both landed on the same element, so Remove did nothing however
1604
+ // often it was pressed. The rows hold still until the question is answered
1605
+ // — `view` is already current, and answering it re-renders from that.
1606
+ if (!pendingConfirm) renderSessions(v)
1567
1607
  renderTrunk(v)
1568
1608
  // the panel behind the expansion just changed: status, turns and what is
1569
1609
  // next live in the session view, so redraw the region from it
@@ -1574,9 +1614,11 @@
1574
1614
  try { render(await api('/api/sessions')) } catch (err) { sysMessage(err.message, 'danger') }
1575
1615
  }
1576
1616
 
1577
- window.addEventListener('leg:sessions', (e) => render(e.detail));
1578
- window.addEventListener('leg:sessions', (e) => render(e.detail));
1579
- window.addEventListener('baton:sessions', (e) => render(e.detail)); // legacy alias
1617
+ // Exactly one listener. board.js publishes `leg:sessions` and the legacy
1618
+ // `baton:sessions` alias for every push; this file had been registered on
1619
+ // `leg:sessions` twice and on the alias once, so one push rebuilt the entire
1620
+ // terminals grid three times over.
1621
+ window.addEventListener('leg:sessions', (e) => render(e.detail))
1580
1622
  document.addEventListener('keydown', (e) => {
1581
1623
  if (e.key !== 'Escape') return
1582
1624
  if (pendingConfirm) { pendingConfirm = null; if (view) renderSessions(view); return }
@@ -1589,6 +1631,6 @@
1589
1631
  setInterval(tickElapsed, 1000)
1590
1632
  // the timed re-sort exists to move the needs-you partition, which can wait a
1591
1633
  // few seconds: it stands down mid-selection rather than clearing the drag
1592
- setInterval(() => { if (view && !selectionInsideGrid()) renderSessions(view) }, 15000)
1634
+ setInterval(() => { if (view && !pendingConfirm && !selectionInsideGrid()) renderSessions(view) }, 15000)
1593
1635
  })
1594
1636
  })()