@legios/quartermaster 0.1.19 → 0.1.21

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 (77) hide show
  1. package/README.md +154 -8
  2. package/bin/qm +12 -8
  3. package/bin/qm-barra.swift +48 -21
  4. package/bin/qm-indicator +71 -23
  5. package/bin/qm-tray.ps1 +63 -21
  6. package/bin/qm.cmd +6 -2
  7. package/bin/qm.mjs +23 -2
  8. package/dist/adapters/antigravity.js +2 -1
  9. package/dist/adapters/antigravity.js.map +1 -1
  10. package/dist/adapters/barra.js +18 -13
  11. package/dist/adapters/barra.js.map +1 -1
  12. package/dist/adapters/cache-cuota.js +3 -2
  13. package/dist/adapters/cache-cuota.js.map +1 -1
  14. package/dist/adapters/codex.js +140 -7
  15. package/dist/adapters/codex.js.map +1 -1
  16. package/dist/adapters/credenciales.js +2 -1
  17. package/dist/adapters/credenciales.js.map +1 -1
  18. package/dist/adapters/cuota-guardada.js +23 -0
  19. package/dist/adapters/cuota-guardada.js.map +1 -0
  20. package/dist/adapters/cuota.js +6 -5
  21. package/dist/adapters/cuota.js.map +1 -1
  22. package/dist/adapters/entorno.js +21 -20
  23. package/dist/adapters/entorno.js.map +1 -1
  24. package/dist/adapters/lineas.js +111 -0
  25. package/dist/adapters/lineas.js.map +1 -0
  26. package/dist/adapters/statusline.js +252 -0
  27. package/dist/adapters/statusline.js.map +1 -0
  28. package/dist/adapters/transcripciones.js +140 -2
  29. package/dist/adapters/transcripciones.js.map +1 -1
  30. package/dist/adapters/utilizacion.js +19 -7
  31. package/dist/adapters/utilizacion.js.map +1 -1
  32. package/dist/adapters/zai.js +5 -4
  33. package/dist/adapters/zai.js.map +1 -1
  34. package/dist/cli/aviso.js +136 -0
  35. package/dist/cli/aviso.js.map +1 -0
  36. package/dist/cli/desglose.js +200 -0
  37. package/dist/cli/desglose.js.map +1 -0
  38. package/dist/cli/mejor.js +140 -0
  39. package/dist/cli/mejor.js.map +1 -0
  40. package/dist/cli/preflight.js +3 -2
  41. package/dist/cli/preflight.js.map +1 -1
  42. package/dist/cli/qm.js +361 -88
  43. package/dist/cli/qm.js.map +1 -1
  44. package/dist/core/aviso.js +66 -0
  45. package/dist/core/aviso.js.map +1 -0
  46. package/dist/core/config.js +6 -2
  47. package/dist/core/config.js.map +1 -1
  48. package/dist/core/desglose.js +343 -0
  49. package/dist/core/desglose.js.map +1 -0
  50. package/dist/core/eleccion.js +105 -0
  51. package/dist/core/eleccion.js.map +1 -0
  52. package/dist/core/idioma.js +51 -0
  53. package/dist/core/idioma.js.map +1 -0
  54. package/dist/core/perfiles.js +69 -3
  55. package/dist/core/perfiles.js.map +1 -1
  56. package/dist/core/presupuesto.js +26 -10
  57. package/dist/core/presupuesto.js.map +1 -1
  58. package/dist/core/proyeccion.js +12 -4
  59. package/dist/core/proyeccion.js.map +1 -1
  60. package/dist/core/relevancia.js +5 -4
  61. package/dist/core/relevancia.js.map +1 -1
  62. package/dist/core/tipos.js +41 -10
  63. package/dist/core/tipos.js.map +1 -1
  64. package/dist/render/barras.js +18 -11
  65. package/dist/render/barras.js.map +1 -1
  66. package/dist/render/desglose.js +237 -0
  67. package/dist/render/desglose.js.map +1 -0
  68. package/dist/render/tablero.html +16 -1
  69. package/extension/gnome43/quartermaster@legios/metadata.json +1 -1
  70. package/extension/quartermaster@legios/metadata.json +1 -1
  71. package/package.json +1 -1
  72. package/scripts/gate-corta.py +97 -0
  73. package/scripts/gate-dibujo.sh +10 -0
  74. package/scripts/gate-duraciones.py +5 -1
  75. package/scripts/gate-edades.py +124 -0
  76. package/scripts/gate-presupuesto.py +4 -1
  77. package/src/render/tablero.html +16 -1
package/README.md CHANGED
@@ -105,30 +105,177 @@ get one, rather than dying with a syntax error.
105
105
 
106
106
  ```sh
107
107
  qm # quota and usage for every account
108
- qm --breve # one line — this is what goes in a statusline
108
+ qm --statusline # one line, for Claude Code's statusLine — and it records
109
+ # the quota Claude Code hands it, no network, no credential
110
+ qm --breve # the quota part of that line, without reading stdin
111
+ qm --todas # dormant accounts in full, not one line each at the bottom
109
112
  qm --json # the same, for scripts and panels
110
113
  qm --refrescar # also ask the endpoint (needs a live token)
111
114
  qm --watch 60 # redraw every N seconds
112
115
  qm --umbral=80 # exit 3 if any bar is over N%
113
116
  qm --esperar # block until quota drops: qm --esperar && codex ...
117
+ qm --mejor -- claude # start claude in the profile with the most room left
118
+ qm --aviso # a UserPromptSubmit hook: warns inside Claude Code
114
119
  qm --diagnostico # everything a bug report needs, already redacted
120
+ qm --desglose # where the week's quota went — disk only, never the network
121
+ qm --idioma=es # this run in Spanish (or =en); QM_IDIOMA does it for good
115
122
  ```
116
123
 
117
124
  In Claude Code's `settings.json`:
118
125
 
119
126
  ```json
120
- { "statusLine": { "type": "command", "command": "qm --breve" } }
127
+ { "statusLine": { "type": "command", "command": "qm --statusline" } }
121
128
  ```
122
129
 
130
+ **Put it here even if you never look at the line.** Claude Code no longer
131
+ leaves the quota in `.claude.json` on every use; what it does do is pass the
132
+ statusline command a `rate_limits` object on every redraw — the session and
133
+ weekly percentages from the last API response. `qm --statusline` saves that
134
+ per profile, so every other `qm` (the terminal, `--json`, the panels) has a
135
+ number that is seconds old and cost no request. It carries only those two
136
+ bars, so it is laid **over** the last endpoint reading rather than replacing
137
+ it: a model-scoped bar the statusline does not know about keeps its value and
138
+ shows its own age.
139
+
140
+ Already have a statusline script? Pipe the event through and print what comes
141
+ back: `echo "$input" | qm --statusline`.
142
+
123
143
  ```
124
- personal 23/75%! · teams 9/42% · codex 49/59%
144
+ ctx 182k · cache 12m · personal 23/75%! · teams 9/42% · codex 49/59%
125
145
  ```
126
146
 
147
+ The first two segments are the session drawing the line, and they are what the
148
+ *next* prompt will cost: the context size (yellow from 400k — prompts that big
149
+ were 35 % of a measured week's weighted cost with 16 % of the requests) and
150
+ how long the prompt cache stays warm. Once it goes cold the line says
151
+ `cold cache (+181k)`: the next request rewrites that many tokens of cache, so
152
+ that is the moment to decide between `/clear` and carrying on. `--breve` prints
153
+ only the quota part.
154
+
127
155
  **Two numbers per account, on purpose.** The first is the session; the second is
128
156
  the bar that stops you first. They answer different questions — "can I keep
129
157
  going right now?" and "do I make it to the end of the week?" — and either one
130
158
  alone is half an answer.
131
159
 
160
+ ### Language
161
+
162
+ `qm` speaks English or Spanish, picked from the locale the way any terminal
163
+ program does: the first non-empty of `LC_ALL`, `LC_MESSAGES` and `LANG` — `es*`
164
+ is Spanish, anything else (including `C` and `C.UTF-8`) is English — and on
165
+ Windows, where those are usually unset, the system's regional setting.
166
+ `QM_IDIOMA=es` or `QM_IDIOMA=en` overrides it for good, `--idioma=` for one run.
167
+ A Spanish speaker on a machine with `LC_ALL=C.UTF-8` gets English until they set
168
+ `QM_IDIOMA=es`. The `--aviso` hook runs with Claude Code's environment, so its
169
+ warning follows the same rule.
170
+
171
+ `--json` is the exception. The four panels draw its sentences (`frase`,
172
+ `nombre`, `credencial`, `porque`) next to labels of their own that are still in
173
+ Spanish, and a panel with half its words in each language reads worse than one
174
+ in Spanish. So the JSON's text stays Spanish unless you ask for a language on
175
+ purpose with `QM_IDIOMA` or `--idioma`. Its keys never change.
176
+
177
+ ## Before the wall
178
+
179
+ **`qm --mejor`** picks the Claude profile with the most room right now: the
180
+ lowest binding bar, then a projection that hits 100% before the reset counts
181
+ against it, then the emptier session. A window whose reset already passed is
182
+ *unknown*, not 0%. Profiles with no session or no stored number are left out.
183
+
184
+ ```sh
185
+ qm --mejor -- claude # start claude there
186
+ qm --mejor # just print the directory, for scripts
187
+ qm --mejor --json # the whole ranking, and why
188
+ ```
189
+
190
+ Use the `--` form to launch. `CLAUDE_CONFIG_DIR=$(qm --mejor) claude` is wrong
191
+ for the default profile: with the variable set, even to `~/.claude`, Claude
192
+ Code reads `~/.claude/.claude.json` instead of `~/.claude.json`, and on macOS
193
+ it stops looking in the keychain — a different profile, with no session.
194
+ `qm --mejor -- …` removes the variable for the default profile.
195
+
196
+ **`qm --aviso`** is a hook that warns you *inside* Claude Code, where you are
197
+ looking, before the bar stops you. In the profile's `settings.json`:
198
+
199
+ ```json
200
+ {
201
+ "hooks": {
202
+ "UserPromptSubmit": [
203
+ { "hooks": [{ "type": "command", "command": "qm --aviso" }] }
204
+ ]
205
+ }
206
+ }
207
+ ```
208
+
209
+ ```
210
+ qm · main: iguana_necktie at 92 % · resets in 3d7h. teams has 94 % free: CLAUDE_CONFIG_DIR=~/.claude-teams claude
211
+ ```
212
+
213
+ It speaks when the binding bar crosses 90% (`--umbral=N`), again at 95 and
214
+ 100, and when the projection says you hit 100% before the reset within 30
215
+ minutes — once per step and per window, so it does not repeat on every
216
+ prompt. The message goes in `systemMessage`, which Claude Code shows to you and
217
+ not to the model; it never blocks the prompt and always exits 0. Disk only, like
218
+ `--breve`: it reads what `qm --statusline` and the bar left, so it needs one of
219
+ them to have a number.
220
+
221
+ ## Where did it go?
222
+
223
+ `qm` tells you how much is left. `qm --desglose` tells you what spent it: the
224
+ same transcripts, broken down over the last 7 days (`--dias=N` for another
225
+ window), one block per account.
226
+
227
+ ```
228
+ .claude · ~/.claude
229
+ 7,909 requests · 282.1M of weighted cost (equivalent input tokens)
230
+
231
+ what to do · shares of the weighted cost: they approximate the quota, they don't measure it
232
+ · 35.0% of the cost came from prompts of 400k or more (16.3% of the
233
+ requests). Every turn rereads the whole context: /compact or /clear
234
+ before you get there makes every request after it cheaper.
235
+
236
+ by token class
237
+ cache read ██████████░░░░░ 67.6% 1.9G tokens
238
+ write 1h ██░░░░░░░░░░░░░ 11.7% 16.5M tokens
239
+ write 5m ██░░░░░░░░░░░░░ 11.9% 26.8M tokens
240
+ output █░░░░░░░░░░░░░░ 8.8% 5.0M tokens
241
+ input ░░░░░░░░░░░░░░░ 0.0% 15.9k tokens
242
+ …
243
+ 400k or more: 35.0% of the cost in 1,288 requests (16.3% of the requests)
244
+ ```
245
+
246
+ It opens with **what to do** — at most three tips per account, each one
247
+ carrying the measured number it rests on, ranked by how much of the cost it
248
+ explains: prompts of 400k or more (`/compact` or `/clear` sooner), cache
249
+ rewritten after a pause, an agent type that costs per request as much as the
250
+ main thread (a `fork` drags the whole conversation along) when a cheaper one is
251
+ in common use, or a few sessions taking most of the week. A tip appears only
252
+ when its number crosses a threshold; an account with nothing to fix gets no
253
+ generic advice. Then the evidence, five answers per account:
254
+
255
+ - **Cost by token class.** Tokens are weighted by their relative API price —
256
+ cache read 0.1, cache write 1.25 (5-minute TTL) or 2 (1-hour TTL), input 1,
257
+ output 5 — as a **proxy** for quota drain. Anthropic does not publish how a
258
+ subscription weighs them, and the output says so every time.
259
+ - **Cost by prompt size**, in buckets from `<50k` to `>700k`, plus how much of
260
+ it came from prompts of 400k or more.
261
+ - **Cache rebuilds**: requests that wrote more than 20k of cache without being
262
+ the first of their transcript, split by how long the cache sat idle (over an
263
+ hour, 5–60 minutes, or no gap) and by main thread vs subagent.
264
+ - **Subagents**: the main thread against each agent type.
265
+ - **The most expensive sessions**: requests, largest and median context,
266
+ compactions and duration, with the project directory — never message
267
+ content.
268
+
269
+ Requests are deduplicated by message and request id, because a reply with
270
+ several content blocks is written once per block with the same usage. Codex is
271
+ included when it is installed (its rollouts report usage per request; they do
272
+ not report cache writes or subagents, and the output says that instead of
273
+ printing zeros). `--json` gives the same numbers for a script, and
274
+ `--redactado` also replaces every project directory with `project 1`,
275
+ `project 2`… (`proyecto 1` in Spanish and in `--json`) and drops session ids, so the report can be pasted somewhere
276
+ public. Reading a week of transcripts — about 2 GB across two profiles — takes
277
+ about two seconds; see [`numeros/desglose.md`](numeros/desglose.md).
278
+
132
279
  ## When something is wrong
133
280
 
134
281
  ```sh
@@ -145,10 +292,10 @@ the cache directory, and `ps` for when the graphical session started — and it
145
292
  prompted it:
146
293
 
147
294
  ```
148
- ⚠ extension.js es 12.9 h MÁS NUEVO que la sesión gráfica.
149
- El shell carga el módulo una vez y lo deja en memoria: lo que está
150
- corriendo es el archivo viejo …
151
- → cerrá sesión y volvé a entrar. Es el único paso que falta.
295
+ ⚠ extension.js is 12.9 h NEWER than the graphical session.
296
+ The shell loads the module once and keeps it in memory: what is
297
+ running is the old file …
298
+ → log out and back in. It is the only step left.
152
299
  ```
153
300
 
154
301
  Anything it cannot find out it says so — it never omits and never guesses. It
@@ -267,7 +414,6 @@ secret configured — and says in the log which ones it skipped and why.
267
414
  | **`.deb`** | `sudo apt install ./quartermaster_*.deb` | the same package, standalone | attached to the release |
268
415
  | **Windows installer** | `quartermaster-<v>-setup.exe` | per-user, no UAC: `qm` on `PATH`, tray in the Start menu | attached to the release |
269
416
  | **scoop** | `scoop install quartermaster` | the portable zip, no installer | the tag, automatically |
270
- | **winget** | `winget install Legios.Quartermaster` | the installer, declaring Node as a dependency | the tag opens the PR |
271
417
  | **AUR** | `yay -S quartermaster` | `PKGBUILD`, with a real `nodejs>=22.6` | the tag, automatically |
272
418
  | **Nix** | `nix run github:legiosai/quartermaster` | the flake, with its own Node in the closure | nothing to publish |
273
419
  | **GNOME Extensions** | from the Extensions app | the Shell extension | **by hand** — no upload API |
package/bin/qm CHANGED
@@ -116,14 +116,18 @@ if [ -f "$RAIZ/dist/cli/qm.js" ]; then
116
116
  # bandera ya mergeada en main, porque el dist/ del disco era de diez horas
117
117
  # antes.
118
118
  #
119
- # Sólo se comprueba cuando hay un src/ al lado: el tarball de npm no lleva
120
- # src/cli, así que quien instaló por npm no tiene nada que reconstruir y no
121
- # tiene por qué ver esto. Y avisa, no falla — el dist/ igual funciona, sólo
122
- # que no es lo que está escrito.
123
- if [ -f "$RAIZ/src/cli/qm.ts" ] && [ "$RAIZ/src/cli/qm.ts" -nt "$RAIZ/dist/cli/qm.js" ] 2>/dev/null; then
124
- echo "qm: dist/ es más viejo que src/, y dist/ es el que se ejecuta." >&2
125
- echo " Tus cambios en src/ NO se están viendo. Corré \`npm run construir\`," >&2
126
- echo " o borrá dist/ para volver a leer el TypeScript directo." >&2
119
+ # Avisar no alcanzó. El 2026-11-01 `npm test` dio dos rojos falsos por esto
120
+ # —los tests corren este lanzador y el dist/ era de cinco semanas antes— y
121
+ # el aviso salía por un stderr que nadie lee dentro de un test. Así que ahora
122
+ # se corre el src/: si algún .ts es más nuevo que el dist/, el dist/ es de una
123
+ # corrida anterior y no describe lo que está escrito.
124
+ #
125
+ # Sólo pasa en un clone. El tarball de npm no lleva src/cli, y brew y el .deb
126
+ # no llevan dist/: en ninguno de los tres hay dos versiones que comparar.
127
+ if [ -f "$RAIZ/src/cli/qm.ts" ] && \
128
+ [ -n "$(find "$RAIZ/src" -name '*.ts' -newer "$RAIZ/dist/cli/qm.js" 2>/dev/null | head -n 1)" ]; then
129
+ echo "qm: dist/ es más viejo que src/: corro src/. \`npm run construir\` lo pone al día." >&2
130
+ exec "$NODO" $SIN_EXPERIMENTAL "$RAIZ/src/cli/qm.ts" "$@"
127
131
  fi
128
132
  exec "$NODO" $SIN_EXPERIMENTAL "$RAIZ/dist/cli/qm.js" "$@"
129
133
  fi
@@ -237,8 +237,19 @@ struct Ventana {
237
237
  let grupo: String?
238
238
  /// Lo decide qm, no acá.
239
239
  let preocupa: Bool
240
+ /// Cuándo se leyó ESTA barra, sólo cuando es de una lectura más vieja que
241
+ /// la cuenta: desde `qm --statusline` la sesión y la semanal pueden ser de
242
+ /// recién y el resto de la última lectura del endpoint. nil = la de la
243
+ /// cuenta. Con valor por defecto para que el `Lider` no tenga que pasarlo.
244
+ var medidoEn: Date? = nil
240
245
 
241
246
  var nombre: String { alcance == nil ? clave : "\(clave) (\(alcance!))" }
247
+
248
+ /// Los segundos desde que se leyó esta barra: la suya si la trae, la de la
249
+ /// cuenta si no.
250
+ func edad(_ deLaCuenta: Int?) -> Int? {
251
+ medidoEn.map { max(0, Int(-$0.timeIntervalSinceNow)) } ?? deLaCuenta
252
+ }
242
253
  }
243
254
 
244
255
  struct Proyeccion {
@@ -305,7 +316,7 @@ struct Trozo {
305
316
  let nombre: String
306
317
  let producto: String
307
318
  let indice: Int
308
- /// La ventana corta: «¿puedo seguir ahora?». Va como medidor y como número.
319
+ /// La sesión de 5 h, si el plan la tiene.
309
320
  let sesion: Int?
310
321
  let sesionAlerta: Bool
311
322
  /// La peor de las semanales: «¿llego al final?». Ya no va como medidor —se
@@ -313,6 +324,12 @@ struct Trozo {
313
324
  /// mitad— pero sigue contando para el aviso.
314
325
  let semanal: Int?
315
326
  let semanalAlerta: Bool
327
+ /// La ventana corta: «¿puedo seguir ahora?». Va como medidor y como número.
328
+ /// Es la sesión o, si el plan no tiene sesión —Codex Pro, medido el
329
+ /// 2026-09-27: `sesion: null` y sólo `weekly_all`—, la semanal: ahí ES la
330
+ /// que te frena ahora, y sin ella la cuenta quedaba sin número ni medidor.
331
+ var corta: Int? { sesion ?? semanal }
332
+ var cortaAlerta: Bool { sesion != nil ? sesionAlerta : semanalAlerta }
316
333
  /// Cuánto del presupuesto de HOY ya se gastó. No se dibuja: va en la
317
334
  /// descripción accesible, donde sí hay lugar para los tres números.
318
335
  let diario: Int?
@@ -454,7 +471,8 @@ func leer() -> Lectura {
454
471
  activa: v["activa"] as? Bool ?? false,
455
472
  reinicia: fecha(v["reinicia"]),
456
473
  grupo: v["grupo"] as? String,
457
- preocupa: v["preocupa"] as? Bool ?? false)
474
+ preocupa: v["preocupa"] as? Bool ?? false,
475
+ medidoEn: fecha(v["medidoEn"]))
458
476
  }
459
477
  let mostrar = (cuota["mostrar"] as? [[String: Any]] ?? []).map(aVentana)
460
478
  let historia: [(t: Double, pct: Int)] = (cuota["historia"] as? [[String: Any]] ?? []).compactMap {
@@ -495,7 +513,8 @@ func leer() -> Lectura {
495
513
  nombre: p["perfil"] as? String ?? "?",
496
514
  directorio: p["directorio"] as? String ?? "",
497
515
  cuenta: p["cuenta"] as? String,
498
- plan: p["plan"] as? String,
516
+ // planNombre es el que se dibuja; `plan` queda para un qm anterior.
517
+ plan: (p["planNombre"] as? String) ?? (p["plan"] as? String),
499
518
  credencial: p["credencial"] as? String ?? "?",
500
519
  hayNumero: hayNumero,
501
520
  frase: cuota["frase"] as? String,
@@ -667,7 +686,12 @@ final class VistaCuenta: NSView {
667
686
  let chocas = p.proyeccion?.chocas ?? false
668
687
  self.barras = p.hayNumero ? visibles.map { v in
669
688
  var pie = v.reinicia.map { "reinicia en \(duracion(Int($0.timeIntervalSinceNow)))" } ?? ""
670
- if let e = p.edadSegundos, v.clave == cual?.clave {
689
+ // Una barra de una lectura más vieja que la cuenta dice la suya,
690
+ // sea o no la que frena: es la de bin/qm-indicator, pie_de_barra().
691
+ if v.medidoEn != nil, let e = v.edad(nil) {
692
+ pie += pie.isEmpty ? "" : " · "
693
+ pie += "leída hace \(duracion(e))" + (e >= VIEJO_SEGUNDOS ? " · vieja" : "")
694
+ } else if let e = p.edadSegundos, v.clave == cual?.clave {
671
695
  pie += pie.isEmpty ? "" : " · "
672
696
  pie += "cache de hace \(duracion(e))" + (e >= VIEJO_SEGUNDOS ? " · viejo" : "")
673
697
  }
@@ -1212,7 +1236,11 @@ final class Barra: NSObject, NSApplicationDelegate {
1212
1236
  menu.addItem(.separator())
1213
1237
 
1214
1238
  if p.hayNumero, let cual = p.frena {
1215
- let viejo = (p.edadSegundos ?? 0) >= VIEJO_SEGUNDOS
1239
+ // La edad de lo que se DIBUJA —la sesión y la semanal—, no la
1240
+ // de la cuenta: con la statusline encima, la cuenta puede ser
1241
+ // de recién y una de las dos venir de una lectura de ayer.
1242
+ let viejo = [p.sesion, p.semanal].compactMap { $0?.edad(p.edadSegundos) }
1243
+ .max().map { $0 >= VIEJO_SEGUNDOS } ?? ((p.edadSegundos ?? 0) >= VIEJO_SEGUNDOS)
1216
1244
  // El `!` no es sólo severidad: también avisa que a este
1217
1245
  // ritmo tocás el techo ANTES del reinicio.
1218
1246
  let chocas = p.proyeccion?.chocas ?? false
@@ -1392,15 +1420,16 @@ final class Barra: NSObject, NSApplicationDelegate {
1392
1420
  let par = ancho
1393
1421
 
1394
1422
  let fuente = NSFont.monospacedDigitSystemFont(ofSize: 10, weight: .medium)
1395
- // El número de cada cuenta es el de la SESIÓN de 5 h: es el que
1396
- // contesta «¿puedo seguir trabajando ahora?». La semanal y el
1397
- // presupuesto del día se leen en el panel, que es donde hay lugar.
1423
+ // El número de cada cuenta es el de su ventana CORTA —la sesión de
1424
+ // 5 h, o la semanal si el plan no tiene sesión—: es el que contesta
1425
+ // «¿puedo seguir trabajando ahora?». El resto se lee en el panel, que
1426
+ // es donde hay lugar.
1398
1427
  func texto(_ t: Trozo) -> NSAttributedString? {
1399
- guard numeros, let s = t.sesion else { return nil }
1400
- // El número es la sesión, así que lleva el estado DE LA SESIÓN. Se
1401
- // tiñe recién cuando aprieta: si se pintara siempre, el color
1402
- // dejaría de querer decir algo.
1403
- let n = nivelDe(s, preocupa: t.sesionAlerta)
1428
+ guard numeros, let s = t.corta else { return nil }
1429
+ // El número es la ventana corta, así que lleva SU estado. Se tiñe
1430
+ // recién cuando aprieta: si se pintara siempre, el color dejaría
1431
+ // de querer decir algo.
1432
+ let n = nivelDe(s, preocupa: t.cortaAlerta)
1404
1433
  let color: NSColor = (n == .aviso || n == .critico) ? n.color : .labelColor
1405
1434
  return NSAttributedString(string: "\(t.viejo ? "~" : "")\(s)", attributes: [
1406
1435
  .font: fuente, .foregroundColor: color,
@@ -1438,15 +1467,13 @@ final class Barra: NSObject, NSApplicationDelegate {
1438
1467
  .draw(in: NSRect(x: x, y: (alto - ladoGlifo) / 2, width: ladoGlifo, height: ladoGlifo))
1439
1468
  }
1440
1469
  let xb = x + ladoGlifo + aireGlifo
1441
- // El medidor es la SESIÓN: es la ventana que te frena AHORA, la
1470
+ // El medidor es la ventana CORTA: la que te frena AHORA, la
1442
1471
  // única que se mueve dentro del rato que estás mirando la
1443
- // barra. La semanal se mueve dos píxeles por día y el
1444
- // presupuesto del día tiene su frase entera en el panel. Si la
1445
- // cuenta no informa sesión, queda la pista vacía: mejor un
1446
- // hueco honesto que dibujar ahí otra cosa.
1447
- barra(xb, t.sesion ?? 0,
1448
- t.sesion == nil ? NSColor.labelColor.withAlphaComponent(0.16)
1449
- : nivelDe(t.sesion!, preocupa: t.sesionAlerta).color)
1472
+ // barra. Con sesión de 5 h es la sesión —la semanal se mueve
1473
+ // dos píxeles por día—; sin sesión, la semanal es la corta.
1474
+ barra(xb, t.corta ?? 0,
1475
+ t.corta == nil ? NSColor.labelColor.withAlphaComponent(0.16)
1476
+ : nivelDe(t.corta!, preocupa: t.cortaAlerta).color)
1450
1477
  if let n = texto(t) {
1451
1478
  n.draw(at: NSPoint(x: xb + par + aireNumero, y: (alto - n.size().height) / 2))
1452
1479
  }
package/bin/qm-indicator CHANGED
@@ -414,6 +414,36 @@ def cada_cuanto(historia: list) -> float | None:
414
414
  return huecos[len(huecos) // 2] / 1000
415
415
 
416
416
 
417
+ def edad_de(v: dict | None, cuota: dict) -> int | None:
418
+ """Los segundos desde que se leyó ESTA barra.
419
+
420
+ Desde `qm --statusline` una cuenta puede mezclar lecturas: la sesión y la
421
+ semanal recién llegadas por la statusline, y el resto de las barras de la
422
+ última lectura del endpoint. La barra que viene de una lectura más vieja
423
+ trae su propio `medidoEn`; las demás son de cuando dice la cuenta.
424
+ """
425
+ if v and v.get("medidoEn"):
426
+ s = faltan(v["medidoEn"])
427
+ if s is not None:
428
+ return max(0, -s)
429
+ return cuota.get("edadSegundos")
430
+
431
+
432
+ def pie_de_barra(v: dict) -> str:
433
+ """«reinicia en 3d7h · leída hace 24m». La edad sólo va cuando la barra
434
+ tiene la suya: si es de cuando dice la cuenta, ya la dice el renglón de
435
+ lecturas, y repetirla en cada barra es ruido."""
436
+ pie = reinicio(faltan(v.get("reinicia")))
437
+ if not v.get("medidoEn"):
438
+ return pie
439
+ s = faltan(v["medidoEn"])
440
+ if s is None:
441
+ return pie
442
+ e = max(0, -s)
443
+ edad = f"leída hace {duracion(e)}" + (" · vieja" if e >= VIEJO_SEGUNDOS else "")
444
+ return f"{pie} · {edad}" if pie else edad
445
+
446
+
417
447
  def reinicio(segundos: int | None) -> str:
418
448
  """«reinicia en vencido» no es castellano. Cuando ya pasó, se dice que pasó."""
419
449
  if segundos is None:
@@ -670,7 +700,8 @@ class VistaCuenta:
670
700
  self.producto = p.get("producto") or "claude"
671
701
  self.indice_color = indice_color
672
702
  self.titulo = corto(p.get("perfil") or "?")
673
- partes = [x for x in (p.get("cuenta"), p.get("plan")) if x]
703
+ # planNombre es el que se dibuja; `plan` queda para un qm anterior.
704
+ partes = [x for x in (p.get("cuenta"), p.get("planNombre") or p.get("plan")) if x]
674
705
  self.sub = " · ".join(partes)
675
706
  self.hay_numero = cuota.get("estado") == "ok"
676
707
  self.frase = None if self.hay_numero else (cuota.get("frase") or "sin cuota")
@@ -688,7 +719,7 @@ class VistaCuenta:
688
719
 
689
720
  self.barras = []
690
721
  for v in (cuota.get("mostrar") or []) if self.hay_numero else []:
691
- pie = reinicio(faltan(v.get("reinicia")))
722
+ pie = pie_de_barra(v)
692
723
  es_la_que_frena = bool(frena and v.get("clave") == frena.get("clave"))
693
724
  self.barras.append({
694
725
  "nombre": nombre_ventana(v),
@@ -958,9 +989,14 @@ class VistaResumen:
958
989
  héroe del tablero —qué me frena primero, en toda la máquina— y que si no
959
990
  está acá hay que sacarla comparando las cuentas a ojo."""
960
991
 
961
- def __init__(self, cuenta: str, barra: str, pct: float, nivel: str, reinicia) -> None:
992
+ def __init__(self, cuenta: str, barra: str, pct: float, nivel: str, reinicia,
993
+ medido_en: str | None = None) -> None:
962
994
  self.cuenta, self.barra, self.pct = cuenta, barra, pct
963
995
  self.nivel, self.reinicia = nivel, reinicia
996
+ # La edad propia de la barra que encabeza, si es de una lectura más
997
+ # vieja que su cuenta. Suele serlo: la statusline refresca la sesión y la
998
+ # semanal, y lo que frena puede ser una barra que sólo trae el endpoint.
999
+ self.medido_en = medido_en
964
1000
 
965
1001
  @staticmethod
966
1002
  def desde(datos: dict) -> "VistaResumen | None":
@@ -991,7 +1027,7 @@ class VistaResumen:
991
1027
  nombre = p.get("perfil") or lider.get("perfil") or "?"
992
1028
  return VistaResumen(corto(nombre), nombre_ventana(v), v["porcentaje"],
993
1029
  nivel_de(v["porcentaje"], v.get("preocupa", False) or choca),
994
- v.get("reinicia"))
1030
+ v.get("reinicia"), v.get("medidoEn"))
995
1031
 
996
1032
  def pintar(self, cr, pluma: Pluma, arriba: float) -> float:
997
1033
  color = TEMA.nivel(self.nivel)
@@ -1036,6 +1072,9 @@ class VistaResumen:
1036
1072
  texto, urgente = f"libre en {duracion(seg)}", True
1037
1073
  else:
1038
1074
  texto, urgente = reinicio(seg), False
1075
+ edad = faltan(self.medido_en)
1076
+ if edad is not None:
1077
+ texto += f" · leída hace {duracion(max(0, -edad))}"
1039
1078
  pluma.escribir(x, arriba + 54, texto, 11, color if urgente else TEMA.terciario,
1040
1079
  Pango.Weight.MEDIUM if urgente else Pango.Weight.NORMAL,
1041
1080
  ancho=ANCHO_PANEL - MARGEN - x, elipsis=True)
@@ -1044,7 +1083,7 @@ class VistaResumen:
1044
1083
 
1045
1084
  # ── el item de la barra, dibujado ────────────────────────────────────────
1046
1085
  # Un medidor vertical por cuenta, en el orden del menú, lleno hasta la SESIÓN de
1047
- # 5 h y pintado por severidad. Es el mismo dibujo que el item de la barra de
1086
+ # 5 h —o la semanal, si el plan no tiene sesión— y pintado por severidad. Es el mismo dibujo que el item de la barra de
1048
1087
  # macOS (bin/qm-barra.swift, medidores()) y con las mismas medidas: tres cuentas
1049
1088
  # entran en el ancho de una palabra.
1050
1089
  #
@@ -1067,17 +1106,17 @@ PROPORCION_ANCHA = 1.6
1067
1106
 
1068
1107
 
1069
1108
  def _numero_de(t: dict) -> str | None:
1070
- """El número de cada cuenta es el de la SESIÓN de 5 h: es el que contesta
1071
- «¿puedo seguir trabajando ahora?». La semanal se sigue viendo —es el
1072
- medidor, con su color— sin gastar dígitos.
1109
+ """El número de cada cuenta es el de su ventana CORTA —la sesión de 5 h, o
1110
+ la semanal si el plan no tiene sesión—: es el que contesta «¿puedo seguir
1111
+ trabajando ahora?». El resto se lee en el panel.
1073
1112
 
1074
1113
  Sin marca de cache viejo: un `~` pegado al número obliga a saber qué
1075
1114
  significa para poder leer el número, y la edad del cache ya está escrita con
1076
1115
  todas las letras en el panel, que es donde se la va a buscar.
1077
1116
  """
1078
- if t["sesion"] is None:
1117
+ if t["corta"] is None:
1079
1118
  return None
1080
- return f"{t['sesion']:.0f}"
1119
+ return f"{t['corta']:.0f}"
1081
1120
 
1082
1121
 
1083
1122
  def piezas_de(datos, avisar=None) -> list[dict]:
@@ -1110,6 +1149,12 @@ def piezas_de(datos, avisar=None) -> list[dict]:
1110
1149
  return bool(v.get("preocupa")) or (_chocas and v.get("clave") == _frena.get("clave"))
1111
1150
 
1112
1151
  ses, sem = cuota.get("sesion"), cuota.get("semanal")
1152
+ # La ventana que va en la barra: la más corta que tenga la cuenta. Casi
1153
+ # siempre es la sesión de 5 h, pero hay planes sin sesión —Codex Pro,
1154
+ # medido el 2026-09-27: `sesion: null` y sólo `weekly_all`— y ahí la
1155
+ # semanal ES la que te frena ahora. Dejar la pista vacía hacía que la
1156
+ # cuenta se viera sin número ni medidor, como si no tuviera cuota.
1157
+ corta = ses or sem
1113
1158
  diario = pct_diario(p.get("presupuesto"))
1114
1159
  nombre = corto(p["perfil"])
1115
1160
  piezas.append({
@@ -1121,6 +1166,8 @@ def piezas_de(datos, avisar=None) -> list[dict]:
1121
1166
  "sesion_alerta": alerta(ses),
1122
1167
  "semanal": sem.get("porcentaje") if sem else None,
1123
1168
  "semanal_alerta": alerta(sem),
1169
+ "corta": corta.get("porcentaje") if corta else None,
1170
+ "corta_alerta": alerta(corta),
1124
1171
  # Cuánto del presupuesto de HOY ya se gastó: es lo que llena el
1125
1172
  # medidor. None deja la pista vacía.
1126
1173
  "diario": diario,
@@ -1132,7 +1179,10 @@ def piezas_de(datos, avisar=None) -> list[dict]:
1132
1179
  # cuenta al 2 % que está quieta de una al 2 % que estás gastando
1133
1180
  # ahora mismo: el número de la segunda se mueve, el de la primera no.
1134
1181
  "ultimo_uso": p.get("ultimoUso"),
1135
- "viejo": (cuota.get("edadSegundos") or 0) >= VIEJO_SEGUNDOS,
1182
+ # La edad de la barra que se DIBUJA, no la de la cuenta: con la
1183
+ # statusline encima, la cuenta puede ser de recién y la ventana
1184
+ # corta venir de una lectura de ayer.
1185
+ "viejo": (edad_de(corta, cuota) or 0) >= VIEJO_SEGUNDOS,
1136
1186
  })
1137
1187
  if avisar is not None and not dormida:
1138
1188
  # Todas las barras, no sólo la que frena: la semanal puede estar
@@ -1201,20 +1251,18 @@ def dibujar_item(piezas: list[dict], destino: str, escala: float = 1.0) -> tuple
1201
1251
  glifo_producto(cr, t["producto"], TEMA.color_cuenta(t["indice"]),
1202
1252
  x, (ALTO_ITEM - LADO_GLIFO) / 2, LADO_GLIFO)
1203
1253
  xb = x + LADO_GLIFO + AIRE_GLIFO
1204
- # El medidor es la SESIÓN: es la ventana que te frena AHORA, la única
1205
- # que se mueve dentro del rato que estás mirando la barra. La semanal se
1206
- # mueve dos píxeles por día —a media semana está siempre por la mitad—
1207
- # y el presupuesto del día tiene su frase entera en el panel. Si la
1208
- # cuenta no informa sesión queda la pista vacía: mejor un hueco honesto
1209
- # que dibujar otra cosa.
1210
- medidor(xb, t["sesion"],
1211
- TEMA.nivel(nivel_de(t["sesion"], t["sesion_alerta"])) if t["sesion"] is not None else None)
1254
+ # El medidor es la ventana CORTA: la que te frena AHORA, la única que se
1255
+ # mueve dentro del rato que estás mirando la barra. Con sesión de 5 h es
1256
+ # la sesión —la semanal se mueve dos píxeles por día y a media semana
1257
+ # está siempre por la mitad—; sin sesión, la semanal es la corta.
1258
+ medidor(xb, t["corta"],
1259
+ TEMA.nivel(nivel_de(t["corta"], t["corta_alerta"])) if t["corta"] is not None else None)
1212
1260
  n = _numero_de(t)
1213
1261
  if n is not None:
1214
- # El número es la sesión, así que lleva el estado DE LA SESIÓN. Se
1215
- # tiñe recién cuando aprieta: si se pintara siempre, el color
1216
- # dejaría de querer decir algo.
1217
- nivel = nivel_de(t["sesion"], t["sesion_alerta"])
1262
+ # El número es la ventana corta, así que lleva SU estado. Se tiñe
1263
+ # recién cuando aprieta: si se pintara siempre, el color dejaría de
1264
+ # querer decir algo.
1265
+ nivel = nivel_de(t["corta"], t["corta_alerta"])
1218
1266
  color = TEMA.nivel(nivel) if nivel in ("aviso", "critico") else TEMA.etiqueta
1219
1267
  alto_n = pluma.alto(n, 10, Pango.Weight.MEDIUM, tabular=True)
1220
1268
  pluma.escribir(xb + ANCHO_MEDIDOR + AIRE_NUMERO, (ALTO_ITEM - alto_n) / 2,