reevesagents 1.2.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.
@@ -0,0 +1,1435 @@
1
+ // Web client: renders the agent sidebar from /api/state, keeps it live over the
2
+ // /api/events SSE stream, and attaches xterm.js to an agent tmux window through
3
+ // the /term websocket bridge. Globals Terminal and FitAddon come from the xterm UMD
4
+ // bundles loaded before this script. No build step, no framework.
5
+
6
+ (() => {
7
+ 'use strict'
8
+
9
+ const TERM_THEME = {
10
+ background: '#15191f',
11
+ foreground: '#ece7dc',
12
+ cursor: '#7eb8f5',
13
+ selectionBackground: '#3a4b5f',
14
+ black: '#15191f', brightBlack: '#817b70',
15
+ red: '#d56a60', brightRed: '#d56a60',
16
+ green: '#83a36f', brightGreen: '#83a36f',
17
+ yellow: '#d7a84f', brightYellow: '#d7a84f',
18
+ blue: '#7eb8f5', brightBlue: '#7eb8f5',
19
+ white: '#ece7dc', brightWhite: '#ffffff',
20
+ }
21
+
22
+ const WEB_EN = {
23
+ 'common.delete': 'Delete',
24
+ 'web.beta': 'web · beta',
25
+ 'web.prebeta': 'web · pre-beta MCP',
26
+ 'web.live': 'live',
27
+ 'web.offline': 'offline',
28
+ 'web.languageTitle': 'Language',
29
+ 'web.activeAgents': 'active agents',
30
+ 'web.agents': 'Agents',
31
+ 'web.noAgents': 'No agents yet',
32
+ 'web.noAgentsBody': 'Create a run first, then add agents as the work grows.',
33
+ 'web.noActiveAgents': 'No active agents',
34
+ 'web.noActiveAgentsBody': 'Start a new run when you are ready. Ended runs stay in History.',
35
+ 'web.noAgentSelected': 'No agent selected',
36
+ 'web.noAgentSub': 'Pick an agent on the left, or create a run.',
37
+ 'web.addAgent': 'Add agent',
38
+ 'web.stop': 'Stop',
39
+ 'web.newAgent': 'New agent',
40
+ 'web.newRun': 'New run',
41
+ 'web.newRunTitle': 'create a new run',
42
+ 'web.webAgent': 'web agent',
43
+ 'web.noAgentAttached': 'No agent attached',
44
+ 'web.overlayBody': 'Select an agent to open its live pane. Closing the browser leaves the run active.',
45
+ 'web.unavailableBody': 'This agent does not have a live tmux window to open.',
46
+ 'web.newRunSubtitle': 'Create a run and start its first provider agent.',
47
+ 'web.addAgentSubtitle': 'Add one provider agent to an active run.',
48
+ 'web.createRun': 'Create run',
49
+ 'web.run': 'Run',
50
+ 'web.runName': 'Run name',
51
+ 'web.provider': 'Provider',
52
+ 'web.model': 'Model',
53
+ 'web.permissionMode': 'Permission mode',
54
+ 'web.askFirst': 'Ask first',
55
+ 'web.askFirstMeta': 'Keep provider approval prompts',
56
+ 'web.skipPrompts': 'Skip prompts',
57
+ 'web.skipPromptsMeta': 'Use only in trusted workspaces',
58
+ 'web.agentName': 'Agent name',
59
+ 'web.optional': 'optional',
60
+ 'web.newRunMode': 'New run mode',
61
+ 'web.workingDirectory': 'Working directory',
62
+ 'web.cwdPlaceholder': 'defaults to the server directory',
63
+ 'web.initialPrompt': 'Initial prompt',
64
+ 'web.initialPromptOpt': 'optional, typed in on start',
65
+ 'web.agentRunHelp': 'Choose the active run that will receive this agent.',
66
+ 'web.runNameHelp': 'Shown in the run list and history.',
67
+ 'web.providerHelp': 'Choose the provider CLI that will run this agent.',
68
+ 'web.modelHelp': 'Provider default is safest when unsure.',
69
+ 'web.permissionsHelp': 'Ask first is safer. Skip prompts only in trusted workspaces.',
70
+ 'web.agentNameHelp': 'Optional display name and tmux window name.',
71
+ 'web.modeHelp': 'Normal runs are direct agent workspaces. Orchestrator MCP is pre-beta.',
72
+ 'web.cwdHelp': 'Agents start in this directory.',
73
+ 'web.promptHelp': 'Sent to the agent after its window opens.',
74
+ 'web.promptPlaceholder': 'What should this agent start working on?',
75
+ 'web.orchestratorPromptPlaceholder': 'What should this orchestrator agent start working on?',
76
+ 'web.cancel': 'Cancel',
77
+ 'web.create': 'Create',
78
+ 'web.providerDefault': 'Provider default',
79
+ 'web.notInstalled': 'Not installed',
80
+ 'web.spawnerOnly': 'Agent run only',
81
+ 'web.readyOrchestrator': 'Ready · Orchestrator',
82
+ 'web.ready': 'Ready',
83
+ 'web.history': 'History',
84
+ 'web.archived': 'archived',
85
+ 'web.noRootProvider': 'no root provider',
86
+ 'web.addAgentTitle': 'add agent to {{name}}',
87
+ 'web.stopRunTitle': 'stop run {{name}}',
88
+ 'web.deleteRunTitle': 'delete stopped run {{name}}',
89
+ 'web.deleteHistoryTitle': 'delete archived run {{name}}',
90
+ 'web.stopAgentTitle': 'stop agent {{name}}',
91
+ 'web.deleteAgentTitle': 'delete stopped agent {{name}}',
92
+ 'web.openAgent': 'Open',
93
+ 'web.openAgentTitle': 'open agent {{name}}',
94
+ 'web.agentUnavailable': 'agent is unavailable',
95
+ 'web.noAgentWindow': 'agent has no tmux window',
96
+ 'web.noLiveTmuxTarget': 'run tmux session is unavailable',
97
+ 'web.unavailable': 'Unavailable',
98
+ 'web.addAgentActiveTitle': 'add an agent to an active run',
99
+ 'web.createRunFirstTitle': 'create a run before adding agents',
100
+ 'web.connecting': 'connecting',
101
+ 'web.closed': 'closed',
102
+ 'web.exited': 'exited',
103
+ 'web.error': 'error',
104
+ 'web.connectionError': 'connection error',
105
+ 'web.disconnected': 'disconnected',
106
+ 'web.stopAgentConfirm': 'Stop agent "{{name}}"? The running window for this agent will be closed.',
107
+ 'web.stopAgentError': 'Could not stop agent: {{message}}',
108
+ 'web.stopRunConfirm': 'Stop run "{{name}}"? Every agent in it will be stopped.',
109
+ 'web.stopRunError': 'Could not stop run: {{message}}',
110
+ 'web.deleteRunConfirm': 'Delete stopped run "{{name}}"? A simple history record will be kept.',
111
+ 'web.deleteRunError': 'Could not delete stopped run: {{message}}',
112
+ 'web.deleteAgentConfirm': 'Delete stopped agent "{{name}}"? This removes the saved agent record.',
113
+ 'web.deleteAgentError': 'Could not delete stopped agent: {{message}}',
114
+ 'web.deleteHistoryConfirm': 'Delete archived run "{{name}}"? This only removes the saved history record.',
115
+ 'web.deleteHistoryError': 'Could not delete archived run: {{message}}',
116
+ 'web.agentEnded': 'agent has ended',
117
+ 'web.createRunFirst': 'Create a run first. Agents are added inside active runs.',
118
+ 'web.runInactive': 'This run is no longer active.',
119
+ 'web.noProvider': 'No installed provider is available for this mode.',
120
+ 'web.addingTo': 'Adding to {{name}} · {{mode}} · {{count}}',
121
+ 'web.oneAgent': '{{count}} agent',
122
+ 'web.manyAgents': '{{count}} agents',
123
+ 'web.spawner': 'Agent run',
124
+ 'web.orchestrator': 'Orchestrator MCP',
125
+ 'web.roleRoot': 'root',
126
+ 'web.roleWorker': 'worker',
127
+ 'web.statusQueued': 'queued',
128
+ 'web.statusWorking': 'working',
129
+ 'web.statusDone': 'done',
130
+ 'web.statusFailed': 'failed',
131
+ 'web.statusBlocked': 'blocked',
132
+ 'web.statusEnded': 'ended',
133
+ 'web.statusStale': 'stale',
134
+ 'web.statusRunning': 'running',
135
+ 'web.unknown': 'unknown',
136
+ 'web.useProvider': 'use {{name}}',
137
+ }
138
+
139
+ const el = {
140
+ sidebarList: document.getElementById('sidebar-list'),
141
+ sidebarEmpty: document.getElementById('sidebar-empty'),
142
+ sidebarCount: document.getElementById('sidebar-count'),
143
+ conn: document.getElementById('conn'),
144
+ brandDuck: document.getElementById('brand-duck'),
145
+ brandBeta: document.getElementById('brand-beta'),
146
+ languageLabel: document.getElementById('language-label'),
147
+ languageSelect: document.getElementById('language-select'),
148
+ stageTitle: document.getElementById('stage-title'),
149
+ stageSub: document.getElementById('stage-sub'),
150
+ stageStatus: document.getElementById('stage-status'),
151
+ overlay: document.getElementById('stage-overlay'),
152
+ termWrap: document.getElementById('term-wrap'),
153
+ termHost: document.getElementById('term-host'),
154
+ newAgentBtn: document.getElementById('new-agent-btn'),
155
+ newRunBtn: document.getElementById('new-run-btn'),
156
+ emptyNewRun: document.getElementById('empty-new-run'),
157
+ overlayNewRun: document.getElementById('overlay-new-run'),
158
+ overlayNewAgent: document.getElementById('overlay-new-agent'),
159
+ stageAddAgent: document.getElementById('stage-add-agent'),
160
+ dialog: document.getElementById('new-dialog'),
161
+ dialogTitle: document.getElementById('new-dialog-title'),
162
+ dialogSubtitle: document.getElementById('new-dialog-subtitle'),
163
+ targetRunNote: document.getElementById('target-run-note'),
164
+ createRunTab: document.getElementById('create-run-tab'),
165
+ createAgentTab: document.getElementById('create-agent-tab'),
166
+ form: document.getElementById('new-form'),
167
+ fProvider: document.getElementById('f-provider'),
168
+ providerGrid: document.getElementById('provider-grid'),
169
+ fModel: document.getElementById('f-model'),
170
+ fPermissions: document.getElementById('f-permissions'),
171
+ permissionGrid: document.getElementById('permission-grid'),
172
+ fNickname: document.getElementById('f-nickname'),
173
+ fRunName: document.getElementById('f-run-name'),
174
+ fAgentRun: document.getElementById('f-agent-run'),
175
+ fMode: document.getElementById('f-mode'),
176
+ agentRunField: document.getElementById('agent-run-field'),
177
+ modeField: document.getElementById('mode-field'),
178
+ runNameField: document.getElementById('run-name-field'),
179
+ fCwd: document.getElementById('f-cwd'),
180
+ cwdField: document.getElementById('cwd-field'),
181
+ fPrompt: document.getElementById('f-prompt'),
182
+ newError: document.getElementById('new-error'),
183
+ newCancel: document.getElementById('new-cancel'),
184
+ newSubmit: document.getElementById('new-submit'),
185
+ }
186
+
187
+ let runs = []
188
+ let history = []
189
+ let providers = []
190
+ let language = 'en'
191
+ let languages = []
192
+ let messages = WEB_EN
193
+ let prebetaOrchestrator = false
194
+ let selectedId = null
195
+ let session = null // { id, ws, term, fit, observer }
196
+ let createContext = { kind: 'run', runId: '' }
197
+ let createSubmitting = false
198
+
199
+ // --- http helpers ---------------------------------------------------------
200
+
201
+ async function api(method, path, body) {
202
+ const res = await fetch(path, {
203
+ method,
204
+ headers: body ? { 'content-type': 'application/json' } : undefined,
205
+ body: body ? JSON.stringify(body) : undefined,
206
+ })
207
+ const text = await res.text()
208
+ let data = null
209
+ try { data = text ? JSON.parse(text) : null } catch { /* non-json error body */ }
210
+ if (!res.ok) {
211
+ const msg = (data && data.error) || text || `request failed (${res.status})`
212
+ throw new Error(msg)
213
+ }
214
+ return data
215
+ }
216
+
217
+ // --- initial load + live stream ------------------------------------------
218
+
219
+ async function loadState() {
220
+ const data = await api('GET', '/api/state')
221
+ applyState(data)
222
+ }
223
+
224
+ async function refreshState() {
225
+ const data = await api('GET', '/api/state')
226
+ applyState(data)
227
+ }
228
+
229
+ function applyState(data) {
230
+ providers = data.providers || []
231
+ runs = data.runs || []
232
+ history = data.history || []
233
+ prebetaOrchestrator = data.prebeta && data.prebeta.orchestrator === true
234
+ applyLanguage(data.language)
235
+ renderProviders()
236
+ renderSidebar()
237
+ reconcileCreateDialog()
238
+ reconcileSelectedAgent()
239
+ }
240
+
241
+ function subscribe() {
242
+ const events = new EventSource('/api/events')
243
+ events.onopen = () => setConn('live')
244
+ events.onerror = () => setConn('down')
245
+ events.onmessage = (e) => {
246
+ try {
247
+ const data = JSON.parse(e.data)
248
+ if (Array.isArray(data.runs)) {
249
+ runs = data.runs
250
+ }
251
+ if (Array.isArray(data.history)) history = data.history
252
+ renderSidebar()
253
+ reconcileCreateDialog()
254
+ reconcileSelectedAgent()
255
+ } catch { /* ignore malformed frame */ }
256
+ }
257
+ }
258
+
259
+ function setConn(state) {
260
+ el.conn.dataset.state = state
261
+ el.conn.textContent = state === 'down' ? t('web.offline') : t('web.live')
262
+ }
263
+
264
+ function t(key, values) {
265
+ let text = messages[key] || WEB_EN[key] || key
266
+ for (const [name, value] of Object.entries(values || {})) {
267
+ text = text.replaceAll(`{{${name}}}`, String(value))
268
+ }
269
+ return text
270
+ }
271
+
272
+ function applyLanguage(payload) {
273
+ if (!payload || typeof payload !== 'object') return
274
+ language = payload.current || language
275
+ languages = Array.isArray(payload.languages) ? payload.languages : languages
276
+ messages = { ...WEB_EN, ...(payload.translations || {}) }
277
+ document.documentElement.lang = language
278
+ const current = languages.find(item => item.code === language)
279
+ document.documentElement.dir = current && current.dir === 'rtl' ? 'rtl' : 'ltr'
280
+ renderLanguageSelect()
281
+ applyStaticTranslations()
282
+ }
283
+
284
+ function renderLanguageSelect() {
285
+ if (!el.languageSelect) return
286
+ const current = el.languageSelect.value || language
287
+ el.languageSelect.innerHTML = ''
288
+ for (const option of languages) {
289
+ const item = document.createElement('option')
290
+ item.value = option.code
291
+ item.textContent = `${option.flag} ${option.nativeName}`
292
+ item.title = option.name
293
+ el.languageSelect.appendChild(item)
294
+ }
295
+ el.languageSelect.value = [...el.languageSelect.options].some(option => option.value === current) ? current : language
296
+ }
297
+
298
+ function applyStaticTranslations() {
299
+ el.brandBeta.textContent = prebetaOrchestrator ? t('web.prebeta') : t('web.beta')
300
+ el.languageLabel.textContent = t('web.languageTitle')
301
+ el.languageSelect.setAttribute('aria-label', t('web.languageTitle'))
302
+ el.languageSelect.parentElement.title = t('web.languageTitle')
303
+ el.newAgentBtn.textContent = t('web.newAgent')
304
+ el.newRunBtn.textContent = t('web.newRun')
305
+ el.newRunBtn.title = t('web.newRunTitle')
306
+ el.emptyNewRun.textContent = t('web.newRun')
307
+ el.overlayNewRun.textContent = t('web.newRun')
308
+ el.overlayNewAgent.textContent = t('web.newAgent')
309
+ el.stageAddAgent.textContent = t('web.addAgent')
310
+ document.querySelector('.sidebar-title').textContent = t('web.agents')
311
+ document.querySelector('.sidebar-kicker').textContent = t('web.activeAgents')
312
+ document.querySelector('.empty-title').textContent = t('web.noAgents')
313
+ document.querySelector('.empty-body').textContent = t('web.noAgentsBody')
314
+ document.querySelector('.overlay-eyebrow').textContent = t('web.webAgent')
315
+ if (!selectedId) {
316
+ document.querySelector('.overlay-title').textContent = t('web.noAgentAttached')
317
+ document.querySelector('.overlay-body').textContent = t('web.overlayBody')
318
+ } else {
319
+ const found = findAgent(selectedId)
320
+ if (found && !found.terminal.canAttach) {
321
+ setOverlayCopy(disabledReasonLabel(found.terminal), t('web.unavailableBody'))
322
+ setStageStatus('closed', disabledReasonLabel(found.terminal))
323
+ }
324
+ }
325
+ el.createRunTab.textContent = t('web.newRun')
326
+ el.createAgentTab.textContent = t('web.newAgent')
327
+ document.querySelector('#agent-run-field .field-label').textContent = t('web.run')
328
+ document.querySelector('#run-name-field .field-label').textContent = t('web.runName')
329
+ document.querySelector('.provider-field .field-label').textContent = t('web.provider')
330
+ document.querySelector('.model-field .field-label').textContent = t('web.model')
331
+ document.querySelector('.permissions-field .field-label').textContent = t('web.permissionMode')
332
+ document.querySelector('[data-permission="ask"] .permission-title').textContent = t('web.askFirst')
333
+ document.querySelector('[data-permission="ask"] .permission-meta').textContent = t('web.askFirstMeta')
334
+ document.querySelector('[data-permission="skip"] .permission-title').textContent = t('web.skipPrompts')
335
+ document.querySelector('[data-permission="skip"] .permission-meta').textContent = t('web.skipPromptsMeta')
336
+ document.querySelector('#f-permissions option[value="ask"]').textContent = t('web.askFirst')
337
+ document.querySelector('#f-permissions option[value="skip"]').textContent = t('web.skipPrompts')
338
+ document.querySelector('#agent-name-field .field-label').innerHTML = `${t('web.agentName')} <span class="field-opt">${t('web.optional')}</span>`
339
+ document.querySelector('#mode-field .field-label').textContent = t('web.newRunMode')
340
+ document.querySelector('#f-mode option[value="spawner"]').textContent = t('web.spawner')
341
+ document.querySelector('#f-mode option[value="orchestrator"]').textContent = `${t('web.orchestrator')} · pre-beta`
342
+ document.querySelector('#cwd-field .field-label').textContent = t('web.workingDirectory')
343
+ document.querySelector('#f-cwd').placeholder = t('web.cwdPlaceholder')
344
+ document.querySelector('#prompt-field .field-label').innerHTML = `${t('web.initialPrompt')} <span class="field-opt">${t('web.initialPromptOpt')}</span>`
345
+ setText('#agent-run-help', t('web.agentRunHelp'))
346
+ setText('#run-name-help', t('web.runNameHelp'))
347
+ setText('#provider-help', t('web.providerHelp'))
348
+ setText('#model-help', t('web.modelHelp'))
349
+ setText('#permissions-help', t('web.permissionsHelp'))
350
+ setText('#agent-name-help', t('web.agentNameHelp'))
351
+ setText('#mode-help', t('web.modeHelp'))
352
+ setText('#cwd-help', t('web.cwdHelp'))
353
+ setText('#prompt-help', t('web.promptHelp'))
354
+ el.newCancel.textContent = t('web.cancel')
355
+ syncCreateFields()
356
+ if (!selectedId) {
357
+ el.stageTitle.textContent = t('web.noAgentSelected')
358
+ el.stageSub.textContent = t('web.noAgentSub')
359
+ }
360
+ renderSidebar()
361
+ }
362
+
363
+ function setText(selector, value) {
364
+ const node = document.querySelector(selector)
365
+ if (node) node.textContent = value
366
+ }
367
+
368
+ // --- rendering ------------------------------------------------------------
369
+
370
+ function findAgent(id) {
371
+ for (const run of runs) {
372
+ for (const t of run.terminals) if (t.id === id) return { run, terminal: t }
373
+ }
374
+ return null
375
+ }
376
+
377
+ function runningRuns() {
378
+ return runs.filter(run => run.status === 'running')
379
+ }
380
+
381
+ function preferredRunId() {
382
+ const selected = selectedId ? findAgent(selectedId) : null
383
+ if (selected && selected.run.status === 'running') return selected.run.id
384
+ const first = runningRuns()[0]
385
+ return first ? first.id : ''
386
+ }
387
+
388
+ function providerById(id) {
389
+ return providers.find(provider => provider.id === id) || null
390
+ }
391
+
392
+ function providerColor(id) {
393
+ const provider = providerById(id)
394
+ return provider ? provider.color : '#7eb8f5'
395
+ }
396
+
397
+ function renderProviders() {
398
+ const current = el.fProvider.value
399
+ const mode = selectedCreateMode()
400
+ el.fProvider.innerHTML = ''
401
+ el.providerGrid.innerHTML = ''
402
+ for (const p of providers) {
403
+ const opt = document.createElement('option')
404
+ opt.value = p.id
405
+ const supported = mode !== 'orchestrator' || p.orchestrator === true
406
+ opt.textContent = p.available ? p.name : `${p.name} (${t('web.notInstalled')})`
407
+ if (mode === 'orchestrator' && !supported) opt.textContent = `${p.name} (${t('web.spawnerOnly')})`
408
+ opt.disabled = !p.available || !supported
409
+ el.fProvider.appendChild(opt)
410
+
411
+ const choice = document.createElement('button')
412
+ choice.className = 'provider-option'
413
+ choice.type = 'button'
414
+ choice.role = 'option'
415
+ choice.dataset.provider = p.id
416
+ choice.style.setProperty('--provider-color', p.color)
417
+ choice.disabled = opt.disabled
418
+ choice.title = opt.disabled ? opt.textContent : t('web.useProvider', { name: p.name })
419
+ choice.addEventListener('click', () => selectProvider(p.id))
420
+ choice.addEventListener('keydown', (ev) => handleProviderKeydown(ev, p.id))
421
+
422
+ const swatch = document.createElement('span')
423
+ swatch.className = 'provider-swatch'
424
+ choice.appendChild(swatch)
425
+
426
+ const body = document.createElement('span')
427
+ body.className = 'provider-body'
428
+ const name = document.createElement('span')
429
+ name.className = 'provider-name'
430
+ name.textContent = p.name
431
+ body.appendChild(name)
432
+ const meta = document.createElement('span')
433
+ meta.className = 'provider-meta'
434
+ meta.textContent = providerMeta(p, supported)
435
+ body.appendChild(meta)
436
+ choice.appendChild(body)
437
+ el.providerGrid.appendChild(choice)
438
+ }
439
+ const currentOption = [...el.fProvider.options].find(opt => opt.value === current && !opt.disabled)
440
+ const firstAvailable = [...el.fProvider.options].find(opt => !opt.disabled)
441
+ if (currentOption) el.fProvider.value = currentOption.value
442
+ else if (firstAvailable) el.fProvider.value = firstAvailable.value
443
+ updateProviderSelection()
444
+ renderModels()
445
+ updateCreateSubmitState()
446
+ }
447
+
448
+ function providerMeta(provider, supported) {
449
+ if (!provider.available) return t('web.notInstalled')
450
+ if (!supported) return t('web.spawnerOnly')
451
+ if (selectedCreateMode() === 'orchestrator' && provider.orchestrator) return t('web.readyOrchestrator')
452
+ return t('web.ready')
453
+ }
454
+
455
+ function selectProvider(providerId) {
456
+ const option = [...el.fProvider.options].find(item => item.value === providerId)
457
+ if (!option || option.disabled) return
458
+ el.fProvider.value = providerId
459
+ updateProviderSelection()
460
+ renderModels()
461
+ updateCreateSubmitState()
462
+ }
463
+
464
+ function handleProviderKeydown(ev, providerId) {
465
+ if (ev.key === 'Enter' || ev.key === ' ') {
466
+ ev.preventDefault()
467
+ selectProvider(providerId)
468
+ return
469
+ }
470
+ if (ev.key === 'ArrowRight' || ev.key === 'ArrowDown' || ev.key === 'ArrowLeft' || ev.key === 'ArrowUp') {
471
+ ev.preventDefault()
472
+ focusProvider(providerId, ev.key === 'ArrowRight' || ev.key === 'ArrowDown' ? 1 : -1)
473
+ }
474
+ }
475
+
476
+ function focusProvider(providerId, delta) {
477
+ const choices = [...el.providerGrid.querySelectorAll('.provider-option')].filter(option => !option.disabled)
478
+ if (choices.length === 0) return
479
+ const currentIdx = Math.max(0, choices.findIndex(option => option.dataset.provider === providerId))
480
+ const next = choices[(currentIdx + delta + choices.length) % choices.length]
481
+ if (next) next.focus()
482
+ }
483
+
484
+ function updateProviderSelection() {
485
+ const selected = providerById(el.fProvider.value)
486
+ if (selected) el.dialog.style.setProperty('--selected-provider-color', selected.color)
487
+ else el.dialog.style.removeProperty('--selected-provider-color')
488
+ for (const option of el.providerGrid.querySelectorAll('.provider-option')) {
489
+ const active = option.dataset.provider === el.fProvider.value && !option.disabled
490
+ option.setAttribute('aria-selected', String(active))
491
+ option.tabIndex = active ? 0 : -1
492
+ }
493
+ }
494
+
495
+ function modelLabel(model) {
496
+ return model || t('web.providerDefault')
497
+ }
498
+
499
+ function agentCountLabel(count) {
500
+ return count === 1 ? t('web.oneAgent', { count }) : t('web.manyAgents', { count })
501
+ }
502
+
503
+ function renderModels() {
504
+ const selected = providerById(el.fProvider.value)
505
+ const current = el.fModel.value
506
+ el.fModel.innerHTML = ''
507
+ const models = selected && Array.isArray(selected.models) ? selected.models : ['']
508
+ for (const model of models) {
509
+ const opt = document.createElement('option')
510
+ opt.value = model
511
+ opt.textContent = modelLabel(model)
512
+ el.fModel.appendChild(opt)
513
+ }
514
+ const hasCurrent = [...el.fModel.options].some(opt => opt.value === current)
515
+ if (hasCurrent) el.fModel.value = current
516
+ else el.fModel.value = ''
517
+ el.fModel.disabled = !selectedProviderAvailable()
518
+ updateCreateSubmitState()
519
+ }
520
+
521
+ function updatePermissionSelection() {
522
+ for (const option of el.permissionGrid.querySelectorAll('.permission-option')) {
523
+ const active = option.dataset.permission === el.fPermissions.value
524
+ option.setAttribute('aria-checked', String(active))
525
+ option.tabIndex = active ? 0 : -1
526
+ }
527
+ }
528
+
529
+ function selectPermission(value) {
530
+ if (value !== 'ask' && value !== 'skip') return
531
+ el.fPermissions.value = value
532
+ updatePermissionSelection()
533
+ }
534
+
535
+ function handlePermissionKeydown(ev) {
536
+ if (ev.key === 'Enter' || ev.key === ' ') {
537
+ ev.preventDefault()
538
+ selectPermission(ev.currentTarget.dataset.permission)
539
+ return
540
+ }
541
+ if (ev.key !== 'ArrowRight' && ev.key !== 'ArrowDown' && ev.key !== 'ArrowLeft' && ev.key !== 'ArrowUp') return
542
+ ev.preventDefault()
543
+ const values = ['ask', 'skip']
544
+ const currentIdx = Math.max(0, values.indexOf(el.fPermissions.value))
545
+ const delta = ev.key === 'ArrowRight' || ev.key === 'ArrowDown' ? 1 : -1
546
+ const next = values[(currentIdx + delta + values.length) % values.length]
547
+ selectPermission(next)
548
+ const nextButton = el.permissionGrid.querySelector(`[data-permission="${next}"]`)
549
+ if (nextButton) nextButton.focus()
550
+ }
551
+
552
+ function selectedProviderAvailable() {
553
+ const selected = el.fProvider.selectedOptions[0]
554
+ return !!selected && !selected.disabled && !!selected.value
555
+ }
556
+
557
+ function showDialogError(message) {
558
+ el.newError.textContent = message
559
+ el.newError.hidden = false
560
+ }
561
+
562
+ // --- brand animation ------------------------------------------------------
563
+
564
+ async function initBrandDuck() {
565
+ try {
566
+ const animation = await api('GET', '/brand-duck.json')
567
+ renderBrandDuck(animation)
568
+ } catch {
569
+ el.brandDuck.dataset.ready = 'error'
570
+ }
571
+ }
572
+
573
+ function renderBrandDuck(animation) {
574
+ if (!animation || !Array.isArray(animation.layers) || !Array.isArray(animation.assets)) return
575
+
576
+ const svg = svgEl('svg')
577
+ svg.setAttribute('viewBox', `0 0 ${animation.w || 51} ${animation.h || 63}`)
578
+ svg.setAttribute('role', 'img')
579
+ svg.setAttribute('focusable', 'false')
580
+
581
+ const title = svgEl('title')
582
+ title.textContent = 'ReevesAgents duck'
583
+ svg.appendChild(title)
584
+
585
+ const assets = new Map(animation.assets.map(asset => [asset.id, asset]))
586
+ const animatedLayers = []
587
+ for (const layer of [...animation.layers].reverse()) {
588
+ const asset = assets.get(layer.refId)
589
+ if (!asset || !Array.isArray(asset.layers)) continue
590
+ const group = svgEl('g')
591
+ group.dataset.layer = layer.nm || layer.refId
592
+ renderAssetLayers(group, asset.layers)
593
+ svg.appendChild(group)
594
+ animatedLayers.push({ layer, group })
595
+ }
596
+
597
+ el.brandDuck.innerHTML = ''
598
+ el.brandDuck.appendChild(svg)
599
+ el.brandDuck.dataset.ready = 'true'
600
+
601
+ const durationFrames = (animation.op || 120) - (animation.ip || 0)
602
+ const frameRate = animation.fr || 60
603
+ const reducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches
604
+ const applyFrame = frame => {
605
+ for (const item of animatedLayers) item.group.setAttribute('transform', layerTransform(item.layer, frame))
606
+ el.brandDuck.dataset.frame = String(Math.round(frame))
607
+ }
608
+
609
+ applyFrame(animation.ip || 0)
610
+ if (reducedMotion) return
611
+
612
+ const startedAt = window.performance.now()
613
+ const tick = now => {
614
+ const elapsed = (now - startedAt) / 1000
615
+ const frame = (animation.ip || 0) + ((elapsed * frameRate) % durationFrames)
616
+ applyFrame(frame)
617
+ window.requestAnimationFrame(tick)
618
+ }
619
+ window.requestAnimationFrame(tick)
620
+ }
621
+
622
+ function renderAssetLayers(parent, layers) {
623
+ for (const layer of [...layers].reverse()) {
624
+ const shape = (layer.shapes || []).find(item => item.ty === 'sh')
625
+ const fill = (layer.shapes || []).find(item => item.ty === 'fl')
626
+ if (!shape || !fill) continue
627
+ const path = svgEl('path')
628
+ path.setAttribute('d', shapePath(shape.ks && shape.ks.k))
629
+ path.setAttribute('fill', rgb(fill.c && fill.c.k))
630
+ path.setAttribute('fill-opacity', String(valueOf(fill.o) / 100))
631
+
632
+ const group = svgEl('g')
633
+ group.setAttribute('transform', layerTransform(layer, 0))
634
+ group.setAttribute('opacity', String(valueOf(layer.ks && layer.ks.o) / 100))
635
+ group.appendChild(path)
636
+ parent.appendChild(group)
637
+ }
638
+ }
639
+
640
+ function svgEl(name) {
641
+ return document.createElementNS('http://www.w3.org/2000/svg', name)
642
+ }
643
+
644
+ function shapePath(shape) {
645
+ if (!shape || !Array.isArray(shape.v) || shape.v.length === 0) return ''
646
+ const parts = [`M ${fmt(shape.v[0][0])} ${fmt(shape.v[0][1])}`]
647
+ for (let i = 1; i < shape.v.length; i += 1) {
648
+ addSegment(parts, shape, i - 1, i)
649
+ }
650
+ if (shape.c) {
651
+ addSegment(parts, shape, shape.v.length - 1, 0)
652
+ parts.push('Z')
653
+ }
654
+ return parts.join(' ')
655
+ }
656
+
657
+ function addSegment(parts, shape, fromIndex, toIndex) {
658
+ const from = shape.v[fromIndex]
659
+ const to = shape.v[toIndex]
660
+ const out = shape.o && shape.o[fromIndex] ? shape.o[fromIndex] : [0, 0]
661
+ const inn = shape.i && shape.i[toIndex] ? shape.i[toIndex] : [0, 0]
662
+ const c1 = [from[0] + out[0], from[1] + out[1]]
663
+ const c2 = [to[0] + inn[0], to[1] + inn[1]]
664
+ if (samePoint(c1, from) && samePoint(c2, to)) {
665
+ parts.push(`L ${fmt(to[0])} ${fmt(to[1])}`)
666
+ } else {
667
+ parts.push(`C ${fmt(c1[0])} ${fmt(c1[1])} ${fmt(c2[0])} ${fmt(c2[1])} ${fmt(to[0])} ${fmt(to[1])}`)
668
+ }
669
+ }
670
+
671
+ function layerTransform(layer, frame) {
672
+ const ks = layer.ks || {}
673
+ const anchor = valueOf(ks.a, frame)
674
+ const position = valueOf(ks.p, frame)
675
+ const scale = valueOf(ks.s, frame)
676
+ const rotation = valueOf(ks.r, frame)
677
+ const sx = Array.isArray(scale) ? scale[0] / 100 : 1
678
+ const sy = Array.isArray(scale) ? scale[1] / 100 : sx
679
+ return [
680
+ `translate(${fmt(position[0])} ${fmt(position[1])})`,
681
+ `rotate(${fmt(rotation || 0)})`,
682
+ `scale(${fmt(sx)} ${fmt(sy)})`,
683
+ `translate(${-fmt(anchor[0])} ${-fmt(anchor[1])})`,
684
+ ].join(' ')
685
+ }
686
+
687
+ function valueOf(prop, frame = 0) {
688
+ if (!prop) return [0, 0]
689
+ if (prop.a === 1 && Array.isArray(prop.k)) return keyedValue(prop.k, frame)
690
+ return prop.k
691
+ }
692
+
693
+ function keyedValue(keys, frame) {
694
+ if (keys.length === 0) return [0, 0]
695
+ for (let i = 0; i < keys.length - 1; i += 1) {
696
+ const current = keys[i]
697
+ const next = keys[i + 1]
698
+ if (frame < current.t || frame > next.t) continue
699
+ const span = Math.max(1, next.t - current.t)
700
+ const eased = ease((frame - current.t) / span)
701
+ return mix(current.s, next.s, eased)
702
+ }
703
+ return keys[keys.length - 1].s
704
+ }
705
+
706
+ function mix(from, to, amount) {
707
+ return from.map((value, index) => value + ((to[index] || 0) - value) * amount)
708
+ }
709
+
710
+ function ease(value) {
711
+ const x = Math.max(0, Math.min(1, value))
712
+ return x * x * (3 - (2 * x))
713
+ }
714
+
715
+ function rgb(value) {
716
+ if (!Array.isArray(value)) return '#ffffff'
717
+ return `rgb(${Math.round(value[0] * 255)}, ${Math.round(value[1] * 255)}, ${Math.round(value[2] * 255)})`
718
+ }
719
+
720
+ function samePoint(a, b) {
721
+ return Math.abs(a[0] - b[0]) < 0.0001 && Math.abs(a[1] - b[1]) < 0.0001
722
+ }
723
+
724
+ function fmt(value) {
725
+ return Number.parseFloat(Number(value || 0).toFixed(3))
726
+ }
727
+
728
+ function renderSidebar() {
729
+ const runsWithAgents = runs.filter(r => r.status !== 'ended' && r.terminals.length > 0)
730
+ const agentCount = runsWithAgents.reduce((sum, run) => sum + run.terminals.length, 0)
731
+ el.sidebarCount.textContent = String(agentCount)
732
+ el.sidebarEmpty.hidden = runsWithAgents.length > 0
733
+ if (!el.sidebarEmpty.hidden) {
734
+ document.querySelector('.empty-title').textContent = history.length > 0 ? t('web.noActiveAgents') : t('web.noAgents')
735
+ document.querySelector('.empty-body').textContent = history.length > 0 ? t('web.noActiveAgentsBody') : t('web.noAgentsBody')
736
+ }
737
+ el.sidebarList.innerHTML = ''
738
+
739
+ for (const run of runsWithAgents) {
740
+ const group = document.createElement('div')
741
+ group.className = 'run-group'
742
+ const rootColor = run.terminals[0] ? run.terminals[0].color : '#7eb8f5'
743
+ group.style.setProperty('--run-color', rootColor)
744
+
745
+ const head = document.createElement('div')
746
+ head.className = 'run-head'
747
+ const headBody = document.createElement('div')
748
+ headBody.className = 'run-head-body'
749
+ const name = document.createElement('span')
750
+ name.className = 'run-name'
751
+ name.textContent = run.name
752
+ name.title = `${run.name} · ${run.working_dir}`
753
+ headBody.appendChild(name)
754
+ const meta = document.createElement('span')
755
+ meta.className = 'run-meta'
756
+ meta.textContent = `${statusLabel(run.status)} · ${modeLabel(run.mode)} · ${agentCountLabel(run.terminals.length)}`
757
+ headBody.appendChild(meta)
758
+ head.appendChild(headBody)
759
+
760
+ const actions = document.createElement('div')
761
+ actions.className = 'run-actions'
762
+ if (run.status === 'running') {
763
+ const add = document.createElement('button')
764
+ add.className = 'run-action'
765
+ add.type = 'button'
766
+ add.textContent = t('web.addAgent')
767
+ add.title = t('web.addAgentTitle', { name: run.name })
768
+ add.addEventListener('click', () => openAgentDialog(run.id))
769
+ actions.appendChild(add)
770
+ }
771
+ if (run.canStop) {
772
+ const stop = document.createElement('button')
773
+ stop.className = 'run-stop'
774
+ stop.type = 'button'
775
+ stop.textContent = t('web.stop')
776
+ stop.title = t('web.stopRunTitle', { name: run.name })
777
+ stop.addEventListener('click', () => stopRun(run))
778
+ actions.appendChild(stop)
779
+ }
780
+ if (run.canDelete) {
781
+ const del = document.createElement('button')
782
+ del.className = 'run-delete'
783
+ del.type = 'button'
784
+ del.textContent = t('common.delete')
785
+ del.title = t('web.deleteRunTitle', { name: run.name })
786
+ del.addEventListener('click', () => deleteRun(run))
787
+ actions.appendChild(del)
788
+ }
789
+ if (actions.childElementCount > 0) head.appendChild(actions)
790
+ group.appendChild(head)
791
+
792
+ for (const agent of run.terminals) group.appendChild(renderCard(run, agent))
793
+ el.sidebarList.appendChild(group)
794
+ }
795
+
796
+ if (history.length > 0) {
797
+ const group = document.createElement('div')
798
+ group.className = 'history-group'
799
+
800
+ const head = document.createElement('div')
801
+ head.className = 'history-head'
802
+ const title = document.createElement('span')
803
+ title.className = 'history-title'
804
+ title.textContent = t('web.history')
805
+ head.appendChild(title)
806
+ const count = document.createElement('span')
807
+ count.className = 'history-count'
808
+ count.textContent = `${history.length} ${t('web.archived')}`
809
+ head.appendChild(count)
810
+ group.appendChild(head)
811
+
812
+ for (const record of history) group.appendChild(renderHistoryRecord(record))
813
+ el.sidebarList.appendChild(group)
814
+ }
815
+
816
+ updateStageActions()
817
+ updateCreateActions()
818
+ }
819
+
820
+ function renderHistoryRecord(record) {
821
+ const item = document.createElement('div')
822
+ item.className = 'history-card'
823
+ item.dataset.status = record.status
824
+ if (record.root_provider) item.style.setProperty('--run-color', providerColor(record.root_provider))
825
+
826
+ const body = document.createElement('div')
827
+ body.className = 'history-body'
828
+ const name = document.createElement('span')
829
+ name.className = 'history-name'
830
+ name.textContent = record.name
831
+ name.title = `${record.name} · ${record.working_dir}`
832
+ body.appendChild(name)
833
+ const meta = document.createElement('span')
834
+ meta.className = 'history-meta'
835
+ const provider = record.root_provider_label || t('web.noRootProvider')
836
+ meta.textContent = `${modeLabel(record.mode)} · ${statusLabel(record.status)} · ${agentCountLabel(record.agent_count)} · ${provider}`
837
+ body.appendChild(meta)
838
+ item.appendChild(body)
839
+
840
+ const date = document.createElement('span')
841
+ date.className = 'history-date'
842
+ date.textContent = shortIso(record.ended_at || record.archived_at)
843
+ item.appendChild(date)
844
+ const del = document.createElement('button')
845
+ del.className = 'history-delete'
846
+ del.type = 'button'
847
+ del.textContent = t('common.delete')
848
+ del.title = t('web.deleteHistoryTitle', { name: record.name })
849
+ del.addEventListener('click', () => deleteHistoryRecord(record))
850
+ item.appendChild(del)
851
+ return item
852
+ }
853
+
854
+ function renderCard(run, agent) {
855
+ const card = document.createElement('div')
856
+ card.className = 'card' + (agent.status === 'ended' ? ' is-ended' : '')
857
+ card.setAttribute('aria-selected', String(agent.id === selectedId))
858
+ card.dataset.status = agent.status
859
+ card.dataset.provider = agent.provider
860
+ card.dataset.attachable = String(agent.canAttach)
861
+ card.style.setProperty('--agent-color', agent.color)
862
+
863
+ const open = document.createElement('button')
864
+ open.className = 'card-main'
865
+ open.type = 'button'
866
+
867
+ const avatar = document.createElement('span')
868
+ avatar.className = 'avatar'
869
+ avatar.textContent = agent.monogram
870
+ open.appendChild(avatar)
871
+
872
+ const body = document.createElement('span')
873
+ body.className = 'card-body'
874
+ const nm = document.createElement('span')
875
+ nm.className = 'card-name'
876
+ nm.textContent = agent.nickname
877
+ const meta = document.createElement('span')
878
+ meta.className = 'card-meta'
879
+ const prov = document.createElement('span')
880
+ prov.className = 'card-provider'
881
+ prov.textContent = agent.provider_label || agent.provider
882
+ prov.style.setProperty('--provider-color', agent.color)
883
+ meta.appendChild(prov)
884
+ meta.append(document.createTextNode(` · ${roleLabel(agent.role)}`))
885
+ if (agent.model) meta.append(document.createTextNode(` · ${agent.model}`))
886
+ body.appendChild(nm)
887
+ body.appendChild(meta)
888
+ open.appendChild(body)
889
+ card.appendChild(open)
890
+
891
+ const tail = document.createElement('span')
892
+ tail.className = 'card-tail'
893
+ const dot = document.createElement('span')
894
+ dot.className = 'dot'
895
+ dot.dataset.status = agent.status
896
+ tail.appendChild(dot)
897
+ const status = document.createElement('span')
898
+ status.className = 'card-status'
899
+ status.textContent = statusLabel(agent.status)
900
+ tail.appendChild(status)
901
+ const availability = document.createElement('span')
902
+ availability.className = 'card-open-hint'
903
+ availability.textContent = agent.canAttach ? t('web.openAgent') : disabledReasonLabel(agent)
904
+ availability.title = agent.canAttach
905
+ ? t('web.openAgentTitle', { name: agent.nickname })
906
+ : disabledReasonLabel(agent)
907
+ tail.appendChild(availability)
908
+ if (agent.canKill || agent.canDelete) {
909
+ const lifecycle = document.createElement('button')
910
+ const isDelete = agent.canDelete
911
+ lifecycle.className = 'card-agent-action'
912
+ lifecycle.dataset.kind = isDelete ? 'delete' : 'stop'
913
+ lifecycle.type = 'button'
914
+ lifecycle.setAttribute('aria-label', t(isDelete ? 'web.deleteAgentTitle' : 'web.stopAgentTitle', { name: agent.nickname }))
915
+ lifecycle.title = t(isDelete ? 'web.deleteAgentTitle' : 'web.stopAgentTitle', { name: agent.nickname })
916
+ lifecycle.textContent = isDelete ? t('common.delete') : t('web.stop')
917
+ lifecycle.addEventListener('click', () => isDelete ? deleteAgentRecord(agent) : stopAgent(agent))
918
+ tail.appendChild(lifecycle)
919
+ }
920
+ card.appendChild(tail)
921
+
922
+ if (agent.canAttach) {
923
+ open.title = t('web.openAgentTitle', { name: agent.nickname })
924
+ open.addEventListener('click', () => attach(agent.id))
925
+ } else {
926
+ open.disabled = true
927
+ card.classList.add('is-disabled')
928
+ open.title = disabledReasonLabel(agent)
929
+ }
930
+ return card
931
+ }
932
+
933
+ function disabledReasonLabel(agent) {
934
+ if (!agent) return t('web.unavailable')
935
+ if (agent.status === 'ended' || agent.disabledReason === 'agent has ended') return t('web.agentEnded')
936
+ if (agent.disabledReason === 'run tmux session is unavailable') return t('web.noLiveTmuxTarget')
937
+ if (agent.disabledReason === 'agent has no tmux window' || agent.headless || !agent.hasWindow) return t('web.noAgentWindow')
938
+ return agent.disabledReason || t('web.unavailable')
939
+ }
940
+
941
+ function setStageStatus(kind, text) {
942
+ if (!kind) { el.stageStatus.hidden = true; return }
943
+ el.stageStatus.hidden = false
944
+ el.stageStatus.dataset.kind = kind
945
+ el.stageStatus.textContent = text
946
+ }
947
+
948
+ function updateStageActions() {
949
+ const selected = selectedId ? findAgent(selectedId) : null
950
+ const canAdd = !!selected && selected.run.status === 'running'
951
+ el.stageAddAgent.hidden = !canAdd
952
+ if (canAdd) el.stageAddAgent.title = t('web.addAgentTitle', { name: selected.run.name })
953
+ }
954
+
955
+ function updateCreateActions() {
956
+ const hasRunningRun = runningRuns().length > 0
957
+ el.newAgentBtn.disabled = !hasRunningRun
958
+ el.newAgentBtn.title = hasRunningRun ? t('web.addAgentActiveTitle') : t('web.createRunFirstTitle')
959
+ el.overlayNewAgent.hidden = !hasRunningRun
960
+ el.createAgentTab.disabled = !hasRunningRun
961
+ updateCreateSubmitState()
962
+ }
963
+
964
+ function updateCreateSubmitState() {
965
+ const validRunTarget = createContext.kind !== 'agent' || !!selectedRunForCreate()
966
+ el.newSubmit.disabled = createSubmitting || !selectedProviderAvailable() || !validRunTarget
967
+ }
968
+
969
+ // --- agent attach ---------------------------------------------------------
970
+
971
+ function disposeSession() {
972
+ if (!session) return
973
+ try { session.observer.disconnect() } catch { /* not observing */ }
974
+ try { session.ws.close() } catch { /* already closed */ }
975
+ try { session.term.dispose() } catch { /* already disposed */ }
976
+ session = null
977
+ }
978
+
979
+ function attach(id) {
980
+ if (session && session.id === id) return
981
+ const found = findAgent(id)
982
+ if (found && !found.terminal.canAttach) {
983
+ showUnavailableAgent(id, found)
984
+ return
985
+ }
986
+ disposeSession()
987
+
988
+ selectedId = id
989
+ renderSidebar()
990
+ el.overlay.hidden = true
991
+ el.stageTitle.textContent = found ? found.terminal.nickname : id
992
+ el.stageSub.textContent = found ? `${modeLabel(found.run.mode)} · ${found.terminal.provider_label || found.terminal.provider} · ${found.run.name}` : ''
993
+ if (found) el.termWrap.style.setProperty('--agent-color', found.terminal.color)
994
+ setStageStatus('connecting', t('web.connecting'))
995
+
996
+ const term = new Terminal({
997
+ fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
998
+ fontSize: 13,
999
+ cursorBlink: true,
1000
+ theme: TERM_THEME,
1001
+ scrollback: 5000,
1002
+ })
1003
+ const fit = new FitAddon.FitAddon()
1004
+ term.loadAddon(fit)
1005
+ el.termHost.innerHTML = ''
1006
+ term.open(el.termHost)
1007
+ fit.fit()
1008
+
1009
+ const proto = location.protocol === 'https:' ? 'wss' : 'ws'
1010
+ const ws = new WebSocket(`${proto}://${location.host}/term?id=${encodeURIComponent(id)}`)
1011
+
1012
+ const sendResize = () => {
1013
+ if (ws.readyState !== WebSocket.OPEN) return
1014
+ ws.send(JSON.stringify({ t: 'r', c: term.cols, r: term.rows }))
1015
+ }
1016
+ const observer = new ResizeObserver(() => {
1017
+ try { fit.fit() } catch { /* host detached */ }
1018
+ sendResize()
1019
+ })
1020
+ observer.observe(el.termHost)
1021
+
1022
+ session = { id, ws, term, fit, observer }
1023
+ let finalState = null
1024
+
1025
+ ws.onopen = () => { setStageStatus('live', t('web.live')); fit.fit(); sendResize(); term.focus() }
1026
+ ws.onmessage = (e) => {
1027
+ let f
1028
+ try { f = JSON.parse(e.data) } catch { return }
1029
+ if (f.t === 'o') term.write(f.d)
1030
+ else if (f.t === 'x') { finalState = 'exited'; setStageStatus('closed', t('web.exited')); term.write(`\r\n\x1b[2m[${t('web.exited')} ${f.code}]\x1b[0m\r\n`) }
1031
+ else if (f.t === 'e') { finalState = 'error'; setStageStatus('error', t('web.error')); term.write(`\r\n\x1b[31m[${f.m}]\x1b[0m\r\n`) }
1032
+ }
1033
+ ws.onerror = () => { finalState = 'error'; setStageStatus('error', t('web.connectionError')) }
1034
+ ws.onclose = () => { if (session && session.id === id && !finalState) setStageStatus('closed', t('web.disconnected')) }
1035
+ term.onData((d) => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ t: 'i', d })) })
1036
+ }
1037
+
1038
+ function showUnavailableAgent(id, found) {
1039
+ disposeSession()
1040
+ selectedId = id
1041
+ renderSidebar()
1042
+ el.termHost.innerHTML = ''
1043
+ el.overlay.hidden = false
1044
+ if (!found) {
1045
+ showOverlay()
1046
+ return
1047
+ }
1048
+ el.stageTitle.textContent = found.terminal.nickname
1049
+ el.stageSub.textContent = `${modeLabel(found.run.mode)} · ${found.terminal.provider_label || found.terminal.provider} · ${found.run.name}`
1050
+ el.termWrap.style.setProperty('--agent-color', found.terminal.color)
1051
+ setOverlayCopy(disabledReasonLabel(found.terminal), t('web.unavailableBody'))
1052
+ setStageStatus('closed', disabledReasonLabel(found.terminal))
1053
+ updateStageActions()
1054
+ }
1055
+
1056
+ function reconcileSelectedAgent() {
1057
+ if (!selectedId) return
1058
+ const found = findAgent(selectedId)
1059
+ if (!found) {
1060
+ disposeSession()
1061
+ showOverlay()
1062
+ return
1063
+ }
1064
+ if (!found.terminal.canAttach) {
1065
+ showUnavailableAgent(selectedId, found)
1066
+ }
1067
+ }
1068
+
1069
+ // --- actions --------------------------------------------------------------
1070
+
1071
+ async function stopAgent(agent) {
1072
+ if (!confirm(t('web.stopAgentConfirm', { name: agent.nickname }))) return
1073
+ const selectedWasAgent = agent.id === (session ? session.id : selectedId)
1074
+ try {
1075
+ await api('POST', `/api/terminals/${encodeURIComponent(agent.id)}/kill`, { confirm: true })
1076
+ markAgentEnded(agent.id)
1077
+ if (selectedWasAgent) { disposeSession(); showOverlay() }
1078
+ else renderSidebar()
1079
+ await refreshState()
1080
+ if (selectedWasAgent) showOverlay()
1081
+ } catch (err) {
1082
+ alert(t('web.stopAgentError', { message: err.message }))
1083
+ }
1084
+ }
1085
+
1086
+ async function stopRun(run) {
1087
+ if (!confirm(t('web.stopRunConfirm', { name: run.name }))) return
1088
+ const selectedWasInRun = run.terminals.some(agent => agent.id === (session ? session.id : selectedId))
1089
+ try {
1090
+ await api('POST', `/api/runs/${encodeURIComponent(run.id)}/stop`, { confirm: true })
1091
+ markRunStopped(run.id)
1092
+ if (selectedWasInRun) { disposeSession(); showOverlay() }
1093
+ else renderSidebar()
1094
+ await refreshState()
1095
+ if (selectedWasInRun) showOverlay()
1096
+ } catch (err) {
1097
+ alert(t('web.stopRunError', { message: err.message }))
1098
+ }
1099
+ }
1100
+
1101
+ async function deleteRun(run) {
1102
+ if (!confirm(t('web.deleteRunConfirm', { name: run.name }))) return
1103
+ const selectedWasInRun = run.terminals.some(agent => agent.id === (session ? session.id : selectedId))
1104
+ try {
1105
+ await api('POST', `/api/runs/${encodeURIComponent(run.id)}/delete`, { confirm: true })
1106
+ runs = runs.filter(item => item.id !== run.id)
1107
+ if (selectedWasInRun) { disposeSession(); showOverlay() }
1108
+ else renderSidebar()
1109
+ await refreshState()
1110
+ if (selectedWasInRun) showOverlay()
1111
+ } catch (err) {
1112
+ alert(t('web.deleteRunError', { message: err.message }))
1113
+ }
1114
+ }
1115
+
1116
+ async function deleteAgentRecord(agent) {
1117
+ if (!confirm(t('web.deleteAgentConfirm', { name: agent.nickname }))) return
1118
+ const selectedWasAgent = agent.id === (session ? session.id : selectedId)
1119
+ try {
1120
+ await api('POST', `/api/terminals/${encodeURIComponent(agent.id)}/delete`, { confirm: true })
1121
+ for (const run of runs) run.terminals = run.terminals.filter(item => item.id !== agent.id)
1122
+ if (selectedWasAgent) { disposeSession(); showOverlay() }
1123
+ else renderSidebar()
1124
+ await refreshState()
1125
+ if (selectedWasAgent) showOverlay()
1126
+ } catch (err) {
1127
+ alert(t('web.deleteAgentError', { message: err.message }))
1128
+ }
1129
+ }
1130
+
1131
+ async function deleteHistoryRecord(record) {
1132
+ if (!confirm(t('web.deleteHistoryConfirm', { name: record.name }))) return
1133
+ try {
1134
+ await api('POST', `/api/history/${encodeURIComponent(record.id)}/delete`, { confirm: true })
1135
+ history = history.filter(item => item.id !== record.id)
1136
+ renderSidebar()
1137
+ await refreshState()
1138
+ } catch (err) {
1139
+ alert(t('web.deleteHistoryError', { message: err.message }))
1140
+ }
1141
+ }
1142
+
1143
+ function markAgentEnded(agentId) {
1144
+ const found = findAgent(agentId)
1145
+ if (!found) return
1146
+ found.terminal.status = 'ended'
1147
+ found.terminal.canAttach = false
1148
+ found.terminal.canKill = false
1149
+ found.terminal.canDelete = true
1150
+ found.terminal.disabledReason = t('web.agentEnded')
1151
+ if (!found.run.terminals.some(agent => agent.status !== 'ended')) {
1152
+ found.run.status = 'ended'
1153
+ found.run.canStop = false
1154
+ found.run.canDelete = true
1155
+ }
1156
+ }
1157
+
1158
+ function markRunStopped(runId) {
1159
+ const run = runs.find(item => item.id === runId)
1160
+ if (!run) return
1161
+ run.status = 'ended'
1162
+ run.canStop = false
1163
+ run.canDelete = true
1164
+ for (const agent of run.terminals) {
1165
+ agent.status = 'ended'
1166
+ agent.canAttach = false
1167
+ agent.canKill = false
1168
+ agent.canDelete = true
1169
+ agent.disabledReason = t('web.agentEnded')
1170
+ }
1171
+ }
1172
+
1173
+ function showOverlay() {
1174
+ selectedId = null
1175
+ el.overlay.hidden = false
1176
+ setOverlayCopy(t('web.noAgentAttached'), t('web.overlayBody'))
1177
+ el.termWrap.style.removeProperty('--agent-color')
1178
+ el.stageTitle.textContent = t('web.noAgentSelected')
1179
+ el.stageSub.textContent = t('web.noAgentSub')
1180
+ setStageStatus(null)
1181
+ updateStageActions()
1182
+ renderSidebar()
1183
+ }
1184
+
1185
+ function setOverlayCopy(title, body) {
1186
+ setText('.overlay-title', title)
1187
+ setText('.overlay-body', body)
1188
+ }
1189
+
1190
+ // --- create dialog --------------------------------------------------------
1191
+
1192
+ function resetCreateForm() {
1193
+ el.newError.hidden = true
1194
+ el.fNickname.value = ''
1195
+ el.fRunName.value = ''
1196
+ el.fModel.value = ''
1197
+ el.fPermissions.value = 'ask'
1198
+ el.fPrompt.value = ''
1199
+ el.fCwd.value = ''
1200
+ updatePermissionSelection()
1201
+ }
1202
+
1203
+ function openRunDialog() {
1204
+ createContext = { kind: 'run', runId: '' }
1205
+ resetCreateForm()
1206
+ syncCreateFields()
1207
+ el.dialog.showModal()
1208
+ el.fRunName.focus()
1209
+ }
1210
+
1211
+ function openAgentDialog(runId) {
1212
+ const targetRunId = runId || preferredRunId()
1213
+ const run = runs.find(item => item.id === targetRunId && item.status === 'running')
1214
+ if (!run && runningRuns().length === 0) {
1215
+ openRunDialog()
1216
+ showDialogError(t('web.createRunFirst'))
1217
+ return
1218
+ }
1219
+ if (!run) {
1220
+ alert(t('web.runInactive'))
1221
+ return
1222
+ }
1223
+ createContext = { kind: 'agent', runId: run.id }
1224
+ resetCreateForm()
1225
+ syncCreateFields()
1226
+ el.dialog.showModal()
1227
+ el.fAgentRun.focus()
1228
+ }
1229
+
1230
+ function populateAgentRunSelect(preferred) {
1231
+ const current = preferred || el.fAgentRun.value || preferredRunId()
1232
+ el.fAgentRun.innerHTML = ''
1233
+ for (const run of runningRuns()) {
1234
+ const opt = document.createElement('option')
1235
+ opt.value = run.id
1236
+ const count = agentCountLabel(run.terminals.length)
1237
+ opt.textContent = `${run.name} · ${modeLabel(run.mode)} · ${count}`
1238
+ el.fAgentRun.appendChild(opt)
1239
+ }
1240
+ const hasCurrent = [...el.fAgentRun.options].some(opt => opt.value === current)
1241
+ if (hasCurrent) el.fAgentRun.value = current
1242
+ else if (el.fAgentRun.options.length > 0) el.fAgentRun.selectedIndex = 0
1243
+ createContext.runId = el.fAgentRun.value || ''
1244
+ }
1245
+
1246
+ function selectedRunForCreate() {
1247
+ if (createContext.kind !== 'agent') return null
1248
+ return runs.find(item => item.id === createContext.runId && item.status === 'running') || null
1249
+ }
1250
+
1251
+ function selectedCreateMode() {
1252
+ const run = selectedRunForCreate()
1253
+ if (run) return run.mode || 'spawner'
1254
+ return prebetaOrchestrator && el.fMode.value === 'orchestrator' ? 'orchestrator' : 'spawner'
1255
+ }
1256
+
1257
+ function syncCreateFields() {
1258
+ const addingToRun = createContext.kind === 'agent'
1259
+ if (addingToRun) populateAgentRunSelect(createContext.runId)
1260
+ const run = selectedRunForCreate()
1261
+ const mode = selectedCreateMode()
1262
+ el.dialog.dataset.intent = addingToRun ? 'agent' : 'run'
1263
+ el.dialogTitle.textContent = addingToRun ? t('web.addAgent') : t('web.newRun')
1264
+ el.dialogSubtitle.textContent = addingToRun
1265
+ ? t('web.addAgentSubtitle')
1266
+ : t('web.newRunSubtitle')
1267
+ el.newSubmit.textContent = addingToRun ? t('web.addAgent') : t('web.createRun')
1268
+ el.createRunTab.setAttribute('aria-selected', String(!addingToRun))
1269
+ el.createAgentTab.setAttribute('aria-selected', String(addingToRun))
1270
+ el.agentRunField.hidden = !addingToRun
1271
+ el.runNameField.hidden = addingToRun
1272
+ el.modeField.hidden = !prebetaOrchestrator || addingToRun
1273
+ el.cwdField.hidden = addingToRun
1274
+ el.targetRunNote.hidden = !addingToRun
1275
+ if (addingToRun && run) {
1276
+ const count = agentCountLabel(run.terminals.length)
1277
+ el.targetRunNote.textContent = t('web.addingTo', { name: run.name, mode: modeLabel(run.mode), count })
1278
+ } else {
1279
+ el.targetRunNote.textContent = ''
1280
+ }
1281
+ el.fNickname.placeholder = addingToRun ? 'reviewer' : 'lead'
1282
+ el.fPrompt.placeholder = mode === 'orchestrator'
1283
+ ? t('web.orchestratorPromptPlaceholder')
1284
+ : t('web.promptPlaceholder')
1285
+ renderProviders()
1286
+ updatePermissionSelection()
1287
+ updateCreateActions()
1288
+ if (addingToRun && !run) {
1289
+ showDialogError(t('web.runInactive'))
1290
+ return
1291
+ }
1292
+ if (el.dialog.open && !selectedProviderAvailable()) {
1293
+ showDialogError(t('web.noProvider'))
1294
+ } else if (el.newError.textContent === t('web.noProvider')) {
1295
+ el.newError.hidden = true
1296
+ }
1297
+ updateCreateSubmitState()
1298
+ }
1299
+
1300
+ function reconcileCreateDialog() {
1301
+ if (el.dialog.open && createContext.kind === 'agent') syncCreateFields()
1302
+ }
1303
+
1304
+ async function submitNew(ev) {
1305
+ ev.preventDefault()
1306
+ el.newError.hidden = true
1307
+ const provider = el.fProvider.value
1308
+ if (!selectedProviderAvailable()) {
1309
+ showDialogError(t('web.noProvider'))
1310
+ return
1311
+ }
1312
+ const run = selectedRunForCreate()
1313
+ if (createContext.kind === 'agent' && !run) {
1314
+ showDialogError(t('web.runInactive'))
1315
+ return
1316
+ }
1317
+ const payload = {
1318
+ provider,
1319
+ model: el.fModel.value,
1320
+ permissions: el.fPermissions.value,
1321
+ nickname: el.fNickname.value.trim(),
1322
+ prompt: el.fPrompt.value,
1323
+ run_id: createContext.kind === 'agent' ? createContext.runId : undefined,
1324
+ run_name: createContext.kind === 'run' ? el.fRunName.value.trim() || undefined : undefined,
1325
+ working_dir: createContext.kind === 'run' ? el.fCwd.value.trim() || undefined : undefined,
1326
+ mode: createContext.kind === 'run' ? selectedCreateMode() : undefined,
1327
+ }
1328
+ createSubmitting = true
1329
+ updateCreateSubmitState()
1330
+ try {
1331
+ const created = await api('POST', '/api/terminals', payload)
1332
+ await refreshState()
1333
+ el.dialog.close()
1334
+ if (created && created.id) {
1335
+ selectedId = created.id
1336
+ renderSidebar()
1337
+ setTimeout(async () => {
1338
+ try { await refreshState() } catch { /* keep local state */ }
1339
+ const found = findAgent(created.id)
1340
+ if (found && found.terminal.canAttach) attach(created.id)
1341
+ else showUnavailableAgent(created.id, found)
1342
+ }, 400)
1343
+ }
1344
+ } catch (err) {
1345
+ el.newError.textContent = err.message
1346
+ el.newError.hidden = false
1347
+ } finally {
1348
+ createSubmitting = false
1349
+ updateCreateSubmitState()
1350
+ }
1351
+ }
1352
+
1353
+ // --- wire up --------------------------------------------------------------
1354
+
1355
+ el.newAgentBtn.addEventListener('click', () => openAgentDialog(preferredRunId()))
1356
+ el.newRunBtn.addEventListener('click', openRunDialog)
1357
+ el.emptyNewRun.addEventListener('click', openRunDialog)
1358
+ el.overlayNewRun.addEventListener('click', openRunDialog)
1359
+ el.overlayNewAgent.addEventListener('click', () => openAgentDialog(preferredRunId()))
1360
+ el.stageAddAgent.addEventListener('click', () => {
1361
+ const selected = selectedId ? findAgent(selectedId) : null
1362
+ if (selected) openAgentDialog(selected.run.id)
1363
+ })
1364
+ el.createRunTab.addEventListener('click', () => {
1365
+ createContext = { kind: 'run', runId: '' }
1366
+ syncCreateFields()
1367
+ el.fRunName.focus()
1368
+ })
1369
+ el.createAgentTab.addEventListener('click', () => {
1370
+ if (runningRuns().length === 0) return
1371
+ createContext = { kind: 'agent', runId: preferredRunId() }
1372
+ syncCreateFields()
1373
+ el.fAgentRun.focus()
1374
+ })
1375
+ el.newCancel.addEventListener('click', () => el.dialog.close())
1376
+ el.fAgentRun.addEventListener('change', () => {
1377
+ createContext.runId = el.fAgentRun.value
1378
+ syncCreateFields()
1379
+ })
1380
+ el.fMode.addEventListener('change', syncCreateFields)
1381
+ el.fProvider.addEventListener('change', () => {
1382
+ updateProviderSelection()
1383
+ renderModels()
1384
+ })
1385
+ el.languageSelect.addEventListener('change', async () => {
1386
+ try {
1387
+ const payload = await api('POST', '/api/language', { language: el.languageSelect.value })
1388
+ applyLanguage(payload)
1389
+ await refreshState()
1390
+ } catch (err) {
1391
+ alert(err.message)
1392
+ el.languageSelect.value = language
1393
+ }
1394
+ })
1395
+ el.fPermissions.addEventListener('change', updatePermissionSelection)
1396
+ for (const option of el.permissionGrid.querySelectorAll('.permission-option')) {
1397
+ option.addEventListener('click', () => {
1398
+ selectPermission(option.dataset.permission)
1399
+ })
1400
+ option.addEventListener('keydown', handlePermissionKeydown)
1401
+ }
1402
+ el.form.addEventListener('submit', submitNew)
1403
+
1404
+ function modeLabel(mode) {
1405
+ return mode === 'orchestrator' ? t('web.orchestrator') : t('web.spawner')
1406
+ }
1407
+
1408
+ function roleLabel(role) {
1409
+ return role === 'root' ? t('web.roleRoot') : t('web.roleWorker')
1410
+ }
1411
+
1412
+ function statusLabel(status) {
1413
+ if (status === 'queued') return t('web.statusQueued')
1414
+ if (status === 'working') return t('web.statusWorking')
1415
+ if (status === 'done') return t('web.statusDone')
1416
+ if (status === 'failed') return t('web.statusFailed')
1417
+ if (status === 'blocked') return t('web.statusBlocked')
1418
+ if (status === 'ended') return t('web.statusEnded')
1419
+ if (status === 'stale') return t('web.statusStale')
1420
+ if (status === 'running') return t('web.statusRunning')
1421
+ return status
1422
+ }
1423
+
1424
+ function shortIso(value) {
1425
+ if (!value) return t('web.unknown')
1426
+ return `${String(value).replace('T', ' ').slice(0, 16)}Z`
1427
+ }
1428
+
1429
+ initBrandDuck()
1430
+ loadState().catch((err) => {
1431
+ el.sidebarEmpty.hidden = false
1432
+ el.sidebarEmpty.querySelector('.empty-body').textContent = `Could not load state: ${err.message}`
1433
+ })
1434
+ subscribe()
1435
+ })()