@xiangyixie/dsh-superagent 0.9.3 → 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.
package/lib/watch.js CHANGED
@@ -5,6 +5,11 @@
5
5
  * files the host writes and draws one line per run, so it works from another
6
6
  * process, survives a host restart, and never needs IPC.
7
7
  *
8
+ * Two questions matter more than the raw numbers: who is running beside whom,
9
+ * and who is waiting on what. Overlapping runs therefore share a coloured
10
+ * gutter label, and a waiting row leads with its cause (a full slot, a full
11
+ * worker pool, or a retry backoff) before the ordinary activity phrase.
12
+ *
8
13
  * There is no dependency here on purpose — the package is a zero-dependency
9
14
  * plugin, and a monitoring aid is not a reason to pull in an ANSI toolkit. The
10
15
  * escape sequences used are the small, stable subset: alternate screen, hide
@@ -12,18 +17,17 @@
12
17
  *
13
18
  * @module dsh-superagent/watch
14
19
  */
20
+ import { formatMoney } from './cost.js'
15
21
  import { ACTIVE_STATUSES, createStore, resolveStateRoot } from './store.js'
16
22
 
17
23
  /** Refresh cadence. A run file is small, so one read per second is cheap. */
18
24
  export const DEFAULT_INTERVAL_MS = 1000
19
25
 
20
- const COLUMNS = {
21
- id: 20,
22
- status: 12,
23
- calls: 8,
24
- elapsed: 7,
25
- parent: 9,
26
- }
26
+ /** Width of the concurrency gutter, including its trailing space. */
27
+ const GUTTER = 3
28
+
29
+ /** Gutter colours, one per overlapping group, cycled when there are many. */
30
+ const GROUP_COLORS = [6, 3, 5, 2, 4]
27
31
 
28
32
  const STATUS_COLOR = {
29
33
  queued: 2,
@@ -49,6 +53,32 @@ const STATUS_LABEL = {
49
53
  interrupted: 'interrupted',
50
54
  }
51
55
 
56
+ /** Medium-width labels, all within ten cells. */
57
+ const STATUS_MEDIUM = {
58
+ queued: 'queued',
59
+ planning: 'plan',
60
+ running: 'running',
61
+ aggregating: 'aggreg.',
62
+ completed: 'done',
63
+ partial: 'partial',
64
+ failed: 'failed',
65
+ cancelled: 'cancel',
66
+ interrupted: 'interrupt',
67
+ }
68
+
69
+ /** Compact and narrow labels: the word is kept, vowels are not. */
70
+ const STATUS_SHORT = {
71
+ queued: 'que',
72
+ planning: 'plan',
73
+ running: 'run',
74
+ aggregating: 'agg',
75
+ completed: 'done',
76
+ partial: 'part',
77
+ failed: 'FAIL',
78
+ cancelled: 'cncl',
79
+ interrupted: 'intr',
80
+ }
81
+
52
82
  const ANSI = {
53
83
  reset: '\u001b[0m',
54
84
  dim: '\u001b[2m',
@@ -72,6 +102,11 @@ function paint(code, text, color) {
72
102
  return color ? `\u001b[${code}m${text}\u001b[0m` : text
73
103
  }
74
104
 
105
+ /** Cell count of a string that may already carry SGR escapes. */
106
+ function visibleLength(text) {
107
+ return String(text ?? '').replace(/\u001b\[[0-9;?]*[a-zA-Z]/g, '').length
108
+ }
109
+
75
110
  /**
76
111
  * Shorten to `width` cells, appending an ellipsis when it does not fit.
77
112
  * @param {string} text - input.
@@ -124,6 +159,12 @@ function firstLine(text) {
124
159
  return value.split(/\r?\n/, 1)[0]
125
160
  }
126
161
 
162
+ /** Last dash-separated segment of a run id: the part that fits a narrow cell. */
163
+ function runTail(run) {
164
+ const parts = String(run?.id ?? '').split('-')
165
+ return parts[parts.length - 1] || String(run?.id ?? '')
166
+ }
167
+
127
168
  /** Parent session label: the uuid tail is what the user recognises. */
128
169
  export function parentLabel(run) {
129
170
  const id = String(run?.parentSessionId ?? '').trim()
@@ -147,6 +188,129 @@ export function elapsedOf(run, now) {
147
188
  return Math.max(0, end - start)
148
189
  }
149
190
 
191
+ /** Half-open lifetime of a run, used for overlap detection. */
192
+ function spanOf(run, now) {
193
+ const start = Date.parse(run?.createdAt ?? run?.startedAt ?? '')
194
+ if (!Number.isFinite(start)) return null
195
+ const end = ACTIVE_STATUSES.has(run?.status)
196
+ ? now
197
+ : Date.parse(run?.finishedAt ?? '') || now
198
+ return { start, end: Math.max(start, end) }
199
+ }
200
+
201
+ /**
202
+ * Cluster runs into connected groups of overlapping lifetimes.
203
+ *
204
+ * Two runs that were alive at the same moment end up in the same group, and
205
+ * overlap is transitive: if A overlaps B and B overlaps C, one group covers
206
+ * all three. A run that never overlapped anything is its own group and is left
207
+ * out of the gutter, so the panel only spends visual noise on real parallelism.
208
+ *
209
+ * @param {object[]} runs - run records.
210
+ * @param {number} [now] - wall clock for live runs.
211
+ * @returns {object[][]} groups, each sorted by start time.
212
+ */
213
+ export function overlapGroups(runs, now = Date.now()) {
214
+ const entries = []
215
+ for (const run of runs ?? []) {
216
+ const span = spanOf(run, now)
217
+ if (span) entries.push({ run, span })
218
+ }
219
+ entries.sort((a, b) => a.span.start - b.span.start || String(a.run.id).localeCompare(String(b.run.id)))
220
+ const groups = []
221
+ let open = null
222
+ for (const entry of entries) {
223
+ if (open && entry.span.start < open.end) {
224
+ open.items.push(entry.run)
225
+ open.end = Math.max(open.end, entry.span.end)
226
+ } else {
227
+ open = { end: entry.span.end, items: [entry.run] }
228
+ groups.push(open)
229
+ }
230
+ }
231
+ return groups.map(group => group.items)
232
+ }
233
+
234
+ /**
235
+ * Gutter label per run for the groups that actually contain more than one run.
236
+ * @param {object[]} runs - run records.
237
+ * @param {number} [now] - wall clock.
238
+ * @returns {Map<string, { label: string, color: number, size: number }>}
239
+ */
240
+ export function groupingOf(runs, now = Date.now()) {
241
+ const map = new Map()
242
+ const groups = overlapGroups(runs, now).filter(group => group.length > 1)
243
+ groups.forEach((group, index) => {
244
+ const label = index < 9
245
+ ? String(index + 1)
246
+ : index < 35
247
+ ? String.fromCharCode(65 + index - 9)
248
+ : '#'
249
+ const meta = { label, color: GROUP_COLORS[index % GROUP_COLORS.length], size: group.length }
250
+ for (const run of group) map.set(run.id, meta)
251
+ })
252
+ return map
253
+ }
254
+
255
+ /**
256
+ * Why a run is not making progress, in the run store's own terms.
257
+ *
258
+ * Only observable facts are used, so the panel never guesses a cause it cannot
259
+ * see: a queued run is waiting for an active-run slot (the other active runs are
260
+ * its candidates), a pending worker behind a full `maxParallel` pool is waiting
261
+ * for a slot inside its own run, and a pending worker that already burned an
262
+ * attempt is in retry backoff.
263
+ *
264
+ * @param {object} run - run record.
265
+ * @param {{ runs?: object[], now?: number }} [options] - sibling runs and clock.
266
+ * @returns {{ kind: 'slot' | 'parallel' | 'retry', text: string } | null}
267
+ */
268
+ export function waitingOf(run, options = {}) {
269
+ if (!run) return null
270
+ const runs = options.runs ?? []
271
+ const subtasks = Array.isArray(run.subtasks) ? run.subtasks : []
272
+
273
+ if (run.status === 'queued') {
274
+ // Only a run that is actually working holds a slot; other queued runs are
275
+ // waiting beside this one, not blocking it.
276
+ const active = runs
277
+ .filter(other => other.id !== run.id && ACTIVE_STATUSES.has(other.status) && other.status !== 'queued')
278
+ .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))
279
+ const queued = runs
280
+ .filter(other => other.status === 'queued')
281
+ .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))
282
+ const position = queued.findIndex(other => other.id === run.id) + 1
283
+ // Blockers first: a narrow terminal clips the tail of a cell, and the run
284
+ // holding the slot is the one fact the reader can act on.
285
+ const parts = []
286
+ if (active.length > 0) {
287
+ parts.push(`slot ← ${active.slice(0, 2).map(runTail).join(',')}`)
288
+ parts.push(`${active.length} active`)
289
+ } else {
290
+ parts.push('waiting on a slot')
291
+ }
292
+ if (position > 1) parts.push(`#${position}`)
293
+ return { kind: 'slot', text: parts.join(' · ') }
294
+ }
295
+
296
+ if (!ACTIVE_STATUSES.has(run.status)) return null
297
+
298
+ const running = subtasks.filter(subtask => subtask.status === 'running')
299
+ const pending = subtasks.filter(subtask => subtask.status === 'pending')
300
+ const retrying = pending.filter(subtask => Number(subtask.attempts) > 0)
301
+ if (retrying.length > 0) {
302
+ const cap = Number(run.limits?.attempts) || 0
303
+ const used = Math.max(...retrying.map(subtask => Number(subtask.attempts) || 0))
304
+ return { kind: 'retry', text: `retry ${used}${cap > 0 ? `/${cap}` : ''} backoff` }
305
+ }
306
+
307
+ const parallel = Number(run.limits?.maxParallel)
308
+ if (pending.length > 0 && Number.isFinite(parallel) && parallel > 0 && running.length >= parallel) {
309
+ return { kind: 'parallel', text: `worker pool full ${running.length}/${parallel} · ${pending.length} waiting` }
310
+ }
311
+ return null
312
+ }
313
+
150
314
  /**
151
315
  * What the run is doing right now, or how it ended. One short phrase, because
152
316
  * the panel's job is to answer "is it stuck?" at a glance.
@@ -156,6 +320,7 @@ export function activityOf(run) {
156
320
  const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
157
321
  const completed = subtasks.filter(subtask => subtask.status === 'completed').length
158
322
  const running = subtasks.filter(subtask => subtask.status === 'running')
323
+ const failed = subtasks.filter(subtask => subtask.status === 'failed').length
159
324
  switch (run?.status) {
160
325
  case 'queued':
161
326
  return 'waiting for an active-run slot'
@@ -163,7 +328,9 @@ export function activityOf(run) {
163
328
  return 'planner is decomposing the goal'
164
329
  case 'running':
165
330
  if (running.length > 0) {
166
- return `${running.length} running · ${running[0].title ?? 'subtask'}`
331
+ const waiting = subtasks.filter(subtask => subtask.status === 'waiting').length
332
+ const held = waiting > 0 ? ` · ${waiting} waiting on dependencies` : ''
333
+ return `${running.length} running${held} · ${running[0].title ?? 'subtask'}`
167
334
  }
168
335
  if (subtasks.length > 0) return `${completed}/${subtasks.length} subtasks done`
169
336
  return 'starting the first subtask'
@@ -172,7 +339,7 @@ export function activityOf(run) {
172
339
  case 'completed':
173
340
  return `report ready · ${completed}/${subtasks.length} subtasks`
174
341
  case 'partial':
175
- return `partial report · ${completed}/${subtasks.length} subtasks`
342
+ return `partial report · ${completed}/${subtasks.length} subtasks${failed > 0 ? ` · ${failed} failed` : ''}`
176
343
  case 'failed':
177
344
  return firstLine(run.error) || 'failed without a recorded error'
178
345
  case 'cancelled':
@@ -202,7 +369,10 @@ export function orderRuns(runs) {
202
369
  export function totalsOf(runs) {
203
370
  let calls = 0
204
371
  let tokens = 0
205
- let cost = 0
372
+ // Integer micro-units keep a long-running panel's total exactly additive.
373
+ let costMicros = 0
374
+ let currency = null
375
+ const currencies = new Set()
206
376
  let unpriced = false
207
377
  let active = 0
208
378
  let failed = 0
@@ -210,7 +380,12 @@ export function totalsOf(runs) {
210
380
  calls += callsOf(run)
211
381
  tokens += run?.usage?.totalTokens ?? 0
212
382
  if (run?.cost) {
213
- cost += run.cost.total ?? 0
383
+ costMicros += Number.isFinite(run.cost.totalMicros)
384
+ ? run.cost.totalMicros
385
+ : Math.round((run.cost.total ?? 0) * 1e6)
386
+ const code = run.cost.currency ?? 'USD'
387
+ currencies.add(code)
388
+ currency = currency ?? code
214
389
  if (run.cost.complete === false) unpriced = true
215
390
  } else if ((run?.usage?.modelCalls ?? 0) > 0) {
216
391
  unpriced = true
@@ -218,46 +393,160 @@ export function totalsOf(runs) {
218
393
  if (ACTIVE_STATUSES.has(run?.status)) active += 1
219
394
  if (run?.status === 'failed') failed += 1
220
395
  }
221
- return { calls, tokens, cost, unpriced, active, failed, total: (runs ?? []).length }
396
+ return {
397
+ calls,
398
+ tokens,
399
+ cost: costMicros / 1e6,
400
+ costMicros,
401
+ currency: currencies.size === 1 ? currency : null,
402
+ mixedCurrency: currencies.size > 1,
403
+ unpriced,
404
+ active,
405
+ failed,
406
+ total: (runs ?? []).length,
407
+ }
222
408
  }
223
409
 
224
- /** Header + column names, reused by every frame so the layout never shifts. */
225
- function headerRow(color) {
226
- const cells = [
227
- pad('RUN ID', COLUMNS.id),
228
- pad('STATUS', COLUMNS.status),
229
- pad('CALLS', COLUMNS.calls),
230
- pad('ELAPSED', COLUMNS.elapsed),
231
- pad('ACTIVITY', 32),
232
- 'PARENT',
233
- ]
234
- return paint('2', ` ${cells.join(' ')}`, color)
410
+ /**
411
+ * Column sets, widest first. The first one whose fixed columns plus a readable
412
+ * activity column fit the terminal wins; the narrowest fallback stacks id and
413
+ * activity onto two lines instead of squeezing them together.
414
+ */
415
+ const TIERS = [
416
+ {
417
+ name: 'wide',
418
+ min: 22,
419
+ cells: [['gutter', GUTTER], ['id', 20], ['status', 12], ['calls', 8], ['elapsed', 7], ['workers', 9], ['activity', 0], ['parent', 8]],
420
+ },
421
+ {
422
+ name: 'standard',
423
+ min: 16,
424
+ cells: [['gutter', GUTTER], ['id', 16], ['status', 10], ['calls', 7], ['elapsed', 6], ['workers', 7], ['activity', 0]],
425
+ },
426
+ {
427
+ name: 'compact',
428
+ min: 10,
429
+ cells: [['gutter', GUTTER], ['id', 12], ['status', 8], ['elapsed', 6], ['workers', 6], ['activity', 0]],
430
+ },
431
+ {
432
+ name: 'narrow',
433
+ min: 10,
434
+ cells: [['gutter', GUTTER], ['id', 9], ['status', 5], ['elapsed', 5], ['activity', 0]],
435
+ },
436
+ ]
437
+
438
+ /**
439
+ * Pick the widest column set that still leaves a usable activity column.
440
+ * @param {number} width - terminal columns.
441
+ */
442
+ function layoutFor(width) {
443
+ for (const tier of TIERS) {
444
+ const fixed = tier.cells.reduce((sum, [, cells]) => sum + cells, 0)
445
+ const separators = tier.cells.length - 1
446
+ const activity = width - fixed - separators
447
+ if (activity >= tier.min) return { ...tier, activity }
448
+ }
449
+ // Below this, a single-line row cannot hold an id and a reason at once.
450
+ return { name: 'tiny', cells: [['gutter', GUTTER], ['id', 0], ['status', 6], ['elapsed', 6]], min: 6, activity: 0 }
451
+ }
452
+
453
+ /** Status text for the chosen width. */
454
+ function statusText(status, tier) {
455
+ if (tier === 'wide') return STATUS_LABEL[status] ?? String(status ?? '?')
456
+ if (tier === 'standard') return STATUS_MEDIUM[status] ?? String(status ?? '?')
457
+ return STATUS_SHORT[status] ?? String(status ?? '?')
458
+ }
459
+
460
+ /**
461
+ * Run id for a narrow cell: the head and the tail survive, the middle does not.
462
+ * Run ids share their date prefix, so a left truncation would leave every row
463
+ * looking identical exactly when the panel is too narrow to compare columns.
464
+ */
465
+ function shortId(id, width) {
466
+ const value = String(id ?? '')
467
+ if (value.length <= width) return value
468
+ if (width <= 1) return '…'
469
+ const tail = Math.max(2, Math.floor((width - 1) / 2))
470
+ const head = width - 1 - tail
471
+ return `${value.slice(0, head)}…${value.slice(-tail)}`
472
+ }
473
+
474
+ /**
475
+ * Worker column: what the pool is doing now, or what it ended with.
476
+ *
477
+ * A live run shows running and pending counts because that is the pool's
478
+ * pressure; a finished run shows completed and failed counts because that is
479
+ * its outcome. `0▶` or `0✓` on a row with no workers would answer a question
480
+ * nobody asked, so an empty pool is left blank.
481
+ */
482
+ function workersOf(run) {
483
+ const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
484
+ const running = subtasks.filter(subtask => subtask.status === 'running').length
485
+ const pending = subtasks.filter(subtask => subtask.status === 'pending').length
486
+ const completed = subtasks.filter(subtask => subtask.status === 'completed').length
487
+ const failed = subtasks.filter(subtask => subtask.status === 'failed').length
488
+ const parts = []
489
+ if (ACTIVE_STATUSES.has(run?.status)) {
490
+ if (running > 0) parts.push(`${running}▶`)
491
+ if (pending > 0) parts.push(`${pending}·`)
492
+ } else if (completed > 0) {
493
+ parts.push(`${completed}✓`)
494
+ }
495
+ if (failed > 0) parts.push(`${failed}✕`)
496
+ return parts.join(' ')
497
+ }
498
+
499
+ /** Column names, with a shorter spelling when the column itself is narrow. */
500
+ function headerFor(layout, color) {
501
+ const labels = {
502
+ gutter: ['', ''],
503
+ id: ['RUN ID', 'ID'],
504
+ status: ['STATUS', 'ST'],
505
+ calls: ['CALLS', 'CALLS'],
506
+ elapsed: ['ELAPSED', 'TIME'],
507
+ workers: ['WORKERS', 'WKRS'],
508
+ activity: ['ACTIVITY / WAITING ON', 'ACTIVITY'],
509
+ parent: ['PARENT', 'PARENT'],
510
+ }
511
+ const cells = layout.cells.map(([key, width]) => {
512
+ const cellWidth = key === 'activity' ? layout.activity : width
513
+ const [long, short] = labels[key] ?? [key, key]
514
+ return pad(long.length <= cellWidth ? long : short, cellWidth)
515
+ })
516
+ return paint('2', cells.join(' '), color)
235
517
  }
236
518
 
237
519
  function rule(width, color) {
238
520
  return paint('2', ` ${'─'.repeat(Math.max(0, width - 2))}`, color)
239
521
  }
240
522
 
523
+ /** Gutter cell: a shared label and colour for runs alive at the same time. */
524
+ function gutterOf(group, color) {
525
+ if (!group) return ' '.repeat(GUTTER)
526
+ const text = `▐${group.label}`
527
+ return paint(group.color, `${text}${' '.repeat(Math.max(0, GUTTER - text.length))}`, color)
528
+ }
529
+
241
530
  /**
242
531
  * Render one complete frame, with no trailing newline.
243
532
  *
244
- * Kept pure so the layout can be asserted in tests without a terminal.
533
+ * Kept pure so the layout can be asserted in tests without a terminal, and so
534
+ * every tier can be checked for the promise that no line exceeds the terminal
535
+ * width.
245
536
  *
246
537
  * @param {object[]} runs - run records.
247
- * @param {{ now?: number, width?: number, color?: boolean, stateRoot?: string, intervalMs?: number, columns?: number }} [options]
538
+ * @param {{ now?: number, width?: number, rows?: number, color?: boolean, stateRoot?: string, intervalMs?: number }} [options]
248
539
  * @returns {string} frame text, ANSI-painted only when `color` is true.
249
540
  */
250
541
  export function renderFrame(runs, options = {}) {
251
542
  const now = options.now ?? Date.now()
252
- const width = Math.max(60, options.width ?? 100)
543
+ const width = Math.max(24, Math.floor(options.width ?? 100))
253
544
  const color = options.color === true
254
545
  const interval = options.intervalMs ?? DEFAULT_INTERVAL_MS
255
546
  const list = orderRuns(runs)
256
547
  const totals = totalsOf(list)
257
- const activityWidth = Math.max(
258
- 20,
259
- width - (COLUMNS.id + COLUMNS.status + COLUMNS.calls + COLUMNS.elapsed + COLUMNS.parent + 6),
260
- )
548
+ const groups = groupingOf(list, now)
549
+ const layout = layoutFor(width)
261
550
 
262
551
  const clock = new Date(now).toISOString().slice(11, 19)
263
552
  const headline = [
@@ -267,65 +556,125 @@ export function renderFrame(runs, options = {}) {
267
556
  totals.active > 0 ? paint('6', `${totals.active} active`, color) : paint('2', 'idle', color),
268
557
  paint('2', `· ${clock}Z`, color),
269
558
  ].join(' ')
559
+ const headlineText = visibleLength(headline) <= width
560
+ ? headline
561
+ : paint('2', clip(`dsh-superagent · ${totals.total} run${totals.total === 1 ? '' : 's'} · ${totals.active} active · ${clock}Z`, width), color)
270
562
 
271
- const lines = [headline, rule(width, color)]
563
+ const lines = [headlineText, rule(width, color)]
272
564
  if (list.length === 0) {
273
565
  lines.push('')
274
- lines.push(paint('2', ' no runs recorded yet', color))
275
- lines.push(paint('2', ` state: ${options.stateRoot ?? '-'}`, color))
566
+ lines.push(paint('2', ` ${clip('no runs recorded yet', width - 2)}`, color))
567
+ lines.push(paint('2', ` ${clip(`state: ${options.stateRoot ?? '-'}`, width - 2)}`, color))
276
568
  lines.push('')
277
- lines.push(paint('2', ' start one with the superagent_start tool; this panel updates itself.', color))
569
+ lines.push(paint('2', ` ${clip('start one with the superagent_start tool; this panel updates itself.', width - 2)}`, color))
278
570
  } else {
279
- lines.push(headerRow(color))
280
- for (const run of list) {
571
+ // A live panel is bounded by the terminal height; a one-shot frame is not,
572
+ // so `--once` and log capture keep every row.
573
+ const budget = Number.isFinite(options.rows) ? Math.max(1, Math.floor(options.rows) - 6) : Infinity
574
+ const visible = list.slice(0, budget)
575
+ const hidden = list.length - visible.length
576
+
577
+ if (layout.name !== 'tiny') lines.push(headerFor(layout, color))
578
+ for (const run of visible) {
579
+ const why = waitingOf(run, { runs: list, now })
580
+ const activity = activityOf(run)
581
+ // A queued run's only fact is its wait, so repeating "waiting for an
582
+ // active-run slot" after the concrete reason would just spend cells.
583
+ const activityText = why
584
+ ? (run.status === 'queued' ? why.text : `${why.text} · ${activity}`)
585
+ : activity
281
586
  const elapsed = elapsedOf(run, now)
282
587
  const calls = callsOf(run)
283
588
  const cap = run?.limits?.maxModelCalls ?? 0
284
589
  const callsText = cap > 0 ? `${calls}/${cap}` : String(calls)
285
- const status = STATUS_LABEL[run.status] ?? String(run.status ?? '?')
286
- const activity = activityOf(run)
287
- const row = [
288
- ` ${paint('1', pad(run.id, COLUMNS.id), color)}`,
289
- ` ${paint(String(STATUS_COLOR[run.status] ?? 0), pad(status, COLUMNS.status), color)}`,
290
- ` ${pad(callsText, COLUMNS.calls)}`,
291
- ` ${pad(elapsed === null ? '-' : formatDuration(elapsed), COLUMNS.elapsed)}`,
292
- ` ${pad(activity, activityWidth)}`,
293
- ` ${paint('2', pad(parentLabel(run), COLUMNS.parent), color)}`,
294
- ].join('')
295
- lines.push(row.replace(/\s+$/, ''))
590
+ const group = groups.get(run.id)
591
+ const status = statusText(run.status, layout.name)
592
+ const statusColor = STATUS_COLOR[run.status] ?? 0
593
+ const elapsedText = elapsed === null ? '-' : formatDuration(elapsed)
594
+
595
+ if (layout.name === 'tiny') {
596
+ // gutter + sep + id + sep + status + sep + elapsed = width
597
+ const idWidth = Math.max(4, width - GUTTER - 3 - 6 - 6)
598
+ const top = [
599
+ gutterOf(group, color),
600
+ ` ${paint('1', pad(shortId(run.id, idWidth), idWidth), color)}`,
601
+ ` ${paint(String(statusColor), pad(status, 6), color)}`,
602
+ ` ${pad(elapsedText, 6)}`,
603
+ ].join('')
604
+ lines.push(top.replace(/\s+$/, ''))
605
+ lines.push(` ${paint('2', '└', color)} ${clip(activityText, Math.max(1, width - 4))}`)
606
+ continue
607
+ }
608
+
609
+ const cells = layout.cells.map(([key, cellWidth]) => {
610
+ switch (key) {
611
+ case 'gutter':
612
+ return gutterOf(group, color)
613
+ case 'id':
614
+ return paint('1', pad(shortId(run.id, cellWidth), cellWidth), color)
615
+ case 'status':
616
+ return paint(String(statusColor), pad(status, cellWidth), color)
617
+ case 'calls':
618
+ return pad(callsText, cellWidth)
619
+ case 'elapsed':
620
+ return pad(elapsedText, cellWidth)
621
+ case 'workers':
622
+ return pad(workersOf(run), cellWidth)
623
+ case 'activity':
624
+ return pad(activityText, layout.activity)
625
+ case 'parent':
626
+ return paint('2', pad(parentLabel(run), cellWidth), color)
627
+ default:
628
+ return pad('', cellWidth)
629
+ }
630
+ })
631
+ lines.push(cells.join(' ').replace(/\s+$/, ''))
632
+ }
633
+
634
+ if (hidden > 0) {
635
+ lines.push(paint('2', ` ${clip(`… ${hidden} more run(s) · enlarge the terminal to see them`, width - 2)}`, color))
296
636
  }
297
637
  }
298
638
 
299
- const money = totals.unpriced ? `$${totals.cost.toFixed(4)}+` : `$${totals.cost.toFixed(4)}`
639
+ // An unpriced panel says so. Printing 0.0000 there would look like "this run
640
+ // was free", when the truth is "no price is configured for its model".
641
+ const shown = formatMoney({ totalMicros: totals.costMicros, currency: totals.currency ?? 'USD' })
642
+ const money = totals.unpriced
643
+ ? (totals.costMicros > 0 ? `${shown}+` : 'unpriced')
644
+ : shown
300
645
  const summary = [
301
- paint('2', 'calls', color),
302
- `${totals.calls}`,
303
- paint('2', 'tokens', color),
304
- formatCount(totals.tokens),
305
- paint('2', 'cost', color),
306
- money,
646
+ `calls ${totals.calls}`,
647
+ `${formatCount(totals.tokens)} tok`,
648
+ `cost ${money}`,
307
649
  totals.failed > 0 ? paint('1', `${totals.failed} failed`, color) : null,
308
- ].filter(Boolean).join(' ')
309
-
310
- const footer = [
311
- paint('2', `${summary} · refreshing every ${interval >= 1000 ? `${interval / 1000}s` : `${interval}ms`} · Ctrl-C to quit`, color),
312
- ].join('')
650
+ ].filter(Boolean).join(' · ')
651
+ const legend = list.length > 0 && groups.size > 0
652
+ ? ' · ▐n overlapping · ▶ running · · pending'
653
+ : ''
654
+ const footer = paint('2', clip(`${summary} · ${interval >= 1000 ? `${interval / 1000}s` : `${interval}ms`} refresh · Ctrl-C quit${legend}`, width), color)
313
655
 
314
656
  lines.push(rule(width, color))
315
657
  lines.push(footer)
316
658
  return lines.join('\n')
317
659
  }
318
660
 
319
- /** Status + progress fingerprint; a change here is worth an immediate repaint. */
320
- export function signatureOf(runs) {
661
+ /** Status + progress + blocking fingerprint; a change here is worth an immediate repaint. */
662
+ export function signatureOf(runs, now = Date.now()) {
663
+ const groups = groupingOf(runs, now)
321
664
  return orderRuns(runs)
322
- .map(run => [
323
- run.id,
324
- run.status,
325
- callsOf(run),
326
- (run.subtasks ?? []).filter(subtask => subtask.status === 'running').length,
327
- (run.subtasks ?? []).filter(subtask => subtask.status === 'completed').length,
328
- ].join(':'))
665
+ .map(run => {
666
+ const subtasks = Array.isArray(run.subtasks) ? run.subtasks : []
667
+ const attempts = subtasks.reduce((sum, subtask) => sum + (Number(subtask.attempts) || 0), 0)
668
+ return [
669
+ run.id,
670
+ run.status,
671
+ callsOf(run),
672
+ subtasks.filter(subtask => subtask.status === 'running').length,
673
+ subtasks.filter(subtask => subtask.status === 'completed').length,
674
+ attempts,
675
+ groups.get(run.id)?.label ?? '-',
676
+ ].join(':')
677
+ })
329
678
  .join('|')
330
679
  }
331
680
 
@@ -339,7 +688,7 @@ export function signatureOf(runs) {
339
688
  * the process exits. When output is a pipe, each change is appended as a plain
340
689
  * frame instead, which keeps `watch --once | ...` and log capture useful.
341
690
  *
342
- * @param {{ stateDir?: string, intervalMs?: number, once?: boolean, out?: NodeJS.WriteStream | { write: Function, isTTY?: boolean, columns?: number }, now?: () => number }} [options]
691
+ * @param {{ stateDir?: string, intervalMs?: number, once?: boolean, out?: NodeJS.WriteStream | { write: Function, isTTY?: boolean, columns?: number, rows?: number }, now?: () => number }} [options]
343
692
  * @returns {Promise<void>} resolves after cleanup.
344
693
  */
345
694
  export async function watch(options = {}) {
@@ -367,6 +716,9 @@ export async function watch(options = {}) {
367
716
  const frame = renderFrame(runs, {
368
717
  now: now(),
369
718
  width: out.columns || 100,
719
+ // A one-shot frame goes to a log or a pipe, where nothing scrolls: only a
720
+ // live alternate-screen panel is bounded by the terminal height.
721
+ rows: altScreen ? out.rows : undefined,
370
722
  color,
371
723
  stateRoot: store.root,
372
724
  intervalMs,
@@ -444,7 +796,7 @@ export async function watch(options = {}) {
444
796
  // A status transition (planning -> running -> aggregating) can happen
445
797
  // inside one interval. Re-read at once when the fingerprint moved, then
446
798
  // settle back to the normal cadence so an idle panel costs one read/s.
447
- const signature = signatureOf(runs)
799
+ const signature = signatureOf(runs, now())
448
800
  const moved = signature !== lastSignature
449
801
  lastSignature = signature
450
802
  await new Promise(resolve => {