From 19ee5ed47a1eb78c31cf62ed883aff28a52fe606 Mon Sep 17 00:00:00 2001 From: Claudio Date: Thu, 27 Aug 2026 16:29:32 +0200 Subject: [PATCH] docs: README and CLAUDE.md in English The rule is now the whole project, not just the code: identifiers, comments, errors, logs, CLI output, documentation and commit messages. Italian survives only where it is a translation - translations/it.po and the localised package descriptions in the spec. Translating surfaced a stale claim: the README still described the state being read with XMLHttpRequest over file://, which Qt 6 refuses. That correction had been made once and lost in a revert. The section now says what the code actually does, and why. Also tidied the daemon/plasmoid contract section, where an earlier edit had left a paragraph wedged between the sentence introducing the two rules and the rules themselves. --- CLAUDE.md | 149 +++++++++--------- README.md | 441 ++++++++++++++++++++++++++++-------------------------- 2 files changed, 307 insertions(+), 283 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 837aabb..e3601b3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,86 +1,89 @@ # CLAUDE.md — dipstick -> Seed creato al kickoff. Espandilo quando c'e' codice vero da descrivere. +## What this is -## Cos'e' +A KDE Plasma 6 plasmoid showing how much Claude Max quota is left, in the +panel. Scope, non-goals and the data-source contract: `README.md`. -Plasmoide KDE Plasma 6 che mostra la quota Claude Max residua nel panel. -Scope, non-goals, contratto delle fonti dati e domande aperte: `README.md`. +## Constraints -## Vincoli +- **Target: Plasma 6 on Wayland.** No X11, no other desktop environments. + The plasmoid runs inside `plasmashell`: no heavy work (parsing, blocking + network calls) in that process, or it takes the user's panel down with it. +- **Never touch `~/.claude/.credentials.json`.** The project runs its own OAuth + flow with its own token. Touching that file risks invalidating the user's + Claude Code session. +- **Never modify the desktop session.** KDE configuration, panel, shortcuts, + compositor: document how to install the plasmoid, do not do it. Installation + is the user's to run. +- **No network beyond `api.anthropic.com`** and the OAuth hosts used for login. + No telemetry, no analytics, no crash reporter, no third-party endpoints. +- **Credentials never in the repository** and never in the logs. The token + lives only in the user's configuration directory. +- **`~/.claude/projects/` is READ-ONLY.** Those are the user's real session + logs, and Claude Code is writing to them while dipstick reads. Always open + them read-only; any cache or state file belongs in dipstick's own + configuration directory, never inside that tree. +- The quota endpoint is **undocumented**: treat it as unstable. Every path that + uses it must have a fallback onto local data. -- **Target: Plasma 6 su Wayland.** Niente X11, niente altri desktop environment. - Il plasmoide gira dentro `plasmashell`: nessun lavoro pesante (parsing, rete - bloccante) in quel processo, o si porta giu' il panel dell'utente. -- **Mai toccare `~/.claude/.credentials.json`.** Il progetto usa un proprio flusso - OAuth e un proprio token. Toccare quel file rischia di invalidare la sessione - Claude Code dell'utente. -- **Mai modificare la sessione desktop.** Configurazione KDE, panel, shortcut, - compositor: si documenta come installare il plasmoide, non si esegue. - L'installazione la fa l'utente. -- **Nessuna rete oltre `api.anthropic.com`.** Nessuna telemetria, nessun analytics, - nessun crash reporter, nessun endpoint di terze parti. -- **Credenziali mai in chiaro nel repo** e mai nei log. Il token vive solo nella - cartella di configurazione dell'utente. -- **`~/.claude/projects/` e' SOLA LETTURA.** Sono i log reali delle sessioni di lavoro - dell'utente, e Claude Code ci sta scrivendo mentre dipstick li legge. Aprili sempre in - sola lettura; qualunque cache o file di stato va nella cartella di configurazione di - dipstick, mai dentro quell'albero. -- L'endpoint della quota **non e' documentato pubblicamente**: trattalo come - instabile. Ogni percorso che lo usa deve avere un fallback sui dati locali. +## Language -## Lingua +**All code is in English**: identifiers, comments, error messages, logs, CLI +output and interface source strings. Documentation and commit messages too. -**Tutto il codice e' in inglese**: identificatori, commenti, messaggi di errore, -log, output della CLI e stringhe sorgente dell'interfaccia. Nessuna eccezione. +Italian survives only where it *is* a translation: `translations/it.po` and the +localised package descriptions in the spec (`Summary(it)`, +`%description -l it`). -Sono in italiano, e restano tali: `README.md`, `CLAUDE.md`, i messaggi di -commit, il catalogo `translations/it.po` e le descrizioni localizzate nello -spec (`Summary(it)`, `%description -l it`) - che sono traduzioni, non codice. +## Working on it -## Come si lavora +Build, installation, code layout and diagnostic commands: `README.md`. -Build, installazione, layout del codice e comandi di diagnosi: `README.md`. -In breve: `make test` per i test (non toccano la rete), `make vet` prima di -committare, `plasmawindowed org.kde.plasma.dipstick` per provare il plasmoide -senza metterlo nel panel - i suoi errori QML finiscono nel journal utente, non -sul terminale. +In short: `make test` for the tests (they never touch the network), `make vet` +before committing, and `plasmawindowed org.kde.plasma.dipstick` to try the +plasmoid without putting it in the panel — its QML errors go to the user +journal, not to the terminal. -## Trappole gia' incontrate +## Traps already hit -- **`plasmashell` NON rilegge il QML dopo `kpackagetool6 --upgrade`.** Tiene in - memoria la versione caricata quando il widget e' stato aggiunto al panel. - Serve `systemctl --user restart plasma-plasmashell.service`, che va chiesto - all'utente perche' gli fa sparire il panel per qualche secondo. - `plasmawindowed` e' un processo nuovo ogni volta e vede sempre l'ultima - versione: da qui il rischio di credere che una modifica sia applicata quando - l'utente sta ancora guardando quella vecchia. Prima di dire che una modifica - di UI e' fatta, verificare che l'utente veda la stessa build. -- **`XMLHttpRequest` su `file://` non funziona in QML.** Qt 6 lo disabilita. - La lettura dello stato passa da `Plasma5Support.DataSource` (`executable`). -- **I transcript contengono messaggi duplicati**, in quantita': ~3900 righe con - `usage` per ~2000 `message.id` distinti. Va deduplicato per `message.id`, o i - token quasi raddoppiano. Il modello `` non e' una chiamata reale. -- **`seven_day_opus` e `seven_day_sonnet` arrivano `null`.** Il breakdown per - modello sta in `limits[]`, col nome deciso dal server: non e' un elenco chiuso. -- **Il token va preso col lock.** Demone e CLI condividono `auth.json`: senza - `flock` due refresh concorrenti possono bruciare il refresh token e causare - un logout. E' lo stesso rischio per cui il progetto non tocca - `~/.claude/.credentials.json`, quindi non va inflitto a se' stesso. -- **Le finestre temporali dei totali sono di CALENDARIO, non scorrevoli.** Il - grafico e' fatto di giorni, quindi `MonthTokens` e il breakdown per modello - devono partire dalla stessa mezzanotte da cui parte la serie. Con un confine - scorrevole restava una fetta di messaggi contati nei totali ma non disegnati. -- **I duplicati nei transcript non sono copie identiche**: sono istantanee - progressive dello stesso messaggio, quindi si tiene la piu' grande. Tenere la - prima vista sottostima. -- **`LDFLAGS` nel Makefile va chiamato `GO_LDFLAGS`.** E' una variabile - d'ambiente standard che `rpmbuild` valorizza con i flag del linker C: con - `?=` vince l'ambiente, Go riceve flag che non capisce e la build fallisce - **solo dentro rpmbuild**, non in locale. -- **`xgettext` marca come `javascript-format` le stringhe con `%1d` o `%1h`.** - Non lo sono: `%1` e `%2` sono i segnaposto di KDE e la lettera dopo e' - l'unita' di misura. Con quei flag `msgfmt` rifiuta una traduzione che cambia - la lettera (`%1d` -> `%1g` per "giorni"). `translations/extract.sh` li toglie. -- **`state.json` non contiene stringhe di interfaccia.** La localizzazione e' del - plasmoide; il demone gira senza contesto di locale. +- **`plasmashell` does NOT re-read the QML after `kpackagetool6 --upgrade`.** + It keeps in memory the version loaded when the widget was added to the panel. + It needs `systemctl --user restart plasma-plasmashell.service`, which has to + be asked of the user because it makes their panel disappear for a few + seconds. `plasmawindowed` is a fresh process every time and always sees the + latest version: hence the risk of believing a change has landed while the + user is still looking at the old one. Before calling a UI change done, make + sure the user is looking at the same build. +- **`XMLHttpRequest` on `file://` does not work in QML.** Qt 6 disables it. The + state is read through `Plasma5Support.DataSource` (`executable`) instead. +- **Transcripts contain duplicate messages**, in quantity: ~3900 lines with + `usage` for ~2000 distinct `message.id`. Deduplicate by `message.id` or the + token counts nearly double. The `` model is not a real call. +- **Duplicates are not identical copies**: they are progressive snapshots of + the same message, so keep the largest. Keeping the first one seen + understates the total. +- **`seven_day_opus` and `seven_day_sonnet` come back `null`.** The per-model + breakdown lives in `limits[]`, with the name the server chooses: it is not a + closed set. +- **The token must be taken under a lock.** The daemon and the CLI share + `auth.json`: without `flock`, two concurrent refreshes can spend the refresh + token twice and force a logout. It is the same risk for which this project + refuses to touch `~/.claude/.credentials.json`, so it must not inflict it on + itself. +- **Window boundaries for the totals are CALENDAR boundaries, not rolling + ones.** The chart is made of days, so `MonthTokens` and the per-model + breakdown must start from the same midnight the series starts from. With a + rolling boundary a sliver of messages was counted in the totals but drawn in + no column. +- **`LDFLAGS` in the Makefile must be called `GO_LDFLAGS`.** The former is a + standard environment variable that `rpmbuild` fills with C linker flags: with + `?=` the environment wins, Go gets flags it does not understand, and the + build fails **only inside rpmbuild**, never locally. +- **`xgettext` marks strings containing `%1d` or `%1h` as + `javascript-format`.** They are not: `%1` and `%2` are KDE's placeholders and + the letter after them is a unit of measure. With those flags `msgfmt` + rejects a translation that changes the letter (`%1d` becoming `%1g` for + "days"). `translations/extract.sh` strips them. +- **`state.json` carries no interface strings.** Localisation belongs to the + plasmoid; the daemon runs with no locale context. diff --git a/README.md b/README.md index cf87658..6d3d93b 100644 --- a/README.md +++ b/README.md @@ -1,302 +1,323 @@ # dipstick -Widget per il panel di KDE Plasma che mostra quanta quota Claude Max resta, -a colpo d'occhio. +A KDE Plasma panel widget showing how much Claude Max quota is left, at a +glance. -## Perche' esiste +## Why it exists -Lavorando con Claude Code su un abbonamento Max non c'e' modo di sapere quanta -quota resta senza fermarsi e lanciare `/usage` dentro una sessione. Il limite si -scopre quando lo si tocca, cioe' sempre nel momento peggiore. Un indicatore -sempre visibile nel panel toglie la domanda di mezzo. +Working with Claude Code on a Max subscription, there is no way to know how +much quota is left without stopping and running `/usage` inside a session. You +discover the limit by hitting it, which is always the worst moment. An +indicator that is always visible in the panel takes the question away. ## Scope -- Plasmoide QML per **Plasma 6 su Wayland**, nel panel, con popup di dettaglio al click. -- Mostra la **finestra 5h** e la **settimana**: percentuale usata e istante di reset. -- Mostra il **breakdown per modello** che l'endpoint fornisce, **con i nomi che manda lui**: - la finestra scoped e' generica, non e' fissa su Opus/Sonnet. -- Legge la quota da `GET https://api.anthropic.com/api/oauth/usage` con OAuth proprio. -- Se l'endpoint non risponde, **degrada sui transcript locali** (`~/.claude/projects/**/*.jsonl`) - e segnala esplicitamente che la quota non e' disponibile. +- A QML plasmoid for **Plasma 6 on Wayland**, in the panel, with a detail popup + on click. +- Shows the **5-hour window** and the **week**: percentage used and reset time. +- Shows the **per-model breakdown** the endpoint provides, **with the names it + sends**: the scoped window is generic, not fixed to Opus/Sonnet. +- Reads the quota from `GET https://api.anthropic.com/api/oauth/usage` using its + own OAuth flow. +- If the endpoint does not answer, it **degrades onto local transcripts** + (`~/.claude/projects/**/*.jsonl`) and says explicitly that the quota is + unavailable. ## Non-goals -- **Nessuna notifica.** Il widget e' passivo: si guarda, non interrompe. - Niente soglie configurabili, niente notifiche KDE. -- **Niente analytics.** Niente trend, niente burn rate proiettato, niente ranking - per progetto, niente sessioni. E' un widget, non un'applicazione di analytics. - *Rivisto in corsa:* il grafico giornaliero a 30 giorni era escluso da questo - punto ed e' stato reintrodotto su richiesta esplicita - e' un istogramma di - totali, non una serie da analizzare. -- **Non gestisce piu' account.** Un solo abbonamento, quello configurato. -- **Non e' un client Claude.** Non lancia sessioni, non parla con Claude Code, - non fa nulla oltre a leggere e mostrare. -- **Non supporta X11 ne' altri desktop.** Plasma 6 / Wayland e basta. Se serve - altrove, e' un altro progetto. - -## Decisioni gia' prese - -- **Plasmoide QML sottile + demone Go.** Il plasmoide gira dentro il processo - `plasmashell`: parsare li' ~150 MB di jsonl significa che un picco di memoria o - un crash porta giu' l'intero panel. Il demone fa parsing, OAuth, polling e cache, - ed espone uno stato JSON minuscolo; il plasmoide legge solo quello e disegna. -- **Go per il demone**, perche' e' un binario singolo senza runtime da installare - nel contesto del panel, ed e' veloce sul volume di transcript. -- **OAuth proprio, non le credenziali di Claude Code.** Flusso PKCE dedicato, token - in una cartella del progetto. Due processi che fanno refresh dello stesso token - possono invalidarsi a vicenda: il rischio di far cadere la sessione CLI non vale - il login risparmiato. -- **Stato via file JSON, non D-Bus ne' socket.** Il demone scrive - `~/.config/dipstick/state.json` in modo atomico (write + rename), il plasmoide lo - rilegge a intervallo con `XMLHttpRequest` su `file://`. E' l'unica opzione che tiene - il plasmoide QML puro: in Qt6/Plasma6 non esiste un modulo QML per D-Bus ne' per i - socket unix, quindi entrambi imporrebbero un plugin C++ e la fine - dell'installazione con il solo `kpackagetool6`. In piu' lo stato sopravvive al - riavvio del demone e si ispeziona con `cat`. -- **Polling della quota a 5 minuti, adattivo.** Lato server `utilization` e' un intero - che si muove ogni ~5 minuti: interrogare piu' spesso ripete la stessa risposta. - Rallenta a 15-30 min quando i transcript locali non mostrano attivita' recente, - torna a 5 min appena riprende. -- **Transcript letti per `mtime`, senza cache.** Un file non toccato da 5 ore non puo' - contenere righe delle ultime 5 ore: il filtro e' esatto, non euristico. Misurato sui - 146 MB reali dell'utente: 23 ms per la finestra 5h (4 file), 366 ms per i 7 giorni - (66 file), contro 850 ms a rileggere tutto. Una cache a offset risparmierebbe - ~340 ms ogni 5 minuti in cambio dello stato piu' delicato del progetto - (truncation, inode riusati, righe a cavallo): non vale. -- **Demone come systemd user unit residente.** Backoff adattivo e token OAuth vivono - nel processo invece che spalmati nella configurazione di un timer; in piu' restart - automatico e log in `journalctl`. Il ciclo di vita resta indipendente da - `plasmashell`, che riparte spesso. L'utente abilita l'unit a mano: dipstick non - tocca la sessione desktop. -- **Nel panel: la percentuale che stringe per prima, con una barra dello stesso dato.** - La compact representation ha ~34px di altezza: un numero si legge con la coda - dell'occhio, due grafici no. Mostra la piu' alta fra finestra 5h e settimana, cioe' - il vincolo che si tocca per primo. *Rivisto in corsa:* la barra mostrava la - **seconda** finestra, ma un numero e una barra affiancati che dicono valori - diversi si leggono come incoerenti. Ora sono lo stesso dato in due forme, e la - seconda finestra vive nel tooltip e nel popup. -- **Distribuzione: si clona e si builda.** `make install` compila il demone in - `~/.local/bin`, mette l'unit in `~/.config/systemd/user` e registra il plasmoide - con `kpackagetool6`: e' l'unica forma che installa entrambe le meta' insieme. - **Niente KDE Store**: distribuisce solo il pacchetto QML, e un widget senza il - suo demone e' rotto per costruzione. **Niente binari precompilati**: un RPM - costruito qui vale solo per la stessa architettura e la stessa versione di - Fedora, e pubblicarlo lascerebbe intendere il contrario. Lo spec c'e' - (`make rpm`) per chi il pacchetto se lo vuole fare, non per distribuirlo. -- **Si legge `limits[]`, non `five_hour`/`seven_day`.** Verificato sul campo: - `seven_day_opus` e `seven_day_sonnet` tornano `null`, e il breakdown per modello - esiste solo dentro `limits[]`, con il nome del modello deciso dal server. I campi - di primo livello restano come fallback. In piu' `limits[]` porta `severity`, cioe' - le soglie le decide gia' Anthropic e non dobbiamo inventarne. -- **Scope OAuth ridotto a `user:profile user:inference`.** Il prior art chiede anche - `org:create_api_key`, che serve a creare chiavi API: dipstick legge e basta. - Verificato che l'endpoint quota risponde lo stesso. -- **Ibrido con degrado**, non una sola fonte: la quota e' precisa ma poggia su un - endpoint non documentato, i transcript sono affidabili ma non conoscono i limiti. - -## Contratto delle fonti dati - -Endpoint quota (**non documentato pubblicamente** — puo' cambiare senza preavviso). -Forma **verificata sul campo il 2026-08-27**, non dedotta: fixture in -`internal/anthropic/testdata/usage.json`. +- **No notifications.** The widget is passive: you look at it, it does not + interrupt. No configurable thresholds, no KDE notifications. +- **No analytics.** No trends, no projected burn rate, no per-project ranking, + no session lists. It is a widget, not an analytics application. + *Revised in flight:* the 30-day daily chart was excluded by this point and + was reintroduced on explicit request — it is a histogram of totals, not a + series to analyse. +- **No multi-account support.** One subscription, the configured one. +- **Not a Claude client.** It starts no sessions, does not talk to Claude Code, + and does nothing beyond reading and displaying. +- **No X11 and no other desktops.** Plasma 6 on Wayland, full stop. If it is + needed elsewhere, that is a different project. + +## Decisions already made + +- **Thin QML plasmoid plus a Go daemon.** The plasmoid runs inside the + `plasmashell` process: parsing ~150 MB of jsonl there means a memory spike or + a crash takes the whole panel down. The daemon does the parsing, OAuth, + polling and caching, and exposes a tiny JSON state; the plasmoid reads only + that and draws. +- **Go for the daemon**, because it is a single binary with no runtime to + install in the panel's context, and it is fast over the transcript volume. +- **Its own OAuth, not Claude Code's credentials.** A dedicated PKCE flow, with + the token in the project's own directory. Two processes refreshing the same + token can invalidate each other: the risk of dropping the CLI session is not + worth the saved login. +- **State through a JSON file, not D-Bus or a socket.** The daemon writes + `~/.config/dipstick/state.json` atomically (write plus rename) and the + plasmoid re-reads it on a timer. It is the only option that keeps the + plasmoid pure QML: Qt 6 and Plasma 6 ship no QML module for D-Bus or for unix + sockets, so either would force a C++ plugin and the end of installing with + `kpackagetool6` alone. The state also survives a daemon restart and can be + inspected with `cat`. +- **The read goes through `Plasma5Support.DataSource` (`executable` plus + `cat`), not `XMLHttpRequest`.** Verified in the field: Qt 6 answers + *"XMLHttpRequest: Using GET on a local file is disabled by default"* and only + unlocks it with `QML_XHR_ALLOW_FILE_READ=1` in plasmashell's environment — + that is, by loosening that protection for all of the panel's QML and reaching + into the user's session. Forking `cat` every fifteen seconds costs less than + either. +- **Quota polling every 5 minutes, adaptive.** Server-side, `utilization` moves + about every 5 minutes: asking more often repeats the same answer. It slows to + 15–30 minutes when local transcripts show no recent activity, and returns to + 5 minutes as soon as work resumes. +- **Transcripts read by `mtime`, without a cache.** A file untouched for 5 hours + cannot contain lines from the last 5 hours: the filter is exact, not + heuristic. Measured on a real 146 MB tree: 23 ms for the 5-hour window (4 + files), 366 ms for 7 days (66 files), against 850 ms to re-read everything. + An offset cache would save ~340 ms every 5 minutes in exchange for the most + delicate state in the project (truncation, reused inodes, lines spanning two + reads): not worth it. +- **The daemon as a resident systemd user unit.** Adaptive backoff and the + OAuth token live in the process rather than smeared across a timer's + configuration; on top of that come automatic restarts and logs in + `journalctl`. Its lifecycle stays independent of `plasmashell`, which + restarts often. The user enables the unit by hand: dipstick does not touch + the desktop session. +- **In the panel: the percentage that binds first, with a bar of the same + figure.** The compact representation is ~34px tall: a number reads out of the + corner of your eye, two graphics do not. It shows the higher of the 5-hour + and weekly windows, that is, the constraint hit first. *Revised in flight:* + the bar used to show the **second** window, but a number and a bar side by + side reporting different values read as incoherent. They are now the same + figure in two shapes, and the second window lives in the tooltip and the + popup. +- **Distribution: clone it and build it.** `make install` compiles the daemon + into `~/.local/bin`, puts the unit in `~/.config/systemd/user` and registers + the plasmoid with `kpackagetool6`: it is the only form that installs both + halves together. **No KDE Store**: it distributes the QML package only, and a + widget without its daemon is broken by construction. **No prebuilt + binaries**: an RPM built here is only valid for the same architecture and the + same Fedora release, and publishing it would imply otherwise. The spec exists + (`make rpm`) for whoever wants to build the package, not to distribute it. +- **Read `limits[]`, not `five_hour`/`seven_day`.** Verified in the field: + `seven_day_opus` and `seven_day_sonnet` come back `null`, and the per-model + breakdown exists only inside `limits[]`, with the model name chosen by the + server. The top-level fields remain as a fallback. `limits[]` also carries + `severity`, meaning Anthropic already decides the thresholds and we do not + have to invent any. +- **OAuth scope reduced to `user:profile user:inference`.** The prior art also + asks for `org:create_api_key`, which exists to create API keys: dipstick only + reads. Verified that the quota endpoint answers just the same. +- **A hybrid with degradation**, not a single source: the quota is precise but + rests on an undocumented endpoint, the transcripts are reliable but know + nothing about limits. + +## Data source contract + +The quota endpoint is **undocumented** — it can change without notice. The +shape below was **verified in the field on 2026-08-27**, not inferred: fixture +in `internal/anthropic/testdata/usage.json`. ``` GET https://api.anthropic.com/api/oauth/usage Authorization: Bearer anthropic-beta: oauth-2025-04-20 anthropic-version: 2023-06-01 - User-Agent: claude-cli/ (external, cli) + User-Agent: claude-cli/ (external, cli) ``` -La fonte da leggere e' **`limits[]`**, non i campi di primo livello: +The source to read is **`limits[]`**, not the top-level fields: ``` limits: [ { kind: "session" | "weekly_all" | "weekly_scoped", group: "session" | "weekly", - percent: intero 0-100, - severity: "normal" | ..., <- soglie gia' decise dal server + percent: integer 0-100, + severity: "normal" | ..., <- thresholds already set by the server resets_at: RFC3339 | null, - is_active: bool, <- quale finestra sta accumulando + is_active: bool, <- which window is accumulating scope: null | { model: { display_name } } } ] ``` -`five_hour` e `seven_day` esistono ancora e restano allineati a `limits[]` -(`utilization` e' un **float**, es. `30.0`, mentre `limits[].percent` e' intero): -si usano solo come fallback se `limits` manca o e' vuoto. +`five_hour` and `seven_day` still exist and stay consistent with `limits[]` +(`utilization` is a **float**, e.g. `30.0`, while `limits[].percent` is an +integer): they are used only as a fallback when `limits` is missing or empty. -`seven_day_opus` e `seven_day_sonnet` **arrivano `null`**: il breakdown per modello -vive solo in `limits[]` con `kind: weekly_scoped`, e `scope.model.display_name` porta -il nome che decide il server (sull'account di test: `Fable`). Va reso come arriva. +`seven_day_opus` and `seven_day_sonnet` **come back `null`**: the per-model +breakdown lives only in `limits[]` with `kind: weekly_scoped`, and +`scope.model.display_name` carries the name the server picks (on the test +account: `Fable`). Render it as it arrives. -La risposta contiene anche campi con nomi in codice (`tangelo`, `iguana_necktie`, -`nimbus_quill`, `seven_day_cowork`, `omelette_promotional`, ...), quasi tutti `null`: -feature non annunciate. **Ogni campo non riconosciuto si ignora in silenzio.** +The response also contains code-named fields (`tangelo`, `iguana_necktie`, +`nimbus_quill`, `seven_day_cowork`, `omelette_promotional`, ...), almost all +`null`: unannounced features. **Every unrecognised field is ignored silently.** -`extra_usage` e `spend` descrivono i crediti oltre il piano. Fuori scope, ma con -`extra_usage.is_enabled: true` il 100% smette di essere un muro: il widget lo -mostrerebbe come tale a torto. +`extra_usage` and `spend` describe credits beyond the plan. Out of scope, but +with `extra_usage.is_enabled: true` reaching 100% stops being a wall, and the +widget would be wrong to show it as one. -`GET /api/oauth/profile` (stessi header) -> `account.email`, `account.display_name`, -`account.has_claude_max` / `has_claude_pro`. +`GET /api/oauth/profile` (same headers) gives `account.email`, +`account.display_name`, `account.has_claude_max` / `has_claude_pro`, and +`organization.rate_limit_tier`. -Fallback locale: `~/.claude/projects/**/*.jsonl`, un JSON per riga, campo `usage` per -messaggio con `input_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`, -`output_tokens`, `output_tokens_details.thinking_tokens`. +Local fallback: `~/.claude/projects/**/*.jsonl`, one JSON object per line, with +a `usage` field per message carrying `input_tokens`, +`cache_creation_input_tokens`, `cache_read_input_tokens` and `output_tokens`. -## Contratto fra demone e plasmoide +## Contract between daemon and plasmoid -`$XDG_CONFIG_HOME/dipstick/state.json` (0644), riscritto in modo atomico -(write su temporaneo + rename): il plasmoide rilegge senza coordinamento, quindi -deve vedere sempre o il vecchio o il nuovo, mai meta' JSON. +`$XDG_CONFIG_HOME/dipstick/state.json` (0644), rewritten atomically (write to a +temporary file plus rename): the plasmoid re-reads without coordination, so it +must always see either the old file or the new one, never half a JSON document. ``` -schema: intero, versionato. Il plasmoide rifiuta uno schema che non conosce - invece di disegnare numeri a caso. +schema: integer, versioned. The plasmoid refuses a schema it does not know + rather than draw arbitrary numbers. quota: { status: "fresh" | "stale" | "unavailable", - fetched_at, <- ultima lettura RIUSCITA, non questo giro - error, needs_auth } <- "rifai il login" vs "riprova piu' tardi" -compact: null | { primary, secondary } <- gia' scelto dal demone -windows: [ finestra, ... ] <- dettaglio per il popup + fetched_at, <- the last SUCCESSFUL read, not this round + error, needs_auth } <- "log in again" vs "try later" +compact: null | { primary, secondary } <- already chosen by the daemon +windows: [ window, ... ] <- detail for the popup extra_usage_enabled: bool -account: null | { email, name, plan } <- da /api/oauth/profile +account: null | { email, name, plan } <- from /api/oauth/profile local: null | { scanned_at, last_activity, messages, session_tokens, today_tokens, week_tokens, month_tokens, - models: [ {id, tokens, messages} ], <- 30 giorni - daily: [ {date, tokens, models{id:n}} ] } <- 30 giorni, continua + models: [ {id, tokens, messages} ], <- 30 days + daily: [ {date, tokens, models{id:n}} ] } <- 30 days, continuous -finestra: { kind, group, percent, severity, resets_at, is_active, model? } +window: { kind, group, percent, severity, resets_at, is_active, model? } ``` -Due regole, entrambe per tenere il plasmoide stupido: +Two rules, both there to keep the plasmoid stupid: -`account.plan` ("Max 20x") viene da `organization.rate_limit_tier`, che distingue -5x da 20x dove `has_claude_max` no. E' un nome di prodotto, non testo tradotto: -per questo puo' stare nel file. `local.models`, `local.daily` e `month_tokens` coprono gli stessi 30 giorni di -**calendario**, cosi' legenda, grafico e totale coincidono davvero - un -confine scorrevole per i totali contro uno di calendario per il grafico -lasciava una fetta di messaggi contati ma mai disegnati. `daily` e' **continuo**: i giorni senza -attivita' restano nella serie a zero, perche' saltarli comprimerebbe il tempo e -farebbe sembrare regolare un lavoro a singhiozzo. La scansione a 30 giorni costa -~900 ms sull'albero reale (197 file), ogni 5 minuti. +- **No interface strings.** Only semantic `kind` values and the model name as + the server sends it. Localisation belongs to the plasmoid, which has `i18n()` + and follows the session language; the daemon runs with no locale context and + would have to be restarted to change it. +- **The daemon makes the decisions.** `compact.primary` is already the + constraint hit first — the higher of session and week, with the week winning + ties because the session refills within hours and the week does not. Per-model + windows never enter the panel: a high scoped window does not block, you switch + model. QML only draws. -- **Nessuna stringa di interfaccia.** Solo `kind` semantici e il nome del modello - come lo manda il server. La localizzazione e' del plasmoide, che ha `i18n()` e - segue la lingua della sessione; il demone gira senza contesto di locale e - andrebbe riavviato per cambiarla. -- **Le decisioni le prende il demone.** `compact.primary` e' gia' il vincolo che si - tocca per primo - la piu' alta fra sessione e settimana, con la settimana che - vince a parita' perche' la sessione si ricarica in poche ore e lei no. Le - finestre per modello non entrano mai nel panel: una scoped alta non blocca, - si cambia modello. QML disegna e basta. +`compact: null` means no data: the plasmoid shows a dash, not a zero. -`compact: null` significa nessun dato: il plasmoide mostra un trattino, non uno zero. +`account.plan` ("Max 20x") comes from `organization.rate_limit_tier`, which +tells 5x from 20x where `has_claude_max` does not. It is a product name, not +translated text, which is why it can live in the file. +`local.models`, `local.daily` and `month_tokens` all cover the same 30 +**calendar** days, so the legend, the chart and the total genuinely agree — a +rolling boundary for the totals against a calendar boundary for the chart left +a sliver of messages counted but never drawn. `daily` is **continuous**: days +without activity stay in the series at zero, because dropping them would +compress time and make intermittent work look steady. The 30-day scan costs +~900 ms on a real tree (197 files), every 5 minutes. -## Assunzioni +## Assumptions -- L'abbonamento e' Claude Max (`rateLimitTier: default_claude_max_20x`). Il comportamento - su Pro non e' stato verificato. +- The subscription is Claude Max (`rateLimitTier: default_claude_max_20x`). + Behaviour on Pro has not been verified. ## Prior art [renatoaug/claude-usage-monitor](https://github.com/renatoaug/claude-usage-monitor) -("Clauddy") risolve lo stesso problema su macOS ed e' la fonte del contratto qui sopra. -Architettura dati identica (OAuth per le percentuali, jsonl locali per i token); la forma -**non** e' trasferibile: e' un desktop pet Electron in finestra flottante, e su Wayland un -client non puo' posizionarsi liberamente ne' imporsi always-on-top. +("Clauddy") solves the same problem on macOS and is the source of the contract +above. The data architecture is identical (OAuth for the percentages, local +jsonl for the tokens); the *form* is **not** transferable: it is an Electron +desktop pet in a floating window, and on Wayland a client can neither position +itself freely nor force itself always-on-top. -## Domande aperte +## Building, installing, testing -Nessuna: chiuse tutte al kickoff, vedi "Decisioni gia' prese". - -## Come si builda, si installa, si testa - -Si clona e si compila: non ci sono pacchetti precompilati. +Clone it and compile it: there are no prebuilt packages. ``` -git clone && cd dipstick +git clone && cd dipstick make install ``` -Gli altri comandi: +The other targets: ``` -make # compila il demone e i cataloghi di traduzione -make test # test unitari, nessuna rete -make vet # go vet + gofmt -make extract # riestrae le stringhe traducibili dal QML -make install # demone in ~/.local/bin, unit in ~/.config/systemd/user, - # plasmoide via kpackagetool6 +make # build the daemon and the translation catalogues +make test # unit tests, no network +make vet # go vet, and fail on anything not gofmt-ed +make extract # re-extract the translatable strings from the QML +make install # daemon into ~/.local/bin, unit into ~/.config/systemd/user, + # plasmoid through kpackagetool6 ``` -Per un pacchetto, invece della home: +For a package, instead of the home directory: ``` -make install DESTDIR=/percorso/buildroot PREFIX=/usr SYSTEM=1 +make install DESTDIR=/path/to/buildroot PREFIX=/usr SYSTEM=1 ``` -`SYSTEM=1` non tocca `systemd` ne' `kpackagetool6`: in un buildroot non avrebbe -senso, e ci pensano gli scriptlet del pacchetto. +`SYSTEM=1` touches neither `systemd` nor `kpackagetool6`: inside a buildroot +that would make no sense, and the package scriptlets handle it. -`make rpm` costruisce il pacchetto (richiede `rpm-build`). Il tarball viene da -`HEAD`, non dall'albero di lavoro: quel che non e' committato non finisce nel -pacchetto. Se Go e' installato fuori da RPM - mise, tarball ufficiale - il -`BuildRequires` non si risolve e serve: +`make rpm` builds the package (it needs `rpm-build`). The tarball comes from +`HEAD`, not the working tree: whatever is uncommitted does not end up in the +package. If Go is installed outside RPM — mise, the official tarball — the +`BuildRequires` will not resolve and you need: ``` make rpm RPMBUILD_FLAGS=--nodeps ``` -Verificato su Fedora 44 aarch64. Mai passato per COPR, che builda anche per -altre architetture e versioni. +Verified on Fedora 44 aarch64. Never been through COPR, which also builds for +other architectures and releases. -Poi, e questi passi restano all'utente perche' dipstick non tocca la sessione: +Then these steps, which stay with the user because dipstick does not touch the +session: ``` -dipstick auth # login OAuth (apre il browser) -systemctl --user enable --now dipstick # avvia il demone +dipstick auth # OAuth login (opens the browser) +systemctl --user enable --now dipstick # start the daemon ``` -e infine "Aggiungi Widget" -> Dipstick nel panel. +and finally "Add Widgets" → Dipstick in the panel. -Comandi utili per diagnosticare: +Useful for diagnosis: ``` -dipstick usage # JSON grezzo dell'endpoint, senza interpretazione -dipstick state # lo stato che leggerebbe il plasmoide, senza scriverlo +dipstick usage # the endpoint's raw JSON, uninterpreted +dipstick state # the state the plasmoid would read, without writing it journalctl --user -u dipstick -f ``` -Per lavorare sul plasmoide senza il panel: `plasmawindowed org.kde.plasma.dipstick`. -Gli errori QML finiscono nel journal dell'utente, non sul terminale. +To work on the plasmoid without the panel: +`plasmawindowed org.kde.plasma.dipstick`. QML errors land in the user journal, +not on the terminal. Note that `plasmashell` does **not** re-read the QML after +an upgrade — it needs +`systemctl --user restart plasma-plasmashell.service` — while `plasmawindowed` +always sees the latest build. -Il codice e' interamente in inglese - identificatori, commenti, log, stringhe -sorgente dell'interfaccia. Italiano solo dove e' traduzione: questo documento, -`translations/it.po` e le descrizioni localizzate nel pacchetto. - -## Layout del codice +## Code layout ``` -cmd/dipstick/ CLI e entry point del demone -internal/anthropic/ OAuth PKCE, endpoint quota/profilo, normalizzazione -internal/transcript/ lettura (SOLA LETTURA) dei transcript locali -internal/state/ lo schema di state.json e la scrittura atomica -internal/daemon/ il loop: cadenza adattiva, backoff, degrado -plasmoid/ il pacchetto QML -translations/ .pot, cataloghi .po e lo script di estrazione -packaging/ systemd user unit (template) e spec RPM +cmd/dipstick/ the CLI and the daemon's entry point +internal/anthropic/ OAuth PKCE, quota/profile endpoints, normalisation +internal/transcript/ READ-ONLY reading of the local transcripts +internal/state/ the state.json schema and the atomic write +internal/daemon/ the loop: adaptive cadence, backoff, degradation +plasmoid/ the QML package +translations/ .pot, .po catalogues and the extraction script +packaging/ systemd user unit (template) and the RPM spec ``` -## Stato +Everything is in English — identifiers, comments, logs, interface source +strings, documentation. Italian survives only where it *is* a translation: +`translations/it.po` and the localised package descriptions. + +## Status -Funzionante da capo a fondo: demone, plasmoide, degrado e installazione. -Il contratto dell'endpoint e' verificato contro l'endpoint reale, non dedotto. +Working end to end: daemon, plasmoid, degradation and installation. The +endpoint contract is verified against the real endpoint, not inferred. -Le stringhe del plasmoide sono in inglese e passano da `i18n()`; esiste il -catalogo italiano (`translations/it.po`), compilato da `make` e installato sia -dentro il pacchetto del plasmoide sia nel percorso standard delle locale. +The plasmoid's strings go through `i18n()`; an Italian catalogue exists +(`translations/it.po`), compiled by `make` and installed inside the plasmoid +package. -Lo spec RPM e' stato compilato e il pacchetto ispezionato: contiene binario, -unit, plasmoide, catalogo e licenza, e la unit punta a `/usr/bin/dipstick`. -Non e' mai passato per COPR. +The RPM spec has been built and the package inspected: it contains the binary, +the unit, the plasmoid, the catalogue and the licence, and the unit points at +`/usr/bin/dipstick`. It has never been through COPR. -- knotmirror 0.0.1