hopdeck 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,10 @@
1
1
  # Cambios
2
2
 
3
- ## Sin publicar
3
+ ## 1.4.2
4
4
 
5
5
  ### Nuevo
6
+ - **Estadísticas de cada conversación en la fila del título**, a la derecha: `MSGS 2324 │ TOK 206.9M │ TOOLS 1249 │ opus`. Mensajes, tokens (entrada, salida y caché de cada mensaje de Claude), herramientas usadas y modelo; la rama de git sigue a la izquierda, junto al título. Salen en la vista previa al pasar el cursor y con el chat abierto. Si el panel es estrecho se quitan primero los campos menos importantes (TOOLS, luego el modelo). Se calculan en segundo plano (una conversación de 79 MB tarda unos 250 ms) y después solo se lee lo que Claude añade, como mucho cada 3 s.
7
+ - **Barra inferior con las teclas entre corchetes**, como `[/] buscar [n] nueva [Ctrl+P] saltar`. Cambia con el foco: con la lista activa muestra las teclas de letra, y con un chat abierto solo las F (`[F1] lista [F3] copiar texto [F4] ocultar lista [F5] saltar [F8] git [F9] tema`), porque las letras son de Claude. A la derecha, los chats abiertos y cuántos proyectos y chats hay; ese resumen se omite si no caben las teclas enteras.
6
8
  - **La mascota de Hopdeck, un sapo naranja con auriculares.** Sale en la pantalla de inicio (el panel derecho cuando no hay ningún chat abierto), encima del texto y del mayor tamaño que quepa; si el terminal es pequeño o usas `NO_COLOR`, se queda el texto de siempre. También en la pantalla de carga y en el panel de tmux. Y con el comando `hopdeck mascot` (`--size small|normal|large`, `--plain` para dibujarla sin colores). Va dentro del programa, sin archivos de imagen ni Python; en el README hay una imagen (`docs/mascot.png`).
7
9
 
8
10
  ## 1.4.1
package/README.en.md CHANGED
@@ -112,6 +112,8 @@ Every text box supports a cursor: `←` `→`, `Home`/`End`, `Delete`, and `Ctrl
112
112
 
113
113
  With no chat open, the right pane shows the last messages of the selected conversation. With the mouse you only need to **hover** the list, no click needed.
114
114
 
115
+ On the title row, at the right, you get the conversation statistics: `MSGS` (messages), `TOK` (tokens: input, output and cache), `TOOLS` (tools used) and the model. They show in the preview and with the chat open, and on a narrow pane the least important ones are dropped first. They are computed in the background the first time, and afterwards only what Claude appends is read.
116
+
115
117
  ### Pick a folder
116
118
 
117
119
  <picture>
package/README.md CHANGED
@@ -112,6 +112,8 @@ En todas las cajas de texto puedes mover el cursor con `←` `→`, ir al princi
112
112
 
113
113
  Sin ningún chat abierto, el panel derecho muestra los últimos mensajes de la conversación seleccionada. Con el ratón basta **pasar el cursor** por la lista, sin hacer clic.
114
114
 
115
+ En la fila del título, a la derecha, salen las estadísticas de la conversación: `MSGS` (mensajes), `TOK` (tokens: entrada, salida y caché), `TOOLS` (herramientas usadas) y el modelo. Aparecen tanto en la vista previa como con el chat abierto, y si el panel es estrecho se quitan primero los menos importantes. Se calculan en segundo plano la primera vez, y después solo se lee lo que Claude va añadiendo.
116
+
115
117
  ### Elegir una carpeta
116
118
 
117
119
  <picture>
package/bin/hopdeck.js CHANGED
@@ -14,6 +14,7 @@ const readline = require('readline');
14
14
  const { LANG, T } = require('../lib/i18n');
15
15
  const { TRUE, NOCOL, LIGHT, setTheme, isLight, fg, bg, R, C, cw, strW, fit, clean } = require('../lib/style');
16
16
  const mascot = require('../lib/mascot');
17
+ const stats = require('../lib/stats');
17
18
  const { baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, wrapText } = require('../lib/text');
18
19
  const hist = require('../lib/history');
19
20
  const { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, readSession, decodeDir, projectDirs, buildProject, beginScan, endScan } = hist;
@@ -1380,9 +1381,62 @@ function previewRows(msgs, width, height, info = '') {
1380
1381
  }
1381
1382
 
1382
1383
  /** Título del panel del chat: proyecto › conversación ⎇ rama */
1383
- function headerRow(sh, width) {
1384
+ // ── Estadísticas de la conversación (mensajes, tokens, herramientas, modelo), en la fila del título del chat ──
1385
+ const STATS = new Map(); // archivo → { st, sum, at, busy, m, z }; solo se guardan las últimas conversaciones vistas
1386
+ let sidIdx = { src: null, map: new Map() };
1387
+ /** Archivo de una conversación por su id (la lista se recorre una vez por escaneo). */
1388
+ function fileOfSid(sid) {
1389
+ if (sidIdx.src !== S.projects) sidIdx = { src: S.projects, map: new Map(S.projects.flatMap((p) => p.sessions.map((q) => [q.id, q.file]))) };
1390
+ return sidIdx.map.get(sid) || null;
1391
+ }
1392
+ const chatFile = (x) => x.file || (x.sid ? fileOfSid(x.sid) : null);
1393
+ /**
1394
+ * Resumen de la conversación de ese archivo, o null mientras se lee la primera vez (undefined si no hay archivo). Se calcula en segundo
1395
+ * plano y, si el archivo crece (el chat abierto), se actualiza leyendo solo lo nuevo, como mucho cada 3 s.
1396
+ */
1397
+ function chatStats(file) {
1398
+ if (!file) return undefined;
1399
+ let e = STATS.get(file);
1400
+ if (e) { STATS.delete(file); STATS.set(file, e); } // los más recientes al final
1401
+ else { e = { st: stats.newState(), sum: null, at: 0, busy: false, m: -1, z: -1 }; STATS.set(file, e); if (STATS.size > 12) STATS.delete(STATS.keys().next().value); }
1402
+ const now = Date.now();
1403
+ if (!e.busy && now - e.at > (e.sum ? 3000 : 0)) {
1404
+ e.at = now;
1405
+ let s; try { s = fs.statSync(file); } catch { return e.sum; }
1406
+ if (!e.sum || s.size !== e.z || s.mtimeMs !== e.m) {
1407
+ e.busy = true; e.z = s.size; e.m = s.mtimeMs;
1408
+ stats.update(e.st, file).then(() => { e.sum = stats.summary(e.st); }, () => { e.sum = e.sum || stats.summary(e.st); }).finally(() => { e.busy = false; if (active) scheduleRender(); });
1409
+ }
1410
+ }
1411
+ return e.sum;
1412
+ }
1413
+
1414
+ /** Campos de las estadísticas, de más a menos importante: se muestran los que quepan, siempre en este orden: MSGS │ TOK │ TOOLS │ modelo. */
1415
+ function statFields(sum) {
1416
+ if (sum === undefined) return [];
1417
+ if (sum === null) return [{ t: '…', c: C.dim, o: 0 }];
1418
+ return [
1419
+ { t: 'MSGS ' + sum.msgs, c: C.accent, o: 0 },
1420
+ sum.tok ? { t: 'TOK ' + stats.fmtNum(sum.tok), c: C.ok, o: 1 } : null,
1421
+ sum.model ? { t: stats.modelShort(sum.model), c: C.brand + C.bold, o: 3 } : null,
1422
+ sum.tools ? { t: 'TOOLS ' + sum.tools, c: C.warn, o: 2 } : null,
1423
+ ].filter(Boolean);
1424
+ }
1425
+
1426
+ /** Título del panel del chat: proyecto › conversación ⎇ rama, y a la derecha MSGS │ TOK │ TOOLS │ modelo (los que quepan). */
1427
+ function headerRow(sh, width, sum) {
1384
1428
  if (!sh) return ' '.repeat(width);
1385
- return fit([[' ' + sh.project, C.accent + C.bold], [' › ' + sh.title, C.text], [sh.branch ? ' ⎇ ' + sh.branch : '', C.dim]], width);
1429
+ const left = [[' ' + sh.project, C.accent + C.bold], [' › ' + sh.title, C.text], [sh.branch ? ' ⎇ ' + sh.branch : '', C.dim]];
1430
+ const leftW = left.reduce((a, [t]) => a + strW(t), 0), budget = width - Math.min(leftW, Math.floor(width * 0.5)) - 1; // el título puede acortarse, pero no desaparecer
1431
+ const chosen = []; let used = 0;
1432
+ for (const f of statFields(sum)) { const w = strW(f.t) + (chosen.length ? 3 : 0); if (used + w > budget) break; chosen.push(f); used += w; } // en orden de importancia
1433
+ if (!chosen.length) return fit(left, width);
1434
+ chosen.sort((a, b) => a.o - b.o);
1435
+ const right = [];
1436
+ chosen.forEach((f, i) => { if (i) right.push([' │ ', C.faint]); right.push([f.t, f.c]); });
1437
+ right.push([' ', '']);
1438
+ const rw = right.reduce((a, [t]) => a + strW(t), 0);
1439
+ return fit(left, width - rw) + fit(right, rw);
1386
1440
  }
1387
1441
 
1388
1442
  function renderEmbed() {
@@ -1395,7 +1449,7 @@ function renderEmbed() {
1395
1449
  const selEnt = !sh && !S.help && !S.qs ? flatList()[S.c] : null;
1396
1450
  const pvMsgs = selEnt && selEnt.t === 's' ? previewFor(selEnt.s) : null;
1397
1451
  const pvRows = pvMsgs && pvMsgs.length ? previewRows(pvMsgs, rw, th, T.prevInfo(ago(selEnt.s.mtime), pvMsgs.length)) : null;
1398
- const hdr = sh || (selEnt && selEnt.t === 's' ? { project: selEnt.p.name, title: selEnt.s.title, branch: gitBranch(selEnt.p.cwd) } : null);
1452
+ const hdr = sh || (selEnt && selEnt.t === 's' ? { project: selEnt.p.name, title: selEnt.s.title, branch: gitBranch(selEnt.p.cwd), file: selEnt.s.file } : null);
1399
1453
  const gRows = E.gallery ? galleryRows(rw, th) : null;
1400
1454
  const hv = !E.gallery && sh && sh.ready && E.hover && !E.hover.g.loading && E.hover.g.images.length ? E.hover : null;
1401
1455
  const pop = hv ? hoverPopup(hv, rw, th) : null;
@@ -1411,17 +1465,24 @@ function renderEmbed() {
1411
1465
  const right = gRows ? (y === 0 ? fit([[' ' + E.gallery.project, C.accent + C.bold], [' › ' + E.gallery.title, C.text],
1412
1466
  [E.gallery.images.length ? ` ▣ ${E.gallery.i + 1}/${E.gallery.images.length}` + (gd ? ` · ${gd.w}×${gd.h}` : '') : '', C.dim]], rw)
1413
1467
  : y === 1 ? C.faint + '─'.repeat(rw) + R : gRows[ty])
1414
- : y === 0 ? headerRow(hdr, rw) : y === 1 ? C.faint + '─'.repeat(rw) + R
1468
+ : y === 0 ? headerRow(hdr, rw, hdr ? chatStats(chatFile(hdr)) : undefined) : y === 1 ? C.faint + '─'.repeat(rw) + R
1415
1469
  : sh && sh.ready ? (popRow(ty) || termRow(sh.term, ty, rw, selRange(ty, rw))) : sh ? loaderRow(ty, rw, th, sh.title) : pvRows ? pvRows[ty] : idleRow(ty, rw, th);
1416
1470
  rowsOut.push((left ? (left[y] || ' '.repeat(SW)) + div : '') + right + (gitR ? gdiv + gitR[y] : ''));
1417
1471
  }
1418
1472
  const live = E.sessions.size;
1419
- const k = (key, d) => [[key, C.accent], [' ' + d + ' ', C.dim]];
1473
+ const k = (key, d) => [['[' + key + ']', C.accent + C.bold], [' ' + d + ' ', C.text]]; // [tecla] descripción
1420
1474
  const sb = sh && sh.ready ? sh.term.buffer.active : null;
1421
1475
  const back = sb ? sb.baseY - sb.viewportY : 0;
1422
- rowsOut.push(fit([[' ', ''], [E.note ? E.note.t + ' ' : '', C.ok], [back > 0 ? T.up(back, sb && sb.baseY ? Math.round((100 * sb.viewportY) / sb.baseY) : -1) + ' ' : '', C.warn],
1423
- ...k('F1', T.bar1), ...k('F2', T.bar2), ...k('F3', E.mouse ? T.bar4 : T.bar5), ...k('F4', E.hideSide ? T.bar7 : T.bar6), ...k('F8', T.bar8),
1424
- [live ? '● ' + live : '', C.ok]], W));
1476
+ // las teclas cambian con el foco: en el chat, las letras son de Claude y solo valen las F; en la lista valen las letras
1477
+ const keys = E.focus === 'right' && sh
1478
+ ? [...k('F1', T.barList), ...k('F3', E.mouse ? T.bar4 : T.bar5), ...k('F4', E.hideSide ? T.bar7 : T.bar6), ...k('F5', T.barJump), ...k('F8', T.bar8), ...k('F9', T.barTheme)]
1479
+ : [...k('/', T.k.find), ...k('n', T.k.neu), ...k('Ctrl+P', T.barJump), ...k('b', T.bar8), ...k('t', T.barTheme), ...k('?', T.kHelp), ...k('q', T.k.quit)];
1480
+ // a la derecha: los chats abiertos y cuántos proyectos y chats hay (se omiten si no caben)
1481
+ const stat = [[live ? '● ' + live + ' ' : '', C.ok], [T.barCount(S.projects.length, S.projects.reduce((a, p) => a + p.sessions.length, 0)), C.dim], [' ', '']];
1482
+ const statW = stat.reduce((a, [t]) => a + strW(t), 0), keysW = keys.reduce((a, [t]) => a + strW(t), 0) + strW(E.note ? E.note.t : '') + 8;
1483
+ const full = W - statW >= keysW; // el resumen solo sale si las teclas caben enteras
1484
+ const barL = fit([[' ', ''], [E.note ? E.note.t + ' ' : '', C.ok], [back > 0 ? T.up(back, sb && sb.baseY ? Math.round((100 * sb.viewportY) / sb.baseY) : -1) + ' ' : '', C.warn], ...keys], full ? W - statW : W);
1485
+ rowsOut.push(full ? barL + fit(stat, statW) : barL);
1425
1486
  const changes = diffRows(rowsOut);
1426
1487
  // imagen real (Sixel) sobre el hueco del cuadro: se dibuja al aparecer y se repite si algo reescribe esas filas (con un mínimo de 150 ms entre dibujos)
1427
1488
  let sx = '';
package/lib/i18n.js CHANGED
@@ -44,6 +44,7 @@ const T = {
44
44
  'c F6 cerrar el chat abierto', 'i F7 ver imágenes del chat', 'R a renombrar / archivar', 'Ctrl+P F5 saltar a cualquier chat', '[ ] ancho de la lista', 'r recargar',
45
45
  'F1 F2 foco lista / chat', 'F3 copiar texto (ratón)', 'F4 ocultar la lista', 'b F8 panel de git', 't F9 tema claro / oscuro', '⠋ ✔ ● trabajando · terminó · abierta', 'q salir'],
46
46
  bar4: 'copiar texto', bar5: 'ratón', up: (n, pct) => `↑ ${n} líneas${pct >= 0 ? ` (${pct}%)` : ''} · PgDn/End`, loading: 'Cargando proyectos', opening: 'Abriendo conversación', close: 'cerrar', idle1: 'Elige una conversación', idle2: 'Usa ↑↓ y ⏎ en el panel izquierdo',
47
+ barList: 'lista', barJump: 'saltar', barTheme: 'tema', barCount: (p, c) => `${p} ${p === 1 ? 'proyecto' : 'proyectos'} · ${c} ${c === 1 ? 'chat' : 'chats'}`,
47
48
  idle3: 'F1 proyectos · F2 chat', bar1: 'proyectos', bar2: 'chat', bar3: 'minimizar',
48
49
  selHint: 'Ctrl+C o clic derecho: copiar · Esc: quitar la selección',
49
50
  searchPh: 'buscar conversación o proyecto…', found: (n) => `${n} ${n === 1 ? 'resultado' : 'resultados'}`, noRes: (q) => `Sin resultados para «${q}»`,
@@ -91,6 +92,7 @@ const T = {
91
92
  'c F6 close the open chat', 'i F7 view the chat images', 'R a rename / archive', 'Ctrl+P F5 jump to any chat', '[ ] list width', 'r reload',
92
93
  'F1 F2 focus list / chat', 'F3 copy text (mouse)', 'F4 hide the list', 'b F8 git panel', 't F9 light / dark theme', '⠋ ✔ ● working · done · open', 'q quit'],
93
94
  bar4: 'copy text', bar5: 'mouse', up: (n, pct) => `↑ ${n} lines${pct >= 0 ? ` (${pct}%)` : ''} · PgDn/End`, loading: 'Loading projects', opening: 'Opening conversation', close: 'close', idle1: 'Pick a conversation', idle2: 'Use ↑↓ and ⏎ in the left pane',
95
+ barList: 'list', barJump: 'jump', barTheme: 'theme', barCount: (p, c) => `${p} ${p === 1 ? 'project' : 'projects'} · ${c} ${c === 1 ? 'chat' : 'chats'}`,
94
96
  idle3: 'F1 projects · F2 chat', bar1: 'projects', bar2: 'chat', bar3: 'minimize',
95
97
  selHint: 'Ctrl+C or right click: copy · Esc: clear the selection',
96
98
  searchPh: 'search conversation or project…', found: (n) => `${n} ${n === 1 ? 'result' : 'results'}`, noRes: (q) => `No results for “${q}”`,
package/lib/stats.js ADDED
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+ // Estadísticas de una conversación (mensajes, tokens, herramientas, modelo) sacadas de su archivo .jsonl. Claude Code solo añade
3
+ // líneas al final, así que se lee todo una vez y, cuando el archivo crece, únicamente lo que se añadió. Los archivos llegan a pesar
4
+ // decenas de MB: se lee por bloques y se cede el control entre ellos para no congelar la interfaz.
5
+ const fs = require('fs');
6
+
7
+ const newState = () => ({ pos: 0, carry: Buffer.alloc(0), users: 0, asst: new Map(), anon: 0, anonTok: 0, tools: new Set(), anonTools: 0, model: '' });
8
+
9
+ const num = (v) => (Number.isFinite(v) && v > 0 ? v : 0);
10
+
11
+ /**
12
+ * Suma una línea del archivo. Las de la conversación empiezan por {"parentUuid" y llevan el rol dentro de "message", al principio:
13
+ * con eso basta para saber si es de usuario o de Claude (el "type" de la línea va al final en las de Claude). Solo se lee entera
14
+ * la línea de Claude; las de usuario con imágenes miden cientos de KB y no hace falta leerlas.
15
+ */
16
+ function feed(st, head, full) {
17
+ if (!head.startsWith('{"parentUuid"')) return; // otras líneas: títulos, adjuntos, copias de peticiones…
18
+ const m = /"message":\{[^{}]{0,240}?"role":"(user|assistant)"/.exec(head);
19
+ if (!m) return;
20
+ if (m[1] === 'user') { if (!head.includes('"isMeta":true') && !head.includes('"isSidechain":true')) st.users++; return; }
21
+ let j; try { j = JSON.parse(full()); } catch { return; }
22
+ const msg = j && j.message; if (!msg) return;
23
+ if (typeof msg.model === 'string' && msg.model && !msg.model.startsWith('<')) st.model = msg.model; // «<synthetic>» no es un modelo
24
+ const u = msg.usage || {};
25
+ const cur = { i: num(u.input_tokens), o: num(u.output_tokens), cc: num(u.cache_creation_input_tokens), cr: num(u.cache_read_input_tokens) };
26
+ // Claude Code escribe un mensaje en varias líneas (una por bloque) repitiendo el uso: cada mensaje cuenta una vez, con el mayor valor visto
27
+ if (msg.id) {
28
+ const prev = st.asst.get(msg.id);
29
+ st.asst.set(msg.id, prev ? { i: Math.max(prev.i, cur.i), o: Math.max(prev.o, cur.o), cc: Math.max(prev.cc, cur.cc), cr: Math.max(prev.cr, cur.cr) } : cur);
30
+ } else { st.anon++; st.anonTok += cur.i + cur.o + cur.cc + cur.cr; }
31
+ if (Array.isArray(msg.content)) for (const b of msg.content) if (b && b.type === 'tool_use') { if (b.id) st.tools.add(b.id); else st.anonTools++; }
32
+ }
33
+
34
+ /** Lee lo que se haya añadido al archivo desde la última vez. */
35
+ async function update(st, file) {
36
+ const fh = await fs.promises.open(file, 'r');
37
+ try {
38
+ const { size } = await fh.stat();
39
+ if (size < st.pos) Object.assign(st, newState()); // el archivo se reescribió más corto: se empieza de nuevo
40
+ const CHUNK = 2 * 1024 * 1024;
41
+ while (st.pos < size) {
42
+ const buf = Buffer.alloc(Math.min(CHUNK, size - st.pos));
43
+ const { bytesRead } = await fh.read(buf, 0, buf.length, st.pos);
44
+ if (!bytesRead) break;
45
+ st.pos += bytesRead;
46
+ const data = st.carry.length ? Buffer.concat([st.carry, buf.subarray(0, bytesRead)]) : buf.subarray(0, bytesRead);
47
+ let start = 0, nl;
48
+ while ((nl = data.indexOf(10, start)) >= 0) {
49
+ const s = start, e = nl;
50
+ feed(st, data.toString('utf8', s, Math.min(e, s + 700)), () => data.toString('utf8', s, e));
51
+ start = nl + 1;
52
+ }
53
+ st.carry = data.subarray(start); // la última línea, si aún no está completa
54
+ await new Promise((r) => setImmediate(r));
55
+ }
56
+ } finally { await fh.close(); }
57
+ }
58
+
59
+ /** Resumen: { msgs, tok, tools, model }. tok suma entrada, salida y caché de cada mensaje de Claude. */
60
+ function summary(st) {
61
+ let tok = st.anonTok;
62
+ for (const u of st.asst.values()) tok += u.i + u.o + u.cc + u.cr;
63
+ return { msgs: st.users + st.asst.size + st.anon, tok, tools: st.tools.size + st.anonTools, model: st.model };
64
+ }
65
+
66
+ /** 1234 → «1.2K», 206900000 → «206.9M». */
67
+ function fmtNum(n) {
68
+ if (n < 1000) return String(n);
69
+ for (const [div, s] of [[1e9, 'B'], [1e6, 'M'], [1e3, 'K']]) if (n >= div) return (n / div).toFixed(1).replace(/\.0$/, '') + s;
70
+ return String(n);
71
+ }
72
+
73
+ /** «claude-opus-4-5-20251101» → «opus». */
74
+ function modelShort(model) {
75
+ const m = /(opus|sonnet|haiku|fable)/i.exec(model || '');
76
+ return m ? m[1].toLowerCase() : String(model || '').replace(/^claude-/, '').replace(/-\d{8}$/, '').slice(0, 14);
77
+ }
78
+
79
+ module.exports = { newState, update, summary, feed, fmtNum, modelShort };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopdeck",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
4
4
  "description": "Selector visual de proyectos y conversaciones para Claude Code, en la terminal: salta entre proyectos sin hacer cd.",
5
5
  "author": "fabriciodev26",
6
6
  "license": "MIT",