project-brain 0.43.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.
Files changed (30) hide show
  1. package/README.md +97 -11
  2. package/package.json +6 -6
  3. package/templates/claude-tui/activity-pane/.claude-plugin/plugin.json +7 -0
  4. package/templates/claude-tui/activity-pane/hooks/feat-agents.tsx +179 -0
  5. package/templates/claude-tui/activity-pane/hooks/feat-blocked.tsx +232 -0
  6. package/templates/claude-tui/activity-pane/hooks/feat-ci.tsx +400 -0
  7. package/templates/claude-tui/activity-pane/hooks/feat-context.tsx +283 -0
  8. package/templates/claude-tui/activity-pane/hooks/feat-notify.tsx +145 -0
  9. package/templates/claude-tui/activity-pane/hooks/feat-progress.tsx +413 -0
  10. package/templates/claude-tui/activity-pane/hooks/feat-running.tsx +528 -0
  11. package/templates/claude-tui/activity-pane/hooks/feat-savings.tsx +533 -0
  12. package/templates/claude-tui/activity-pane/hooks/hooks.json +1 -0
  13. package/templates/claude-tui/activity-pane/hooks/register.tsx +2141 -0
  14. package/templates/claude-tui/activity-pane/types/index.d.ts +201 -0
  15. package/templates/claude-tui/context-gate/.claude-plugin/plugin.json +7 -0
  16. package/templates/claude-tui/context-gate/hooks/hooks.json +1 -0
  17. package/templates/claude-tui/context-gate/hooks/register.tsx +355 -0
  18. package/templates/claude-tui/context-gate/types/index.d.ts +28 -0
  19. package/templates/claude-tui/skill-listing/.claude-plugin/plugin.json +7 -0
  20. package/templates/claude-tui/skill-listing/hooks/hooks.json +1 -0
  21. package/templates/claude-tui/skill-listing/hooks/register.tsx +300 -0
  22. package/templates/claude-tui/skill-listing/types/index.d.ts +22 -0
  23. package/templates/model-routing.md +10 -0
  24. package/templates/skills/brain-design-review/SKILL.md +65 -0
  25. package/templates/skills/brain-design-review/references/audit.md +56 -0
  26. package/templates/skills/brain-design-review/references/fix-loop.md +36 -0
  27. package/templates/skills/brain-design-review/references/probes.md +80 -0
  28. package/templates/skills/brain-qa-only/SKILL.md +59 -0
  29. package/templates/skills/brain-qa-only/references/report.md +63 -0
  30. package/templates/skills/brain-worktree/SKILL.md +18 -0
@@ -0,0 +1,2141 @@
1
+ import { atom, read, update } from 'claude-code'
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'
24
+
25
+ import type {
26
+ AgentRecord,
27
+ AgentState,
28
+ BranchCommit,
29
+ BranchView,
30
+ CallStatus,
31
+ CambiosScope,
32
+ CommitCall,
33
+ CommitRecord,
34
+ ContextUsage,
35
+ StepContext,
36
+ Decision,
37
+ DiffPatch,
38
+ DiffRow,
39
+ EditorState,
40
+ FileChange,
41
+ HistoryFiles,
42
+ HistoryRow,
43
+ HistoryView,
44
+ PaneScroll,
45
+ Tab,
46
+ TestFile,
47
+ ToolEntry,
48
+ } from '../types'
49
+
50
+ const PANE = 'activity'
51
+ const PANE_ARGS = { id: PANE, title: 'Actividad', columns: 1000 } as const
52
+ export const MAIN = 'main'
53
+ const KEEP = 300
54
+ const OUTPUT_LINES = 40
55
+ const DIFF_LINES = 120
56
+ const TEST_FILES = 30
57
+ const UNTRACKED_MAX = 100
58
+ const COMMIT_FILES = 100
59
+ const BRANCH_COMMITS = 100
60
+ const OPEN_DIFFS = 40
61
+ const REFRESH_MS = 400
62
+ const RESCAN_MS = 800
63
+ const SCAN_COMMITS = 200
64
+ const COMMIT_CALLS = 100
65
+ const HISTORY_COMMITS = 400
66
+ const HISTORY_FILES = 40
67
+ const WINDOW_SLACK_MS = 2000
68
+ const SUMMARY_FIELDS = ['command', 'file_path', 'notebook_path', 'pattern', 'url', 'query', 'description', 'prompt', 'skill'] as const
69
+ const ENVELOPE_FIELDS = new Set(['tool', 'tool_use_id', 'agentId', 'consent', 'requestMeta'])
70
+ const CHANGE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
71
+ const READ_TOOLS = new Set(['Read', 'Grep', 'Glob'])
72
+ export const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
73
+
74
+ export const ICONS = {
75
+ summary: '\u{F0756}',
76
+ commands: '\u{E795}',
77
+ diff: '\u{F4D2}',
78
+ history: '\u{F02A2}',
79
+ ok: '\u{F00C}',
80
+ error: '\u{F00D}',
81
+ running: '\u{F0996}',
82
+ denied: '\u{F05E}',
83
+ interrupted: '\u{F073A}',
84
+ waiting: '\u{F252}',
85
+ agent: '\u{F06A9}',
86
+ cost: '\u{F01C1}',
87
+ time: '\u{F051B}',
88
+ files: '\u{F0222}',
89
+ gauge: '\u{F029A}',
90
+ brain: '\u{F09D1}',
91
+ question: '\u{F02D7}',
92
+ decision: '\u{F062C}',
93
+ read: '\u{F0349}',
94
+ edit: '\u{F03EB}',
95
+ validate: '\u{F0668}',
96
+ command: '\u{E795}',
97
+ other: '\u{F0EB}',
98
+ log: '\u{F1DA}',
99
+ folder: '\u{F07C}',
100
+ file: '\u{F016}',
101
+ commit: '\u{E729}',
102
+ merge: '\u{E727}',
103
+ branch: '\u{E725}',
104
+ uncommitted: '\u{F11E7}',
105
+ hunk: '\u{F4D2}',
106
+ ts: '\u{F06E6}',
107
+ tsx: '\u{E7BA}',
108
+ json: '\u{F0626}',
109
+ md: '\u{F0354}',
110
+ sh: '\u{E691}',
111
+ } as const
112
+
113
+ const FILE_ICONS: Record<string, string> = {
114
+ ts: ICONS.ts,
115
+ mts: ICONS.ts,
116
+ cts: ICONS.ts,
117
+ tsx: ICONS.tsx,
118
+ jsx: ICONS.tsx,
119
+ json: ICONS.json,
120
+ md: ICONS.md,
121
+ sh: ICONS.sh,
122
+ zsh: ICONS.sh,
123
+ bash: ICONS.sh,
124
+ }
125
+
126
+ const entries = atom({ plugin: 'project-brain-activity', key: 'entries' } as const, [] as ToolEntry[], { shape: 'entries-4' })
127
+ const tabs = atom({ plugin: 'project-brain-activity', key: 'tabs' } as const, {} as Record<string, Tab>, { shape: 'tabs-1' })
128
+ const toggled = atom({ plugin: 'project-brain-activity', key: 'toggled' } as const, [] as string[], { shape: 'toggled-2' })
129
+ const changes = atom({ plugin: 'project-brain-activity', key: 'changes' } as const, [] as FileChange[], { shape: 'changes-2' })
130
+ const openFiles = atom({ plugin: 'project-brain-activity', key: 'openFiles' } as const, [] as string[], { shape: 'open-files-2' })
131
+ const diffs = atom({ plugin: 'project-brain-activity', key: 'diffs' } as const, {} as Record<string, DiffPatch>, { shape: 'diffs-2' })
132
+ const costUsd = atom({ plugin: 'project-brain-activity', key: 'costUsd' } as const, 0, { shape: 'cost-1' })
133
+ const stepContext = atom({ plugin: 'project-brain-activity', key: 'stepContext' } as const, {} as Record<string, StepContext>, { shape: 'step-context-1' })
134
+ const contextUsage = atom({ plugin: 'project-brain-activity', key: 'context' } as const, { window: 0 } as ContextUsage, { shape: 'context-2' })
135
+ const agents = atom({ plugin: 'project-brain-activity', key: 'agents' } as const, [] as AgentRecord[], { shape: 'agents-1' })
136
+ const pickedAgent = atom({ plugin: 'project-brain-activity', key: 'pickedAgent' } as const, '', { shape: 'picked-1' })
137
+ const working = atom({ plugin: 'project-brain-activity', key: 'working' } as const, false, { shape: 'working-1' })
138
+ const scroll = atom({ plugin: 'project-brain-activity', key: 'scroll' } as const, { offset: 0, follow: false } as PaneScroll, { shape: 'scroll-1' })
139
+ const commits = atom({ plugin: 'project-brain-activity', key: 'commits' } as const, [] as CommitRecord[], { shape: 'commits-1' })
140
+ const scopes = atom({ plugin: 'project-brain-activity', key: 'scopes' } as const, {} as Record<string, CambiosScope>, { shape: 'scopes-1' })
141
+ const branch = atom({ plugin: 'project-brain-activity', key: 'branch' } as const, { isLoaded: false, files: [], commits: [] } as BranchView, { shape: 'branch-1' })
142
+ const autoOpen = atom({ plugin: 'project-brain-activity', key: 'autoOpen' } as const, true, { shape: 'auto-open-1' })
143
+ const editor = atom({ plugin: 'project-brain-activity', key: 'editor' } as const, { dir: '', tab: '' } as EditorState, { shape: 'editor-1' })
144
+ const accentColor = atom({ plugin: 'project-brain-activity', key: 'accent' } as const, 'claude' as string, { shape: 'accent-1' })
145
+
146
+ /** Claude Code's session colours (/color) as their Dracula counterparts; 'default' and unknown names keep the claude tone. */
147
+ const SESSION_COLORS: Record<string, string> = {
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 } : {}) }
166
+ }
167
+
168
+ /** The last `"agentColor":"<name>"` grep match in the transcript, as a colour the pane can paint. */
169
+ export const accentOf = (grepOutput: string): string => {
170
+ const names = [...grepOutput.matchAll(/"agentColor":"([a-z]+)"/g)].map(match => match[1] ?? '')
171
+ return SESSION_COLORS[names.at(-1) ?? ''] ?? 'claude'
172
+ }
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
+
178
+ /** Reads the session colour Claude Code writes into the transcript as an `agent-color` entry. */
179
+ const refreshAccent = async ($: Api): Promise<void> => {
180
+ const [id, root, home] = await Promise.all([
181
+ $.session.id(),
182
+ $.session.root(),
183
+ $.process.run(['/usr/bin/printenv', 'HOME']).then(out => out.stdout.trim()).catch(() => ''),
184
+ ])
185
+ if (!home || !/^[0-9a-f-]{36}$/.test(id)) return
186
+ const transcript = `${home}/.claude/projects/${root.replace(/[^A-Za-z0-9]/g, '-')}/${id}.jsonl`
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)
191
+ if (!found) return
192
+ const wasScanned = accentScanned
193
+ accentScanned = true
194
+ if (wasScanned && !found.stdout.includes('"agentColor":"')) return
195
+ const next = accentOf(found.stdout)
196
+ if (next !== (await read($, accentColor))) await update($, accentColor, () => next)
197
+ }
198
+
199
+ const sessionStart = atom({ plugin: 'project-brain-activity', key: 'sessionStart' } as const, 0, { shape: 'session-start-1' })
200
+ const commitCalls = atom({ plugin: 'project-brain-activity', key: 'commitCalls' } as const, [] as CommitCall[], { shape: 'commit-calls-1' })
201
+ const history = atom({ plugin: 'project-brain-activity', key: 'history' } as const, { state: 'idle', rows: [], more: 0, loadedAt: 0 } as HistoryView, { shape: 'history-1' })
202
+ const historyFiles = atom({ plugin: 'project-brain-activity', key: 'historyFiles' } as const, {} as Record<string, HistoryFiles>, { shape: 'history-files-1' })
203
+
204
+ export type Api = Parameters<Hook<'turn.complete'>>[0]
205
+
206
+ // Timers are not drawn state: a reload dropping them only loses one debounce.
207
+ let refreshTimer: { cancel: () => void } | undefined
208
+ let autoOpenSent = false
209
+ let rescanTimer: { cancel: () => void } | undefined
210
+ let scanning: Promise<void> | undefined
211
+ let scanAgain = false
212
+ let historyLoading: Promise<void> | undefined
213
+
214
+ // ---------------------------------------------------------------- text
215
+
216
+ const ANSI = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007]*(?:\u0007|\u001b\\)|\u001b[@-_]/g
217
+ const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g
218
+ export const clean = (value: string): string => value.replace(ANSI, '').replace(/\t/g, ' ').replace(CONTROL, '')
219
+
220
+ const text = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined)
221
+
222
+ export const oneLine = (raw: string): string => clean(raw).replace(/\s+/g, ' ').trim()
223
+
224
+ const cleanText = (value: unknown): string | undefined => {
225
+ const found = text(value)
226
+ return found === undefined ? undefined : oneLine(found)
227
+ }
228
+
229
+ export const summarize = (input: Record<string, unknown>): string => {
230
+ const field = SUMMARY_FIELDS.find(name => text(input[name]) !== undefined)
231
+ if (field) return oneLine(String(input[field])).slice(0, 200)
232
+ const own = Object.fromEntries(Object.entries(input).filter(([name]) => !ENVELOPE_FIELDS.has(name)))
233
+ return oneLine(JSON.stringify(own)).slice(0, 200)
234
+ }
235
+
236
+ const lastLines = (raw: string | undefined, count: number): string =>
237
+ clean(raw ?? '')
238
+ .split('\n')
239
+ .map(line => line.trimEnd())
240
+ .filter(line => line !== '')
241
+ .slice(-count)
242
+ .map(line => line.slice(0, 300))
243
+ .join('\n')
244
+
245
+ export const dollars = (usd: number): string => `~$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
246
+
247
+ export const seconds = (ms: number | undefined): string => (ms === undefined ? '' : `${(ms / 1000).toFixed(1)} s`)
248
+
249
+ export const fit = (value: string, width: number): string => {
250
+ const room = Math.max(1, width)
251
+ return value.length <= room ? value : `${value.slice(0, Math.max(0, room - 1))}…`
252
+ }
253
+
254
+ const baseName = (path: string): string => path.split('/').pop() ?? path
255
+
256
+ const stem = (path: string): string => baseName(path).replace(/\.[^.]+$/, '')
257
+
258
+ const joinY = (parts: string[]): string =>
259
+ parts.length <= 1 ? (parts[0] ?? '') : `${parts.slice(0, -1).join(', ')} y ${parts.at(-1)}`
260
+
261
+ const distinct = (values: (string | undefined)[]): string[] => [...new Set(values.filter((one): one is string => one !== undefined))]
262
+
263
+ export const fileIcon = (path: string): string => FILE_ICONS[baseName(path).split('.').pop()?.toLowerCase() ?? ''] ?? ICONS.file
264
+
265
+ export const compact = (count: number): string => {
266
+ const trimmed = (value: number) => value.toFixed(1).replace(/\.0$/, '')
267
+ if (count < 1000) return String(Math.round(count))
268
+ if (count < 1_000_000) return count < 10_000 ? `${trimmed(count / 1000)}k` : `${Math.round(count / 1000)}k`
269
+ return `${trimmed(count / 1_000_000)}M`
270
+ }
271
+
272
+ export const contextPercentOf = (usage: ContextUsage): number | undefined =>
273
+ usage.tokens === undefined || usage.window <= 0 ? undefined : (usage.percent ?? (usage.tokens / usage.window) * 100)
274
+
275
+ export const contextLabel = (usage: ContextUsage): string => {
276
+ if (usage.window <= 0) return usage.tokens === undefined ? 'Contexto: sin medir' : `Contexto: ${compact(usage.tokens)} tokens`
277
+ const percent = contextPercentOf(usage)
278
+ const tokens = usage.tokens === undefined ? '—' : compact(usage.tokens)
279
+ return `Contexto: ${tokens} / ${compact(usage.window)} tokens${percent === undefined ? '' : ` (${Math.round(percent)} %)`}`
280
+ }
281
+
282
+ /**
283
+ * The context of the selected loop: the session's own figures for the main loop; for a subagent, its last
284
+ * model request (input + cache written + cache read) over the main window when it runs the same model.
285
+ */
286
+ export const scopedContext = (snap: Pick<Snapshot, 'context' | 'steps'>, scope: string): ContextUsage => {
287
+ if (scope === MAIN) return snap.context
288
+ const own = snap.steps[scope]
289
+ if (own === undefined) return { window: snap.context.window }
290
+ const sameModel = snap.steps[MAIN] !== undefined && snap.steps[MAIN].model === own.model
291
+ return sameModel ? { tokens: own.tokens, window: snap.context.window } : { tokens: own.tokens, window: 0 }
292
+ }
293
+
294
+ export const contextBar = (percent: number | undefined): string => {
295
+ const filled = percent === undefined ? 0 : Math.min(10, Math.max(0, Math.round(percent / 10)))
296
+ return '▰'.repeat(filled) + '▱'.repeat(10 - filled)
297
+ }
298
+
299
+ const contextTone = (percent: number | undefined): Tone =>
300
+ percent === undefined ? 'subtle' : percent < 60 ? 'success' : percent <= 85 ? 'warning' : 'error'
301
+
302
+ // ---------------------------------------------------------------- commands
303
+
304
+ const SEGMENT_SPLIT = /\s*(?:&&|\|\||;|\||\n)\s*/
305
+
306
+ export const commandHeads = (command: string): string[] =>
307
+ command
308
+ .split(SEGMENT_SPLIT)
309
+ .map(segment => segment.trim().replace(/^(?:[A-Za-z_]\w*=\S*\s+)*/, '').replace(/^(?:time|exec|command)\s+/, ''))
310
+ .filter(Boolean)
311
+
312
+ const TEST_HEADS = [
313
+ /^bun\s+(?:run\s+)?test\b/,
314
+ /^(?:npx\s+|bunx\s+|yarn\s+|pnpm\s+(?:exec\s+|dlx\s+)?)?(?:vitest|jest)\b/,
315
+ /^(?:python3?\s+-m\s+|uv\s+run\s+)?pytest\b/,
316
+ /^go\s+test\b/,
317
+ /^cargo\s+test\b/,
318
+ /^(?:pnpm|npm|yarn)\s+(?:run\s+)?test\b/,
319
+ ]
320
+
321
+ const CHECK_HEADS = [
322
+ /^(?:npx\s+|bunx\s+|yarn\s+|pnpm\s+(?:exec\s+)?)?(?:tsc|eslint|biome)\b/,
323
+ /^(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?(?:lint|typecheck|check)\b/,
324
+ ]
325
+
326
+ export const isTestCommand = (command: string): boolean => commandHeads(command).some(head => TEST_HEADS.some(pattern => pattern.test(head)))
327
+
328
+ export const isCheckCommand = (command: string): boolean => commandHeads(command).some(head => CHECK_HEADS.some(pattern => pattern.test(head)))
329
+
330
+ export const isValidationCommand = (command: string): boolean => isTestCommand(command) || isCheckCommand(command)
331
+
332
+ const WORD = String.raw`(?:'[^']*'|"[^"]*"|[^\s'"]+)`
333
+ const GIT_OPTION = String.raw`(?:\s+-[Cc]\s+${WORD}|\s+--?[\w-]+(?:=${WORD})?)`
334
+ const GIT_VERB = new RegExp(String.raw`^\(*\s*git(${GIT_OPTION}*)\s+(commit|merge|cherry-pick|revert)\b`)
335
+ const CD_HEAD = new RegExp(String.raw`^\(*\s*(?:cd|pushd)\s+(${WORD})\s*\)?$`)
336
+ const DASH_C = new RegExp(String.raw`\s-C\s+(${WORD})`, 'g')
337
+
338
+ const unquote = (word: string): string => word.replace(/^'([\s\S]*)'$/, '$1').replace(/^"([\s\S]*)"$/, '$1')
339
+
340
+ const joinDir = (base: string | undefined, next: string): string =>
341
+ base === undefined || next.startsWith('/') || next.startsWith('~') ? next : `${base.replace(/\/+$/, '')}/${next}`
342
+
343
+ /** The git verbs that make a commit, in a command with any `cd`, `git -C` or global option before them. */
344
+ export const gitCommitVerbs = (command: string): string[] =>
345
+ distinct(commandHeads(command).map(head => GIT_VERB.exec(head)?.[2]))
346
+
347
+ /**
348
+ * The directory the first commit verb runs in, as the command names it: every
349
+ * `cd` before it, then its own `-C` options. Undefined when it names none.
350
+ */
351
+ export const commitDirOf = (command: string): string | undefined => {
352
+ let dir: string | undefined
353
+ for (const head of commandHeads(command)) {
354
+ const cd = CD_HEAD.exec(head)
355
+ if (cd?.[1] !== undefined) {
356
+ dir = joinDir(dir, unquote(cd[1]))
357
+ continue
358
+ }
359
+ const verb = GIT_VERB.exec(head)
360
+ if (verb === null) continue
361
+ for (const option of (verb[1] ?? '').matchAll(DASH_C)) dir = joinDir(dir, unquote(option[1] ?? ''))
362
+ return dir
363
+ }
364
+ return undefined
365
+ }
366
+
367
+ export const exitCodeOf = (output: string | undefined, isError: boolean): number | undefined => {
368
+ if (!isError) return 0
369
+ const stated = /^\s*Exit code:?\s*(\d+)/i.exec(output ?? '')?.[1]
370
+ return stated === undefined ? undefined : Number(stated)
371
+ }
372
+
373
+ export type TestCounts = { passed?: number; failed?: number; pending?: number }
374
+
375
+ const countOf = (output: string, pattern: RegExp): number | undefined => {
376
+ const found = pattern.exec(output)?.[1]
377
+ return found === undefined ? undefined : Number(found)
378
+ }
379
+
380
+ export const testCounts = (output: string): TestCounts => ({
381
+ passed: countOf(output, /(\d+)\s+(?:pass(?:ed)?|passing)\b/i),
382
+ failed: countOf(output, /(\d+)\s+(?:fail(?:ed)?|failing)\b/i),
383
+ pending: countOf(output, /(\d+)\s+(?:skip(?:ped)?|todo|pending)\b/i),
384
+ })
385
+
386
+ const TEST_PATH = String.raw`[\w./@-]+\.(?:test|spec)\.[cm]?[jt]sx?`
387
+ const JEST_LINE = new RegExp(String.raw`^\s*(PASS|FAIL)\s+(${TEST_PATH})`)
388
+ const VITEST_LINE = new RegExp(String.raw`^\s*([✓✔]|[×✗❯])\s+(${TEST_PATH})`)
389
+ const BUN_HEADER = new RegExp(String.raw`^(${TEST_PATH}):\s*$`)
390
+
391
+ export const testFilesOf = (output: string): TestFile[] => {
392
+ const found = new Map<string, boolean>()
393
+ let bunFile: string | undefined
394
+ for (const line of clean(output).split('\n')) {
395
+ const jest = JEST_LINE.exec(line)
396
+ if (jest?.[2]) { found.set(jest[2], jest[1] === 'PASS'); continue }
397
+ const vitest = VITEST_LINE.exec(line)
398
+ if (vitest?.[2]) { found.set(vitest[2], /[✓✔]/.test(vitest[1] ?? '')); continue }
399
+ const header = BUN_HEADER.exec(line.trim())
400
+ if (header?.[1]) { bunFile = header[1]; found.set(bunFile, found.get(bunFile) ?? true); continue }
401
+ if (bunFile !== undefined && /^\s*(?:\(fail\)|✗)/.test(line)) found.set(bunFile, false)
402
+ }
403
+ return [...found].slice(0, TEST_FILES).map(([file, ok]) => ({ file, ok }))
404
+ }
405
+
406
+ export const verdictOf = (entry: ToolEntry): 'PASS' | 'FAIL' | undefined => {
407
+ if (entry.status === 'running' || entry.command === undefined) return undefined
408
+ const counts = testCounts(entry.output)
409
+ const validates = isValidationCommand(entry.command)
410
+ if (validates && counts.failed !== undefined && counts.failed > 0) return 'FAIL'
411
+ if (validates) return entry.exitCode === 0 ? 'PASS' : 'FAIL'
412
+ return undefined
413
+ }
414
+
415
+ export const resultLine = (entry: ToolEntry): string => {
416
+ const counts = isTestCommand(entry.command ?? '') ? testCounts(entry.output) : {}
417
+ const parts: string[] = []
418
+ if (counts.passed !== undefined) parts.push(`${counts.passed} pruebas`)
419
+ if (counts.failed !== undefined && counts.failed > 0) parts.push(`${counts.failed} fallaron`)
420
+ if (counts.pending !== undefined && counts.pending > 0) parts.push(`${counts.pending} ${counts.pending === 1 ? 'pendiente' : 'pendientes'}`)
421
+ if (entry.exitCode !== undefined) parts.push(`exit ${entry.exitCode}`)
422
+ return parts.join(' · ')
423
+ }
424
+
425
+ // ---------------------------------------------------------------- git parsing
426
+
427
+ const SHA = /^[0-9a-f]{7,40}$/
428
+
429
+ export const parseNumstatZ = (stdout: string): FileChange[] =>
430
+ stdout
431
+ .split('\0')
432
+ .map(record => record.replace(/^\n+/, ''))
433
+ .map(record => /^(-|\d+)\t(-|\d+)\t([\s\S]+)$/.exec(record))
434
+ .filter((found): found is RegExpExecArray => found !== null)
435
+ .map(([, added, removed, path]) => ({
436
+ path: path ?? '',
437
+ added: added === '-' ? 0 : Number(added),
438
+ removed: removed === '-' ? 0 : Number(removed),
439
+ ...(added === '-' ? { binary: true } : {}),
440
+ }))
441
+
442
+ export const lineCount = (body: string): number => (body === '' ? 0 : body.split('\n').length - (body.endsWith('\n') ? 1 : 0))
443
+
444
+ export type FoundCommit = { sha: string; subject: string; branch: string }
445
+
446
+ const COMMIT_LINE = /^\[(.+?) ([0-9a-f]{7,40})\] (.*)$/
447
+
448
+ export const commitsIn = (command: string, output: string): FoundCommit[] => {
449
+ if (gitCommitVerbs(command).length === 0) return []
450
+ return clean(output)
451
+ .split('\n')
452
+ .map(line => COMMIT_LINE.exec(line.trim()))
453
+ .filter((found): found is RegExpExecArray => found !== null)
454
+ .map(([, name, sha, subject]) => ({ sha: sha ?? '', subject: oneLine(subject ?? ''), branch: oneLine((name ?? '').replace(/ \(root-commit\)$/, '')) }))
455
+ }
456
+
457
+ export const madeMergeCommit = (command: string, output: string): boolean =>
458
+ gitCommitVerbs(command).includes('merge') && /^Merge made by/m.test(output)
459
+
460
+ export const addCommits = (list: CommitRecord[], found: FoundCommit[], agentId: string | undefined, at: number): CommitRecord[] => {
461
+ const fresh = found.filter(one => SHA.test(one.sha) && !list.some(known => known.sha === one.sha))
462
+ return [...list, ...fresh.map(one => ({ ...one, at, ...(agentId === undefined ? {} : { agentId }) }))].slice(-200)
463
+ }
464
+
465
+ export const parseLogZ = (stdout: string): BranchCommit[] =>
466
+ stdout
467
+ .split('\0')
468
+ .map(record => record.replace(/^\n+/, '').split('\u001f'))
469
+ .filter(([sha]) => sha !== undefined && SHA.test(sha))
470
+ .map(([sha, subject]) => ({ sha: sha ?? '', subject: oneLine(subject ?? '') }))
471
+
472
+ export const diffRows = (patch: string): DiffRow[] => {
473
+ const rows: DiffRow[] = []
474
+ let oldLine = 0
475
+ let newLine = 0
476
+ for (const raw of patch.split('\n')) {
477
+ const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/.exec(raw)
478
+ if (hunk) {
479
+ oldLine = Number(hunk[1])
480
+ newLine = Number(hunk[2])
481
+ rows.push({ gutter: '', sign: '@@', text: clean(`línea ${newLine}${hunk[3] ?? ''}`), kind: 'hunk' })
482
+ continue
483
+ }
484
+ if (rows.length === 0 || raw.startsWith('\\')) continue
485
+ const sign = raw.charAt(0)
486
+ const body = clean(raw.slice(1))
487
+ if (sign === '+') rows.push({ gutter: String(newLine++), sign: '+', text: body, kind: 'add' })
488
+ else if (sign === '-') rows.push({ gutter: String(oldLine++), sign: '-', text: body, kind: 'del' })
489
+ else if (sign === ' ') { rows.push({ gutter: String(newLine), sign: ' ', text: body, kind: 'same' }); oldLine++; newLine++ }
490
+ }
491
+ return rows
492
+ }
493
+
494
+ // ---------------------------------------------------------------- git loaders
495
+
496
+ export type RunResult = { exitCode: number; stdout: string; stderr: string }
497
+ export type Run = (argv: readonly string[], init?: { cwd?: string; timeoutMs?: number; stdin?: string }) => Promise<RunResult>
498
+ export type ReadText = (path: string) => Promise<string>
499
+
500
+ export const quietly = (run: Run, argv: readonly string[], cwd?: string, stdin?: string): Promise<RunResult | undefined> =>
501
+ run(argv, cwd === undefined && stdin === undefined ? undefined : { ...(cwd === undefined ? {} : { cwd }), ...(stdin === undefined ? {} : { stdin }) }).catch(() => undefined)
502
+
503
+ export const gitTop = async (run: Run, cwd?: string): Promise<string | undefined> => {
504
+ const found = await quietly(run, ['git', 'rev-parse', '--show-toplevel'], cwd)
505
+ return found?.exitCode === 0 ? found.stdout.replace(/\n$/, '') : undefined
506
+ }
507
+
508
+ export const loadUncommitted = async (run: Run, top: string, readText: ReadText): Promise<FileChange[] | undefined> => {
509
+ const head = await quietly(run, ['git', 'rev-parse', '--verify', '-q', 'HEAD'], top)
510
+ const base = head?.exitCode === 0 ? 'HEAD' : EMPTY_TREE
511
+ const tracked = await quietly(run, ['git', 'diff', '--numstat', '-z', '--no-renames', base], top)
512
+ if (tracked?.exitCode !== 0) return undefined
513
+ const others = await quietly(run, ['git', 'ls-files', '--others', '--exclude-standard', '-z'], top)
514
+ const paths = others?.exitCode === 0 ? others.stdout.split('\0').filter(Boolean).slice(0, UNTRACKED_MAX) : []
515
+ const untracked = await Promise.all(
516
+ paths.map(async (path): Promise<FileChange> => {
517
+ const body = await readText(`${top}/${path}`).catch(() => undefined)
518
+ const isBinary = body === undefined || body.includes('\0')
519
+ return { path, added: isBinary ? 0 : lineCount(body), removed: 0, untracked: true, ...(isBinary ? { binary: true } : {}) }
520
+ }),
521
+ )
522
+ return [...parseNumstatZ(tracked.stdout), ...untracked]
523
+ }
524
+
525
+ export type CommitStats = { added: number; removed: number; files: FileChange[]; isMerge: boolean }
526
+
527
+ export const loadCommitStats = async (run: Run, top: string, sha: string): Promise<CommitStats | undefined> => {
528
+ if (!SHA.test(sha)) return undefined
529
+ const shown = await quietly(run, ['git', 'show', '--numstat', '-z', '--no-renames', '--diff-merges=first-parent', '--format=', sha], top)
530
+ if (shown?.exitCode !== 0) return undefined
531
+ const parents = await quietly(run, ['git', 'show', '-s', '--format=%P', sha], top)
532
+ const files = parseNumstatZ(shown.stdout)
533
+ return {
534
+ added: files.reduce((sum, one) => sum + one.added, 0),
535
+ removed: files.reduce((sum, one) => sum + one.removed, 0),
536
+ files: files.slice(0, COMMIT_FILES),
537
+ isMerge: (parents?.stdout.trim().split(/\s+/).filter(Boolean).length ?? 0) > 1,
538
+ }
539
+ }
540
+
541
+ export const loadHeadCommit = async (run: Run, top: string): Promise<FoundCommit | undefined> => {
542
+ const head = await quietly(run, ['git', 'log', '-1', '--format=%h%x1f%s', 'HEAD'], top)
543
+ const name = await quietly(run, ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], top)
544
+ const [sha, subject] = (head?.stdout ?? '').replace(/\n$/, '').split('\u001f')
545
+ if (head?.exitCode !== 0 || sha === undefined || !SHA.test(sha)) return undefined
546
+ return { sha, subject: oneLine(subject ?? ''), branch: oneLine(name?.stdout ?? '') }
547
+ }
548
+
549
+ const BASE_REFS = ['main', 'master', 'origin/main', 'origin/master']
550
+
551
+ export const loadBranch = async (run: Run, top: string): Promise<BranchView> => {
552
+ for (const ref of BASE_REFS) {
553
+ const exists = await quietly(run, ['git', 'rev-parse', '--verify', '-q', `${ref}^{commit}`], top)
554
+ if (exists?.exitCode !== 0) continue
555
+ const merged = await quietly(run, ['git', 'merge-base', 'HEAD', ref], top)
556
+ const base = merged?.stdout.trim() ?? ''
557
+ if (merged?.exitCode !== 0 || !/^[0-9a-f]{40,64}$/.test(base)) continue
558
+ const numstat = await quietly(run, ['git', 'diff', '--numstat', '-z', '--no-renames', `${base}...HEAD`], top)
559
+ const log = await quietly(run, ['git', 'log', '-z', `-n${BRANCH_COMMITS}`, '--format=%h%x1f%s', `${base}..HEAD`], top)
560
+ return { isLoaded: true, baseRef: ref, base, files: parseNumstatZ(numstat?.stdout ?? ''), commits: parseLogZ(log?.stdout ?? '') }
561
+ }
562
+ return { isLoaded: true, files: [], commits: [], error: 'No encontré main ni master para comparar la rama.' }
563
+ }
564
+
565
+ // ---------------------------------------------------------------- session commits
566
+
567
+ export type ScannedCommit = { sha: string; subject: string; at: number; isMerge: boolean; branch: string; agentId?: string }
568
+ export type Worktree = { path: string; branch?: string; head?: string }
569
+
570
+ export const SCAN_FORMAT = '--format=%H%x1f%ct%x1f%P%x1f%s'
571
+
572
+ export const parseScanZ = (stdout: string): Omit<ScannedCommit, 'branch'>[] =>
573
+ stdout
574
+ .split('\0')
575
+ .map(record => record.replace(/^\n+/, '').split('\u001f'))
576
+ .filter(([sha, at]) => sha !== undefined && /^[0-9a-f]{40,64}$/.test(sha) && /^\d+$/.test(at ?? ''))
577
+ .map(([sha, at, parents, ...subject]) => ({
578
+ sha: sha ?? '',
579
+ at: Number(at) * 1000,
580
+ isMerge: (parents ?? '').trim().split(/\s+/).filter(Boolean).length > 1,
581
+ subject: oneLine(subject.join(' ')),
582
+ }))
583
+
584
+ export const parseWorktrees = (porcelain: string): Worktree[] =>
585
+ porcelain
586
+ .split(/\n\s*\n/)
587
+ .map(block => {
588
+ const lines = block.split('\n')
589
+ const value = (name: string) => lines.find(one => one.startsWith(`${name} `))?.slice(name.length + 1)
590
+ const path = value('worktree')
591
+ const branchRef = value('branch')
592
+ const head = value('HEAD')
593
+ return path === undefined || !SAFE_PATH.test(path)
594
+ ? undefined
595
+ : { path, ...(branchRef ? { branch: oneLine(branchRef.replace(/^refs\/heads\//, '')) } : {}), ...(head ? { head } : {}) }
596
+ })
597
+ .filter((one): one is Worktree => one !== undefined)
598
+
599
+ /** `git name-rev --name-only` lines, one per sha in order: `main~2` names `main`. */
600
+ export const parseNameRev = (stdout: string, shas: string[]): Record<string, string> => {
601
+ const names = stdout.split('\n')
602
+ return Object.fromEntries(
603
+ shas
604
+ .map((sha, index) => [sha, oneLine((names[index] ?? '').replace(/[~^].*$/, ''))] as const)
605
+ .filter(([, name]) => name !== '' && name !== 'undefined'),
606
+ )
607
+ }
608
+
609
+ /**
610
+ * Who made a commit the rescan found: the agent whose commit-verb call was
611
+ * running when it was made (preferring one in the commit's worktree); else the
612
+ * agent whose latest commit-verb call ran in that worktree; else the main loop.
613
+ */
614
+ export const attributeCommit = (commit: Pick<ScannedCommit, 'at' | 'branch'>, calls: CommitCall[], worktrees: Worktree[]): string | undefined => {
615
+ const tree = worktrees.find(one => one.branch !== undefined && one.branch === commit.branch)?.path
616
+ const during = calls.filter(call => call.startedAt - WINDOW_SLACK_MS <= commit.at && commit.at <= call.endedAt + WINDOW_SLACK_MS)
617
+ const inTree = tree === undefined ? [] : during.filter(call => call.top === tree)
618
+ const owners = distinct((inTree.length > 0 ? inTree : during).map(call => call.agentId ?? MAIN))
619
+ if (owners.length === 1) return owners[0] === MAIN ? undefined : owners[0]
620
+ if (tree === undefined) return undefined
621
+ const there = calls.filter(call => call.top === tree).sort((a, b) => a.startedAt - b.startedAt)
622
+ const latest = there.filter(call => call.startedAt <= commit.at + WINDOW_SLACK_MS).at(-1) ?? there.at(-1)
623
+ return latest?.agentId
624
+ }
625
+
626
+ const sameSha = (a: string, b: string): boolean => a.length > 0 && b.length > 0 && (a.startsWith(b) || b.startsWith(a))
627
+
628
+ /** Adds what the rescan found to the list, keyed by sha: a commit already known keeps its agent. */
629
+ export const mergeScanned = (list: CommitRecord[], found: ScannedCommit[]): CommitRecord[] => {
630
+ const merged = list.map(known => {
631
+ const same = found.find(one => sameSha(known.sha, one.sha))
632
+ return same !== undefined && known.branch === '' ? { ...known, branch: same.branch } : known
633
+ })
634
+ for (const one of found) {
635
+ if (merged.some(known => sameSha(known.sha, one.sha))) continue
636
+ merged.push({
637
+ sha: one.sha,
638
+ subject: one.subject,
639
+ branch: one.branch,
640
+ at: one.at,
641
+ ...(one.isMerge ? { isMerge: true } : {}),
642
+ ...(one.agentId === undefined ? {} : { agentId: one.agentId }),
643
+ })
644
+ }
645
+ return merged.sort((a, b) => a.at - b.at).slice(-SCAN_COMMITS)
646
+ }
647
+
648
+ export type SessionScan = { repo: string; commits: ScannedCommit[] }
649
+
650
+ /** Every commit this user made since `since`, on any branch of any worktree of the session's repository. */
651
+ export const scanSessionCommits = async (run: Run, since: number, calls: CommitCall[]): Promise<SessionScan | undefined> => {
652
+ const top = await gitTop(run)
653
+ if (top === undefined) return undefined
654
+ const common = await quietly(run, ['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], top)
655
+ const repo = common?.exitCode === 0 && SAFE_PATH.test(common.stdout.trim()) ? common.stdout.trim() : top
656
+ const email = (await quietly(run, ['git', 'config', 'user.email'], top))?.stdout.trim() ?? ''
657
+ const author = email !== '' && SAFE_PATH.test(email) ? ['-F', `--author=<${email}>`] : []
658
+ const log = await quietly(run, ['git', 'log', '--all', `--since=@${Math.floor(since / 1000)}`, ...author, '-z', `-n${SCAN_COMMITS}`, SCAN_FORMAT], repo)
659
+ if (log?.exitCode !== 0) return undefined
660
+ const found = parseScanZ(log.stdout)
661
+ if (found.length === 0) return { repo, commits: [] }
662
+ const listed = await quietly(run, ['git', 'worktree', 'list', '--porcelain'], repo)
663
+ const worktrees = listed?.exitCode === 0 ? parseWorktrees(listed.stdout) : []
664
+ const shas = found.map(one => one.sha)
665
+ const named = await quietly(run, ['git', 'name-rev', '--name-only', '--refs=refs/heads/*', ...shas], repo)
666
+ const branches = named?.exitCode === 0 ? parseNameRev(named.stdout, shas) : {}
667
+ return {
668
+ repo,
669
+ commits: found.map(one => {
670
+ const branchName = branches[one.sha] ?? ''
671
+ const agentId = attributeCommit({ at: one.at, branch: branchName }, calls, worktrees)
672
+ return { ...one, branch: branchName, ...(agentId === undefined ? {} : { agentId }) }
673
+ }),
674
+ }
675
+ }
676
+
677
+ // ---------------------------------------------------------------- history
678
+
679
+ export const HISTORY_FORMAT = '--format=%x1e%h%x1f%D%x1f%ct%x1f%an%x1f%s'
680
+
681
+ export const parseGraphLog = (stdout: string): HistoryRow[] =>
682
+ stdout
683
+ .split('\n')
684
+ .filter(raw => raw.trim() !== '')
685
+ .map((raw): HistoryRow => {
686
+ const mark = raw.indexOf('\u001e')
687
+ const [sha, refs, at, author, ...subject] = mark < 0 ? [] : raw.slice(mark + 1).split('\u001f')
688
+ if (mark < 0 || sha === undefined || !SHA.test(sha)) return { graph: clean(raw).trimEnd() }
689
+ return {
690
+ graph: clean(raw.slice(0, mark)),
691
+ sha,
692
+ refs: (refs ?? '').split(', ').map(oneLine).filter(Boolean),
693
+ subject: oneLine(subject.join(' ')),
694
+ ...(/^\d+$/.test(at ?? '') ? { at: Number(at) } : {}),
695
+ author: oneLine(author ?? ''),
696
+ }
697
+ })
698
+
699
+ export const loadHistory = async (run: Run, now: number): Promise<HistoryView> => {
700
+ const top = await gitTop(run)
701
+ if (top === undefined) return { state: 'error', rows: [], more: 0, loadedAt: now, error: 'No hay repositorio git aquí.' }
702
+ const log = await quietly(run, ['git', 'log', '--graph', '--all', '--date-order', '--no-color', `-n${HISTORY_COMMITS}`, HISTORY_FORMAT], top)
703
+ if (log?.exitCode !== 0) {
704
+ const reason = oneLine(log?.stderr ?? '').slice(0, 160)
705
+ return { state: 'error', rows: [], more: 0, loadedAt: now, error: `git log falló${reason ? `: ${reason}` : '.'}` }
706
+ }
707
+ const rows = parseGraphLog(log.stdout)
708
+ const shown = rows.filter(row => row.sha !== undefined).length
709
+ const counted = await quietly(run, ['git', 'rev-list', '--all', '--count'], top)
710
+ const total = counted?.exitCode === 0 ? Number(counted.stdout.trim()) : shown
711
+ return { state: 'ready', rows, more: Number.isFinite(total) ? Math.max(0, total - shown) : 0, loadedAt: now }
712
+ }
713
+
714
+ export const ago = (atSeconds: number | undefined, nowMs: number): string => {
715
+ if (atSeconds === undefined) return ''
716
+ const minutes = Math.max(0, Math.round((nowMs / 1000 - atSeconds) / 60))
717
+ if (minutes < 1) return 'ahora'
718
+ if (minutes < 60) return `hace ${minutes} min`
719
+ const hours = Math.round(minutes / 60)
720
+ if (hours < 24) return `hace ${hours} h`
721
+ const days = Math.round(hours / 24)
722
+ if (days < 14) return `hace ${days} d`
723
+ if (days < 60) return `hace ${Math.round(days / 7)} sem`
724
+ if (days < 365) return `hace ${Math.round(days / 30)} meses`
725
+ const years = Math.round(days / 365)
726
+ return `hace ${years} ${years === 1 ? 'año' : 'años'}`
727
+ }
728
+
729
+ export type DiffTarget = { scope: 'uncommitted' | 'commit' | 'branch'; path: string; sha?: string; untracked?: boolean }
730
+
731
+ export const targetKey = (target: DiffTarget): string =>
732
+ target.scope === 'commit' ? `c:${target.sha ?? ''}:${target.path}` : `${target.scope === 'branch' ? 'b' : 'u'}:${target.path}`
733
+
734
+ export const diffArgv = (target: DiffTarget): string[] | undefined => {
735
+ const plain = ['--no-color', '--no-ext-diff']
736
+ if (target.scope === 'uncommitted' && target.untracked) return ['git', 'diff', '--no-index', ...plain, '--', '/dev/null', target.path]
737
+ if (target.scope === 'uncommitted') return ['git', '--literal-pathspecs', 'diff', ...plain, 'HEAD', '--', target.path]
738
+ if (target.sha === undefined || !/^[0-9a-f]{7,64}$/.test(target.sha)) return undefined
739
+ if (target.scope === 'commit') return ['git', '--literal-pathspecs', 'show', ...plain, '--diff-merges=first-parent', '--format=', target.sha, '--', target.path]
740
+ return ['git', '--literal-pathspecs', 'diff', ...plain, `${target.sha}...HEAD`, '--', target.path]
741
+ }
742
+
743
+ export const fetchDiff = async (run: Run, top: string, target: DiffTarget): Promise<DiffPatch> => {
744
+ const argv = diffArgv(target)
745
+ const shown = argv ? await quietly(run, argv, top) : undefined
746
+ const rows = shown !== undefined && shown.exitCode <= 1 ? diffRows(shown.stdout) : []
747
+ return { rows: rows.slice(0, DIFF_LINES), total: rows.length }
748
+ }
749
+
750
+ // ---------------------------------------------------------------- editor
751
+
752
+ /** POSIX single quoting: the one quoting helper every command string uses. */
753
+ export const shQuote = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`
754
+
755
+ const SAFE_PATH = /^[^\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]+$/
756
+ const SAFE_DIR = /^[\w./-]+$/
757
+ const SAFE_BASE = /^(?:HEAD|[0-9a-f]{7,64})(?:~1)?$/
758
+ const SAFE_TAB = /^[\w-]{1,64}$/
759
+
760
+ export const diffCommand = (base: string): string =>
761
+ `lua vim.defer_fn(function() pcall(vim.cmd, "Gitsigns diffthis ${base}") end, 200)`
762
+
763
+ export const RESET_KEYS = '<C-\\><C-n>:silent! diffoff! | only<CR>'
764
+
765
+ export const diffKeys = (base: string): string => `<C-\\><C-n>:${diffCommand(base)}<CR>`
766
+
767
+ export type EditorRequest = { top: string; path: string; base: string; editor: EditorState }
768
+ export type EditorOutcome = { ok: boolean; message?: string; editor?: EditorState }
769
+
770
+ const ENV_NAMES = ['TMPDIR', 'XDG_RUNTIME_DIR', 'SUPACODE_SOCKET_PATH', 'TMUX'] as const
771
+
772
+ const readEnv = async (run: Run): Promise<Record<(typeof ENV_NAMES)[number], string>> => {
773
+ const values = await Promise.all(ENV_NAMES.map(name => quietly(run, ['printenv', name])))
774
+ return Object.fromEntries(ENV_NAMES.map((name, index) => [name, values[index]?.exitCode === 0 ? (values[index]?.stdout ?? '').replace(/\n$/, '') : ''])) as Record<(typeof ENV_NAMES)[number], string>
775
+ }
776
+
777
+ /**
778
+ * Opens `path` in one nvim per session, reused on every call. Every piece of
779
+ * data travels as its own argv item; the only command string is the one a
780
+ * terminal multiplexer needs, and every item in it goes through shQuote.
781
+ */
782
+ export const openInEditor = async (run: Run, exists: (path: string) => Promise<boolean>, request: EditorRequest): Promise<EditorOutcome> => {
783
+ if (!SAFE_PATH.test(request.path) || !SAFE_PATH.test(request.top)) return { ok: false, message: 'Ese nombre de archivo no se puede abrir en el editor.' }
784
+ if (!SAFE_BASE.test(request.base)) return { ok: false, message: 'Referencia de git no válida.' }
785
+ const file = `${request.top}/${request.path}`
786
+ const env = await readEnv(run)
787
+
788
+ let dir = request.editor.dir
789
+ if (dir !== '' && !(await isPrivateDir(run, dir))) dir = ''
790
+ if (dir === '' || !(await exists(dir).catch(() => false))) {
791
+ const base = (env.XDG_RUNTIME_DIR || env.TMPDIR || '/tmp').replace(/\/+$/, '')
792
+ const made = await quietly(run, ['mktemp', '-d', `${base}/pb-nvim.XXXXXX`])
793
+ dir = made?.exitCode === 0 ? made.stdout.trim() : ''
794
+ if (dir === '' || !SAFE_DIR.test(dir)) return { ok: false, message: 'No se pudo crear la carpeta privada del editor.' }
795
+ }
796
+ const sock = `${dir}/nvim.sock`
797
+ const state: EditorState = { dir, tab: dir === request.editor.dir ? request.editor.tab : '' }
798
+
799
+ const alive = await quietly(run, ['nvim', '--server', sock, '--remote-expr', '1'])
800
+ if (alive?.exitCode === 0) {
801
+ await quietly(run, ['nvim', '--server', sock, '--remote-send', RESET_KEYS])
802
+ const opened = await quietly(run, ['nvim', '--server', sock, '--remote', file])
803
+ if (opened?.exitCode !== 0) return { ok: false, message: 'nvim no pudo abrir el archivo.', editor: state }
804
+ await quietly(run, ['nvim', '--server', sock, '--remote-send', diffKeys(request.base)])
805
+ if (state.tab !== '' && env.SUPACODE_SOCKET_PATH !== '') await quietly(run, ['supacode', 'tab', 'focus', '-t', state.tab])
806
+ return { ok: true, editor: state }
807
+ }
808
+
809
+ await quietly(run, ['rm', '-f', '--', sock])
810
+ const launcher = `${dir}/open.sh`
811
+ const script = `#!/bin/sh\ncd ${shQuote(request.top)} && exec nvim --listen ${shQuote(sock)} ${shQuote(`+${diffCommand(request.base)}`)} -- ${shQuote(file)}\n`
812
+ const written = await quietly(run, ['sh', '-c', 'umask 077 && cat > "$1"', 'write-launcher', launcher], undefined, script)
813
+ if (written?.exitCode !== 0) return { ok: false, message: 'No se pudo preparar el editor.', editor: state }
814
+ const start = `/bin/sh ${launcher}`
815
+ if (env.SUPACODE_SOCKET_PATH !== '') {
816
+ const split = await quietly(run, ['supacode', 'pane', 'split', '-d', 'h', '-i', start])
817
+ if (split?.exitCode === 0) {
818
+ const tab = split.stdout.trim()
819
+ return { ok: true, editor: { dir, tab: SAFE_TAB.test(tab) ? tab : '' } }
820
+ }
821
+ }
822
+ if (env.TMUX !== '') {
823
+ const split = await quietly(run, ['tmux', 'split-window', '-h', start])
824
+ if (split?.exitCode === 0) return { ok: true, editor: { dir, tab: '' } }
825
+ }
826
+ const terminal = await quietly(run, [
827
+ 'osascript',
828
+ '-e', 'on run argv',
829
+ '-e', 'tell application "Terminal" to do script (item 1 of argv)',
830
+ '-e', 'end run',
831
+ start,
832
+ ])
833
+ return terminal?.exitCode === 0
834
+ ? { ok: true, editor: { dir, tab: '' } }
835
+ : { ok: false, message: 'No se pudo abrir el editor (sin Supacode, tmux ni Terminal).', editor: { dir, tab: '' } }
836
+ }
837
+
838
+ /** The socket directory is reused only while it is still ours: a directory, owned by this user, mode 0700. */
839
+ const isPrivateDir = async (run: Run, dir: string): Promise<boolean> => {
840
+ if (!SAFE_DIR.test(dir)) return false
841
+ const uid = (await quietly(run, ['id', '-u']))?.stdout.trim() ?? ''
842
+ if (!/^\d+$/.test(uid)) return false
843
+ const found = await quietly(run, ['find', dir, '-maxdepth', '0', '-type', 'd', '-user', uid, '-perm', '700'])
844
+ return found?.exitCode === 0 && found.stdout.trim() === dir
845
+ }
846
+
847
+ export const editorBase = (target: DiffTarget): string =>
848
+ target.scope === 'commit' ? `${target.sha ?? ''}~1` : target.scope === 'branch' ? (target.sha ?? '') : 'HEAD'
849
+
850
+ // ---------------------------------------------------------------- steps
851
+
852
+ export type StepKind = 'read' | 'edit' | 'validate' | 'command' | 'agent' | 'question' | 'other'
853
+
854
+ export type Step = {
855
+ key: string
856
+ kind: StepKind
857
+ title: string
858
+ detail: string
859
+ status: CallStatus
860
+ durationMs?: number
861
+ }
862
+
863
+ export const stepKindOf = (entry: ToolEntry): StepKind => {
864
+ if (READ_TOOLS.has(entry.tool)) return 'read'
865
+ if (CHANGE_TOOLS.has(entry.tool)) return 'edit'
866
+ if (entry.tool === 'Bash') return isValidationCommand(entry.command ?? '') ? 'validate' : 'command'
867
+ if (entry.tool === 'Agent' || entry.tool === 'Task') return 'agent'
868
+ if (entry.tool === 'AskUserQuestion') return 'question'
869
+ return 'other'
870
+ }
871
+
872
+ const SOLO_KINDS = new Set<StepKind>(['agent', 'question', 'other'])
873
+
874
+ const groupStatus = (group: ToolEntry[]): CallStatus => {
875
+ if (group.some(one => one.status === 'running')) return 'running'
876
+ if (group.some(one => one.status === 'error')) return 'error'
877
+ if (group.some(one => one.status === 'interrupted')) return 'interrupted'
878
+ if (group.some(one => one.status === 'denied')) return 'denied'
879
+ return 'ok'
880
+ }
881
+
882
+ export const wallTime = (group: ToolEntry[]): number | undefined => {
883
+ if (group.length === 0 || group.some(one => one.durationMs === undefined)) return undefined
884
+ const start = Math.min(...group.map(one => one.startedAt))
885
+ const end = Math.max(...group.map(one => one.startedAt + (one.durationMs ?? 0)))
886
+ return end - start
887
+ }
888
+
889
+ const filesLine = (files: string[], verb: string): string =>
890
+ files.length > 3 ? `${files.length} archivos ${verb}` : files.map(baseName).join(' · ')
891
+
892
+ const describeRead = (group: ToolEntry[], running: boolean) => {
893
+ const files = distinct(group.filter(one => one.tool === 'Read').map(one => one.file))
894
+ const searches = group.filter(one => one.tool !== 'Read')
895
+ const topic = files.length === 0 ? 'el código' : files.length > 2 ? `${files.length} archivos` : joinY(files.map(stem))
896
+ const parts = [files.length > 0 ? filesLine(files, 'consultados') : '', searches.length > 0 ? `${searches.length} ${searches.length === 1 ? 'búsqueda' : 'búsquedas'}` : '']
897
+ return { title: `${running ? 'Revisando' : 'Revisó'} ${topic}`, detail: parts.filter(Boolean).join(' · ') }
898
+ }
899
+
900
+ const describeEdit = (group: ToolEntry[], running: boolean) => {
901
+ const files = distinct(group.map(one => one.file))
902
+ const title =
903
+ files.length === 1
904
+ ? `${running ? 'Actualizando' : 'Actualizó'} ${stem(files[0] ?? '')}`
905
+ : files.length > 1
906
+ ? `${running ? 'Actualizando' : 'Actualizó'} ${files.length} archivos`
907
+ : running ? 'Aplicando cambios' : 'Aplicó cambios'
908
+ return { title, detail: filesLine(files, 'modificados') }
909
+ }
910
+
911
+ const describeValidate = (group: ToolEntry[], running: boolean) => {
912
+ const commands = group.map(one => one.command ?? '')
913
+ const hasTests = commands.some(isTestCommand)
914
+ const passed = group.reduce((sum, one) => sum + (isTestCommand(one.command ?? '') ? (testCounts(one.output).passed ?? 0) : 0), 0)
915
+ const parts = distinct([
916
+ commands.some(command => commandHeads(command).some(head => /\btsc\b|typecheck/.test(head))) ? 'tipos' : undefined,
917
+ commands.some(command => commandHeads(command).some(head => /\b(?:lint|eslint|biome)\b/.test(head))) ? 'lint' : undefined,
918
+ hasTests ? (passed > 0 ? `${passed} pruebas` : 'pruebas') : undefined,
919
+ ])
920
+ const title = running ? (hasTests ? 'Ejecutando pruebas' : 'Ejecutando validaciones') : 'Ejecutó validaciones'
921
+ return { title, detail: parts.join(' · ') }
922
+ }
923
+
924
+ const describeCommand = (group: ToolEntry[], running: boolean) => {
925
+ const commands = group.map(one => one.command ?? '')
926
+ const detail = commands.length === 1 ? (commands[0] ?? '') : `${commands.length} comandos: ${distinct(commands.map(command => command.split(' ')[0])).join(' · ')}`
927
+ return { title: running ? 'Ejecutando comandos' : 'Ejecutó comandos', detail }
928
+ }
929
+
930
+ const TITLES: Record<string, string> = {
931
+ Bash: 'Ejecución de comando',
932
+ Read: 'Lectura de archivo',
933
+ Edit: 'Edición de archivo',
934
+ Write: 'Escritura de archivo',
935
+ Grep: 'Búsqueda en código',
936
+ Glob: 'Búsqueda de archivos',
937
+ Agent: 'Subagente',
938
+ WebFetch: 'Consulta web',
939
+ WebSearch: 'Búsqueda web',
940
+ Skill: 'Skill',
941
+ }
942
+
943
+ const titleOf = (tool: string): string => TITLES[tool] ?? (tool.startsWith('mcp__') ? `MCP · ${tool.split('__').pop()}` : tool)
944
+
945
+ const describeStep = (kind: StepKind, group: ToolEntry[], running: boolean): { title: string; detail: string } => {
946
+ const first = group[0]
947
+ if (kind === 'read') return describeRead(group, running)
948
+ if (kind === 'edit') return describeEdit(group, running)
949
+ if (kind === 'validate') return describeValidate(group, running)
950
+ if (kind === 'command') return describeCommand(group, running)
951
+ if (kind === 'agent') return { title: `${running ? 'Delegando' : 'Delegó'}: ${first?.summary ?? ''}`, detail: first?.note ?? 'subagente' }
952
+ if (kind === 'question') {
953
+ const asked = first?.decisions ?? []
954
+ return { title: running ? 'Esperando tu respuesta' : 'Preguntó al usuario', detail: asked.map(one => one.question).join(' · ') }
955
+ }
956
+ return { title: titleOf(first?.tool ?? ''), detail: first?.summary ?? '' }
957
+ }
958
+
959
+ export const groupSteps = (list: ToolEntry[]): Step[] => {
960
+ const groups: { kind: StepKind; items: ToolEntry[] }[] = []
961
+ for (const entry of list) {
962
+ const kind = stepKindOf(entry)
963
+ const last = groups.at(-1)
964
+ if (last && last.kind === kind && !SOLO_KINDS.has(kind)) last.items.push(entry)
965
+ else groups.push({ kind, items: [entry] })
966
+ }
967
+ return groups.map(({ kind, items }) => {
968
+ const status = groupStatus(items)
969
+ return { key: items[0]?.id ?? kind, kind, status, durationMs: wallTime(items), ...describeStep(kind, items, status === 'running') }
970
+ })
971
+ }
972
+
973
+ // ---------------------------------------------------------------- agents
974
+
975
+ export const shortName = (record: Pick<AgentRecord, 'description' | 'name'>): string => {
976
+ if (record.name) return fit(record.name, 16)
977
+ const words = record.description.replace(/^\s*[\w-]+:\s*/, '').split(/\s+/).filter(Boolean)
978
+ const pair = words.slice(0, 2).join(' ')
979
+ const short = pair.length <= 16 && (words[1] ?? '').length > 3 ? pair : (words[0] ?? '')
980
+ const named = short === '' ? 'Agente' : short.charAt(0).toUpperCase() + short.slice(1)
981
+ return fit(named, 16)
982
+ }
983
+
984
+ export const defaultAgent = (records: AgentRecord[], picked: string): string => {
985
+ if (picked !== '' && (picked === MAIN || records.some(one => one.id === picked))) return picked
986
+ const running = records.filter(one => one.state === 'running').sort((a, b) => b.startedAt - a.startedAt)
987
+ return running[0]?.id ?? MAIN
988
+ }
989
+
990
+ export const mergeAgent = (list: AgentRecord[], record: AgentRecord): AgentRecord[] => {
991
+ const known = list.find(one => one.id === record.id)
992
+ const merged = known ? { ...known, ...record, startedAt: known.startedAt, description: record.description || known.description } : record
993
+ return [...list.filter(one => one.id !== record.id), merged].slice(-30)
994
+ }
995
+
996
+ export const setAgentState = (list: AgentRecord[], id: string, state: AgentState): AgentRecord[] =>
997
+ list.map(one => (one.id === id ? { ...one, state } : one))
998
+
999
+ const agentStateOf = (status: string): AgentState =>
1000
+ status === 'completed' || status === 'idle' ? 'done' : status === 'failed' || status === 'killed' ? 'failed' : 'running'
1001
+
1002
+ /** The Agent tool's own result: only a completed run is done; a launch is still running. */
1003
+ export const agentResultState = (status: CallStatus, result: unknown): AgentState | undefined => {
1004
+ if (status !== 'ok') return 'failed'
1005
+ const reported = (result as { status?: unknown } | undefined)?.status
1006
+ if (reported === 'completed') return 'done'
1007
+ if (reported === 'async_launched' || reported === 'remote_launched' || reported === 'teammate_spawned') return 'running'
1008
+ return undefined
1009
+ }
1010
+
1011
+ export const turnEndState = (reason: string): AgentState => (reason === 'answer' ? 'done' : 'failed')
1012
+
1013
+ export const decisionsOf = (input: Record<string, unknown>): Decision[] =>
1014
+ rawQuestions(input).map(question => ({ question: oneLine(question), answer: '' }))
1015
+
1016
+ const rawQuestions = (input: Record<string, unknown>): string[] =>
1017
+ (Array.isArray(input.questions) ? input.questions : [])
1018
+ .map(one => text((one as { question?: unknown }).question))
1019
+ .filter((question): question is string => question !== undefined)
1020
+
1021
+ /** Answers are keyed by the question text exactly as the model sent it. */
1022
+ export const answered = (input: Record<string, unknown>, status: CallStatus, result: unknown): Decision[] => {
1023
+ const record = (result ?? {}) as { answers?: unknown; response?: unknown }
1024
+ const answers = (record.answers ?? {}) as Record<string, unknown>
1025
+ const response = cleanText(record.response)
1026
+ return rawQuestions(input).map(raw => {
1027
+ if (status !== 'ok') return { question: oneLine(raw), answer: 'rechazada', refused: true }
1028
+ const given = answers[raw]
1029
+ return { question: oneLine(raw), answer: given !== undefined && given !== '' ? oneLine(String(given)) : (response ?? '') }
1030
+ })
1031
+ }
1032
+
1033
+ // ---------------------------------------------------------------- scroll
1034
+
1035
+ export const scrolled = (state: PaneScroll, by: number, total: number, room: number, isJump: boolean): PaneScroll => {
1036
+ const maxOffset = Math.max(0, total - room)
1037
+ const from = state.follow ? maxOffset : Math.min(state.offset, maxOffset)
1038
+ const step = isJump ? Math.sign(by) * total : Math.abs(by) >= room ? Math.sign(by) * Math.max(1, room - 1) : by
1039
+ const offset = Math.min(maxOffset, Math.max(0, from + step))
1040
+ return { offset, follow: maxOffset > 0 && offset === maxOffset }
1041
+ }
1042
+
1043
+ export const windowStart = (state: PaneScroll, total: number, room: number): number => {
1044
+ const maxOffset = Math.max(0, total - room)
1045
+ return state.follow ? maxOffset : Math.min(state.offset, maxOffset)
1046
+ }
1047
+
1048
+ // ---------------------------------------------------------------- pane model
1049
+
1050
+ export type Tone = 'success' | 'error' | 'warning' | 'subtle' | 'permission' | 'claude' | 'suggestion' | 'diffAdded' | 'diffRemoved'
1051
+ export type Span = { text: string; color?: Tone | (string & {}); dim?: boolean; bold?: boolean; inverse?: boolean }
1052
+ export type Action =
1053
+ | { kind: 'toggle'; key: string }
1054
+ | { kind: 'tab'; tab: Tab }
1055
+ | { kind: 'agent'; id: string }
1056
+ | { kind: 'scope'; scope: CambiosScope }
1057
+ | { kind: 'diff'; target: DiffTarget }
1058
+ | { kind: 'open'; target: DiffTarget }
1059
+ | { kind: 'commit'; sha: string }
1060
+ | AgentsAction
1061
+ export type Cell = { spans: Span[]; action?: Action; label?: string; key?: string }
1062
+ export type Row = { key: string; cells: Cell[]; right?: Span[] }
1063
+
1064
+ export type Snapshot = {
1065
+ list: ToolEntry[]
1066
+ tabByAgent: Record<string, Tab>
1067
+ flipped: string[]
1068
+ files: FileChange[]
1069
+ usd: number
1070
+ context: ContextUsage
1071
+ steps: Record<string, StepContext>
1072
+ accent: string
1073
+ opened: string[]
1074
+ patches: Record<string, DiffPatch>
1075
+ records: AgentRecord[]
1076
+ picked: string
1077
+ isWorking: boolean
1078
+ commitList: CommitRecord[]
1079
+ scopeByAgent: Record<string, CambiosScope>
1080
+ branchView: BranchView
1081
+ view: PaneScroll
1082
+ historyView: HistoryView
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
1091
+ }
1092
+
1093
+ export type PaneModel = { header: Row[]; body: Row[]; footer: Row[]; scope: string; cambios: CambiosScope; tab: Tab }
1094
+
1095
+ export type Look = { icon: string; color: Tone }
1096
+
1097
+ const STATUS_LOOK: Record<CallStatus, Look> = {
1098
+ running: { icon: ICONS.running, color: 'warning' },
1099
+ ok: { icon: ICONS.ok, color: 'success' },
1100
+ error: { icon: ICONS.error, color: 'error' },
1101
+ denied: { icon: ICONS.denied, color: 'subtle' },
1102
+ interrupted: { icon: ICONS.interrupted, color: 'subtle' },
1103
+ }
1104
+
1105
+ export const AGENT_LOOK: Record<AgentState, Look & { label: string }> = {
1106
+ running: { icon: ICONS.running, color: 'warning', label: 'ejecutando' },
1107
+ done: { icon: ICONS.ok, color: 'success', label: 'terminó' },
1108
+ failed: { icon: ICONS.error, color: 'error', label: 'falló' },
1109
+ }
1110
+
1111
+ const KIND_ICONS: Record<StepKind, string> = {
1112
+ read: ICONS.read,
1113
+ edit: ICONS.edit,
1114
+ validate: ICONS.validate,
1115
+ command: ICONS.command,
1116
+ agent: ICONS.agent,
1117
+ question: ICONS.question,
1118
+ other: ICONS.other,
1119
+ }
1120
+
1121
+ const TAB_LABELS: { value: Tab; icon: string; label: string }[] = [
1122
+ { value: 'summary', icon: ICONS.summary, label: 'Resumen' },
1123
+ { value: 'commands', icon: ICONS.commands, label: 'Comandos' },
1124
+ { value: 'diff', icon: ICONS.diff, label: 'Cambios' },
1125
+ { value: 'history', icon: ICONS.history, label: 'Historial' },
1126
+ ]
1127
+
1128
+ const SCOPE_LABELS: { value: CambiosScope; icon: string; label: string }[] = [
1129
+ { value: 'commits', icon: ICONS.commit, label: 'Commits' },
1130
+ { value: 'uncommitted', icon: ICONS.uncommitted, label: 'Sin commitear' },
1131
+ { value: 'branch', icon: ICONS.branch, label: 'Rama' },
1132
+ ]
1133
+
1134
+ export const span = (value: string, style: Omit<Span, 'text'> = {}): Span => ({ text: value, ...style })
1135
+
1136
+ const touches = (change: FileChange, edited: string[]): boolean =>
1137
+ edited.some(path => path === change.path || path.endsWith(`/${change.path}`))
1138
+
1139
+ /** The main loop's view lists every session commit; an agent's, its own. */
1140
+ export const commitsFor = (list: CommitRecord[], scope: string): CommitRecord[] =>
1141
+ scope === MAIN ? list : list.filter(one => (one.agentId ?? MAIN) === scope)
1142
+
1143
+ /** Which loop made each session commit, by its first seven hex digits; the caller checks the full sha. */
1144
+ export const sessionOwners = (list: CommitRecord[]): Map<string, CommitRecord[]> => {
1145
+ const owners = new Map<string, CommitRecord[]>()
1146
+ for (const commit of list) owners.set(commit.sha.slice(0, 7), [...(owners.get(commit.sha.slice(0, 7)) ?? []), commit])
1147
+ return owners
1148
+ }
1149
+
1150
+ export const ownerOf = (owners: Map<string, CommitRecord[]>, sha: string): CommitRecord | undefined =>
1151
+ owners.get(sha.slice(0, 7))?.find(one => sameSha(one.sha, sha))
1152
+
1153
+ export const cambiosScopeOf = (snap: Pick<Snapshot, 'scopeByAgent' | 'commitList'>, scope: string): CambiosScope =>
1154
+ snap.scopeByAgent[scope] ?? (commitsFor(snap.commitList, scope).length > 0 ? 'commits' : 'uncommitted')
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
+
1181
+ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
1182
+ const { list, flipped, opened, patches, records } = snap
1183
+ const accent = snap.accent
1184
+ const scope = defaultAgent(records, snap.picked)
1185
+ const current: Tab = snap.tabByAgent[scope] ?? 'summary'
1186
+ const cambios = cambiosScopeOf(snap, scope)
1187
+ const agent = records.find(one => one.id === scope)
1188
+ const scoped = list.filter(one => (one.agentId ?? MAIN) === scope)
1189
+ const commands = scoped.filter(one => one.command !== undefined)
1190
+ const lastCommand = commands.at(-1)
1191
+ const edited = distinct(scoped.filter(one => CHANGE_TOOLS.has(one.tool)).map(one => one.file))
1192
+ const sessionEdited = distinct(list.filter(one => CHANGE_TOOLS.has(one.tool)).map(one => one.file))
1193
+ const visibleFiles = snap.files.filter(change => !change.untracked || touches(change, sessionEdited))
1194
+ const hiddenUntracked = snap.files.length - visibleFiles.length
1195
+ const scopedFiles = scope === MAIN ? visibleFiles : visibleFiles.filter(change => touches(change, edited))
1196
+ const waiting = list.some(one => one.tool === 'AskUserQuestion' && one.status === 'running')
1197
+
1198
+ const isOpen = (key: string, byDefault: boolean): boolean => byDefault !== flipped.includes(key)
1199
+ const line = (key: string, value: string, style: Omit<Span, 'text'> = {}): Row => ({ key, cells: [{ spans: [span(fit(value, width), style)] }] })
1200
+ const blank = (key: string): Row => line(key, ' ')
1201
+ const divider = (key: string): Row => line(key, '─'.repeat(width), { dim: true })
1202
+ const agentTag = (agentId: string | undefined): string => {
1203
+ if (agentId === undefined) return ''
1204
+ const record = records.find(one => one.id === agentId)
1205
+ return ` · ${record ? shortName(record) : 'agente'}`
1206
+ }
1207
+ const toggleRow = (key: string, label: string, open: boolean, indent = ''): Row => ({
1208
+ key,
1209
+ cells: [{ spans: [span(fit(`${indent}${open ? '▼' : '▶'} ${label}`, width))], action: { kind: 'toggle', key }, label, key: `btn-${key}` }],
1210
+ })
1211
+ const section = (key: string, label: string, byDefault: boolean, body: () => Row[]): Row[] => {
1212
+ const open = isOpen(key, byDefault)
1213
+ return [toggleRow(key, label, open), ...(open ? body() : [])]
1214
+ }
1215
+
1216
+ const stepRows = (steps: Step[]): Row[] =>
1217
+ steps.flatMap(step => {
1218
+ const look = STATUS_LOOK[step.status]
1219
+ const right = step.status === 'running' ? '…' : seconds(step.durationMs)
1220
+ return [
1221
+ {
1222
+ key: `step-${step.key}`,
1223
+ cells: [{ spans: [span(`${look.icon} `, { color: look.color }), span(`${KIND_ICONS[step.kind]} ${fit(step.title, width - right.length - 6)}`)] }],
1224
+ right: [span(right, { dim: true })],
1225
+ },
1226
+ ...(step.detail === '' ? [] : [line(`detail-${step.key}`, ` ${step.detail}`, { dim: true })]),
1227
+ ]
1228
+ })
1229
+
1230
+ const commandRows = (entry: ToolEntry, keyPrefix: string): Row[] => {
1231
+ const verdict = verdictOf(entry)
1232
+ const summary = resultLine(entry)
1233
+ const outputOpen = isOpen(`${keyPrefix}-output`, false)
1234
+ const rows: Row[] = [line(`${keyPrefix}-cmd`, `$ ${entry.command ?? ''}`, { color: 'permission' })]
1235
+ if (entry.status === 'running') rows.push(line(`${keyPrefix}-running`, ` ${ICONS.running} ejecutando…`, { color: 'warning' }))
1236
+ for (const test of entry.testFiles ?? []) {
1237
+ rows.push({
1238
+ key: `${keyPrefix}-test-${test.file}`,
1239
+ cells: [{ spans: [span(' '), span(`${test.ok ? ICONS.ok : ICONS.error} `, { color: test.ok ? 'success' : 'error' }), span(fit(test.file, width - 6))] }],
1240
+ })
1241
+ }
1242
+ if (entry.status !== 'running') {
1243
+ const look = entry.status === 'interrupted' ? STATUS_LOOK.interrupted : verdict === 'FAIL' || entry.status !== 'ok' ? STATUS_LOOK.error : STATUS_LOOK.ok
1244
+ const label = entry.status === 'interrupted' ? ' interrumpido' : verdict ? ` ${verdict}` : ''
1245
+ const tail = `${summary}${summary && entry.durationMs !== undefined ? ' · ' : ''}${seconds(entry.durationMs)}`
1246
+ rows.push({
1247
+ key: `${keyPrefix}-verdict`,
1248
+ cells: [{ spans: [span(`${look.icon}${label}`, { color: look.color, bold: true }), span(` ${fit(tail, width - 16)}`, { dim: true })] }],
1249
+ })
1250
+ }
1251
+ if (entry.output !== '') {
1252
+ rows.push(toggleRow(`${keyPrefix}-output`, outputOpen ? 'Ocultar salida' : 'Ver salida completa', outputOpen))
1253
+ if (outputOpen) entry.output.split('\n').forEach((out, index) => rows.push(line(`${keyPrefix}-out-${index}`, ` ${out}`, { dim: true })))
1254
+ }
1255
+ return rows
1256
+ }
1257
+
1258
+ const historyRows = (): Row[] =>
1259
+ commands
1260
+ .slice()
1261
+ .reverse()
1262
+ .map(entry => {
1263
+ const look = STATUS_LOOK[entry.status]
1264
+ const right = entry.status === 'running' ? '…' : `exit ${entry.exitCode ?? '?'} · ${seconds(entry.durationMs)}`
1265
+ return {
1266
+ key: `hist-${entry.id}`,
1267
+ cells: [{ spans: [span(' '), span(`${look.icon} `, { color: look.color }), span(fit(entry.command ?? '', width - right.length - 7))] }],
1268
+ right: [span(right, { dim: true })],
1269
+ }
1270
+ })
1271
+
1272
+ const fileRows = (target: DiffTarget, file: FileChange, indent: string): Row[] => {
1273
+ const key = targetKey(target)
1274
+ const isOpenFile = opened.includes(key)
1275
+ const shown = clean(file.path)
1276
+ const counts = file.binary ? 'bin' : `+${file.added} −${file.removed}`
1277
+ const mark = file.untracked ? ' nuevo' : ''
1278
+ const rows: Row[] = [
1279
+ {
1280
+ key: `file-${key}`,
1281
+ cells: [
1282
+ { spans: [span(`${indent}${isOpenFile ? '▾' : '▸'} `)], action: { kind: 'diff', target }, label: isOpenFile ? 'Ocultar diff' : 'Ver diff aquí', key: `fold-${key}` },
1283
+ {
1284
+ spans: [span(`${fileIcon(file.path)} ${fit(shown, width - counts.length - mark.length - indent.length - 7)}`), ...(mark ? [span(mark, { color: 'success', dim: true })] : [])],
1285
+ action: { kind: 'open', target },
1286
+ label: `Abrir ${shown} en nvim`,
1287
+ key: `open-${key}`,
1288
+ },
1289
+ ],
1290
+ right: file.binary ? [span('bin', { dim: true })] : [span(`+${file.added}`, { color: 'success' }), span(' '), span(`−${file.removed}`, { color: 'error' })],
1291
+ },
1292
+ ]
1293
+ if (!isOpenFile) return rows
1294
+ const patch = patches[key]
1295
+ if (patch === undefined) return [...rows, line(`loading-${key}`, `${indent} Cargando diff…`, { dim: true })]
1296
+ if (patch.rows.length === 0) return [...rows, line(`nodiff-${key}`, `${indent} Sin diferencias.`, { dim: true })]
1297
+ const gutter = Math.max(3, ...patch.rows.map(row => row.gutter.length))
1298
+ patch.rows.forEach((row, index) =>
1299
+ rows.push(
1300
+ row.kind === 'hunk'
1301
+ ? line(`hunk-${key}-${index}`, `${indent} ${ICONS.hunk} ${row.text}`, { color: 'suggestion' })
1302
+ : {
1303
+ key: `row-${key}-${index}`,
1304
+ cells: [{
1305
+ spans: [
1306
+ span(`${indent} ${row.gutter.padStart(gutter)} │`, { dim: true }),
1307
+ span(`${row.sign} ${fit(row.text, width - gutter - indent.length - 8)}`, { color: row.kind === 'add' ? 'diffAdded' : row.kind === 'del' ? 'diffRemoved' : undefined }),
1308
+ ],
1309
+ }],
1310
+ },
1311
+ ),
1312
+ )
1313
+ if (patch.total > patch.rows.length) rows.push(line(`more-${key}`, `${indent} … ${patch.total - patch.rows.length} líneas más`, { dim: true }))
1314
+ return rows
1315
+ }
1316
+
1317
+ const uncommittedRows = (): Row[] => {
1318
+ const hidden = scope === MAIN && hiddenUntracked > 0
1319
+ ? [line('hidden-untracked', `${hiddenUntracked} archivos sin seguimiento de antes de la sesión, ocultos`, { dim: true })]
1320
+ : []
1321
+ if (scopedFiles.length === 0) return [line('no-changes', scope === MAIN ? 'Sin cambios sin commitear.' : 'Este agente no tiene cambios sin commitear.', { dim: true }), ...hidden]
1322
+ return [...scopedFiles.flatMap(file => fileRows({ scope: 'uncommitted', path: file.path, ...(file.untracked ? { untracked: true } : {}) }, file, '')), ...hidden]
1323
+ }
1324
+
1325
+ const commitRows = (): Row[] => {
1326
+ const own = commitsFor(snap.commitList, scope).slice().reverse()
1327
+ const rows: Row[] = []
1328
+ if (own.length === 0) rows.push(line('no-commits', scope === MAIN ? 'Sin commits en esta sesión todavía.' : 'Este agente no ha hecho commits.', { dim: true }))
1329
+ for (const commit of own) {
1330
+ const key = `commit-${commit.sha}`
1331
+ const open = isOpen(key, false)
1332
+ const totals = commit.added === undefined ? (commit.statsFailed ? '?' : '…') : `+${commit.added} −${commit.removed ?? 0}`
1333
+ const tag = scope === MAIN ? agentTag(commit.agentId) : ''
1334
+ rows.push({
1335
+ key,
1336
+ cells: [
1337
+ { spans: [span(`${open ? '▾' : '▸'} `)], action: { kind: 'toggle', key }, label: open ? 'Ocultar archivos' : 'Ver archivos', key: `btn-${key}` },
1338
+ {
1339
+ spans: [
1340
+ span(`${commit.isMerge ? ICONS.merge : ICONS.commit} `, { color: accent }),
1341
+ span(`${commit.sha.slice(0, 7)} `, { color: 'warning' }),
1342
+ span(fit(commit.subject, width - totals.length - tag.length - 14)),
1343
+ ...(tag ? [span(tag, { color: accent, dim: true })] : []),
1344
+ ],
1345
+ },
1346
+ ],
1347
+ right: commit.added === undefined ? [span(totals, { dim: true })] : [span(`+${commit.added}`, { color: 'success' }), span(' '), span(`−${commit.removed ?? 0}`, { color: 'error' })],
1348
+ })
1349
+ if (!open) continue
1350
+ rows.push(line(`${key}-meta`, ` ${ICONS.branch} ${commit.branch}`, { dim: true }))
1351
+ if (commit.files === undefined) rows.push(line(`${key}-loading`, commit.statsFailed ? ' No se pudo leer el commit.' : ' Cargando archivos…', { dim: true }))
1352
+ else commit.files.forEach(file => rows.push(...fileRows({ scope: 'commit', sha: commit.sha, path: file.path }, file, ' ')))
1353
+ }
1354
+ return rows
1355
+ }
1356
+
1357
+ const historyTabRows = (): Row[] => {
1358
+ const view = snap.historyView
1359
+ if (view.state === 'error') return [line('hist-error', view.error ?? 'git falló.', { color: 'warning' })]
1360
+ if (view.rows.length === 0) return [line('hist-loading', view.state === 'ready' ? 'Sin commits todavía.' : 'Cargando historial…', { dim: true })]
1361
+ const owners = sessionOwners(snap.commitList)
1362
+ const shown = view.rows.filter(row => row.sha !== undefined).length
1363
+ const ours = view.rows.filter(row => row.sha !== undefined && ownerOf(owners, row.sha) !== undefined).length
1364
+ const rows: Row[] = [{
1365
+ key: 'hist-legend',
1366
+ cells: [{ spans: [span(`${ICONS.history} ${shown} commits · `, { dim: true }), span('●', { color: accent }), span(` ${ours} de esta sesión`, { dim: true }), ...(view.state === 'loading' ? [span(' · actualizando…', { dim: true })] : [])] }],
1367
+ }]
1368
+ view.rows.forEach((row, index) => {
1369
+ const sha = row.sha
1370
+ if (sha === undefined) {
1371
+ rows.push(line(`hg-${index}`, ` ${row.graph}`, { dim: true }))
1372
+ return
1373
+ }
1374
+ const owner = ownerOf(owners, sha)
1375
+ const loop = owner === undefined ? undefined : (owner.agentId ?? MAIN)
1376
+ const strength = loop === undefined ? 'none' : scope === MAIN || loop === scope ? 'strong' : 'soft'
1377
+ const mark: Omit<Span, 'text'> = strength === 'strong' ? { color: accent } : strength === 'soft' ? { color: accent, dim: true } : {}
1378
+ const key = `hist-${sha}`
1379
+ const open = isOpen(key, false)
1380
+ const right = [ago(row.at, view.loadedAt), fit(row.author ?? '', 14)].filter(Boolean).join(' · ')
1381
+ const tag = owner !== undefined && scope === MAIN ? agentTag(owner.agentId) : ''
1382
+ const refSpans = (row.refs ?? []).flatMap((ref, at): Span[] => {
1383
+ const isHead = ref === 'HEAD' || ref.startsWith('HEAD -> ')
1384
+ return [span(at === 0 ? '(' : ', ', { color: 'suggestion', dim: true }), span(ref, { color: 'suggestion', bold: isHead })]
1385
+ })
1386
+ const refsText = refSpans.length > 0 ? refSpans.map(one => one.text).join('').length + 2 : 0
1387
+ const used = 2 + row.graph.length + sha.length + 1 + refsText + tag.length + right.length + 2
1388
+ rows.push({
1389
+ key,
1390
+ cells: [{
1391
+ spans: [
1392
+ span(strength === 'none' ? ' ' : '● ', { ...mark, bold: strength === 'strong' }),
1393
+ span(row.graph, { dim: true }),
1394
+ span(`${sha} `, strength === 'none' ? { color: 'warning' } : { ...mark, bold: strength === 'strong' }),
1395
+ ...refSpans,
1396
+ ...(refSpans.length > 0 ? [span(') ', { color: 'suggestion', dim: true })] : []),
1397
+ span(fit(row.subject ?? '', width - used), mark),
1398
+ ...(tag ? [span(tag, { color: accent, dim: true })] : []),
1399
+ ],
1400
+ action: { kind: 'commit', sha },
1401
+ label: open ? 'Ocultar archivos' : 'Ver archivos',
1402
+ key: `btn-${key}`,
1403
+ }],
1404
+ right: [span(right, { dim: true })],
1405
+ })
1406
+ if (!open) return
1407
+ const files = owner?.files ?? snap.historyFiles[sha]?.files
1408
+ const failed = owner?.statsFailed === true || snap.historyFiles[sha]?.failed === true
1409
+ if (files === undefined) rows.push(line(`${key}-loading`, failed ? ' No se pudo leer el commit.' : ' Cargando archivos…', { dim: true }))
1410
+ else if (files.length === 0) rows.push(line(`${key}-empty`, ' El commit no cambia archivos.', { dim: true }))
1411
+ else files.forEach(file => rows.push(...fileRows({ scope: 'commit', sha: owner?.sha ?? sha, path: file.path }, file, ' ')))
1412
+ })
1413
+ if (view.more > 0) rows.push(line('hist-more', `… ${view.more} más`, { dim: true }))
1414
+ return rows
1415
+ }
1416
+
1417
+ const branchRows = (): Row[] => {
1418
+ const view = snap.branchView
1419
+ if (!view.isLoaded) return [line('branch-loading', 'Cargando la rama…', { dim: true })]
1420
+ if (view.error !== undefined) return [line('branch-error', view.error, { color: 'warning' })]
1421
+ return [
1422
+ line('branch-base', `${ICONS.branch} vs ${view.baseRef ?? ''} (${(view.base ?? '').slice(0, 7)}) · ${view.commits.length} commits · ${view.files.length} archivos`, { dim: true }),
1423
+ ...section('branch-commits', `Commits de la rama · ${view.commits.length}`, true, () =>
1424
+ view.commits.map(commit => ({
1425
+ key: `bc-${commit.sha}`,
1426
+ cells: [{ spans: [span(` ${ICONS.commit} `, { color: accent }), span(`${commit.sha} `, { color: 'warning' }), span(fit(commit.subject, width - commit.sha.length - 6))] }],
1427
+ })),
1428
+ ),
1429
+ ...(view.files.length === 0 ? [line('branch-nofiles', 'La rama no cambia archivos.', { dim: true })] : view.files.flatMap(file => fileRows({ scope: 'branch', sha: view.base, path: file.path }, file, ''))),
1430
+ ]
1431
+ }
1432
+
1433
+ const cambiosRows = (): Row[] => (cambios === 'commits' ? commitRows() : cambios === 'branch' ? branchRows() : uncommittedRows())
1434
+
1435
+ const decisions = scoped.flatMap(one => one.decisions ?? [])
1436
+ const readFiles = distinct(scoped.filter(one => one.tool === 'Read').map(one => one.file)).reverse()
1437
+ const usage = scopedContext(snap, scope)
1438
+ const percent = contextPercentOf(usage)
1439
+ const contextRow = (key: string, indent: string): Row => {
1440
+ const label = contextLabel(usage)
1441
+ const hint = scope === MAIN ? ' de la última respuesta' : ' de la última respuesta de este agente'
1442
+ const used = indent.length + 2 + 11 + label.length
1443
+ return {
1444
+ key,
1445
+ cells: [{
1446
+ spans: [
1447
+ span(`${indent}${ICONS.gauge} `),
1448
+ span(`${contextBar(percent)} `, { color: contextTone(percent) }),
1449
+ span(fit(label, width - indent.length - 13)),
1450
+ ...(usage.tokens !== undefined && used + hint.length <= width ? [span(hint, { dim: true })] : []),
1451
+ ],
1452
+ }],
1453
+ }
1454
+ }
1455
+
1456
+ const summaryRows = (): Row[] => {
1457
+ const steps = groupSteps(scoped)
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]
1464
+ return [
1465
+ ...lead,
1466
+ ...stepRows(steps),
1467
+ ...tail,
1468
+ ...(lastCommand ? [blank('gap-last'), ...section(`last-cmd-${scope}`, 'Último comando', true, () => commandRows(lastCommand, `last-${scope}`))] : []),
1469
+ blank('gap-changes'),
1470
+ divider('div-changes'),
1471
+ line('changes-title', `${ICONS.uncommitted} SIN COMMITEAR`, { bold: true }),
1472
+ ...uncommittedRows(),
1473
+ blank('gap-sections'),
1474
+ ...section(`decisions-${scope}`, `${ICONS.decision} Decisiones técnicas · ${decisions.length}`, false, () =>
1475
+ decisions.length === 0
1476
+ ? [line('no-decisions', ' Sin preguntas todavía.', { dim: true })]
1477
+ : decisions.flatMap((one, index) => [
1478
+ line(`q-${index}`, ` ${ICONS.question} ${one.question}`),
1479
+ line(`a-${index}`, ` → ${one.answer || 'pendiente'}`, { color: one.refused ? 'error' : one.answer ? 'success' : 'warning' }),
1480
+ ]),
1481
+ ),
1482
+ ...section(`history-${scope}`, `${ICONS.log} ${scope === MAIN ? 'Historial de comandos' : 'Historial de este agente'} · ${commands.length}`, false, historyRows),
1483
+ ...section(`context-${scope}`, `${ICONS.brain} Contexto consultado`, false, () => [
1484
+ contextRow('ctx-usage', ' '),
1485
+ ...readFiles.slice(0, 30).map(path => line(`ctx-${path}`, ` ${fileIcon(path)} ${path}`)),
1486
+ ]),
1487
+ ]
1488
+ }
1489
+
1490
+ const commandsTabRows = (): Row[] => {
1491
+ if (!lastCommand) return [line('no-commands', 'Sin comandos todavía.', { dim: true })]
1492
+ return [
1493
+ line('last-title', `${ICONS.command} Último comando`, { bold: true }),
1494
+ ...commandRows(lastCommand, `cmdtab-${scope}`),
1495
+ blank('gap-history'),
1496
+ line('history-title', `${ICONS.log} Historial · ${commands.length}`, { bold: true }),
1497
+ ...historyRows(),
1498
+ ]
1499
+ }
1500
+
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()
1503
+
1504
+ const status = waiting
1505
+ ? span(`${ICONS.waiting} esperando respuesta`, { color: 'warning' })
1506
+ : snap.isWorking
1507
+ ? span(`${ICONS.running} ejecutando`, { color: 'warning' })
1508
+ : undefined
1509
+
1510
+ const chip = (key: string, label: string, isOn: boolean, action: Action, look?: Look): Cell => ({
1511
+ key,
1512
+ label,
1513
+ action,
1514
+ spans: [span(` ${label}${look ? ' ' : ' '}`, { inverse: isOn, bold: isOn }), ...(look ? [span(`${look.icon} `, { color: look.color, inverse: isOn })] : []), span(' ')],
1515
+ })
1516
+
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])) }]
1518
+ if (records.length > 0) {
1519
+ header.push({
1520
+ key: 'agents',
1521
+ cells: agentChipsGrouped({ records, scope, expanded: snap.agentsPart.expanded, width }),
1522
+ })
1523
+ }
1524
+ if (agent) {
1525
+ const look = AGENT_LOOK[agent.state]
1526
+ header.push(
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 })] }] },
1528
+ line('agent-task', agent.description, { dim: true }),
1529
+ ...rowsAgentReport(agent, snap.agentsPart.reports[agent.id], width),
1530
+ )
1531
+ }
1532
+ header.push({
1533
+ key: 'tabs',
1534
+ cells: TAB_LABELS.map(tab => ({
1535
+ key: `tab-${tab.value}`,
1536
+ label: tab.label,
1537
+ action: { kind: 'tab', tab: tab.value } as Action,
1538
+ spans: [span(` ${tab.icon} ${tab.label} `, { inverse: current === tab.value, bold: current === tab.value, color: current === tab.value ? 'claude' : undefined }), span(' ')],
1539
+ })),
1540
+ })
1541
+ if (current === 'diff') {
1542
+ const counts: Record<CambiosScope, string> = {
1543
+ commits: String(commitsFor(snap.commitList, scope).length),
1544
+ uncommitted: String(scopedFiles.length),
1545
+ branch: snap.branchView.isLoaded && snap.branchView.error === undefined ? String(snap.branchView.commits.length) : '',
1546
+ }
1547
+ header.push({
1548
+ key: 'scopes',
1549
+ cells: SCOPE_LABELS.map(one => ({
1550
+ key: `scope-${one.value}`,
1551
+ label: one.label,
1552
+ action: { kind: 'scope', scope: one.value } as Action,
1553
+ spans: [
1554
+ span(` ${one.icon} ${one.label}${counts[one.value] ? ` ${counts[one.value]}` : ''} `, { inverse: cambios === one.value, bold: cambios === one.value, color: cambios === one.value ? 'suggestion' : undefined }),
1555
+ span(' '),
1556
+ ],
1557
+ })),
1558
+ })
1559
+ }
1560
+ header.push(divider('div-head'))
1561
+
1562
+ const wall = wallTime(scoped.filter(one => one.durationMs !== undefined))
1563
+ const footer: Row[] = [
1564
+ divider('div-foot'),
1565
+ line(
1566
+ 'footer',
1567
+ `${ICONS.files} ${scopedFiles.length} archivos · ${ICONS.command} ${commands.length} comandos · ${ICONS.time} ${seconds(wall) || '0.0 s'} · ${ICONS.cost} ${dollars(snap.usd)} sesión`,
1568
+ { dim: true },
1569
+ ),
1570
+ contextRow('footer-context', ''),
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])) }] })
1574
+
1575
+ return { header, body, footer, scope, cambios, tab: current }
1576
+ }
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
+
1604
+ export type PaneFrame = { rows: Row[]; isWindowed: boolean; total: number; room: number }
1605
+
1606
+ /**
1607
+ * Fixes the header and footer and windows the body between them. When the
1608
+ * frame is too short for even one body row, the tree goes whole and the
1609
+ * engine scrolls it.
1610
+ */
1611
+ export const paneFrame = (model: PaneModel, bodyRows: number, view: PaneScroll, isDock: boolean): PaneFrame => {
1612
+ const total = model.body.length
1613
+ const footer = bodyRows >= model.header.length + model.footer.length + 1 ? model.footer : []
1614
+ const room = bodyRows - model.header.length - footer.length
1615
+ if (room < 1) return { rows: [...model.header, ...model.body, ...model.footer], isWindowed: false, total, room: 0 }
1616
+ const start = windowStart(view, total, room)
1617
+ const visible = model.body.slice(start, start + room)
1618
+ const [title, ...rest] = model.header
1619
+ const indicator = total > room ? [span(` ↕ ${start + 1}-${start + visible.length}/${total}`, { dim: true })] : []
1620
+ const header = title ? [{ ...title, right: [...(title.right ?? []), ...indicator] }, ...rest] : rest
1621
+ const padding = isDock ? Array.from({ length: room - visible.length }, (_, index): Row => ({ key: `pad-${index}`, cells: [{ spans: [span(' ')] }] })) : []
1622
+ return { rows: [...header, ...visible, ...padding, ...footer], isWindowed: true, total, room }
1623
+ }
1624
+
1625
+ // ---------------------------------------------------------------- hooks
1626
+
1627
+ export const runOf = ($: Api): Run => (argv, init) => $.process.run(argv, init)
1628
+
1629
+ const readSnapshot = async ($: Api): Promise<Snapshot> => {
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([
1631
+ read($, entries), read($, tabs), read($, toggled), read($, changes), read($, costUsd), read($, contextUsage), read($, openFiles), read($, diffs),
1632
+ read($, agents), read($, pickedAgent), read($, working), read($, scroll), read($, commits), read($, scopes), read($, branch), read($, stepContext),
1633
+ read($, history), read($, historyFiles), read($, accentColor),
1634
+ readAgents($), readCi($), readContext($), readProgress($), readRunning($), readBlocked($), readSavings($),
1635
+ ])
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 }
1637
+ }
1638
+
1639
+ /** Fills in the line counts and files of up to ten commits that have none yet. */
1640
+ const fillCommitStats = async ($: Api, run: Run, top: string): Promise<void> => {
1641
+ const pending = (await read($, commits)).filter(one => one.added === undefined && !one.statsFailed).slice(0, 10)
1642
+ for (const commit of pending) {
1643
+ const stats = await loadCommitStats(run, top, commit.sha)
1644
+ await update($, commits, list =>
1645
+ list.map(one => (one.sha !== commit.sha ? one : stats ? { ...one, added: stats.added, removed: stats.removed, files: stats.files, isMerge: stats.isMerge } : { ...one, statsFailed: true })),
1646
+ )
1647
+ }
1648
+ }
1649
+
1650
+ /** One history load at a time; a request while one runs joins it. */
1651
+ const reloadHistory = ($: Api): Promise<void> => {
1652
+ historyLoading ??= (async () => {
1653
+ await update($, history, (view): HistoryView => ({ ...view, state: 'loading' }))
1654
+ const loaded = await loadHistory(runOf($), await $.clock.now())
1655
+ await update($, history, () => loaded)
1656
+ })()
1657
+ .catch(() => undefined)
1658
+ .finally(() => {
1659
+ historyLoading = undefined
1660
+ })
1661
+ return historyLoading
1662
+ }
1663
+
1664
+ const rescanOnce = async ($: Api): Promise<void> => {
1665
+ const [start, calls] = await Promise.all([read($, sessionStart), read($, commitCalls)])
1666
+ if (start <= 0) return
1667
+ const run = runOf($)
1668
+ const scan = await scanSessionCommits(run, start, calls)
1669
+ if (scan === undefined) return
1670
+ if (scan.commits.length > 0) await update($, commits, list => mergeScanned(list, scan.commits))
1671
+ await fillCommitStats($, run, scan.repo)
1672
+ if ((await read($, history)).state !== 'idle') await reloadHistory($)
1673
+ }
1674
+
1675
+ /** Asks git for the session's commits shortly after a trigger; one rescan in flight, at most one queued. */
1676
+ const scheduleRescan = ($: Api): void => {
1677
+ rescanTimer?.cancel()
1678
+ rescanTimer = $.clock.after(RESCAN_MS, () => {
1679
+ rescanTimer = undefined
1680
+ if (scanning !== undefined) {
1681
+ scanAgain = true
1682
+ return
1683
+ }
1684
+ scanning = (async () => {
1685
+ do {
1686
+ scanAgain = false
1687
+ await rescanOnce($)
1688
+ } while (scanAgain)
1689
+ })()
1690
+ .catch(() => undefined)
1691
+ .finally(() => {
1692
+ scanning = undefined
1693
+ })
1694
+ })
1695
+ }
1696
+
1697
+ /** The session's start: stored once; a mod loaded mid-session reaches back to what it already recorded. */
1698
+ export const sessionStartOf = (stored: number, now: number, list: ToolEntry[], known: CommitRecord[]): number =>
1699
+ stored > 0 ? stored : Math.min(now, ...list.map(one => one.startedAt), ...known.map(one => one.at))
1700
+
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))
1799
+ scheduleRescan($ as Api)
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)
1875
+
1876
+ on('ui.close', async ($, e, next) => {
1877
+ if (e.id === PANE && e.origin.kind === 'person') await update($, autoOpen, () => false)
1878
+ return next(e)
1879
+ }).catch(($, e, next) => next(e))
1880
+
1881
+ on('session.measure', async ($, e, next) => {
1882
+ if (e.changed.includes('cost') && e.cost !== undefined) await update($, costUsd, () => e.cost?.usd ?? 0)
1883
+ if (e.changed.includes('context')) {
1884
+ const usage: ContextUsage = { window: e.context.window }
1885
+ if (e.context.tokens !== undefined) usage.tokens = e.context.tokens
1886
+ if (e.context.percent !== undefined) usage.percent = e.context.percent
1887
+ await update($, contextUsage, () => usage)
1888
+ await contextMeasured($ as Api, e.context)
1889
+ }
1890
+ return next(e)
1891
+ })
1892
+
1893
+ on('turn.step', async function* ($, e, next) {
1894
+ const result = yield* next(e)
1895
+ const used = result?.usage
1896
+ if (used) {
1897
+ const tokens = used.input_tokens + used.cache_creation_input_tokens + used.cache_read_input_tokens
1898
+ await update($, stepContext, all => ({ ...all, [e.agentId ?? MAIN]: { tokens, model: used.model } })).catch(() => undefined)
1899
+ }
1900
+ return result
1901
+ })
1902
+
1903
+
1904
+
1905
+ on('agent.spawn', async ($, e, next) => {
1906
+ const spawned = await next(e)
1907
+ if (spawned.agentId !== undefined) {
1908
+ const record: AgentRecord = {
1909
+ id: spawned.agentId,
1910
+ description: oneLine(e.description ?? ''),
1911
+ type: oneLine(e.subagentType ?? 'agente'),
1912
+ state: 'running',
1913
+ startedAt: await $.clock.now(),
1914
+ }
1915
+ await update($, agents, list => mergeAgent(list, record))
1916
+ }
1917
+ return spawned
1918
+ }).catch(($, e, next) => next(e))
1919
+
1920
+ on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
1921
+ if (e.viewport?.isFullscreen === true && !autoOpenSent && (await read($, autoOpen))) {
1922
+ autoOpenSent = true
1923
+ void $.ui.open(PANE_ARGS).then(() => paneOpened($ as Api)).catch(() => undefined)
1924
+ }
1925
+ const usd = await read($, costUsd)
1926
+ if (usd <= 0) return next(e)
1927
+ return next({ ...e, props: { ...e.props, suffix: `${e.props.suffix} · ${dollars(usd)}` } })
1928
+ })
1929
+
1930
+ on('command.run', { command: 'activity' }, async ($, e) => {
1931
+ const answered = await notifyCommand($ as Api, e.command, e.args)
1932
+ if (answered) return answered
1933
+ const opened = await $.ui.open(PANE_ARGS).catch(() => undefined)
1934
+ if (opened?.isPlaced !== false) void paneOpened($ as Api).catch(() => undefined)
1935
+ return { text: opened?.isPlaced === false ? 'El panel de actividad espera a que haya espacio.' : 'Panel de actividad abierto.' }
1936
+ })
1937
+
1938
+ on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
1939
+ const snap = await readSnapshot($ as Api)
1940
+ const view = snap.view
1941
+ const frame = paneFrame(buildPane(snap, 80), e.bodyRows, view, false)
1942
+ if (!frame.isWindowed) return next(e)
1943
+ const isJump = Math.abs(e.by) === e.contentRows && e.contentRows !== e.bodyRows
1944
+ await update($, scroll, state => scrolled(state, e.by, frame.total, frame.room, isJump))
1945
+ return {}
1946
+ }).catch(($, e, next) => next(e))
1947
+
1948
+
1949
+ on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
1950
+ if (e.props.isExpanded === true) return next(e)
1951
+ const { Box, Text } = $.ui.resolve(e)
1952
+ const summary = summarize((e.props.input ?? {}) as Record<string, unknown>)
1953
+ if (e.props.isInterrupted) {
1954
+ return <Text dimColor wrap="truncate-end">{ICONS.interrupted} interrumpido: {e.props.tool} {summary}</Text>
1955
+ }
1956
+ if (!e.props.isErrored) return <Box />
1957
+ return (
1958
+ <Text color="error" wrap="truncate-end">
1959
+ {ICONS.error} {e.props.tool} falló: {summary}
1960
+ </Text>
1961
+ )
1962
+ })
1963
+
1964
+ on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
1965
+ if (e.props.isExpanded === true) return next(e)
1966
+ const { Box } = $.ui.resolve(e)
1967
+ return <Box />
1968
+ })
1969
+
1970
+ on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
1971
+ if (e.props.isExpanded) return next(e)
1972
+ const { Box, Text } = $.ui.resolve(e)
1973
+ const notable = e.props.calls.filter(call => call.isErrored || call.isInterrupted)
1974
+ if (notable.length === 0) return <Box />
1975
+ return (
1976
+ <Box flexDirection="column">
1977
+ {notable.map(call => {
1978
+ const summary = summarize((call.input ?? {}) as Record<string, unknown>)
1979
+ return call.isErrored ? (
1980
+ <Text color="error" wrap="truncate-end">{ICONS.error} {call.tool} falló: {summary}</Text>
1981
+ ) : (
1982
+ <Text dimColor wrap="truncate-end">{ICONS.interrupted} interrumpido: {call.tool} {summary}</Text>
1983
+ )
1984
+ })}
1985
+ </Box>
1986
+ )
1987
+ })
1988
+
1989
+ on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
1990
+ if (e.props.origin.kind !== 'composer') return next(e)
1991
+ const { Box, Text } = $.ui.resolve(e)
1992
+ return (
1993
+ <Box flexDirection="column">
1994
+ <Text color="permission" bold>▎ Tú</Text>
1995
+ {await next(e)}
1996
+ </Box>
1997
+ )
1998
+ })
1999
+
2000
+ on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
2001
+ if (!e.props.isFirstOfReply) return next(e)
2002
+ const { Box, Text } = $.ui.resolve(e)
2003
+ return (
2004
+ <Box flexDirection="column">
2005
+ <Text color="claude" bold>▎ Claude</Text>
2006
+ {await next(e)}
2007
+ </Box>
2008
+ )
2009
+ })
2010
+
2011
+ on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
2012
+ const { Box, Text, Button } = $.ui.resolve(e)
2013
+ const snap = await readSnapshot($ as Api)
2014
+ const view = snap.view
2015
+ const width = Math.max(1, e.props.bodyColumns)
2016
+ const model = buildPane(snap, width)
2017
+ const frame = paneFrame(model, e.props.scroll.bodyRows, view, e.props.placement === 'dock')
2018
+ const run: Run = (argv, init) => $.process.run(argv, init)
2019
+ if (model.tab === 'history' && snap.historyView.state === 'idle') void reloadHistory($ as Api)
2020
+
2021
+ const resetScroll = () => update($, scroll, () => ({ offset: 0, follow: false }))
2022
+ const toggleDiff = async (target: DiffTarget) => {
2023
+ const key = targetKey(target)
2024
+ let isOpening = false
2025
+ const keys = await update($, openFiles, current => {
2026
+ isOpening = !current.includes(key)
2027
+ return isOpening ? [...current, key].slice(-OPEN_DIFFS) : current.filter(one => one !== key)
2028
+ })
2029
+ if (!isOpening) {
2030
+ await update($, diffs, all => Object.fromEntries(Object.entries(all).filter(([name]) => name !== key)))
2031
+ return
2032
+ }
2033
+ const top = await gitTop(run)
2034
+ const patch = top === undefined ? { rows: [], total: 0 } : await fetchDiff(run, top, target)
2035
+ await update($, diffs, all => ({ ...Object.fromEntries(Object.entries(all).filter(([name]) => keys.includes(name))), [key]: patch }))
2036
+ }
2037
+ const toggleCommit = async (sha: string) => {
2038
+ const key = `hist-${sha}`
2039
+ let isOpening = false
2040
+ await update($, toggled, keys => {
2041
+ isOpening = !keys.includes(key)
2042
+ return isOpening ? [...keys, key].slice(-200) : keys.filter(one => one !== key)
2043
+ })
2044
+ const known = ownerOf(sessionOwners(await read($, commits)), sha)
2045
+ if (!isOpening || known?.files !== undefined || (await read($, historyFiles))[sha]?.files !== undefined) return
2046
+ const top = await gitTop(run)
2047
+ const stats = top === undefined ? undefined : await loadCommitStats(run, top, sha)
2048
+ const loaded: HistoryFiles = stats ? { files: stats.files } : { failed: true }
2049
+ await update($, historyFiles, all => Object.fromEntries([...Object.entries(all).filter(([name]) => name !== sha), [sha, loaded]].slice(-HISTORY_FILES)))
2050
+ }
2051
+ const openTarget = async (target: DiffTarget) => {
2052
+ const top = await gitTop(run)
2053
+ if (top === undefined) {
2054
+ $.ui.toast('No hay repositorio git aquí.')
2055
+ return
2056
+ }
2057
+ const outcome = await openInEditor(run, path => $.fs.exists(path), { top, path: target.path, base: editorBase(target), editor: await read($, editor) })
2058
+ const kept = outcome.editor
2059
+ if (kept) await update($, editor, () => kept)
2060
+ if (!outcome.ok) $.ui.toast(outcome.message ?? 'No se pudo abrir el editor.')
2061
+ }
2062
+ const act = async (action: Action) => {
2063
+ if (action.kind === 'toggle') {
2064
+ await update($, toggled, keys => (keys.includes(action.key) ? keys.filter(one => one !== action.key) : [...keys, action.key].slice(-200)))
2065
+ } else if (action.kind === 'tab') {
2066
+ await update($, tabs, all => ({ ...all, [model.scope]: action.tab }))
2067
+ await resetScroll()
2068
+ if (action.tab === 'history') await reloadHistory($ as Api)
2069
+ } else if (action.kind === 'agent') {
2070
+ await update($, pickedAgent, () => action.id)
2071
+ await resetScroll()
2072
+ } else if (action.kind === 'scope') {
2073
+ await update($, scopes, all => ({ ...all, [model.scope]: action.scope }))
2074
+ await resetScroll()
2075
+ if (action.scope === 'branch') {
2076
+ const top = await gitTop(run)
2077
+ const loaded: BranchView = top === undefined ? { isLoaded: true, files: [], commits: [], error: 'No hay repositorio git aquí.' } : await loadBranch(run, top)
2078
+ await update($, branch, () => loaded)
2079
+ }
2080
+ } else if (action.kind === 'commit') {
2081
+ await toggleCommit(action.sha)
2082
+ } else if (action.kind === 'diff') {
2083
+ await toggleDiff(action.target)
2084
+ } else if (action.kind === 'agents') {
2085
+ await actAgents($ as Api, action)
2086
+ await resetScroll()
2087
+ } else {
2088
+ await openTarget(action.target)
2089
+ }
2090
+ }
2091
+
2092
+ const spansOf = (spans: Span[]) =>
2093
+ spans.map(one => (
2094
+ <Text {...paint(one)} backgroundColor={one.inverse ? undefined : PANE_BG} bold={one.bold} inverse={one.inverse}>{one.text}</Text>
2095
+ ))
2096
+ const cellOf = (rowKey: string, cell: Cell, index: number) => {
2097
+ const action = cell.action
2098
+ if (!action) return <Text wrap="truncate-end">{spansOf(cell.spans)}</Text>
2099
+ return (
2100
+ <Button key={cell.key ?? `${rowKey}-${index}`} plain label={cell.label ?? ''} onPress={() => void act(action).catch(() => undefined)}>
2101
+ <Text wrap="truncate-end">{spansOf(cell.spans)}</Text>
2102
+ </Button>
2103
+ )
2104
+ }
2105
+ const rowOf = (row: Row) => {
2106
+ const hasAction = row.cells.some(cell => cell.action !== undefined)
2107
+ const left = hasAction
2108
+ ? <Box flexDirection="row">{row.cells.map((cell, index) => cellOf(row.key, cell, index))}</Box>
2109
+ : <Text wrap="truncate-end">{row.cells.flatMap(cell => spansOf(cell.spans))}</Text>
2110
+ if (row.right === undefined) {
2111
+ return hasAction
2112
+ ? <Box key={row.key} flexDirection="row" width={width}>{row.cells.map((cell, index) => cellOf(row.key, cell, index))}</Box>
2113
+ : <Text key={row.key} wrap="truncate-end">{row.cells.flatMap(cell => spansOf(cell.spans))}</Text>
2114
+ }
2115
+ return (
2116
+ <Box key={row.key} flexDirection="row" justifyContent="space-between" width={width}>
2117
+ {left}
2118
+ <Text wrap="truncate-end">{spansOf(row.right.length > 0 ? row.right : [span(' ')])}</Text>
2119
+ </Box>
2120
+ )
2121
+ }
2122
+
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)
2140
+ })
2141
+ }