Clean View y Context Bar en una caja: oculta las herramientas, muestra la tarea en curso con su progreso y el uso de la ventana de contexto.

Marketplace de mods para Claude Code.
claude plugin marketplace add Dos2Locos/claude-code-mods
claude plugin install clean-view@dos2locos-mods
claude plugin install openspec-tracker@dos2locos-mods
claude plugin install clean-bar@dos2locos-mods
En una sesión abierta, ejecuta /reload-plugins después de instalar o actualizar.
Para actualizar: claude plugin marketplace update dos2locos-mods y claude plugin update clean-view@dos2locos-mods.
Vista limpia mientras Claude trabaja:
Pensando · paso 3/5….0 (prompt vacío), el botón de la franja o /clean-view [on|off].Funciona en la terminal y en la pestaña Code de la app de escritorio. Requiere Claude Code v2.1.287 o posterior.
Clean View y Context Bar en un único mod: una sola línea sobre el prompt, con tres secciones que despliegan su detalle al pulsarlas.
work_state_write de claude-mem): el prompt como cabecera en degradado, Paso n de m con barra y porcentaje, y una fila por tarea con su mini barra y estado (Hecho, En curso, Siguiente, Pendiente). Muestra hasta 6 tareas alrededor de la actual y, debajo, la acción en curso (↳ Editar app.ts)./compact.◷ 42:13, verde, amarilla bajo el 50 % y roja bajo el 20 %; ◷ fría al caducar). Pulsar una sección, o 1 (progreso), 2 (contexto) y 3 (caché) en el prompt vacío, despliega su detalle en una caja debajo (una sección a la vez); pulsarla otra vez la recoge.cacheTtl del mod (1h por defecto, el de las suscripciones; 5m con clave de API sin ENABLE_PROMPT_CACHING_1H).0 (prompt vacío), el botón de la caja o /clean-bar [on|off].Sustituye a clean-view y context-bar: conviene no tenerlos activos a la vez.
Seguimiento del flujo de OpenSpec en el proyecto de la sesión:
/openspec abre un panel con los cambios activos: fase (propuesta → specs → diseño → tareas → implementación → listo para archivar), barra de tareas y última modificación. Pulsa 1–9 para abrir uno.tasks.md por sección y validación con openspec validate.a Aplicar, x Archivar y e Revisar: escriben /opsx:apply <id> (o equivalente) en el prompt sin enviarlo. v Validar y r Actualizar se ejecutan al momento.◐ OpenSpec 05-update-member-screens-ux · 7/15 · implementación.Requiere la CLI openspec (v1.x) instalada. Solo se activa en proyectos con carpeta openspec/.
hooks/register.tsx 652 lines1// Clean Bar: Clean View y Context Bar en una sola caja sobre el prompt.
2// Una sola línea: el progreso (tarea en curso, mini barra y porcentaje), el contexto
3// (mini barra apilada y porcentaje) y la vida de la caché de prompts (cuenta atrás desde la
4// última petición). Pulsar una sección, o `1`, `2` y `3` (prompt vacío), despliega su detalle.
5// Oculta las filas de herramientas. Se alterna con `0` (prompt vacío), el botón o /clean-bar.
6import { atom, read, update } from 'claude-code'
7import type { EngineInterface, Register, RenderChildren } from 'claude-code'
8
9import type { Cache, Reading, Run, Section, Step, StepStatus } from '../types'
10import { GLYPH, SPLIT, cells, fromTotals, legend, share, toReading, tokens } from './context'
11
12const isOn = atom({ plugin: 'clean-bar', key: 'isOn' } as const, true)
13const run = atom({ plugin: 'clean-bar', key: 'run' } as const, null as Run | null)
14const reading = atom({ plugin: 'clean-bar', key: 'reading' } as const, null as Reading | null)
15const open = atom({ plugin: 'clean-bar', key: 'open' } as const, null as Section | null)
16const cache = atom({ plugin: 'clean-bar', key: 'cache' } as const, null as Cache | null)
17
18const STORE_KEY = 'isOn'
19const TOGGLE_HOTKEY = '0'
20const SECTION_HOTKEY: Record<Section, string> = { progress: '1', context: '2', cache: '3' }
21const MINUTE = 60_000
22const CACHE_TTL_MS: Record<string, number> = { '5m': 5 * MINUTE, '1h': 60 * MINUTE }
23/** Cada cuánto se redibuja la cuenta atrás mientras la caché está caliente. */
24const TICK_MS = 1000
25/** Ancho de las mini barras de cada tarea en el detalle. */
26const MINI_BAR = 16
27/** Ancho de las barras de la línea. */
28const LINE_BAR = 10
29const GAP = ' '
30/** Lo que ocupa un botón `plain` con atajo antes de su texto: `1: `. */
31const HOTKEY_WIDTH = 3
32const MIN_LABEL = 8
33
34/** El temporizador de la cuenta atrás; una recarga del módulo arranca otro. */
35let ticker: { cancel: () => void } | undefined
36const MIN_WIDTH = 20
37const PLAN_TOOLS = new Set(['TodoWrite', 'TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet'])
38/** La lista de trabajo de claude-mem (`work_state_write`), con el prefijo MCP que tenga instalado. */
39const WORK_STATE_TOOL = /work_state_write$/
40const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
41const HIDDEN_ROWS = ['ToolUse', 'ToolResult', 'ToolGroup', 'ToolProgress'] as const
42
43const ACCENT = '#d97757'
44const OK = '#9ece6a'
45const WARN = '#e0af68'
46const TRACK = '#808080'
47// Degradados del plan: naranja a rosa mientras trabaja, verdes al terminar.
48const ORANGE = '#ff9e64'
49const PINK = '#ff5f87'
50const GREEN_FROM = '#2f9e44'
51const GREEN_TO = '#9ece6a'
52const SHADE = '#3b4252' // el fondo de las barras vacías
53/** Tareas del plan visibles a la vez, alrededor de la actual. */
54const MAX_ROWS = 6
55/** Parte de la mini barra que llena la tarea en curso (no hay progreso real por tarea). */
56const RUNNING_SHARE = 0.4
57const ICON: Record<StepStatus, string> = { pending: '○', running: '◐', done: '✓', error: '✗' }
58const COLOR: Record<StepStatus, string | undefined> = { pending: undefined, running: ACCENT, done: OK, error: 'red' }
59
60const emptyRun = (startedAt: number, title: string): Run => ({
61 isWorking: true,
62 title,
63 startedAt,
64 durationMs: 0,
65 plan: [],
66 toolCalls: 0,
67 changedFiles: [],
68 commands: 0,
69 errors: 0,
70 isAborted: false,
71})
72
73function field(e: object, name: string): string | undefined {
74 const value = (e as Record<string, unknown>)[name]
75 return typeof value === 'string' && value !== '' ? value : undefined
76}
77
78function basename(path: string): string {
79 return path.split('/').filter(Boolean).pop() ?? path
80}
81
82function clip(text: string, max = 48): string {
83 const line = text.replace(/\s+/g, ' ').trim()
84 return line.length > max ? `${line.slice(0, max - 1)}…` : line
85}
86
87/** Una frase legible para cada llamada, en lugar de `Bash(...)`. */
88export function describeCall(tool: string, e: object): string {
89 const file = field(e, 'file_path') ?? field(e, 'notebook_path')
90 switch (tool) {
91 case 'Read':
92 return `Leer ${file ? basename(file) : 'archivo'}`
93 case 'Edit':
94 case 'MultiEdit':
95 case 'NotebookEdit':
96 return `Editar ${file ? basename(file) : 'archivo'}`
97 case 'Write':
98 return `Escribir ${file ? basename(file) : 'archivo'}`
99 case 'Bash': {
100 const what = field(e, 'description') ?? field(e, 'command')
101 return what ? `Ejecutar: ${clip(what)}` : 'Ejecutar comando'
102 }
103 case 'Grep':
104 case 'Glob': {
105 const pattern = field(e, 'pattern')
106 return pattern ? `Buscar «${clip(pattern, 32)}»` : 'Buscar en el código'
107 }
108 case 'WebFetch': {
109 const url = field(e, 'url')
110 return `Consultar ${url ? clip(url.replace(/^https?:\/\//, '').split('/')[0] ?? url, 32) : 'página web'}`
111 }
112 case 'WebSearch':
113 return `Buscar en la web: ${clip(field(e, 'query') ?? '', 36)}`
114 case 'Agent':
115 case 'Task':
116 return `Delegar: ${clip(field(e, 'description') ?? 'subtarea', 40)}`
117 case 'Skill':
118 return `Usar habilidad ${field(e, 'skill') ?? ''}`.trim()
119 default: {
120 const short = tool.startsWith('mcp__') ? tool.split('__').slice(2).join('__') : tool
121 return `Usar ${short}`
122 }
123 }
124}
125
126function todoStatus(status: string): StepStatus {
127 return status === 'completed' || status === 'done'
128 ? 'done'
129 : status === 'in_progress' || status === 'doing'
130 ? 'running'
131 : 'pending'
132}
133
134/** Una entrada de work_state_write con `task` crea o actualiza esa tarea del plan; `dropped` la quita. */
135export function applyWorkState(plan: Step[], e: object): Step[] {
136 const list = field(e, 'list')
137 const fields = (e as { fields?: Record<string, unknown> }).fields ?? {}
138 const task = typeof fields.task === 'string' && fields.task !== '' ? fields.task : undefined
139 if (!list || !task) return plan // estado de la lista, no una tarea
140 const id = `${list}/${task}`
141 const status = typeof fields.status === 'string' ? fields.status : undefined
142 if (status === 'dropped') return plan.filter(s => s.id !== id)
143 const existing = plan.find(s => s.id === id)
144 if (!existing) return [...plan, { id, label: task, status: todoStatus(status ?? 'todo') }]
145 return plan.map(s => (s.id === id && status ? { ...s, status: todoStatus(status) } : s))
146}
147
148export function formatDuration(ms: number): string {
149 const seconds = Math.round(ms / 1000)
150 return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`
151}
152
153/** Progreso del plan: tareas hechas, total y porcentaje. */
154export function progress(plan: Step[]): { done: number; total: number; percent: number } {
155 const done = plan.filter(s => s.status === 'done' || s.status === 'error').length
156 const total = plan.length
157 return { done, total, percent: total === 0 ? 0 : Math.round((done / total) * 100) }
158}
159
160/** La tarea en curso; si ninguna lo está, la siguiente pendiente. */
161export function currentTask(plan: Step[]): { step: Step; index: number } | undefined {
162 const running = plan.findIndex(s => s.status === 'running')
163 const index = running !== -1 ? running : plan.findIndex(s => s.status === 'pending')
164 return index === -1 ? undefined : { step: plan[index]!, index }
165}
166
167export function bar(percent: number, width: number): { filled: string; empty: string } {
168 const n = Math.round((percent / 100) * width)
169 return { filled: '█'.repeat(n), empty: '─'.repeat(width - n) }
170}
171
172/** Mezcla dos colores `#rrggbb`: `t` 0 da `a`, 1 da `b`. */
173export function mix(a: string, b: string, t: number): string {
174 const channel = (hex: string, i: number) => parseInt(hex.slice(1 + i * 2, 3 + i * 2), 16)
175 return `#${[0, 1, 2]
176 .map(i => Math.round(channel(a, i) + (channel(b, i) - channel(a, i)) * t).toString(16).padStart(2, '0'))
177 .join('')}`
178}
179
180/** El estado de cada tarea en palabras; la primera pendiente es «Siguiente». */
181export function stepState(plan: Step[], index: number): string {
182 const status = plan[index]!.status
183 if (status !== 'pending') return { done: 'Hecho', running: 'En curso', error: 'Error' }[status]
184 return plan.findIndex(s => s.status === 'pending') === index ? 'Siguiente' : 'Pendiente'
185}
186
187/** Qué tramo del plan cabe: hasta `max` tareas, con la anterior a la actual arriba. */
188export function visibleRange(total: number, focus: number, max: number): { start: number; end: number } {
189 const start = Math.min(Math.max(focus - 1, 0), Math.max(total - max, 0))
190 return { start, end: Math.min(total, start + max) }
191}
192
193/** El resumen breve que se muestra al terminar. */
194export function summarize(r: Run): string {
195 const parts: string[] = []
196 const files = r.changedFiles
197 if (files.length > 0) {
198 const names = files.slice(0, 4).map(basename).join(', ')
199 const more = files.length > 4 ? ` y ${files.length - 4} más` : ''
200 parts.push(`${files.length} ${files.length === 1 ? 'archivo modificado' : 'archivos modificados'} (${names}${more})`)
201 } else {
202 parts.push('sin cambios en archivos')
203 }
204 if (r.commands > 0) parts.push(`${r.commands} ${r.commands === 1 ? 'comando' : 'comandos'}`)
205 if (r.errors > 0) parts.push(`${r.errors} ${r.errors === 1 ? 'error' : 'errores'}`)
206 return `${r.isAborted ? 'Interrumpido' : 'Listo'} en ${formatDuration(r.durationMs)} · ${parts.join(' · ')}`
207}
208
209/** Cuenta atrás compacta: `42:13`. */
210export function countdown(ms: number): string {
211 const seconds = Math.max(Math.ceil(ms / 1000), 0)
212 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
213}
214
215/** Lo que le queda a la caché, de 0 a 1, y su color: verde, amarillo al 50 % y rojo al 20 %. */
216export function cacheLife(c: Cache, now: number, ttl: number): { left: number; share: number; tone: string } {
217 const left = Math.max(c.at + ttl - now, 0)
218 const share = left / ttl
219 return { left, share, tone: share > 0.5 ? 'green' : share > 0.2 ? 'yellow' : 'red' }
220}
221
222async function setOn($: EngineInterface, value: boolean) {
223 await update($, isOn, () => value)
224 await $.store.set(STORE_KEY, value)
225}
226
227// Pide a Claude Code el desglose de /context, estimado en local (sin llamadas de conteo).
228async function refreshContext($: EngineInterface) {
229 const usage = await $.session.usage({ breakdown: 'summary' })
230 const { breakdown: b, tokens: total, window, percent } = usage.context
231 if (b && b.rawMaxTokens > 0) await update($, reading, () => toReading(b))
232 else if (total !== undefined && window > 0) await update($, reading, () => fromTotals(total, window, percent))
233}
234
235async function toggleSection($: EngineInterface, section: Section) {
236 await update($, open, current => (current === section ? null : section))
237}
238
239async function trackPlan($: EngineInterface, tool: string, e: object, ran: { result?: unknown }) {
240 if (WORK_STATE_TOOL.test(tool)) {
241 await update($, run, r => (r ? { ...r, plan: applyWorkState(r.plan, e) } : r))
242 } else if (tool === 'TodoWrite') {
243 const todos = (e as { todos?: { content: string; status: string }[] }).todos ?? []
244 const plan = todos.map((t, i) => ({ id: String(i), label: t.content, status: todoStatus(t.status) }))
245 await update($, run, r => (r ? { ...r, plan } : r))
246 } else if (tool === 'TaskCreate') {
247 const id = (ran.result as { task?: { id?: string } } | undefined)?.task?.id
248 const subject = field(e, 'subject')
249 if (id && subject) {
250 await update($, run, r => (r ? { ...r, plan: [...r.plan, { id, label: subject, status: 'pending' as StepStatus }] } : r))
251 }
252 } else if (tool === 'TaskUpdate') {
253 const id = field(e, 'taskId')
254 const status = field(e, 'status')
255 const subject = field(e, 'subject')
256 await update($, run, r => {
257 if (!r || !id) return r
258 const plan =
259 status === 'deleted'
260 ? r.plan.filter(s => s.id !== id)
261 : r.plan.map(s =>
262 s.id === id ? { ...s, label: subject ?? s.label, status: status ? todoStatus(status) : s.status } : s,
263 )
264 return { ...r, plan }
265 })
266 }
267}
268
269export const register: Register = (on, options) => {
270 const ttl = CACHE_TTL_MS[String(options.cacheTtl)] ?? CACHE_TTL_MS['1h']!
271
272 on('session.start', async ($, e, next) => {
273 const r = await next(e)
274 const stored = await $.store.get(STORE_KEY).catch(() => undefined)
275 if (typeof stored === 'boolean') await update($, isOn, () => stored)
276 await $.command
277 .register({ name: 'clean-bar', description: 'Activa o desactiva Clean Bar (on | off | sin argumento para alternar)', immediate: true })
278 .catch(() => {})
279 void refreshContext($).catch(() => {})
280 // Redibuja la cuenta atrás cada segundo mientras la caché vive (y una vez más al caducar).
281 ticker?.cancel()
282 ticker = $.clock.every(TICK_MS, () => {
283 void (async () => {
284 const c = await read($, cache)
285 if (c && (await $.clock.now()) - c.at <= ttl + TICK_MS) $.ui.invalidate('ui.render')
286 })().catch(() => {})
287 })
288 return r
289 })
290
291 // Cada petición del hilo principal renueva su caché de prompts.
292 on('turn.step', async function* ($, e, next) {
293 const result = yield* next(e)
294 const usage = result.usage
295 if (e.agentId === undefined && usage) {
296 const at = await $.clock.now()
297 await update($, cache, () => ({
298 at,
299 read: usage.cache_read_input_tokens,
300 write: usage.cache_creation_input_tokens,
301 uncached: usage.input_tokens,
302 })).catch(() => {})
303 }
304 return result
305 })
306
307 // Un /compact vacía la ventana sin que termine un turno.
308 on('session.compact', async ($, e, next) => {
309 const r = await next(e)
310 if (!e.agentId && 'messages' in r) void refreshContext($).catch(() => {})
311 return r
312 })
313
314 on('command.run', { command: 'clean-bar' }, async ($, e) => {
315 const arg = String((e as { args?: unknown }).args ?? '').trim().toLowerCase()
316 const value = arg === 'on' ? true : arg === 'off' ? false : !(await read($, isOn))
317 await setOn($, value)
318 return { text: `Clean Bar ${value ? 'activado' : 'desactivado'}.` }
319 })
320
321 // Cada turno del bucle principal empieza una ejecución nueva.
322 on('turn.start', async ($, e, next) => {
323 const now = await $.clock.now()
324 await update($, run, () => emptyRun(now, e.text))
325 return next(e)
326 })
327
328 on('tool.call', async ($, e, next) => {
329 if (e.agentId !== undefined) return next(e)
330
331 const tool = String(e.tool)
332 if (PLAN_TOOLS.has(tool) || WORK_STATE_TOOL.test(tool)) {
333 const ran = await next(e)
334 await trackPlan($, tool, e, ran).catch(() => {}) // el seguimiento nunca bloquea la herramienta
335 return ran
336 }
337
338 const activity: Step = { id: e.tool_use_id, label: describeCall(tool, e), status: 'running' }
339 await update($, run, r => (r ? { ...r, activity, toolCalls: r.toolCalls + 1 } : r)).catch(() => {})
340
341 const ran = await next(e)
342 const isFailed = ran.deny !== undefined || (ran as { isError?: boolean }).isError === true
343 const file = field(e, 'file_path') ?? field(e, 'notebook_path')
344
345 await update($, run, r => {
346 if (!r) return r
347 // Llamadas en paralelo: solo se cierra la actividad si sigue siendo esta.
348 const status: StepStatus = isFailed ? 'error' : 'done'
349 const changedFiles =
350 !isFailed && EDIT_TOOLS.has(tool) && file && !r.changedFiles.includes(file) ? [...r.changedFiles, file] : r.changedFiles
351 return {
352 ...r,
353 activity: r.activity?.id === activity.id ? { ...activity, status } : r.activity,
354 changedFiles,
355 commands: r.commands + (tool === 'Bash' ? 1 : 0),
356 errors: r.errors + (isFailed ? 1 : 0),
357 }
358 }).catch(() => {})
359 return ran
360 })
361
362 on('turn.complete', async ($, e, next) => {
363 if (e.agentId === undefined) {
364 const now = await $.clock.now()
365 await update($, run, r =>
366 r ? { ...r, isWorking: false, durationMs: e.durationMs || now - r.startedAt, isAborted: e.isAborted } : r,
367 )
368 }
369 const result = await next(e)
370 if (e.agentId === undefined) await refreshContext($).catch(() => {}) // un subagente llena su propia ventana
371 return result
372 })
373
374 // Oculta las filas técnicas mientras está activo (ctrl+o sigue mostrando todo).
375 on('ui.render', { component: HIDDEN_ROWS }, async ($, e, next) => {
376 const isExpanded = (e.props as { isExpanded?: boolean }).isExpanded === true
377 if (isExpanded || !(await read($, isOn))) return next(e)
378 const { Box } = $.ui.resolve(e)
379 return <Box />
380 })
381
382
383 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
384 const rest = await next(e) // lo que dibujan otros mods y Claude Code se queda debajo
385 if (e.props.hasSurvey || e.props.view.agentId !== undefined) return rest
386 const { Box, Text, Button } = $.ui.resolve(e)
387 const active = await read($, isOn)
388
389 const toggleLabel = active ? 'ocultar' : 'Activar Clean Bar'
390 const toggle = (
391 <Button key="toggle" hotkey={TOGGLE_HOTKEY} plain label={toggleLabel} onPress={() => setOn($, !active)} />
392 )
393 if (!active) {
394 return (
395 <Box flexDirection="column">
396 <Box>
397 <Text dimColor>Clean Bar desactivado · </Text>
398 {toggle}
399 </Box>
400 {rest}
401 </Box>
402 )
403 }
404
405 const width = e.props.bodyColumns
406 if (width < MIN_WIDTH) return rest
407 const r = await read($, run)
408 const ctx = await read($, reading)
409 const now = await $.clock.now()
410 const opened = await read($, open)
411 const lastCall = await read($, cache)
412 const inner = width - 4 // el borde y el relleno del detalle ocupan 4 celdas
413
414 const badge = (percent: number, tone: string) => (
415 <Text bold color="black" backgroundColor={tone}>{` ${percent}% `}</Text>
416 )
417 const blocks = (count: number, size: number, a: string, b: string) => (
418 <Text>
419 {Array.from({ length: size }, (_, i) => (
420 <Text color={i < count ? mix(a, b, count > 1 ? i / (count - 1) : 1) : SHADE}>█</Text>
421 ))}
422 </Text>
423 )
424 const stacked = (c: Reading, size: number) => (
425 <Text>
426 {cells(c, size).map(cell => (
427 <Text color={cell.color}>{cell.text}</Text>
428 ))}
429 </Text>
430 )
431 // Cada sección de la línea es un botón que despliega o recoge su detalle.
432 const section = (s: Section, children: RenderChildren) => (
433 <Button key={`fold-${s}`} hotkey={SECTION_HOTKEY[s]} plain onPress={() => toggleSection($, s)}>
434 <Text color={ACCENT}>{opened === s ? '▾ ' : '▸ '}</Text>
435 {children}
436 </Button>
437 )
438
439 // Estado del turno, compartido por la línea y el detalle.
440 const hasPlan = (r?.plan.length ?? 0) > 0
441 const { done, total, percent } = progress(r?.plan ?? [])
442 const current = currentTask(r?.plan ?? [])
443 const elapsed = r ? formatDuration(r.isWorking ? now - r.startedAt : r.durationMs) : ''
444 const isClean = r ? r.errors === 0 && !r.isAborted : true
445 const tone = r?.isWorking ? ACCENT : isClean ? OK : WARN
446 const position = current && r?.isWorking ? current.index + 1 : done
447 const steps = r ? `${r.toolCalls} ${r.toolCalls === 1 ? 'paso' : 'pasos'}` : ''
448 const [from, to] = r?.isWorking ? [ORANGE, PINK] : isClean ? [GREEN_FROM, GREEN_TO] : [ORANGE, WARN]
449 const summary = r ? `${isClean ? '✓' : '!'} ${summarize(r)}` : ''
450
451 // La línea: lo que no es la etiqueta de progreso tiene ancho fijo; la etiqueta se recorta al resto.
452 const used = ctx ? `${tokens(ctx.total)}/${tokens(ctx.window)}` : ''
453 const level = ctx ? ctx.total / (ctx.compactsAt ?? ctx.window) : 0
454 const ctxTone = level >= 0.9 ? 'red' : level >= 0.7 ? 'yellow' : 'green'
455 const progressRight = hasPlan ? `${'█'.repeat(LINE_BAR)} ${position}/${total} ${percent}% ` : ` ${steps} · ${elapsed}`
456 const life = lastCall ? cacheLife(lastCall, now, ttl) : undefined
457 const cacheText = !life ? '◷ —' : life.left > 0 ? `◷ ${'█'.repeat(LINE_BAR)} ${countdown(life.left)}` : '◷ fría'
458 const contextWidth = GAP.length + HOTKEY_WIDTH + 2 + (ctx ? LINE_BAR + ` ${used} ${ctx.percent}% `.length : 'contexto …'.length)
459 const cacheWidth = GAP.length + HOTKEY_WIDTH + 2 + cacheText.length
460 const toggleWidth = GAP.length + HOTKEY_WIDTH + toggleLabel.length
461 const labelWidth = Math.max(
462 width - HOTKEY_WIDTH - 2 - progressRight.length - contextWidth - cacheWidth - toggleWidth,
463 MIN_LABEL,
464 )
465
466 const progressLine = () => {
467 if (!r) return <Text dimColor>esperando una tarea</Text>
468 const doing = r.isWorking ? (current?.step ?? r.activity) : undefined
469 const left = !r.isWorking ? (
470 <Text color={tone}>{clip(summary, labelWidth)}</Text>
471 ) : doing ? (
472 <Text>
473 <Text color={COLOR[doing.status]}>{`${ICON[doing.status]} `}</Text>
474 <Text>{clip(doing.label, labelWidth - 2)}</Text>
475 </Text>
476 ) : (
477 <Text dimColor>Pensando…</Text>
478 )
479 if (!hasPlan) return <Text>{left}<Text dimColor>{` ${steps} · ${elapsed}`}</Text></Text>
480 const mini = bar(percent, LINE_BAR)
481 return (
482 <Text>
483 {left}
484 <Text> </Text>
485 <Text color={tone}>{mini.filled}</Text>
486 <Text color={TRACK}>{mini.empty}</Text>
487 <Text dimColor>{` ${position}/${total} `}</Text>
488 {badge(percent, tone)}
489 </Text>
490 )
491 }
492
493 const cacheLine = () => {
494 if (!life) return <Text dimColor>◷ —</Text>
495 if (life.left === 0) return <Text dimColor>◷ fría</Text>
496 const drain = bar(life.share * 100, LINE_BAR)
497 return (
498 <Text>
499 <Text color={life.tone}>{`◷ ${drain.filled}`}</Text>
500 <Text color={TRACK}>{drain.empty}</Text>
501 <Text bold color={life.tone}>{` ${countdown(life.left)}`}</Text>
502 </Text>
503 )
504 }
505
506 const cacheDetail = () => {
507 if (!lastCall || !life) return <Text dimColor>Aún no hay peticiones al modelo en esta sesión.</Text>
508 const isWarm = life.left > 0
509 const ttlText = ttl >= 60 * MINUTE ? '1h' : `${Math.round(ttl / MINUTE)}m`
510 const state = isWarm ? ` · caduca en ${formatDuration(life.left)}` : ' · la próxima petición la vuelve a escribir'
511 const drain = bar(life.share * 100, inner)
512 return (
513 <Box flexDirection="column">
514 <Text>
515 <Text bold color={isWarm ? life.tone : undefined} dimColor={!isWarm}>{isWarm ? 'Caché caliente' : 'Caché fría'}</Text>
516 <Text dimColor>{`${state} (TTL ${ttlText}) · última petición hace ${formatDuration(now - lastCall.at)}`}</Text>
517 </Text>
518 <Text>
519 <Text color={life.tone}>{drain.filled}</Text>
520 <Text color={TRACK}>{drain.empty}</Text>
521 </Text>
522 <Text dimColor>
523 {`Última petición: ${tokens(lastCall.read)} leídos de caché · ${tokens(lastCall.write)} escritos · ${tokens(lastCall.uncached)} sin caché`}
524 </Text>
525 </Box>
526 )
527 }
528
529 const contextLine = (c: Reading | null) => !c ? <Text dimColor>contexto …</Text> : (
530 <Text>
531 {stacked(c, LINE_BAR)}
532 <Text dimColor>{` ${used} `}</Text>
533 {badge(c.percent, ctxTone)}
534 </Text>
535 )
536
537 const progressDetail = () => {
538 if (!r) return <Text dimColor>esperando una tarea</Text>
539 const doneText = !r.isWorking && <Text color={tone} wrap="wrap">{summary}</Text>
540 if (!hasPlan) {
541 return (
542 <Box flexDirection="column">
543 <Text dimColor>{`${clip(r.title, inner) || 'clean view'} · ${steps} · ${elapsed}`}</Text>
544 {r.isWorking && r.activity && <Text dimColor wrap="truncate-end">{`↳ ${r.activity.label}`}</Text>}
545 {doneText}
546 </Box>
547 )
548 }
549 // Cabecera con el prompt, barra del plan y una fila por tarea con su mini barra.
550 const title = clip(r.title, Math.max(inner - 24, MIN_WIDTH)) || 'clean view'
551 const stepText = `Paso ${position} de ${total} `
552 const pct = ` ${percent}%`
553 const barWidth = Math.max(inner - stepText.length - pct.length, 0)
554 const { start, end } = visibleRange(total, current?.index ?? total - 1, MAX_ROWS)
555 const rowLabel = Math.min(Math.max(...r.plan.map(s => s.label.length)) + 2, Math.floor(inner * 0.45))
556 const hidden = total - (end - start)
557 return (
558 <Box flexDirection="column">
559 <Box flexDirection="row" justifyContent="space-between">
560 <Box flexDirection="row" flexShrink={1}>
561 <Text color={to}>{'✱ '}</Text>
562 <Text bold wrap="truncate-end">
563 {[...title].map((ch, i, all) => (
564 <Text color={mix(from, to, all.length > 1 ? i / (all.length - 1) : 0)}>{ch}</Text>
565 ))}
566 </Text>
567 </Box>
568 <Text dimColor>{elapsed}</Text>
569 </Box>
570 <Text wrap="truncate-end">
571 <Text dimColor>{stepText}</Text>
572 {blocks(Math.round((percent / 100) * barWidth), barWidth, from, to)}
573 <Text bold color={to}>{pct}</Text>
574 </Text>
575 {r.plan.slice(start, end).map((s, k) => {
576 const isRunning = s.status === 'running'
577 const isPending = s.status === 'pending'
578 const fill = isPending ? 0 : isRunning ? Math.round(MINI_BAR * RUNNING_SHARE) : MINI_BAR
579 const [a, b] = s.status === 'done' ? [GREEN_FROM, GREEN_TO] : s.status === 'error' ? [WARN, 'red'] : [ORANGE, PINK]
580 return (
581 <Text wrap="truncate-end">
582 <Text color={isRunning ? PINK : COLOR[s.status]}>{`${isRunning ? '●' : ICON[s.status]} `}</Text>
583 <Text bold={isRunning} dimColor={isPending}>{clip(s.label, rowLabel - 2).padEnd(rowLabel)}</Text>
584 {blocks(fill, MINI_BAR, a, b)}
585 <Text bold={isRunning} color={isRunning ? PINK : undefined} dimColor={isPending}>
586 {` ${stepState(r.plan, start + k)}`}
587 </Text>
588 </Text>
589 )
590 })}
591 {hidden > 0 && <Text dimColor>{` … y ${hidden} ${hidden === 1 ? 'tarea' : 'tareas'} más`}</Text>}
592 {r.isWorking && r.activity && <Text dimColor wrap="truncate-end">{` ↳ ${r.activity.label}`}</Text>}
593 {doneText}
594 </Box>
595 )
596 }
597
598 const contextDetail = (c: Reading) => (
599 <Box flexDirection="column">
600 <Text dimColor>{`${tokens(c.total)} de ${tokens(c.window)}${c.compactsAt ? ` · compacta en ${tokens(c.compactsAt)}` : ''}`}</Text>
601 {stacked(c, inner)}
602 {legend(c, inner).map(line => (
603 <Text wrap="truncate-end">
604 {line.map((sl, i) => (
605 <Text>
606 {i > 0 && <Text>{SPLIT}</Text>}
607 <Text color={sl.color}>{sl.kind === 'used' ? '■ ' : `${GLYPH[sl.kind]} `}</Text>
608 <Text dimColor={sl.kind !== 'used'}>{`${sl.name} `}</Text>
609 <Text bold={sl.kind === 'used'}>{tokens(sl.tokens)}</Text>
610 {sl.kind === 'used' && <Text dimColor>{` ${share(sl.tokens, c.window)}`}</Text>}
611 </Text>
612 ))}
613 </Text>
614 ))}
615 </Box>
616 )
617
618 const detail =
619 opened === 'progress'
620 ? progressDetail()
621 : opened === 'context' && ctx
622 ? contextDetail(ctx)
623 : opened === 'cache'
624 ? cacheDetail()
625 : null
626 const isPlanRunning = r?.isWorking === true && hasPlan
627 return (
628 <Box flexDirection="column">
629 <Box flexDirection="row" justifyContent="space-between">
630 <Box flexDirection="row" flexShrink={1}>
631 {section('progress', progressLine())}
632 </Box>
633 <Box flexDirection="row">
634 <Text>{GAP}</Text>
635 {section('context', contextLine(ctx))}
636 <Text>{GAP}</Text>
637 {section('cache', cacheLine())}
638 <Text>{GAP}</Text>
639 {toggle}
640 </Box>
641 </Box>
642 {detail && (
643 <Box flexDirection="column" borderStyle="round" borderColor={isPlanRunning ? PINK : 'inactive'} paddingX={1}>
644 {detail}
645 </Box>
646 )}
647 {rest}
648 </Box>
649 )
650 })
651}
652hooks/context.ts 98 lines1// La parte de contexto: el desglose de /context como una barra apilada y su leyenda.
2// Adaptado del mod context-bar.
3import type { Reading, Slice } from '../types'
4
5export const SPLIT = ' '
6// El tema de /context repite gris en varias filas: cada fila usada recibe su propio color, en orden.
7const PALETTE = ['#7aa2f7', '#7dcfff', '#bb9af7', '#9ece6a', '#e0af68', '#f7768e', '#73daca', '#ff9e64', '#c0caf5']
8const MESSAGES = '#d97757' // la fila que crece, en el color de acento
9const FREE = '#808080'
10const BUFFER = '#808080'
11export const GLYPH = { used: '█', free: '─', buffer: '░' } as const
12
13export function toReading(b: {
14 categories: { name: string; tokens: number; color: string; kind: string }[]
15 totalTokens: number
16 rawMaxTokens: number
17 percentage: number
18 autoCompactThreshold?: number
19 isAutoCompactEnabled: boolean
20}): Reading {
21 const slices: Slice[] = b.categories
22 .filter(c => c.kind !== 'deferred' && c.tokens > 0)
23 .map(c => ({ name: c.name.toLowerCase(), tokens: c.tokens, color: c.color, kind: c.kind as Slice['kind'] }))
24 const order = { used: 0, free: 1, buffer: 2 }
25 slices.sort((x, y) => order[x.kind] - order[y.kind]) // stable: used rows keep /context's order
26 let next = 0
27 for (const s of slices) {
28 s.color = s.kind === 'free' ? FREE : s.kind === 'buffer' ? BUFFER : s.name === 'messages' ? MESSAGES : PALETTE[next++ % PALETTE.length]!
29 }
30 return {
31 slices,
32 total: b.totalTokens,
33 window: b.rawMaxTokens,
34 percent: b.percentage,
35 compactsAt: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined,
36 }
37}
38
39// Sin desglose: solo lo usado y lo libre, para que la línea nunca se quede sin contexto.
40export function fromTotals(total: number, window: number, percent?: number): Reading {
41 return {
42 slices: [
43 { name: 'usado', tokens: total, color: MESSAGES, kind: 'used' },
44 { name: 'libre', tokens: Math.max(window - total, 0), color: FREE, kind: 'free' },
45 ],
46 total,
47 window,
48 percent: percent ?? Math.round((total / window) * 100),
49 }
50}
51
52// The bar as runs of cells: each slice gets its share of `width`, a used one at least one cell.
53export function cells(r: Reading, width: number) {
54 const sizes = r.slices.map(s => Math.max(s.kind === 'used' ? 1 : 0, Math.round((s.tokens / r.window) * width)))
55 // Rounding leaves the sum a few cells off: free space takes the difference first, then the largest slices.
56 let diff = width - sizes.reduce((a, n) => a + n, 0)
57 const isUsed = (i: number) => r.slices[i]!.kind === 'used'
58 const order = r.slices.map((_, i) => i).sort((a, b) => Number(isUsed(a)) - Number(isUsed(b)) || sizes[b]! - sizes[a]!)
59 for (const i of order) {
60 if (diff === 0) break
61 const size = Math.max(isUsed(i) ? 1 : 0, sizes[i]! + diff)
62 diff -= size - sizes[i]!
63 sizes[i] = size
64 }
65 return r.slices.map((s, i) => ({ color: s.color, kind: s.kind, text: GLYPH[s.kind].repeat(sizes[i]!) })).filter(c => c.text !== '')
66}
67
68// The legend, packed into lines no wider than `width`.
69export function legend(r: Reading, width: number) {
70 const lines: Slice[][] = [[]]
71 let used = 0
72 for (const s of r.slices) {
73 const size = 2 + s.name.length + 1 + tokens(s.tokens).length + (s.kind === 'used' ? 1 + share(s.tokens, r.window).length : 0)
74 const line = lines.at(-1)!
75 if (line.length > 0 && used + SPLIT.length + size > width) {
76 lines.push([s])
77 used = size
78 } else {
79 used += (line.length > 0 ? SPLIT.length : 0) + size
80 line.push(s)
81 }
82 }
83 return lines.filter(l => l.length > 0)
84}
85
86export function tokens(n: number) {
87 if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1)}M`
88 if (n >= 10_000) return `${Math.round(n / 1000)}k`
89 if (n >= 1000) return `${+(n / 1000).toFixed(1)}k`
90 return String(n)
91}
92
93export function share(n: number, window: number) {
94 const p = (n / window) * 100
95 if (p > 0 && p < 0.1) return '<0.1%'
96 return `${p >= 10 ? Math.round(p) : +p.toFixed(1)}%`
97}
98types/index.d.ts 44 lines1export type StepStatus = 'pending' | 'running' | 'done' | 'error'
2
3export type Step = { id: string; label: string; status: StepStatus }
4
5export type Run = {
6 isWorking: boolean
7 /** El prompt que abrió el turno, para la cabecera. */
8 title: string
9 startedAt: number
10 durationMs: number
11 /** El plan del modelo (TodoWrite / TaskCreate), cuando lo hay. */
12 plan: Step[]
13 /** La última llamada a herramienta, en una frase. */
14 activity?: Step
15 toolCalls: number
16 changedFiles: string[]
17 commands: number
18 errors: number
19 isAborted: boolean
20}
21
22export type Slice = { name: string; tokens: number; color: string; kind: 'used' | 'free' | 'buffer' }
23
24/** Lectura de la ventana de contexto, como la desglosa /context. */
25export type Reading = {
26 slices: Slice[]
27 total: number
28 window: number
29 percent: number
30 compactsAt?: number
31}
32
33/** Las secciones de la línea; cada una despliega su detalle al pulsarla. */
34export type Section = 'progress' | 'context' | 'cache'
35
36/** La última petición del hilo principal: cuándo llegó y cómo usó la caché de prompts. */
37export type Cache = { at: number; read: number; write: number; uncached: number }
38
39declare module 'claude-code' {
40 interface PluginState {
41 'clean-bar': { isOn: boolean; open: Section | null; cache: Cache | null; run: Run | null; reading: Reading | null }
42 }
43}
44