project-brain 0.44.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,26 @@
1
1
  import { atom, read, update } from 'claude-code'
2
2
  import type { Hook, Register } from 'claude-code'
3
+ import { actAgents, agentChipsGrouped, readAgents, registerAgents, rowsAgentReport } from './feat-agents'
4
+ import { agentsTurnComplete } from './feat-agents'
5
+ import type { AgentsAction, AgentsPart } from './feat-agents'
6
+ import { footerCi, readCi, registerCi, rowsCi } from './feat-ci'
7
+ import { ciKick, ciSessionStart, ciTurnComplete } from './feat-ci'
8
+ import type { CiPart } from './feat-ci'
9
+ import { footerContext, readContext, registerContext, rowsContext } from './feat-context'
10
+ import { contextKick, contextMeasured, contextSessionStart, contextTurnComplete } from './feat-context'
11
+ import type { ContextPart } from './feat-context'
12
+ import { footerProgress, readProgress, registerProgress, rowsProgress } from './feat-progress'
13
+ import { progressSessionStart, progressToolCall, progressTurnComplete } from './feat-progress'
14
+ import type { ProgressPart } from './feat-progress'
15
+ import { headerRunning, readRunning, registerRunning, rowsRunning } from './feat-running'
16
+ import { runningSessionStart, runningToolCall } from './feat-running'
17
+ import type { RunningPart } from './feat-running'
18
+ import { headerBlocked, readBlocked, registerBlocked, rowsBlocked } from './feat-blocked'
19
+ import { blockedToolCall, blockedTurnStart } from './feat-blocked'
20
+ import type { BlockedPart } from './feat-blocked'
21
+ import { footerSavings, readSavings, rowsSavings, savingsSessionStart, savingsTurnComplete } from './feat-savings'
22
+ import type { SavingsPart } from './feat-savings'
23
+ import { notifyCommand, notifyTurnComplete } from './feat-notify'
3
24
 
4
25
  import type {
5
26
  AgentRecord,
@@ -28,7 +49,7 @@ import type {
28
49
 
29
50
  const PANE = 'activity'
30
51
  const PANE_ARGS = { id: PANE, title: 'Actividad', columns: 1000 } as const
31
- const MAIN = 'main'
52
+ export const MAIN = 'main'
32
53
  const KEEP = 300
33
54
  const OUTPUT_LINES = 40
34
55
  const DIFF_LINES = 120
@@ -122,10 +143,26 @@ const autoOpen = atom({ plugin: 'project-brain-activity', key: 'autoOpen' } as c
122
143
  const editor = atom({ plugin: 'project-brain-activity', key: 'editor' } as const, { dir: '', tab: '' } as EditorState, { shape: 'editor-1' })
123
144
  const accentColor = atom({ plugin: 'project-brain-activity', key: 'accent' } as const, 'claude' as string, { shape: 'accent-1' })
124
145
 
125
- /** Claude Code's session colours (/color) in the default theme; 'default' and unknown names keep the claude tone. */
146
+ /** Claude Code's session colours (/color) as their Dracula counterparts; 'default' and unknown names keep the claude tone. */
126
147
  const SESSION_COLORS: Record<string, string> = {
127
- red: 'rgb(220,38,38)', blue: 'rgb(106,155,204)', green: 'rgb(22,163,74)', yellow: 'rgb(202,138,4)',
128
- purple: 'rgb(130,125,189)', orange: 'rgb(217,119,87)', pink: 'rgb(196,102,134)', cyan: 'rgb(8,145,178)',
148
+ red: '#FF5555', blue: '#6272A4', green: '#50FA7B', yellow: '#F1FA8C',
149
+ purple: '#BD93F9', orange: '#FFB86C', pink: '#FF79C6', cyan: '#8BE9FD',
150
+ }
151
+
152
+ /** The pane's palette (Dracula): each tone the rows name, painted as the owner's chosen hex. */
153
+ export const PALETTE: Record<Tone, string> = {
154
+ success: '#50FA7B', error: '#FF5555', warning: '#FFB86C', subtle: '#6272A4', permission: '#BD93F9',
155
+ claude: '#FF79C6', suggestion: '#8BE9FD', diffAdded: '#50FA7B', diffRemoved: '#FF5555',
156
+ }
157
+ const COMMENT = '#6272A4'
158
+ /** The pane's own background, darker than the terminal's so the palette stands out. */
159
+ export const PANE_BG = '#181320'
160
+
161
+ /** A span's colour as the surface draws it: palette tones become hex, a dim span without colour takes the comment grey. */
162
+ export const paint = (one: Pick<Span, 'color' | 'dim'>): { color?: string; dimColor?: boolean } => {
163
+ if (one.color === undefined) return one.dim ? { color: COMMENT } : {}
164
+ const color = (PALETTE as Record<string, string>)[one.color] ?? one.color
165
+ return { color, ...(one.dim ? { dimColor: true } : {}) }
129
166
  }
130
167
 
131
168
  /** The last `"agentColor":"<name>"` grep match in the transcript, as a colour the pane can paint. */
@@ -134,6 +171,10 @@ export const accentOf = (grepOutput: string): string => {
134
171
  return SESSION_COLORS[names.at(-1) ?? ''] ?? 'claude'
135
172
  }
136
173
 
174
+ /** After the first full scan, only the transcript's tail can hold a newer `/color` change. */
175
+ const ACCENT_TAIL_BYTES = 262_144
176
+ let accentScanned = false
177
+
137
178
  /** Reads the session colour Claude Code writes into the transcript as an `agent-color` entry. */
138
179
  const refreshAccent = async ($: Api): Promise<void> => {
139
180
  const [id, root, home] = await Promise.all([
@@ -143,8 +184,14 @@ const refreshAccent = async ($: Api): Promise<void> => {
143
184
  ])
144
185
  if (!home || !/^[0-9a-f-]{36}$/.test(id)) return
145
186
  const transcript = `${home}/.claude/projects/${root.replace(/[^A-Za-z0-9]/g, '-')}/${id}.jsonl`
146
- const found = await $.process.run(['/usr/bin/grep', '-a', '-o', '"agentColor":"[a-z]*"', transcript], { timeoutMs: 3000 }).catch(() => undefined)
187
+ const scan = accentScanned
188
+ ? ['/usr/bin/tail', '-c', String(ACCENT_TAIL_BYTES), transcript]
189
+ : ['/usr/bin/grep', '-a', '-o', '"agentColor":"[a-z]*"', transcript]
190
+ const found = await $.process.run(scan, { timeoutMs: 3000 }).catch(() => undefined)
147
191
  if (!found) return
192
+ const wasScanned = accentScanned
193
+ accentScanned = true
194
+ if (wasScanned && !found.stdout.includes('"agentColor":"')) return
148
195
  const next = accentOf(found.stdout)
149
196
  if (next !== (await read($, accentColor))) await update($, accentColor, () => next)
150
197
  }
@@ -154,7 +201,7 @@ const commitCalls = atom({ plugin: 'project-brain-activity', key: 'commitCalls'
154
201
  const history = atom({ plugin: 'project-brain-activity', key: 'history' } as const, { state: 'idle', rows: [], more: 0, loadedAt: 0 } as HistoryView, { shape: 'history-1' })
155
202
  const historyFiles = atom({ plugin: 'project-brain-activity', key: 'historyFiles' } as const, {} as Record<string, HistoryFiles>, { shape: 'history-files-1' })
156
203
 
157
- type Api = Parameters<Hook<'turn.complete'>>[0]
204
+ export type Api = Parameters<Hook<'turn.complete'>>[0]
158
205
 
159
206
  // Timers are not drawn state: a reload dropping them only loses one debounce.
160
207
  let refreshTimer: { cancel: () => void } | undefined
@@ -450,7 +497,7 @@ export type RunResult = { exitCode: number; stdout: string; stderr: string }
450
497
  export type Run = (argv: readonly string[], init?: { cwd?: string; timeoutMs?: number; stdin?: string }) => Promise<RunResult>
451
498
  export type ReadText = (path: string) => Promise<string>
452
499
 
453
- const quietly = (run: Run, argv: readonly string[], cwd?: string, stdin?: string): Promise<RunResult | undefined> =>
500
+ export const quietly = (run: Run, argv: readonly string[], cwd?: string, stdin?: string): Promise<RunResult | undefined> =>
454
501
  run(argv, cwd === undefined && stdin === undefined ? undefined : { ...(cwd === undefined ? {} : { cwd }), ...(stdin === undefined ? {} : { stdin }) }).catch(() => undefined)
455
502
 
456
503
  export const gitTop = async (run: Run, cwd?: string): Promise<string | undefined> => {
@@ -1010,6 +1057,7 @@ export type Action =
1010
1057
  | { kind: 'diff'; target: DiffTarget }
1011
1058
  | { kind: 'open'; target: DiffTarget }
1012
1059
  | { kind: 'commit'; sha: string }
1060
+ | AgentsAction
1013
1061
  export type Cell = { spans: Span[]; action?: Action; label?: string; key?: string }
1014
1062
  export type Row = { key: string; cells: Cell[]; right?: Span[] }
1015
1063
 
@@ -1033,11 +1081,18 @@ export type Snapshot = {
1033
1081
  view: PaneScroll
1034
1082
  historyView: HistoryView
1035
1083
  historyFiles: Record<string, HistoryFiles>
1084
+ agentsPart: AgentsPart
1085
+ ci: CiPart
1086
+ contextPart: ContextPart
1087
+ progress: ProgressPart
1088
+ running: RunningPart
1089
+ blocked: BlockedPart
1090
+ savings: SavingsPart
1036
1091
  }
1037
1092
 
1038
1093
  export type PaneModel = { header: Row[]; body: Row[]; footer: Row[]; scope: string; cambios: CambiosScope; tab: Tab }
1039
1094
 
1040
- type Look = { icon: string; color: Tone }
1095
+ export type Look = { icon: string; color: Tone }
1041
1096
 
1042
1097
  const STATUS_LOOK: Record<CallStatus, Look> = {
1043
1098
  running: { icon: ICONS.running, color: 'warning' },
@@ -1047,7 +1102,7 @@ const STATUS_LOOK: Record<CallStatus, Look> = {
1047
1102
  interrupted: { icon: ICONS.interrupted, color: 'subtle' },
1048
1103
  }
1049
1104
 
1050
- const AGENT_LOOK: Record<AgentState, Look & { label: string }> = {
1105
+ export const AGENT_LOOK: Record<AgentState, Look & { label: string }> = {
1051
1106
  running: { icon: ICONS.running, color: 'warning', label: 'ejecutando' },
1052
1107
  done: { icon: ICONS.ok, color: 'success', label: 'terminó' },
1053
1108
  failed: { icon: ICONS.error, color: 'error', label: 'falló' },
@@ -1076,7 +1131,7 @@ const SCOPE_LABELS: { value: CambiosScope; icon: string; label: string }[] = [
1076
1131
  { value: 'branch', icon: ICONS.branch, label: 'Rama' },
1077
1132
  ]
1078
1133
 
1079
- const span = (value: string, style: Omit<Span, 'text'> = {}): Span => ({ text: value, ...style })
1134
+ export const span = (value: string, style: Omit<Span, 'text'> = {}): Span => ({ text: value, ...style })
1080
1135
 
1081
1136
  const touches = (change: FileChange, edited: string[]): boolean =>
1082
1137
  edited.some(path => path === change.path || path.endsWith(`/${change.path}`))
@@ -1098,6 +1153,31 @@ export const ownerOf = (owners: Map<string, CommitRecord[]>, sha: string): Commi
1098
1153
  export const cambiosScopeOf = (snap: Pick<Snapshot, 'scopeByAgent' | 'commitList'>, scope: string): CambiosScope =>
1099
1154
  snap.scopeByAgent[scope] ?? (commitsFor(snap.commitList, scope).length > 0 ? 'commits' : 'uncommitted')
1100
1155
 
1156
+ const cellWidth = (cell: Cell): number => cell.spans.reduce((sum, one) => sum + [...one.text].length, 0)
1157
+
1158
+ /**
1159
+ * The agent chips that fit one row: "Principal" stays pinned, the rest scroll as a window that always holds
1160
+ * the selected agent. Hidden chips collapse into "‹ N" / "N ›" markers that select the nearest hidden agent.
1161
+ */
1162
+ export const agentStrip = (pinned: Cell, chips: Cell[], selected: number, ids: string[], width: number): Cell[] => {
1163
+ const total = cellWidth(pinned) + chips.reduce((sum, one) => sum + cellWidth(one), 0)
1164
+ if (total <= width) return [pinned, ...chips]
1165
+ const marker = (text: string, id: string, key: string): Cell => ({ key, label: text, action: { kind: 'agent', id }, spans: [span(text, { color: 'suggestion', bold: true })] })
1166
+ const room = Math.max(0, width - cellWidth(pinned) - 2 * 5)
1167
+ let start = Math.max(0, selected)
1168
+ let end = start
1169
+ let used = 0
1170
+ const fits = (index: number) => used + cellWidth(chips[index] as Cell) <= room
1171
+ while (end < chips.length && (end === start || fits(end))) used += cellWidth(chips[end++] as Cell)
1172
+ while (start > 0 && fits(start - 1)) used += cellWidth(chips[--start] as Cell)
1173
+ return [
1174
+ pinned,
1175
+ ...(start > 0 ? [marker(`‹ ${start} `, ids[start - 1] ?? MAIN, 'agents-left')] : []),
1176
+ ...chips.slice(start, end),
1177
+ ...(end < chips.length ? [marker(` ${chips.length - end} ›`, ids[end] ?? MAIN, 'agents-right')] : []),
1178
+ ]
1179
+ }
1180
+
1101
1181
  export const buildPane = (snap: Snapshot, width: number): PaneModel => {
1102
1182
  const { list, flipped, opened, patches, records } = snap
1103
1183
  const accent = snap.accent
@@ -1375,9 +1455,16 @@ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
1375
1455
 
1376
1456
  const summaryRows = (): Row[] => {
1377
1457
  const steps = groupSteps(scoped)
1378
- if (steps.length === 0) return [line('empty', 'Sin actividad todavía.', { dim: true })]
1458
+ const ctx = { width, accent, isOpen }
1459
+ const live = scope === MAIN ? [...rowsProgress(snap.progress, ctx), ...rowsRunning(snap.running, ctx), ...rowsBlocked(snap.blocked, ctx)] : rowsRunning(snap.running, ctx)
1460
+ const lead = live.length > 0 ? [...live, blank('gap-live')] : []
1461
+ const contextRows = scope === MAIN ? [...rowsContext(snap.contextPart, ctx), ...rowsSavings(snap.savings, ctx)] : []
1462
+ const tail = contextRows.length > 0 ? [blank('gap-context'), ...contextRows] : []
1463
+ if (steps.length === 0) return [...lead, line('empty', 'Sin actividad todavía.', { dim: true }), ...tail]
1379
1464
  return [
1465
+ ...lead,
1380
1466
  ...stepRows(steps),
1467
+ ...tail,
1381
1468
  ...(lastCommand ? [blank('gap-last'), ...section(`last-cmd-${scope}`, 'Último comando', true, () => commandRows(lastCommand, `last-${scope}`))] : []),
1382
1469
  blank('gap-changes'),
1383
1470
  divider('div-changes'),
@@ -1411,7 +1498,8 @@ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
1411
1498
  ]
1412
1499
  }
1413
1500
 
1414
- const body = current === 'diff' ? cambiosRows() : current === 'commands' ? commandsTabRows() : current === 'history' ? historyTabRows() : summaryRows()
1501
+ const ciRows = rowsCi(snap.ci, { width, accent, isOpen })
1502
+ const body = current === 'diff' ? [...ciRows, ...(ciRows.length > 0 ? [blank('gap-ci')] : []), ...cambiosRows()] : current === 'commands' ? commandsTabRows() : current === 'history' ? historyTabRows() : summaryRows()
1415
1503
 
1416
1504
  const status = waiting
1417
1505
  ? span(`${ICONS.waiting} esperando respuesta`, { color: 'warning' })
@@ -1426,14 +1514,11 @@ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
1426
1514
  spans: [span(` ${label}${look ? ' ' : ' '}`, { inverse: isOn, bold: isOn }), ...(look ? [span(`${look.icon} `, { color: look.color, inverse: isOn })] : []), span(' ')],
1427
1515
  })
1428
1516
 
1429
- const header: Row[] = [{ key: 'title', cells: [{ spans: [span('ACTIVIDAD', { bold: true })] }], right: status ? [status] : [] }]
1517
+ const header: Row[] = [{ key: 'title', cells: [{ spans: [span('ACTIVIDAD', { bold: true })] }], right: [status ? [status] : [], headerRunning(snap.running), headerBlocked(snap.blocked, snap.running.now)].filter(one => one.length > 0).flatMap((one, index) => (index === 0 ? one : [span(' '), ...one])) }]
1430
1518
  if (records.length > 0) {
1431
1519
  header.push({
1432
1520
  key: 'agents',
1433
- cells: [
1434
- chip(`agent-${MAIN}`, 'Principal', scope === MAIN, { kind: 'agent', id: MAIN }),
1435
- ...records.map(one => chip(`agent-${one.id}`, shortName(one), scope === one.id, { kind: 'agent', id: one.id }, AGENT_LOOK[one.state])),
1436
- ],
1521
+ cells: agentChipsGrouped({ records, scope, expanded: snap.agentsPart.expanded, width }),
1437
1522
  })
1438
1523
  }
1439
1524
  if (agent) {
@@ -1441,6 +1526,7 @@ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
1441
1526
  header.push(
1442
1527
  { key: 'agent-head', cells: [{ spans: [span(`${ICONS.agent} ${shortName(agent)}`, { color: accent, bold: true }), span(` · ${agent.id.slice(0, 4)} · `, { dim: true }), span(look.label, { color: look.color })] }] },
1443
1528
  line('agent-task', agent.description, { dim: true }),
1529
+ ...rowsAgentReport(agent, snap.agentsPart.reports[agent.id], width),
1444
1530
  )
1445
1531
  }
1446
1532
  header.push({
@@ -1483,10 +1569,38 @@ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
1483
1569
  ),
1484
1570
  contextRow('footer-context', ''),
1485
1571
  ]
1572
+ const extra = [...footerProgress(snap.progress), ...footerCi(snap.ci), ...footerContext(snap.contextPart), ...footerSavings(snap.savings)]
1573
+ if (extra.length > 0) footer.push({ key: 'footer-extra', cells: [{ spans: extra.flatMap((one, index) => (index === 0 ? [one] : [span(' '), one])) }] })
1486
1574
 
1487
1575
  return { header, body, footer, scope, cambios, tab: current }
1488
1576
  }
1489
1577
 
1578
+ const spansWidth = (spans: readonly Span[]): number => spans.reduce((total, one) => total + one.text.length, 0)
1579
+
1580
+ /**
1581
+ * The last guard against a row wider than the pane: the right-hand spans go
1582
+ * first, then the left is cut to the width. A row that fits passes untouched.
1583
+ */
1584
+ export const clampRow = (row: Row, width: number): Row => {
1585
+ const room = Math.max(1, width)
1586
+ const left = row.cells.reduce((total, cell) => total + spansWidth(cell.spans), 0)
1587
+ // The renderer draws an empty right side as one space.
1588
+ const right = row.right === undefined ? 0 : Math.max(1, spansWidth(row.right))
1589
+ if (left + right <= room) return row
1590
+ const { right: _dropped, ...rest } = row
1591
+ if (left <= room) return rest
1592
+ let budget = room
1593
+ const cut = (one: Span): Span => {
1594
+ const text = budget <= 0 ? '' : one.text.length <= budget ? one.text : fit(one.text, budget)
1595
+ budget -= text.length
1596
+ return { ...one, text }
1597
+ }
1598
+ const cells = row.cells
1599
+ .map(cell => ({ ...cell, spans: cell.spans.map(cut).filter(one => one.text !== '') }))
1600
+ .filter(cell => cell.spans.length > 0)
1601
+ return { ...rest, cells }
1602
+ }
1603
+
1490
1604
  export type PaneFrame = { rows: Row[]; isWindowed: boolean; total: number; room: number }
1491
1605
 
1492
1606
  /**
@@ -1510,15 +1624,16 @@ export const paneFrame = (model: PaneModel, bodyRows: number, view: PaneScroll,
1510
1624
 
1511
1625
  // ---------------------------------------------------------------- hooks
1512
1626
 
1513
- const runOf = ($: Api): Run => (argv, init) => $.process.run(argv, init)
1627
+ export const runOf = ($: Api): Run => (argv, init) => $.process.run(argv, init)
1514
1628
 
1515
1629
  const readSnapshot = async ($: Api): Promise<Snapshot> => {
1516
- const [list, tabByAgent, flipped, files, usd, context, opened, patches, records, picked, isWorking, view, commitList, scopeByAgent, branchView, steps, historyView, historyFilesBySha, accent] = await Promise.all([
1630
+ const [list, tabByAgent, flipped, files, usd, context, opened, patches, records, picked, isWorking, view, commitList, scopeByAgent, branchView, steps, historyView, historyFilesBySha, accent, agentsPart, ci, contextPart, progress, running, blocked, savings] = await Promise.all([
1517
1631
  read($, entries), read($, tabs), read($, toggled), read($, changes), read($, costUsd), read($, contextUsage), read($, openFiles), read($, diffs),
1518
1632
  read($, agents), read($, pickedAgent), read($, working), read($, scroll), read($, commits), read($, scopes), read($, branch), read($, stepContext),
1519
1633
  read($, history), read($, historyFiles), read($, accentColor),
1634
+ readAgents($), readCi($), readContext($), readProgress($), readRunning($), readBlocked($), readSavings($),
1520
1635
  ])
1521
- return { accent, list, tabByAgent, flipped, files, usd, context, steps, opened, patches, records, picked, isWorking, commitList, scopeByAgent, branchView, view, historyView, historyFiles: historyFilesBySha }
1636
+ return { accent, list, tabByAgent, flipped, files, usd, context, steps, opened, patches, records, picked, isWorking, commitList, scopeByAgent, branchView, view, historyView, historyFiles: historyFilesBySha, agentsPart, ci, contextPart, progress, running, blocked, savings }
1522
1637
  }
1523
1638
 
1524
1639
  /** Fills in the line counts and files of up to ten commits that have none yet. */
@@ -1583,16 +1698,180 @@ const scheduleRescan = ($: Api): void => {
1583
1698
  export const sessionStartOf = (stored: number, now: number, list: ToolEntry[], known: CommitRecord[]): number =>
1584
1699
  stored > 0 ? stored : Math.min(now, ...list.map(one => one.startedAt), ...known.map(one => one.at))
1585
1700
 
1586
- export const register: Register = on => {
1587
- on('session.start', async ($, e, next) => {
1588
- await $.command.register({ name: 'activity', description: 'Abre el panel de actividad' })
1589
- const [stored, list, known] = await Promise.all([read($, sessionStart), read($, entries), read($, commits)])
1590
- const now = await $.clock.now()
1591
- await update($, sessionStart, () => sessionStartOf(stored, now, list, known))
1701
+ async function mainSessionStart($: Api, e: Parameters<Hook<'session.start'>>[1], next: Parameters<Hook<'session.start'>>[2]): Promise<Awaited<ReturnType<Hook<'session.start'>>>> {
1702
+ await $.command.register({ name: 'activity', description: 'Abre el panel de actividad · notify on|off|test para las notificaciones del sistema' })
1703
+ const [stored, list, known] = await Promise.all([read($, sessionStart), read($, entries), read($, commits)])
1704
+ const now = await $.clock.now()
1705
+ await update($, sessionStart, () => sessionStartOf(stored, now, list, known))
1706
+ scheduleRescan($ as Api)
1707
+ void refreshAccent($ as Api).catch(() => undefined)
1708
+ return next(e)
1709
+ }
1710
+
1711
+ async function mainTurnStart($: Api, e: Parameters<Hook<'turn.start'>>[1], next: Parameters<Hook<'turn.start'>>[2]): Promise<Awaited<ReturnType<Hook<'turn.start'>>>> {
1712
+ const loopId = e.agentId
1713
+ if (loopId === undefined) await update($, working, () => true)
1714
+ else await update($, agents, list => setAgentState(list, loopId, 'running'))
1715
+ return next(e)
1716
+ }
1717
+
1718
+ async function mainTurnComplete($: Api, e: Parameters<Hook<'turn.complete'>>[1], next: Parameters<Hook<'turn.complete'>>[2]): Promise<Awaited<ReturnType<Hook<'turn.complete'>>>> {
1719
+ const done = await next(e)
1720
+ const loopId = e.agentId
1721
+ if (loopId === undefined) await update($, working, () => false)
1722
+ else await update($, agents, list => setAgentState(list, loopId, turnEndState(e.reason)))
1723
+ scheduleRescan($)
1724
+ void refreshAccent($).catch(() => undefined)
1725
+ return done
1726
+ }
1727
+
1728
+ async function mainToolCall($: Api, e: Parameters<Hook<'tool.call'>>[1], next: Parameters<Hook<'tool.call'>>[2]): Promise<Awaited<ReturnType<Hook<'tool.call'>>>> {
1729
+ const input = e as unknown as Record<string, unknown>
1730
+ const run: Run = (argv, init) => $.process.run(argv, init)
1731
+ const startedAt = await $.clock.now()
1732
+ const loopId = e.agentId
1733
+ const entry: ToolEntry = {
1734
+ id: e.tool_use_id,
1735
+ tool: e.tool,
1736
+ summary: summarize(input),
1737
+ status: 'running',
1738
+ output: '',
1739
+ startedAt,
1740
+ ...(loopId === undefined ? {} : { agentId: loopId }),
1741
+ }
1742
+ if (e.tool === 'Bash') entry.command = cleanText(input.command)
1743
+ const file = cleanText(input.file_path) ?? cleanText(input.notebook_path)
1744
+ if (file !== undefined) entry.file = file
1745
+ if (e.tool === 'Agent') entry.note = cleanText(input.subagent_type)
1746
+ if (e.tool === 'AskUserQuestion') entry.decisions = decisionsOf(input)
1747
+ await update($, entries, list => [...list, entry].slice(-KEEP))
1748
+
1749
+ if (loopId !== undefined && !(await read($, agents)).some(one => one.id === loopId)) {
1750
+ const info = (await $.agent.list().catch(() => [])).find(one => one.id === loopId)
1751
+ if (info) {
1752
+ const record: AgentRecord = { id: loopId, description: oneLine(info.description), type: oneLine(info.type), state: agentStateOf(info.status), startedAt }
1753
+ if (info.name) record.name = oneLine(info.name)
1754
+ await update($, agents, list => mergeAgent(list, record))
1755
+ }
1756
+ }
1757
+
1758
+ const finish = async (finished: Partial<ToolEntry>) => {
1759
+ const durationMs = (await $.clock.now()) - startedAt
1760
+ await update($, entries, list => list.map(one => (one.id === entry.id ? { ...one, durationMs, ...finished } : one)))
1761
+ }
1762
+
1763
+ let ran: Awaited<ReturnType<typeof next>> | undefined
1764
+ try {
1765
+ ran = await next(e)
1766
+ } finally {
1767
+ if (ran === undefined) await finish({ status: 'interrupted', output: 'interrumpido' }).catch(() => undefined)
1768
+ }
1769
+
1770
+ const wasInterrupted = (ran.result as { interrupted?: unknown } | undefined)?.interrupted === true
1771
+ const status: CallStatus = ran.deny !== undefined ? 'denied' : wasInterrupted ? 'interrupted' : ran.isError === true ? 'error' : 'ok'
1772
+ const full = ran.deny ?? ran.text ?? ''
1773
+ const finished: Partial<ToolEntry> = { status, output: lastLines(full, OUTPUT_LINES) }
1774
+ if (entry.command !== undefined) {
1775
+ const exitCode = exitCodeOf(full, ran.isError === true)
1776
+ if (exitCode !== undefined) finished.exitCode = exitCode
1777
+ if (isTestCommand(entry.command)) finished.testFiles = testFilesOf(full)
1778
+ }
1779
+ if (e.tool === 'AskUserQuestion') finished.decisions = answered(input, status, ran.result)
1780
+ const spawnedId = text((ran.result as { agentId?: unknown } | undefined)?.agentId)
1781
+ if (e.tool === 'Agent' && spawnedId !== undefined) {
1782
+ finished.spawned = spawnedId
1783
+ const state = agentResultState(status, ran.result)
1784
+ const known = (await read($, agents)).some(one => one.id === spawnedId) || (await $.agent.list().catch(() => [])).some(one => one.id === spawnedId)
1785
+ if (state !== undefined && known) {
1786
+ const record: AgentRecord = { id: spawnedId, description: cleanText(input.description) ?? '', type: entry.note ?? 'agente', state, startedAt }
1787
+ await update($, agents, list => mergeAgent(list, record))
1788
+ }
1789
+ }
1790
+ await finish(finished)
1791
+
1792
+ const rawCommand = text(input.command)
1793
+ if (e.tool === 'Bash' && status !== 'denied' && rawCommand !== undefined && gitCommitVerbs(rawCommand).length > 0) {
1794
+ const endedAt = await $.clock.now()
1795
+ const dir = commitDirOf(rawCommand)
1796
+ const top = dir === undefined || !SAFE_PATH.test(dir) ? undefined : await gitTop(run, dir)
1797
+ const call: CommitCall = { startedAt, endedAt, ...(loopId === undefined ? {} : { agentId: loopId }), ...(top === undefined ? {} : { top }) }
1798
+ await update($, commitCalls, list => [...list, call].slice(-COMMIT_CALLS))
1592
1799
  scheduleRescan($ as Api)
1593
- void refreshAccent($ as Api).catch(() => undefined)
1594
- return next(e)
1595
- })
1800
+ }
1801
+ if (e.tool === 'Bash' && status === 'ok' && rawCommand !== undefined && ran.text !== undefined) {
1802
+ const found = commitsIn(rawCommand, ran.text)
1803
+ if (found.length > 0) await update($, commits, list => addCommits(list, found, loopId, startedAt))
1804
+ if (madeMergeCommit(rawCommand, ran.text)) {
1805
+ void (async () => {
1806
+ const top = await gitTop(run)
1807
+ const head = top === undefined ? undefined : await loadHeadCommit(run, top)
1808
+ if (head) await update($, commits, list => addCommits(list, [head], loopId, startedAt))
1809
+ })().catch(() => undefined)
1810
+ }
1811
+ }
1812
+
1813
+ const refresh = async () => {
1814
+ const top = await gitTop(run)
1815
+ if (top === undefined) return
1816
+ const fileList = await loadUncommitted(run, top, async path => {
1817
+ const info = await $.fs.stat(path)
1818
+ return info.isLink || info.kind !== 'file' || info.size > 2_000_000 ? Promise.reject(new Error('skipped')) : $.fs.read(path)
1819
+ })
1820
+ if (fileList !== undefined) await update($, changes, () => fileList)
1821
+
1822
+ for (const key of await read($, openFiles)) {
1823
+ if (!key.startsWith('u:') && !key.startsWith('b:')) continue
1824
+ const path = key.slice(2)
1825
+ const change = key.startsWith('u:') ? fileList?.find(one => one.path === path) : undefined
1826
+ if (key.startsWith('u:') && change === undefined) {
1827
+ await update($, openFiles, keys => keys.filter(one => one !== key))
1828
+ await update($, diffs, all => Object.fromEntries(Object.entries(all).filter(([name]) => name !== key)))
1829
+ continue
1830
+ }
1831
+ const target: DiffTarget = key.startsWith('u:')
1832
+ ? { scope: 'uncommitted', path, ...(change?.untracked ? { untracked: true } : {}) }
1833
+ : { scope: 'branch', path, sha: (await read($, branch)).base }
1834
+ const patch = await fetchDiff(run, top, target)
1835
+ await update($, diffs, all => ({ ...all, [key]: patch }))
1836
+ }
1837
+
1838
+ await fillCommitStats($ as Api, run, top)
1839
+
1840
+ if ((await read($, branch)).isLoaded) {
1841
+ const view = await loadBranch(run, top)
1842
+ await update($, branch, () => view)
1843
+ }
1844
+ }
1845
+
1846
+ const touchesFiles = (e.tool === 'Bash' && ran.isReadOnly !== true) || CHANGE_TOOLS.has(e.tool)
1847
+ if (touchesFiles) {
1848
+ refreshTimer?.cancel()
1849
+ refreshTimer = $.clock.after(REFRESH_MS, () => {
1850
+ refreshTimer = undefined
1851
+ void refresh().catch(() => undefined)
1852
+ })
1853
+ }
1854
+ return ran
1855
+ }
1856
+
1857
+ /** What a draw would otherwise ask for: the CI check and the live context figures, once the pane is up. */
1858
+ async function paneOpened($: Api): Promise<void> {
1859
+ await Promise.all([ciKick($).catch(() => undefined), contextKick($).catch(() => undefined)])
1860
+ }
1861
+
1862
+ /** A `next` that runs at most once: later calls get the first call's settled result. */
1863
+ const onceNext = <T,>(next: (input: T) => unknown): ((input: T) => Promise<unknown>) => {
1864
+ let first: Promise<unknown> | undefined
1865
+ return input => (first ??= Promise.resolve(next(input)))
1866
+ }
1867
+
1868
+ export const register: Register = on => {
1869
+ registerAgents(on)
1870
+ registerCi(on)
1871
+ registerContext(on)
1872
+ registerProgress(on)
1873
+ registerRunning(on)
1874
+ registerBlocked(on)
1596
1875
 
1597
1876
  on('ui.close', async ($, e, next) => {
1598
1877
  if (e.id === PANE && e.origin.kind === 'person') await update($, autoOpen, () => false)
@@ -1606,6 +1885,7 @@ export const register: Register = on => {
1606
1885
  if (e.context.tokens !== undefined) usage.tokens = e.context.tokens
1607
1886
  if (e.context.percent !== undefined) usage.percent = e.context.percent
1608
1887
  await update($, contextUsage, () => usage)
1888
+ await contextMeasured($ as Api, e.context)
1609
1889
  }
1610
1890
  return next(e)
1611
1891
  })
@@ -1620,22 +1900,7 @@ export const register: Register = on => {
1620
1900
  return result
1621
1901
  })
1622
1902
 
1623
- on('turn.start', async ($, e, next) => {
1624
- const loopId = e.agentId
1625
- if (loopId === undefined) await update($, working, () => true)
1626
- else await update($, agents, list => setAgentState(list, loopId, 'running'))
1627
- return next(e)
1628
- })
1629
1903
 
1630
- on('turn.complete', async ($, e, next) => {
1631
- const done = await next(e)
1632
- const loopId = e.agentId
1633
- if (loopId === undefined) await update($, working, () => false)
1634
- else await update($, agents, list => setAgentState(list, loopId, turnEndState(e.reason)))
1635
- scheduleRescan($)
1636
- void refreshAccent($).catch(() => undefined)
1637
- return done
1638
- })
1639
1904
 
1640
1905
  on('agent.spawn', async ($, e, next) => {
1641
1906
  const spawned = await next(e)
@@ -1655,15 +1920,18 @@ export const register: Register = on => {
1655
1920
  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
1656
1921
  if (e.viewport?.isFullscreen === true && !autoOpenSent && (await read($, autoOpen))) {
1657
1922
  autoOpenSent = true
1658
- void $.ui.open(PANE_ARGS).catch(() => undefined)
1923
+ void $.ui.open(PANE_ARGS).then(() => paneOpened($ as Api)).catch(() => undefined)
1659
1924
  }
1660
1925
  const usd = await read($, costUsd)
1661
1926
  if (usd <= 0) return next(e)
1662
1927
  return next({ ...e, props: { ...e.props, suffix: `${e.props.suffix} · ${dollars(usd)}` } })
1663
1928
  })
1664
1929
 
1665
- on('command.run', { command: 'activity' }, async $ => {
1930
+ on('command.run', { command: 'activity' }, async ($, e) => {
1931
+ const answered = await notifyCommand($ as Api, e.command, e.args)
1932
+ if (answered) return answered
1666
1933
  const opened = await $.ui.open(PANE_ARGS).catch(() => undefined)
1934
+ if (opened?.isPlaced !== false) void paneOpened($ as Api).catch(() => undefined)
1667
1935
  return { text: opened?.isPlaced === false ? 'El panel de actividad espera a que haya espacio.' : 'Panel de actividad abierto.' }
1668
1936
  })
1669
1937
 
@@ -1677,134 +1945,6 @@ export const register: Register = on => {
1677
1945
  return {}
1678
1946
  }).catch(($, e, next) => next(e))
1679
1947
 
1680
- on('tool.call', async ($, e, next) => {
1681
- const input = e as unknown as Record<string, unknown>
1682
- const run: Run = (argv, init) => $.process.run(argv, init)
1683
- const startedAt = await $.clock.now()
1684
- const loopId = e.agentId
1685
- const entry: ToolEntry = {
1686
- id: e.tool_use_id,
1687
- tool: e.tool,
1688
- summary: summarize(input),
1689
- status: 'running',
1690
- output: '',
1691
- startedAt,
1692
- ...(loopId === undefined ? {} : { agentId: loopId }),
1693
- }
1694
- if (e.tool === 'Bash') entry.command = cleanText(input.command)
1695
- const file = cleanText(input.file_path) ?? cleanText(input.notebook_path)
1696
- if (file !== undefined) entry.file = file
1697
- if (e.tool === 'Agent') entry.note = cleanText(input.subagent_type)
1698
- if (e.tool === 'AskUserQuestion') entry.decisions = decisionsOf(input)
1699
- await update($, entries, list => [...list, entry].slice(-KEEP))
1700
-
1701
- if (loopId !== undefined && !(await read($, agents)).some(one => one.id === loopId)) {
1702
- const info = (await $.agent.list().catch(() => [])).find(one => one.id === loopId)
1703
- if (info) {
1704
- const record: AgentRecord = { id: loopId, description: oneLine(info.description), type: oneLine(info.type), state: agentStateOf(info.status), startedAt }
1705
- if (info.name) record.name = oneLine(info.name)
1706
- await update($, agents, list => mergeAgent(list, record))
1707
- }
1708
- }
1709
-
1710
- const finish = async (finished: Partial<ToolEntry>) => {
1711
- const durationMs = (await $.clock.now()) - startedAt
1712
- await update($, entries, list => list.map(one => (one.id === entry.id ? { ...one, durationMs, ...finished } : one)))
1713
- }
1714
-
1715
- let ran: Awaited<ReturnType<typeof next>> | undefined
1716
- try {
1717
- ran = await next(e)
1718
- } finally {
1719
- if (ran === undefined) await finish({ status: 'interrupted', output: 'interrumpido' }).catch(() => undefined)
1720
- }
1721
-
1722
- const wasInterrupted = (ran.result as { interrupted?: unknown } | undefined)?.interrupted === true
1723
- const status: CallStatus = ran.deny !== undefined ? 'denied' : wasInterrupted ? 'interrupted' : ran.isError === true ? 'error' : 'ok'
1724
- const full = ran.deny ?? ran.text ?? ''
1725
- const finished: Partial<ToolEntry> = { status, output: lastLines(full, OUTPUT_LINES) }
1726
- if (entry.command !== undefined) {
1727
- const exitCode = exitCodeOf(full, ran.isError === true)
1728
- if (exitCode !== undefined) finished.exitCode = exitCode
1729
- if (isTestCommand(entry.command)) finished.testFiles = testFilesOf(full)
1730
- }
1731
- if (e.tool === 'AskUserQuestion') finished.decisions = answered(input, status, ran.result)
1732
- const spawnedId = text((ran.result as { agentId?: unknown } | undefined)?.agentId)
1733
- if (e.tool === 'Agent' && spawnedId !== undefined) {
1734
- finished.spawned = spawnedId
1735
- const state = agentResultState(status, ran.result)
1736
- const known = (await read($, agents)).some(one => one.id === spawnedId) || (await $.agent.list().catch(() => [])).some(one => one.id === spawnedId)
1737
- if (state !== undefined && known) {
1738
- const record: AgentRecord = { id: spawnedId, description: cleanText(input.description) ?? '', type: entry.note ?? 'agente', state, startedAt }
1739
- await update($, agents, list => mergeAgent(list, record))
1740
- }
1741
- }
1742
- await finish(finished)
1743
-
1744
- const rawCommand = text(input.command)
1745
- if (e.tool === 'Bash' && status !== 'denied' && rawCommand !== undefined && gitCommitVerbs(rawCommand).length > 0) {
1746
- const endedAt = await $.clock.now()
1747
- const dir = commitDirOf(rawCommand)
1748
- const top = dir === undefined || !SAFE_PATH.test(dir) ? undefined : await gitTop(run, dir)
1749
- const call: CommitCall = { startedAt, endedAt, ...(loopId === undefined ? {} : { agentId: loopId }), ...(top === undefined ? {} : { top }) }
1750
- await update($, commitCalls, list => [...list, call].slice(-COMMIT_CALLS))
1751
- scheduleRescan($ as Api)
1752
- }
1753
- if (e.tool === 'Bash' && status === 'ok' && rawCommand !== undefined && ran.text !== undefined) {
1754
- const found = commitsIn(rawCommand, ran.text)
1755
- if (found.length > 0) await update($, commits, list => addCommits(list, found, loopId, startedAt))
1756
- if (madeMergeCommit(rawCommand, ran.text)) {
1757
- void (async () => {
1758
- const top = await gitTop(run)
1759
- const head = top === undefined ? undefined : await loadHeadCommit(run, top)
1760
- if (head) await update($, commits, list => addCommits(list, [head], loopId, startedAt))
1761
- })().catch(() => undefined)
1762
- }
1763
- }
1764
-
1765
- const refresh = async () => {
1766
- const top = await gitTop(run)
1767
- if (top === undefined) return
1768
- const fileList = await loadUncommitted(run, top, async path => {
1769
- const info = await $.fs.stat(path)
1770
- return info.isLink || info.kind !== 'file' || info.size > 2_000_000 ? Promise.reject(new Error('skipped')) : $.fs.read(path)
1771
- })
1772
- if (fileList !== undefined) await update($, changes, () => fileList)
1773
-
1774
- for (const key of await read($, openFiles)) {
1775
- if (!key.startsWith('u:') && !key.startsWith('b:')) continue
1776
- const path = key.slice(2)
1777
- const change = key.startsWith('u:') ? fileList?.find(one => one.path === path) : undefined
1778
- if (key.startsWith('u:') && change === undefined) {
1779
- await update($, openFiles, keys => keys.filter(one => one !== key))
1780
- await update($, diffs, all => Object.fromEntries(Object.entries(all).filter(([name]) => name !== key)))
1781
- continue
1782
- }
1783
- const target: DiffTarget = key.startsWith('u:')
1784
- ? { scope: 'uncommitted', path, ...(change?.untracked ? { untracked: true } : {}) }
1785
- : { scope: 'branch', path, sha: (await read($, branch)).base }
1786
- const patch = await fetchDiff(run, top, target)
1787
- await update($, diffs, all => ({ ...all, [key]: patch }))
1788
- }
1789
-
1790
- await fillCommitStats($ as Api, run, top)
1791
-
1792
- if ((await read($, branch)).isLoaded) {
1793
- const view = await loadBranch(run, top)
1794
- await update($, branch, () => view)
1795
- }
1796
- }
1797
-
1798
- const touchesFiles = (e.tool === 'Bash' && ran.isReadOnly !== true) || CHANGE_TOOLS.has(e.tool)
1799
- if (touchesFiles) {
1800
- refreshTimer?.cancel()
1801
- refreshTimer = $.clock.after(REFRESH_MS, () => {
1802
- refreshTimer = undefined
1803
- void refresh().catch(() => undefined)
1804
- })
1805
- }
1806
- return ran
1807
- }).catch(($, e, next) => next(e))
1808
1948
 
1809
1949
  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
1810
1950
  if (e.props.isExpanded === true) return next(e)
@@ -1941,6 +2081,9 @@ export const register: Register = on => {
1941
2081
  await toggleCommit(action.sha)
1942
2082
  } else if (action.kind === 'diff') {
1943
2083
  await toggleDiff(action.target)
2084
+ } else if (action.kind === 'agents') {
2085
+ await actAgents($ as Api, action)
2086
+ await resetScroll()
1944
2087
  } else {
1945
2088
  await openTarget(action.target)
1946
2089
  }
@@ -1948,7 +2091,7 @@ export const register: Register = on => {
1948
2091
 
1949
2092
  const spansOf = (spans: Span[]) =>
1950
2093
  spans.map(one => (
1951
- <Text color={one.color} dimColor={one.dim} bold={one.bold} inverse={one.inverse}>{one.text}</Text>
2094
+ <Text {...paint(one)} backgroundColor={one.inverse ? undefined : PANE_BG} bold={one.bold} inverse={one.inverse}>{one.text}</Text>
1952
2095
  ))
1953
2096
  const cellOf = (rowKey: string, cell: Cell, index: number) => {
1954
2097
  const action = cell.action
@@ -1972,11 +2115,27 @@ export const register: Register = on => {
1972
2115
  return (
1973
2116
  <Box key={row.key} flexDirection="row" justifyContent="space-between" width={width}>
1974
2117
  {left}
1975
- <Text>{spansOf(row.right.length > 0 ? row.right : [span(' ')])}</Text>
2118
+ <Text wrap="truncate-end">{spansOf(row.right.length > 0 ? row.right : [span(' ')])}</Text>
1976
2119
  </Box>
1977
2120
  )
1978
2121
  }
1979
2122
 
1980
- return <Box flexDirection="column" width={width}>{frame.rows.map(rowOf)}</Box>
2123
+ return <Box flexDirection="column" width={width} height={Math.max(1, e.props.scroll.bodyRows)} backgroundColor={PANE_BG}>{frame.rows.map(row => rowOf(clampRow(row, width)))}</Box>
2124
+ })
2125
+ on('session.start', async ($, e, next) => {
2126
+ const once = onceNext(next as never)
2127
+ return savingsSessionStart($, e, ((e0: typeof e) => ciSessionStart($, e0, ((e1: typeof e) => contextSessionStart($, e1, ((e2: typeof e) => progressSessionStart($, e2, ((e3: typeof e) => runningSessionStart($, e3, ((e4: typeof e) => mainSessionStart($, e4, once as never).catch(() => once(e4))) as never)) as never)) as never)) as never)) as never)
2128
+ })
2129
+ on('turn.start', async ($, e, next) => {
2130
+ const once = onceNext(next as never)
2131
+ return blockedTurnStart($, e, ((e1: typeof e) => mainTurnStart($, e1, once as never).catch(() => once(e1))) as never)
2132
+ })
2133
+ on('turn.complete', async ($, e, next) => {
2134
+ const once = onceNext(next as never)
2135
+ return savingsTurnComplete($, e, ((s0: typeof e) => agentsTurnComplete($, s0, ((e0: typeof e) => ciTurnComplete($, e0, ((e1: typeof e) => contextTurnComplete($, e1, ((e2: typeof e) => progressTurnComplete($, e2, ((e3: typeof e) => notifyTurnComplete($, e3, ((e4: typeof e) => mainTurnComplete($, e4, once as never).catch(() => once(e4))) as never).catch(() => once(e3))) as never)) as never)) as never)) as never)) as never)
2136
+ })
2137
+ on('tool.call', async ($, e, next) => {
2138
+ const once = onceNext(next as never)
2139
+ return blockedToolCall($, e, ((e1: typeof e) => progressToolCall($, e1, ((e2: typeof e) => runningToolCall($, e2, ((e3: typeof e) => mainToolCall($, e3, once as never).catch(() => once(e3))) as never)) as never)) as never)
1981
2140
  })
1982
2141
  }