From e0dff77159c59a3ccb92e35b522ecdcbf79b686a Mon Sep 17 00:00:00 2001 From: Claudio Date: Thu, 27 Aug 2026 16:26:33 +0200 Subject: [PATCH] review: correzioni, e tutto il codice passa all'inglese Otto rilievi da una review adversariale, tutti sistemati. Un 401 non portava mai a "rifai il login": refresh() mappava su ErrNoAuth solo 400 e 403, e un token invalidato dal server prima della scadenza locale non faceva mai scattare un rinnovo. Ora 401 vale come grant morto, e un 401 su una lettura forza un refresh e un solo ritentativo prima di dichiarare il logout. auth.json era condiviso fra demone e CLI senza lock: due refresh concorrenti potevano bruciare il refresh token. E' lo stesso rischio per cui il progetto non tocca le credenziali di Claude Code, inflitto a se' stesso. Ora flock attorno al ciclo carica-rinnova-salva, e file temporanei con nome unico. I totali usavano una finestra scorrevole mentre il grafico usa giorni di calendario: una fetta di messaggi finiva nel totale del mese e nella legenda ma in nessuna colonna disegnata. Ora il confine e' lo stesso, e un test lo blinda: sui dati reali mese, grafico e legenda coincidono. Lo scanner non controllava sc.Err(): una riga oltre 16 MB troncava la scansione in silenzio, dando un numero piu' basso senza dirlo. Ora l'errore risale e i risultati parziali restano usabili. I duplicati non sono copie identiche ma istantanee progressive dello stesso messaggio: si tiene la piu' grande invece della prima vista. Il plasmoide ricostruiva tutti i delegate ogni 15 secondi anche a file invariato. Ora confronta il payload grezzo prima di riassegnare lo stato. Da non autenticato il demone chiedeva il profilo a ogni giro, loggando un warning ogni cinque minuti per sempre. oauth.go non aveva un solo test, ed era dove stava il bug piu' grave: ora ne ha diciassette, contro un server locale. Aggiunti anche i test sulla scrittura atomica dello stato e sul confine mese/grafico. Da 28 a 61 casi. Infine `make vet` fallisce davvero su un file non formattato invece di limitarsi a elencarlo, e la unit ha il Wants= che mancava accanto ad After=. Tutto il codice - identificatori, commenti, errori, log, output della CLI - e' ora in inglese. Restano in italiano solo le traduzioni: README, CLAUDE.md, it.po e le descrizioni localizzate nello spec. --- CLAUDE.md | 20 + Makefile | 57 +-- README.md | 10 +- cmd/dipstick/main.go | 106 +++-- internal/anthropic/oauth.go | 250 ++++++++---- internal/anthropic/oauth_test.go | 380 ++++++++++++++++++ internal/anthropic/profile.go | 26 +- internal/anthropic/profile_test.go | 14 +- internal/anthropic/usage.go | 60 +-- internal/anthropic/usage_test.go | 32 +- internal/daemon/daemon.go | 98 +++-- internal/daemon/daemon_test.go | 95 +++-- internal/state/state.go | 286 ++++++------- internal/state/state_test.go | 112 +++++- internal/transcript/transcript.go | 348 +++++++++------- internal/transcript/transcript_test.go | 348 +++++++++------- packaging/dipstick.service.in | 12 +- packaging/dipstick.spec | 40 +- .../contents/ui/CompactRepresentation.qml | 42 +- plasmoid/contents/ui/DailyChart.qml | 39 +- plasmoid/contents/ui/FullRepresentation.qml | 102 ++--- plasmoid/contents/ui/ModelBreakdown.qml | 29 +- plasmoid/contents/ui/QuotaRow.qml | 17 +- plasmoid/contents/ui/StateSource.qml | 70 ++-- plasmoid/contents/ui/format.js | 78 ++-- plasmoid/contents/ui/main.qml | 26 +- translations/extract.sh | 12 +- 27 files changed, 1747 insertions(+), 962 deletions(-) create mode 100644 internal/anthropic/oauth_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 2f3f890..837aabb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,6 +29,15 @@ Scope, non-goals, contratto delle fonti dati e domande aperte: `README.md`. - L'endpoint della quota **non e' documentato pubblicamente**: trattalo come instabile. Ogni percorso che lo usa deve avere un fallback sui dati locali. +## Lingua + +**Tutto il codice e' in inglese**: identificatori, commenti, messaggi di errore, +log, output della CLI e stringhe sorgente dell'interfaccia. Nessuna eccezione. + +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. + ## Come si lavora Build, installazione, layout del codice e comandi di diagnosi: `README.md`. @@ -54,6 +63,17 @@ sul terminale. 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 diff --git a/Makefile b/Makefile index d86d90a..51669be 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,12 @@ -# dipstick — plasmoide + demone. Le due meta' si installano insieme: un widget -# senza il suo demone mostra un trattino, un demone senza widget non si vede. +# dipstick — plasmoid plus daemon. The two halves install together: a widget +# without its daemon shows a dash, a daemon without its widget is invisible. # -# Due modi di installare: -# make install nella home dell'utente (default) -# make install DESTDIR=... PREFIX=/usr SYSTEM=1 per un pacchetto +# Two ways to install: +# make install into the user's home (default) +# make install DESTDIR=... PREFIX=/usr SYSTEM=1 for a package # -# Con SYSTEM=1 non si tocca systemd ne' kpackagetool6: in un buildroot non -# avrebbe senso, e ci pensa lo scriptlet del pacchetto. +# With SYSTEM=1 neither systemd nor kpackagetool6 is touched: inside a +# buildroot that would make no sense, and the package scriptlets handle it. PREFIX ?= $(HOME)/.local DESTDIR ?= @@ -29,18 +29,19 @@ VERSION ?= 0.1.0 APPLET_ID := org.kde.plasma.dipstick CATALOG := plasma_applet_$(APPLET_ID) -# GO_LDFLAGS e non LDFLAGS: quest'ultima e' una variabile d'ambiente standard -# che rpmbuild valorizza con i flag del linker C, e con `?=` l'ambiente vince. -# Go riceveva flag che non capisce e la build falliva solo dentro rpmbuild. -# Passa --nodeps qui se Go non e' installato come pacchetto RPM (per esempio -# via mise): il BuildRequires resta corretto per una build vera in COPR. +# GO_LDFLAGS and not LDFLAGS: the latter is a standard environment variable +# that rpmbuild fills with C linker flags, and with `?=` the environment wins. +# Go was handed flags it does not understand, and the build failed only inside +# rpmbuild. +# Pass --nodeps here if Go is not installed as an RPM (via mise, say): the +# BuildRequires stays correct for a real build. RPMBUILD_FLAGS ?= GOFLAGS ?= -trimpath GO_LDFLAGS ?= -s -w -# I cataloghi compilati vivono dentro il pacchetto del plasmoide: e' li' che -# Plasma li cerca per un applet di terze parti. +# Compiled catalogues live inside the plasmoid package: that is where Plasma +# looks for them for a third-party applet. PO := $(wildcard translations/*.po) MO := $(patsubst translations/%.po,plasmoid/contents/locale/%/LC_MESSAGES/$(CATALOG).mo,$(PO)) @@ -55,11 +56,16 @@ build: test: go test ./... +# gofmt -l only lists; the test turns an unformatted file into a failure, so +# `make vet` is usable as a gate rather than something to read by eye. vet: go vet ./... - gofmt -l cmd internal + @unformatted=$$(gofmt -l cmd internal); \ + if [ -n "$$unformatted" ]; then \ + echo "not gofmt-ed:"; echo "$$unformatted"; exit 1; \ + fi -# Rigenera il .pot dalle sorgenti e riallinea i cataloghi. +# Regenerate the .pot from the sources and re-align the catalogues. extract: ./translations/extract.sh @@ -72,12 +78,12 @@ plasmoid/contents/locale/%/LC_MESSAGES/$(CATALOG).mo: translations/%.po install: install-daemon install-plasmoid ifeq ($(SYSTEM),) @echo - @echo "Installato. Restano due passi, che tocca a te:" + @echo "Installed. Two steps are left, and they are yours to take:" @echo - @echo " 1. dipstick auth (login OAuth)" + @echo " 1. dipstick auth (OAuth login)" @echo " 2. systemctl --user enable --now dipstick" @echo - @echo "Poi aggiungi 'Dipstick' al panel dal menu Aggiungi Widget." + @echo "Then add 'Dipstick' to the panel from the Add Widgets menu." endif install-daemon: build @@ -101,8 +107,9 @@ else find $(DESTDIR)$(PLASMOIDIR) -type d -exec chmod 755 {} + endif -# Non tocca ne' il token ne' lo stato: sono dati dell'utente, e disinstallare -# non e' il momento di buttarli via. Si rimuovono a mano da ~/.config/dipstick. +# Touches neither the token nor the state: those are the user's data, and +# uninstalling is not the moment to throw them away. Remove them by hand from +# ~/.config/dipstick. uninstall: -systemctl --user disable --now dipstick -rm -f $(BINDIR)/dipstick $(UNITDIR)/dipstick.service @@ -115,14 +122,14 @@ enable: disable: systemctl --user disable --now dipstick -# Tarball del sorgente, come se lo aspetta lo spec. Parte da HEAD, non -# dall'albero di lavoro: un pacchetto deve venire da qualcosa di committato. +# Source tarball, as the spec expects it. Taken from HEAD, not the working +# tree: a package must come from something committed. dist: git archive --format=tar.gz --prefix=$(NAME)-$(VERSION)/ \ -o $(NAME)-$(VERSION).tar.gz HEAD -# Compila l'RPM in locale. Richiede rpm-build, che non e' una dipendenza del -# progetto: serve solo a chi vuole il pacchetto. +# Build the RPM locally. Requires rpm-build, which is not a project +# dependency: it only matters to whoever wants the package. rpm: dist rpmbuild -bb $(RPMBUILD_FLAGS) --define "_sourcedir $(CURDIR)" \ packaging/dipstick.spec diff --git a/README.md b/README.md index cd4f74c..cf87658 100644 --- a/README.md +++ b/README.md @@ -172,8 +172,10 @@ Due regole, entrambe per tenere il plasmoide stupido: `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` e `local.daily` coprono entrambi 30 giorni, cosi' legenda e -grafico parlano dello stesso periodo. `daily` e' **continuo**: i giorni senza +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. @@ -269,6 +271,10 @@ 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. +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 ``` diff --git a/cmd/dipstick/main.go b/cmd/dipstick/main.go index 7dcd07b..a7aaac1 100644 --- a/cmd/dipstick/main.go +++ b/cmd/dipstick/main.go @@ -1,10 +1,9 @@ -// dipstick — quota Claude Max nel panel di Plasma. +// dipstick — Claude Max quota in the Plasma panel. // -// `run` e' il demone, che tiene aggiornato lo stato letto dal plasmoide. Gli -// altri comandi servono a configurarlo e a diagnosticarlo: `usage` e `profile` -// stampano il JSON grezzo, senza interpretarlo, perche' l'endpoint non e' -// documentato e la prima cosa da guardare quando qualcosa cambia e' cosa manda -// davvero. +// `run` is the daemon, which keeps the state the plasmoid reads up to date. +// The other commands configure and diagnose it: `usage` and `profile` print +// the raw JSON, uninterpreted, because the endpoint is undocumented and the +// first thing worth seeing when something changes is what it actually sends. package main import ( @@ -38,7 +37,7 @@ func main() { func run(args []string) error { if len(args) == 0 { usage() - return errors.New("nessun comando") + return errors.New("no command given") } switch args[0] { case "auth": @@ -55,37 +54,37 @@ func run(args []string) error { if err := anthropic.Logout(); err != nil { return err } - fmt.Println("token locale rimosso.") + fmt.Println("local token removed.") return nil case "-h", "--help", "help": usage() return nil default: usage() - return fmt.Errorf("comando sconosciuto: %s", args[0]) + return fmt.Errorf("unknown command: %s", args[0]) } } func usage() { - path, _ := anthropic.TokenPath() + tokenPath, _ := anthropic.TokenPath() statePath, _ := state.Path() - fmt.Fprintf(os.Stderr, `dipstick — quota Claude Max nel panel di Plasma - - dipstick auth [--scope "..."] login OAuth PKCE (apre il browser) - dipstick usage stampa il JSON grezzo della quota - dipstick profile stampa il JSON grezzo del profilo - dipstick state [--write] genera lo stato che leggera' il plasmoide - dipstick run il demone: tiene aggiornato lo stato - dipstick logout rimuove il token locale - -Il token vive in %s (0600). -Lo stato in %s (0644). -~/.claude/ non viene mai toccato. -`, path, statePath) + fmt.Fprintf(os.Stderr, `dipstick — Claude Max quota in the Plasma panel + + dipstick auth [--scope "..."] OAuth PKCE login (opens the browser) + dipstick usage print the raw quota JSON + dipstick profile print the raw profile JSON + dipstick state [--write] produce the state the plasmoid will read + dipstick run the daemon: keeps the state up to date + dipstick logout remove the local token + +The token lives in %s (0600). +The state lives in %s (0644). +~/.claude/ is never touched. +`, tokenPath, statePath) } -// dump stampa la risposta indentata se e' JSON valido, grezza altrimenti: -// se l'endpoint smette di rispondere in JSON e' proprio quello che vogliamo vedere. +// dump prints the response indented if it is valid JSON, raw otherwise: if the +// endpoint stops answering in JSON, that is exactly what we want to see. func dump(fetch func() ([]byte, error)) error { body, err := fetch() if err != nil { @@ -114,33 +113,33 @@ func cmdAuth(args []string) error { return err } - fmt.Println("Apro il browser per il login. Scope richiesto:", scope) + fmt.Println("Opening the browser to sign in. Requested scope:", scope) fmt.Println() fmt.Println(pending.URL) fmt.Println() - // Se xdg-open non c'e' o fallisce non e' un errore: l'URL e' gia' a video - // e l'utente puo' incollarlo a mano. + // If xdg-open is missing or fails it is not an error: the URL is already + // on screen and the user can open it by hand. if err := exec.Command("xdg-open", pending.URL).Start(); err != nil { - fmt.Println("(non sono riuscito ad aprire il browser: apri l'URL qui sopra a mano)") + fmt.Println("(could not open a browser: open the URL above manually)") } - fmt.Print("Dopo aver autorizzato, incolla qui il codice mostrato (forma \"code#state\"): ") + fmt.Print("After authorising, paste the code shown here (in the form \"code#state\"): ") line, err := bufio.NewReader(os.Stdin).ReadString('\n') if err != nil && strings.TrimSpace(line) == "" { - return fmt.Errorf("lettura del codice fallita: %w", err) + return fmt.Errorf("could not read the code: %w", err) } if err := pending.Complete(line); err != nil { return err } path, _ := anthropic.TokenPath() - fmt.Printf("\nAutenticato. Token salvato in %s\nProva con: dipstick usage\n", path) + fmt.Printf("\nAuthenticated. Token saved in %s\nTry it with: dipstick usage\n", path) return nil } -// cmdState produce lo stato una volta sola. Non e' ancora il demone: nessun -// loop, nessuna cadenza. Serve ad avere il file vero da guardare, e a poterci -// sviluppare contro il plasmoide senza un demone acceso. +// cmdState produces the state once. It is not the daemon: no loop, no cadence. +// It exists to have the real file to look at, and to develop the plasmoid +// against without a daemon running. func cmdState(args []string) error { write := false for _, a := range args { @@ -153,22 +152,22 @@ func cmdState(args []string) error { root, _ := transcript.Root() activity, err := transcript.Scan(root, now) if err != nil { - fmt.Fprintln(os.Stderr, "dipstick: scansione dei transcript fallita:", err) + fmt.Fprintln(os.Stderr, "dipstick: transcript scan incomplete:", err) } var st *state.State - if u, err := anthropic.FetchUsage(); err != nil { - // Un fallimento non e' motivo per non scrivere: il plasmoide deve - // poter distinguere "quota non disponibile" da "demone morto", e - // l'unico modo e' che qualcuno glielo dica nel file. - fmt.Fprintln(os.Stderr, "dipstick: quota non disponibile:", err) - st = state.Unavailable(err, errors.Is(err, anthropic.ErrNoAuth), now) + if u, uerr := anthropic.FetchUsage(); uerr != nil { + // A failure is no reason not to write: the plasmoid must be able to + // tell "quota unavailable" from "daemon dead", and the only way is for + // someone to say so in the file. + fmt.Fprintln(os.Stderr, "dipstick: quota unavailable:", uerr) + st = state.Unavailable(uerr, errors.Is(uerr, anthropic.ErrNoAuth), now) } else { st = state.FromUsage(u, now) if p, perr := anthropic.FetchProfile(); perr == nil { st.WithAccount(p) } else { - fmt.Fprintln(os.Stderr, "dipstick: profilo non disponibile:", perr) + fmt.Fprintln(os.Stderr, "dipstick: profile unavailable:", perr) } } st.WithLocal(activity) @@ -184,20 +183,19 @@ func cmdState(args []string) error { return err } path, _ := state.Path() - fmt.Fprintln(os.Stderr, "scritto in", path) + fmt.Fprintln(os.Stderr, "written to", path) } return nil } -// cmdRun e' il demone vero: gira sotto systemd finche' non gli si dice di -// smettere. +// cmdRun is the actual daemon: it runs under systemd until told to stop. func cmdRun() error { level := slog.LevelInfo if os.Getenv("DIPSTICK_DEBUG") != "" { level = slog.LevelDebug } - // Niente timestamp: sotto systemd li mette gia' il journal, e ripeterli - // rende i log solo piu' larghi. + // No timestamps: under systemd the journal already adds them, and + // repeating them only makes the logs wider. log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: level, ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { @@ -210,22 +208,22 @@ func cmdRun() error { root, err := transcript.Root() if err != nil { - // Senza transcript si perde il degrado locale, non il servizio. - log.Warn("cartella dei transcript non trovata", "err", err) + // Without transcripts we lose the local fallback, not the service. + log.Warn("transcript directory not found", "err", err) root = "" } - // SIGTERM e' come systemd ferma il servizio: va onorato subito, non al - // prossimo giro - che puo' essere fra mezz\'ora. + // SIGTERM is how systemd stops the service: honour it immediately, not on + // the next round, which can be half an hour away. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) defer stop() path, _ := state.Path() - log.Info("avvio", "stato", path, "transcript", root) + log.Info("starting", "state", path, "transcripts", root) err = daemon.New(daemon.DefaultConfig(), root, log).Run(ctx) if errors.Is(err, context.Canceled) { - log.Info("arresto") + log.Info("stopping") return nil } return err diff --git a/internal/anthropic/oauth.go b/internal/anthropic/oauth.go index 182eeb7..1f82f53 100644 --- a/internal/anthropic/oauth.go +++ b/internal/anthropic/oauth.go @@ -1,10 +1,10 @@ -// Package anthropic parla con gli endpoint OAuth di Anthropic: il flusso PKCE -// per ottenere un token, e le due letture (usage, profile) su cui poggia dipstick. +// Package anthropic talks to Anthropic's OAuth endpoints: the PKCE flow that +// obtains a token, and the two reads dipstick relies on (usage, profile). // -// Il token vive esclusivamente nella cartella di configurazione di dipstick. -// ~/.claude/.credentials.json non viene mai letto ne' scritto: due processi che -// fanno refresh dello stesso token si invalidano a vicenda, e far cadere la -// sessione di Claude Code non vale il login risparmiato. +// The token lives exclusively in dipstick's own configuration directory. +// ~/.claude/.credentials.json is never read nor written: two processes +// refreshing the same token can invalidate each other, and dropping the user's +// Claude Code session is not worth the saved login. package anthropic import ( @@ -20,36 +20,43 @@ import ( "os" "path/filepath" "strings" + "syscall" "time" ) -// Costanti del client pubblico di Claude Code. Nessun secret: PKCE esiste -// proprio per questo. +// Public client constants, the same ones Claude Code uses. No secret: that is +// exactly what PKCE exists for. const ( clientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e" authorizeURL = "https://claude.ai/oauth/authorize" - tokenURL = "https://platform.claude.com/v1/oauth/token" - usageURL = "https://api.anthropic.com/api/oauth/usage" - profileURL = "https://api.anthropic.com/api/oauth/profile" - // Il redirect NON e' su localhost: la callback mostra a video una stringa - // "code#state" che l'utente incolla. Niente listener locale da aprire. + // The redirect is NOT on localhost: the callback shows a "code#state" + // string that the user pastes back. There is no local listener to open. redirectURI = "https://platform.claude.com/oauth/code/callback" userAgent = "claude-cli/2.1.181 (external, cli)" - // dipstick legge e basta, quindi non chiede org:create_api_key — che il - // prior art include ma serve a creare chiavi API, non a leggere la quota. - // Se un endpoint dovesse rifiutare questo set, DefaultScope si sovrascrive - // da riga di comando. + // dipstick only reads, so it does not ask for org:create_api_key, which + // the prior art requests but which exists to create API keys rather than + // to read a quota. Override from the command line if an endpoint ever + // refuses this set. DefaultScope = "user:profile user:inference" ) -// ErrNoAuth segnala che non c'e' un token utilizzabile: il chiamante deve -// mandare l'utente a rifare il login, non ritentare. -var ErrNoAuth = errors.New("dipstick non e' autenticato: lancia `dipstick auth`") +// The endpoints dipstick talks to. Variables rather than constants so tests +// can point them at a local server: the token exchange and the 401 handling +// are the most delicate code here and must be exercised without the network. +var ( + tokenURL = "https://platform.claude.com/v1/oauth/token" + usageURL = "https://api.anthropic.com/api/oauth/usage" + profileURL = "https://api.anthropic.com/api/oauth/profile" +) + +// ErrNoAuth means there is no usable token: the caller must send the user +// through the login flow again rather than retry. +var ErrNoAuth = errors.New("dipstick is not authenticated: run `dipstick auth`") -// Token e' quanto viene persistito su disco. +// Token is what gets persisted to disk. type Token struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token,omitempty"` @@ -58,19 +65,57 @@ type Token struct { } func (t *Token) expired() bool { - // Un minuto di margine: un token che scade fra dieci secondi e' gia' morto - // per una richiesta che deve ancora partire. + // One minute of margin: a token expiring in ten seconds is already dead + // for a request that still has to go out. return t.ExpiresAt.IsZero() || time.Until(t.ExpiresAt) < time.Minute } -// TokenPath e' dove vive il token: $XDG_CONFIG_HOME/dipstick/auth.json, -// con ~/.config come fallback. -func TokenPath() (string, error) { +func configDir() (string, error) { dir, err := os.UserConfigDir() if err != nil { return "", err } - return filepath.Join(dir, "dipstick", "auth.json"), nil + return filepath.Join(dir, "dipstick"), nil +} + +// TokenPath is where the token lives: $XDG_CONFIG_HOME/dipstick/auth.json, +// falling back to ~/.config. +func TokenPath() (string, error) { + dir, err := configDir() + if err != nil { + return "", err + } + return filepath.Join(dir, "auth.json"), nil +} + +// withTokenLock serialises the read-refresh-write cycle across processes. +// +// The daemon and the CLI share auth.json. Without a lock, two of them finding +// the token expired at the same moment would refresh concurrently, and if the +// server rotates refresh tokens one of the two would persist an already-spent +// one, forcing a logout. That is precisely the failure this project refuses to +// risk against Claude Code's own credentials, so it must not inflict it on +// itself either. +func withTokenLock(fn func() error) error { + dir, err := configDir() + if err != nil { + return err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + f, err := os.OpenFile(filepath.Join(dir, "auth.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return err + } + defer f.Close() + + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { + return fmt.Errorf("cannot lock the token: %w", err) + } + defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN) + + return fn() } func loadToken() (*Token, error) { @@ -87,7 +132,7 @@ func loadToken() (*Token, error) { } var t Token if err := json.Unmarshal(raw, &t); err != nil { - return nil, fmt.Errorf("%s illeggibile: %w", path, err) + return nil, fmt.Errorf("%s is unreadable: %w", path, err) } return &t, nil } @@ -104,16 +149,33 @@ func saveToken(t *Token) error { if err != nil { return err } - // Scrittura atomica con permessi ristretti: il file non deve mai esistere - // leggibile da altri, nemmeno per l'istante fra create e chmod. - tmp := path + ".tmp" - if err := os.WriteFile(tmp, raw, 0o600); err != nil { + + // A unique temporary name, not a fixed "auth.json.tmp": two processes + // writing the same temp file could interleave and rename a torn token. + tmp, err := os.CreateTemp(filepath.Dir(path), "auth-*.json") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + + // Restrictive permissions before any content is written, so the file is + // never readable by others, not even for the instant between create and + // chmod. + if err := tmp.Chmod(0o600); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(raw); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { return err } - return os.Rename(tmp, path) + return os.Rename(tmp.Name(), path) } -// Logout cancella il token locale. Non revoca nulla lato server. +// Logout removes the local token. It revokes nothing server-side. func Logout() error { path, err := TokenPath() if err != nil { @@ -135,8 +197,8 @@ func randB64(n int) (string, error) { return b64url(buf), nil } -// PendingAuth tiene i segreti PKCE fra l'apertura del browser e l'incollaggio -// del codice. Vive solo in memoria: se il processo muore si rifa' il giro. +// PendingAuth holds the PKCE secrets between opening the browser and pasting +// the code back. It lives in memory only: if the process dies, redo the flow. type PendingAuth struct { verifier string state string @@ -144,7 +206,7 @@ type PendingAuth struct { URL string } -// BeginAuth costruisce l'URL di autorizzazione da aprire nel browser. +// BeginAuth builds the authorization URL to open in the browser. func BeginAuth(scope string) (*PendingAuth, error) { verifier, err := randB64(32) if err != nil { @@ -174,21 +236,21 @@ func BeginAuth(scope string) (*PendingAuth, error) { }, nil } -// Complete scambia la stringa "code#state" incollata dall'utente con un token, -// e lo salva. +// Complete exchanges the "code#state" string the user pasted for a token, and +// stores it. func (p *PendingAuth) Complete(pasted string) error { pasted = strings.TrimSpace(pasted) if pasted == "" { - return errors.New("nessun codice incollato") + return errors.New("no code pasted") } code, state, ok := strings.Cut(pasted, "#") if !ok { - return errors.New(`codice malformato: atteso "code#state", incollalo per intero`) + return errors.New(`malformed code: expected "code#state", paste it whole`) } if state != p.state { - // Uno state che non torna significa che la risposta non appartiene a - // questa richiesta: si butta via, non si prova a usarla. - return errors.New("state non corrispondente: rilancia `dipstick auth`") + // A state that does not match means the response does not belong to + // this request: throw it away rather than try to use it. + return errors.New("state mismatch: run `dipstick auth` again") } body, err := postJSON(tokenURL, map[string]string{ @@ -202,11 +264,15 @@ func (p *PendingAuth) Complete(pasted string) error { if err != nil { return err } - return storeGrant(body, "", p.scope) + return withTokenLock(func() error { + return storeGrant(body, "", p.scope) + }) } -// refresh rinnova il token in atto. Distingue un grant morto (rifare il login) -// da un guasto passeggero (ritentare piu' tardi). +// refresh renews the token in place. It distinguishes a dead grant (log in +// again) from a transient failure (retry later). +// +// Must be called while holding the token lock. func refresh(t *Token) (*Token, error) { if t.RefreshToken == "" { return nil, ErrNoAuth @@ -218,7 +284,10 @@ func refresh(t *Token) (*Token, error) { }) if err != nil { var he *HTTPError - if errors.As(err, &he) && (he.Status == 400 || he.Status == 403) { + // 401 belongs here just as much as 400 and 403: a revoked grant is + // commonly reported as unauthorized, and treating it as transient + // means backing off forever while the user is never told to log in. + if errors.As(err, &he) && (he.Status == 400 || he.Status == 401 || he.Status == 403) { return nil, ErrNoAuth } return nil, err @@ -229,9 +298,9 @@ func refresh(t *Token) (*Token, error) { return loadToken() } -// storeGrant persiste una risposta del token endpoint. prevRefresh copre il -// caso in cui il rinnovo non restituisca un nuovo refresh token: quello vecchio -// resta valido e buttarlo significherebbe un logout gratuito. +// storeGrant persists a token endpoint response. prevRefresh covers the case +// where a renewal returns no new refresh token: the old one stays valid, and +// discarding it would be a free logout. func storeGrant(body []byte, prevRefresh, scope string) error { var g struct { AccessToken string `json:"access_token"` @@ -240,10 +309,10 @@ func storeGrant(body []byte, prevRefresh, scope string) error { Scope string `json:"scope"` } if err := json.Unmarshal(body, &g); err != nil { - return fmt.Errorf("risposta del token endpoint illeggibile: %w", err) + return fmt.Errorf("unreadable token endpoint response: %w", err) } if g.AccessToken == "" { - return errors.New("il token endpoint ha risposto senza access_token") + return errors.New("the token endpoint replied without an access_token") } if g.RefreshToken == "" { g.RefreshToken = prevRefresh @@ -263,22 +332,41 @@ func storeGrant(body []byte, prevRefresh, scope string) error { }) } -// AccessToken restituisce un token valido, rinnovandolo se serve. +// AccessToken returns a valid token, renewing it if needed. func AccessToken() (string, error) { - t, err := loadToken() - if err != nil { - return "", err - } - if t.expired() { - if t, err = refresh(t); err != nil { - return "", err + return tokenMaybeRefreshing(false) +} + +// forceRefresh renews the token even when it looks valid locally. It is the +// answer to a 401 from a read endpoint: the server invalidated the token +// ahead of its stated expiry, and the local clock cannot know that. +func forceRefresh() error { + _, err := tokenMaybeRefreshing(true) + return err +} + +func tokenMaybeRefreshing(force bool) (string, error) { + var token string + err := withTokenLock(func() error { + // Reload inside the lock: another process may have refreshed while we + // waited for it, in which case there is nothing left to do. + t, err := loadToken() + if err != nil { + return err } - } - return t.AccessToken, nil + if force || t.expired() { + if t, err = refresh(t); err != nil { + return err + } + } + token = t.AccessToken + return nil + }) + return token, err } -// HTTPError porta con se' lo status, perche' la reazione giusta dipende da -// quello: 401 vuol dire rifare il login, 429 e 5xx vogliono dire riprovare. +// HTTPError carries the status, because the right reaction depends on it: 401 +// means log in again, 429 and 5xx mean try later. type HTTPError struct { Status int Body string @@ -309,8 +397,32 @@ func postJSON(endpoint string, payload map[string]string) ([]byte, error) { return do(req, "token endpoint") } -// get esegue una lettura autenticata con gli header che l'endpoint si aspetta. +// get performs an authenticated read, retrying once through a forced refresh +// if the server rejects the token. func get(endpoint, what string) ([]byte, error) { + body, err := getOnce(endpoint, what) + if !isUnauthorized(err) { + return body, err + } + // The token looked valid locally but the server disagrees. Renew it and + // try once more; if it still fails, the grant is gone and the user has to + // log in, which is a different instruction than "try later". + if rerr := forceRefresh(); rerr != nil { + return nil, rerr + } + body, err = getOnce(endpoint, what) + if isUnauthorized(err) { + return nil, ErrNoAuth + } + return body, err +} + +func isUnauthorized(err error) bool { + var he *HTTPError + return errors.As(err, &he) && he.Status == http.StatusUnauthorized +} + +func getOnce(endpoint, what string) ([]byte, error) { token, err := AccessToken() if err != nil { return nil, err @@ -342,8 +454,8 @@ func do(req *http.Request, what string) ([]byte, error) { return body, nil } -// RawUsage e RawProfile restituiscono il JSON grezzo, senza interpretarlo. -// Lo scopo di questo spike e' verificare cosa l'endpoint manda davvero: dargli -// una forma qui significherebbe nascondere proprio le sorprese che cerchiamo. +// RawUsage and RawProfile return the raw JSON, uninterpreted. The endpoint is +// undocumented, so when something changes the first thing worth seeing is what +// it actually sends. func RawUsage() ([]byte, error) { return get(usageURL, "usage") } func RawProfile() ([]byte, error) { return get(profileURL, "profile") } diff --git a/internal/anthropic/oauth_test.go b/internal/anthropic/oauth_test.go new file mode 100644 index 0000000..46c7264 --- /dev/null +++ b/internal/anthropic/oauth_test.go @@ -0,0 +1,380 @@ +package anthropic + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// isolate points the token at a throwaway config directory, so no test can +// read or clobber the real one. +func isolate(t *testing.T) string { + t.Helper() + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", dir) + return filepath.Join(dir, "dipstick", "auth.json") +} + +func writeToken(t *testing.T, tok *Token) { + t.Helper() + if err := saveToken(tok); err != nil { + t.Fatal(err) + } +} + +func readToken(t *testing.T) *Token { + t.Helper() + tok, err := loadToken() + if err != nil { + t.Fatal(err) + } + return tok +} + +// serve stands in for the token endpoint and the read endpoints. +func serve(t *testing.T, h http.HandlerFunc) *httptest.Server { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + return srv +} + +func TestBeginAuthBuildsAPKCEChallenge(t *testing.T) { + p, err := BeginAuth(DefaultScope) + if err != nil { + t.Fatal(err) + } + u, err := url.Parse(p.URL) + if err != nil { + t.Fatal(err) + } + q := u.Query() + if q.Get("code_challenge_method") != "S256" { + t.Errorf("challenge method = %q, want S256", q.Get("code_challenge_method")) + } + if q.Get("code_challenge") == "" || q.Get("code_challenge") == p.verifier { + t.Error("the challenge must be the hash of the verifier, not the verifier itself") + } + if q.Get("redirect_uri") != redirectURI { + t.Errorf("redirect_uri = %q", q.Get("redirect_uri")) + } + if q.Get("state") != p.state || p.state == "" { + t.Error("state missing or inconsistent") + } + + // Two flows must never share a verifier or a state. + other, _ := BeginAuth(DefaultScope) + if other.verifier == p.verifier || other.state == p.state { + t.Error("two flows produced the same PKCE secrets") + } +} + +// A state that does not come back unchanged means the response belongs to some +// other request. It must never be exchanged. +func TestCompleteRejectsMismatchedState(t *testing.T) { + isolate(t) + called := false + srv := serve(t, func(w http.ResponseWriter, r *http.Request) { called = true }) + tokenURL = srv.URL + + p, _ := BeginAuth(DefaultScope) + if err := p.Complete("somecode#not-the-state"); err == nil { + t.Error("a mismatched state must be an error") + } + if called { + t.Error("the token endpoint must not be contacted at all") + } +} + +func TestCompleteRejectsMalformedInput(t *testing.T) { + isolate(t) + p, _ := BeginAuth(DefaultScope) + for _, in := range []string{"", " ", "no-hash-separator"} { + if err := p.Complete(in); err == nil { + t.Errorf("Complete(%q) should have failed", in) + } + } +} + +func TestCompleteStoresTheGrant(t *testing.T) { + path := isolate(t) + srv := serve(t, func(w http.ResponseWriter, r *http.Request) { + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) + if body["grant_type"] != "authorization_code" || body["code"] != "abc" { + t.Errorf("unexpected request body: %v", body) + } + if body["code_verifier"] == "" { + t.Error("the verifier was not sent: without it PKCE proves nothing") + } + io.WriteString(w, `{"access_token":"AT","refresh_token":"RT","expires_in":3600}`) + }) + tokenURL = srv.URL + + p, _ := BeginAuth(DefaultScope) + if err := p.Complete("abc#" + p.state); err != nil { + t.Fatal(err) + } + + tok := readToken(t) + if tok.AccessToken != "AT" || tok.RefreshToken != "RT" { + t.Errorf("token = %+v", tok) + } + if time.Until(tok.ExpiresAt) < 50*time.Minute { + t.Errorf("expiry = %v, expected about an hour out", tok.ExpiresAt) + } + + // The token is a credential: it must never be group- or world-readable. + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if perm := info.Mode().Perm(); perm != 0o600 { + t.Errorf("permissions = %o, want 600", perm) + } +} + +// A renewal that returns no new refresh token must keep the old one: dropping +// it would be a free logout. +func TestStoreGrantKeepsThePreviousRefreshToken(t *testing.T) { + isolate(t) + if err := storeGrant([]byte(`{"access_token":"AT2","expires_in":3600}`), "OLD-RT", ""); err != nil { + t.Fatal(err) + } + if tok := readToken(t); tok.RefreshToken != "OLD-RT" { + t.Errorf("refresh token = %q, want OLD-RT", tok.RefreshToken) + } +} + +func TestStoreGrantRejectsAResponseWithoutAToken(t *testing.T) { + isolate(t) + if err := storeGrant([]byte(`{"expires_in":3600}`), "", ""); err == nil { + t.Error("a response without an access_token must be an error") + } +} + +// The distinction that matters: a dead grant means "log in again", anything +// else means "try later". Getting it wrong leaves the user staring at a widget +// that never recovers and never says why. +func TestRefreshMapsDeadGrantsToErrNoAuth(t *testing.T) { + for _, status := range []int{ + http.StatusBadRequest, + http.StatusUnauthorized, + http.StatusForbidden, + } { + isolate(t) + srv := serve(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + io.WriteString(w, `{"error":"invalid_grant"}`) + }) + tokenURL = srv.URL + writeToken(t, &Token{AccessToken: "AT", RefreshToken: "RT", + ExpiresAt: time.Now().Add(-time.Hour)}) + + _, err := AccessToken() + if !errors.Is(err, ErrNoAuth) { + t.Errorf("status %d: err = %v, want ErrNoAuth", status, err) + } + } +} + +// A transient failure must stay transient: turning a 503 into ErrNoAuth would +// throw the user out of a session that is still perfectly valid. +func TestRefreshKeepsTransientFailuresTransient(t *testing.T) { + for _, status := range []int{http.StatusTooManyRequests, http.StatusServiceUnavailable} { + isolate(t) + srv := serve(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + }) + tokenURL = srv.URL + writeToken(t, &Token{AccessToken: "AT", RefreshToken: "RT", + ExpiresAt: time.Now().Add(-time.Hour)}) + + _, err := AccessToken() + if err == nil { + t.Fatalf("status %d: expected an error", status) + } + if errors.Is(err, ErrNoAuth) { + t.Errorf("status %d: reported as a logout, but it is a transient failure", status) + } + } +} + +func TestRefreshWithoutARefreshTokenIsErrNoAuth(t *testing.T) { + isolate(t) + writeToken(t, &Token{AccessToken: "AT", ExpiresAt: time.Now().Add(-time.Hour)}) + if _, err := AccessToken(); !errors.Is(err, ErrNoAuth) { + t.Errorf("err = %v, want ErrNoAuth", err) + } +} + +func TestAccessTokenDoesNotRefreshWhenStillValid(t *testing.T) { + isolate(t) + srv := serve(t, func(w http.ResponseWriter, r *http.Request) { + t.Error("the token endpoint must not be contacted for a valid token") + }) + tokenURL = srv.URL + writeToken(t, &Token{AccessToken: "AT", RefreshToken: "RT", + ExpiresAt: time.Now().Add(time.Hour)}) + + got, err := AccessToken() + if err != nil || got != "AT" { + t.Errorf("AccessToken() = %q, %v", got, err) + } +} + +func TestMissingTokenIsErrNoAuth(t *testing.T) { + isolate(t) + if _, err := AccessToken(); !errors.Is(err, ErrNoAuth) { + t.Errorf("err = %v, want ErrNoAuth", err) + } +} + +// The server can invalidate a token before its stated expiry: the local clock +// cannot know. A 401 on a read must trigger a refresh and a retry rather than +// be reported as an outage. +func TestUnauthorizedReadRefreshesAndRetries(t *testing.T) { + isolate(t) + tokens := serve(t, func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"access_token":"FRESH","refresh_token":"RT2","expires_in":3600}`) + }) + tokenURL = tokens.URL + + var seen []string + reads := serve(t, func(w http.ResponseWriter, r *http.Request) { + auth := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + seen = append(seen, auth) + if auth != "FRESH" { + w.WriteHeader(http.StatusUnauthorized) + return + } + io.WriteString(w, `{"limits":[]}`) + }) + usageURL = reads.URL + + writeToken(t, &Token{AccessToken: "STALE", RefreshToken: "RT", + ExpiresAt: time.Now().Add(time.Hour)}) + + body, err := RawUsage() + if err != nil { + t.Fatalf("the read should have recovered: %v", err) + } + if string(body) != `{"limits":[]}` { + t.Errorf("body = %q", body) + } + if len(seen) != 2 || seen[0] != "STALE" || seen[1] != "FRESH" { + t.Errorf("attempts = %v, expected one with the old token and one with the new", seen) + } +} + +// If it is still unauthorized after a fresh token, the grant is gone: that is +// a logout, not an outage, and the widget must be able to say so. +func TestPersistentUnauthorizedBecomesErrNoAuth(t *testing.T) { + isolate(t) + tokens := serve(t, func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"access_token":"FRESH","refresh_token":"RT2","expires_in":3600}`) + }) + tokenURL = tokens.URL + reads := serve(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + }) + usageURL = reads.URL + + writeToken(t, &Token{AccessToken: "AT", RefreshToken: "RT", + ExpiresAt: time.Now().Add(time.Hour)}) + + if _, err := RawUsage(); !errors.Is(err, ErrNoAuth) { + t.Errorf("err = %v, want ErrNoAuth", err) + } +} + +// A 500 is not a credentials problem and must not be retried as one. +func TestServerErrorIsNotRetriedAsAuthFailure(t *testing.T) { + isolate(t) + tokens := serve(t, func(w http.ResponseWriter, r *http.Request) { + t.Error("a 500 must not trigger a token refresh") + }) + tokenURL = tokens.URL + attempts := 0 + reads := serve(t, func(w http.ResponseWriter, r *http.Request) { + attempts++ + w.WriteHeader(http.StatusInternalServerError) + }) + usageURL = reads.URL + + writeToken(t, &Token{AccessToken: "AT", RefreshToken: "RT", + ExpiresAt: time.Now().Add(time.Hour)}) + + _, err := RawUsage() + var he *HTTPError + if !errors.As(err, &he) || he.Status != http.StatusInternalServerError { + t.Errorf("err = %v, want an HTTPError 500", err) + } + if attempts != 1 { + t.Errorf("attempts = %d, want 1", attempts) + } +} + +// The error message travels through logs and the widget: it must never carry +// the bearer token. +func TestHTTPErrorDoesNotLeakTheToken(t *testing.T) { + e := &HTTPError{Status: 500, What: "usage", Body: strings.Repeat("x", 500)} + if strings.Contains(e.Error(), strings.Repeat("x", 300)) { + t.Error("the body is not truncated") + } +} + +func TestLogoutRemovesTheToken(t *testing.T) { + path := isolate(t) + writeToken(t, &Token{AccessToken: "AT", ExpiresAt: time.Now().Add(time.Hour)}) + if err := Logout(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("the token is still there: %v", err) + } + // Logging out twice is not an error. + if err := Logout(); err != nil { + t.Errorf("a second Logout should be a no-op: %v", err) + } +} + +// Concurrent refreshes must not fight: the lock serialises them, so the second +// one finds the token already renewed and does not spend the refresh token a +// second time. +func TestConcurrentRefreshHappensOnce(t *testing.T) { + isolate(t) + exchanges := 0 + srv := serve(t, func(w http.ResponseWriter, r *http.Request) { + exchanges++ + io.WriteString(w, `{"access_token":"FRESH","refresh_token":"RT2","expires_in":3600}`) + }) + tokenURL = srv.URL + writeToken(t, &Token{AccessToken: "STALE", RefreshToken: "RT", + ExpiresAt: time.Now().Add(-time.Hour)}) + + const n = 8 + errs := make(chan error, n) + for i := 0; i < n; i++ { + go func() { + _, err := AccessToken() + errs <- err + }() + } + for i := 0; i < n; i++ { + if err := <-errs; err != nil { + t.Fatalf("refresh failed: %v", err) + } + } + if exchanges != 1 { + t.Errorf("token exchanges = %d, want 1: the refresh token was spent more than once", exchanges) + } +} diff --git a/internal/anthropic/profile.go b/internal/anthropic/profile.go index 0a657a9..326c073 100644 --- a/internal/anthropic/profile.go +++ b/internal/anthropic/profile.go @@ -6,14 +6,14 @@ import ( "strings" ) -// Profile e' l'identita' dell'account: cambia solo con un logout/login, quindi -// si legge di rado. +// Profile is the account's identity: it only changes on logout/login, so it is +// read rarely. type Profile struct { Email string Name string - // Plan e' il nome commerciale del piano ("Max 20x", "Pro"). E' un nome di - // prodotto, non testo di interfaccia: non si traduce, quindi puo' stare - // nel file di stato senza violare la regola sulle stringhe. + // Plan is the commercial plan name ("Max 20x", "Pro"). It is a product + // name, not interface text: it is not translated, so it can live in the + // state file without breaking the no-UI-strings rule. Plan string } @@ -26,8 +26,8 @@ type rawProfile struct { HasClaudePro bool `json:"has_claude_pro"` } `json:"account"` Organization struct { - // Es. "default_claude_max_20x": piu' preciso di has_claude_max, che - // non distingue 5x da 20x. + // e.g. "default_claude_max_20x": more precise than has_claude_max, + // which does not tell 5x from 20x. RateLimitTier string `json:"rate_limit_tier"` } `json:"organization"` } @@ -35,7 +35,7 @@ type rawProfile struct { func ParseProfile(body []byte) (*Profile, error) { var raw rawProfile if err := json.Unmarshal(body, &raw); err != nil { - return nil, fmt.Errorf("risposta di profile illeggibile: %w", err) + return nil, fmt.Errorf("unreadable profile response: %w", err) } p := &Profile{Email: raw.Account.Email, Name: raw.Account.DisplayName} if p.Name == "" { @@ -45,9 +45,9 @@ func ParseProfile(body []byte) (*Profile, error) { return p, nil } -// planLabel ricava il nome del piano dal tier. Il tier e' la fonte migliore -// perche' distingue 5x da 20x, ma non e' documentato: se cambia forma si -// ricade sui booleani, che sono grossolani ma stabili. +// planLabel derives the plan name from the tier. The tier is the better +// source because it tells 5x from 20x, but it is undocumented: if its shape +// changes we fall back to the booleans, which are coarse but stable. func planLabel(tier string, hasMax, hasPro bool) string { if rest, ok := strings.CutPrefix(tier, "default_claude_"); ok && rest != "" { words := strings.Split(rest, "_") @@ -55,8 +55,8 @@ func planLabel(tier string, hasMax, hasPro bool) string { if w == "" { continue } - // "max" -> "Max", ma "20x" resta "20x": maiuscolare una cifra non - // cambia nulla e maiuscolare la x la imbruttisce. + // "max" -> "Max", but "20x" stays "20x": capitalising a digit + // changes nothing and capitalising the x just looks wrong. if w[0] >= 'a' && w[0] <= 'z' { words[i] = strings.ToUpper(w[:1]) + w[1:] } diff --git a/internal/anthropic/profile_test.go b/internal/anthropic/profile_test.go index fd9de2a..4e5c8a0 100644 --- a/internal/anthropic/profile_test.go +++ b/internal/anthropic/profile_test.go @@ -12,22 +12,22 @@ func TestPlanLabelFromTier(t *testing.T) { {"default_claude_pro", "Pro"}, } { if got := planLabel(tc.tier, false, false); got != tc.want { - t.Errorf("planLabel(%q) = %q, atteso %q", tc.tier, got, tc.want) + t.Errorf("planLabel(%q) = %q, want %q", tc.tier, got, tc.want) } } } -// Il tier non e' documentato: se cambia forma si ricade sui booleani invece di -// mostrare una stringa incomprensibile. +// The tier is undocumented: if its shape changes we fall back to the booleans +// rather than show an unintelligible string. func TestPlanLabelFallsBackToBooleans(t *testing.T) { if got := planLabel("", true, false); got != "Max" { - t.Errorf("got %q, atteso Max", got) + t.Errorf("got %q, want Max", got) } if got := planLabel("qualcosa_di_nuovo", false, true); got != "Pro" { - t.Errorf("got %q, atteso Pro", got) + t.Errorf("got %q, want Pro", got) } if got := planLabel("", false, false); got != "" { - t.Errorf("got %q, atteso vuoto", got) + t.Errorf("got %q, want empty", got) } } @@ -39,6 +39,6 @@ func TestParseProfilePrefersDisplayName(t *testing.T) { t.Fatal(err) } if p.Email != "a@b.it" || p.Name != "Claudio" || p.Plan != "Max 20x" { - t.Errorf("profilo = %+v", p) + t.Errorf("profile = %+v", p) } } diff --git a/internal/anthropic/usage.go b/internal/anthropic/usage.go index 9305856..a86f113 100644 --- a/internal/anthropic/usage.go +++ b/internal/anthropic/usage.go @@ -7,30 +7,30 @@ import ( "time" ) -// Window e' una finestra di rate limit normalizzata: la forma su cui ragiona -// tutto il resto di dipstick, indipendente da come l'endpoint la impacchetta. +// Window is a normalised rate-limit window: the shape everything else in +// dipstick reasons about, independent of how the endpoint packages it. type Window struct { Kind string // "session" | "weekly_all" | "weekly_scoped" | ... Group string // "session" | "weekly" Percent int // 0-100 - Severity string // "normal" e qualunque altra cosa mandi il server - ResetsAt *time.Time // nil se il server non lo dice + Severity string // "normal", and whatever else the server sends + ResetsAt *time.Time // nil when the server does not say IsActive bool - Model string // nome del modello per le finestre scoped, "" altrimenti + Model string // model name for scoped windows, empty otherwise } -// Usage e' la risposta di /api/oauth/usage ridotta a cio' che ci serve. +// Usage is the /api/oauth/usage response reduced to what we need. type Usage struct { Windows []Window - // ExtraUsageEnabled: con i crediti attivi il 100% non e' piu' un muro. - // Mostrarlo come tale sarebbe una bugia, quindi il dato risale. + // ExtraUsageEnabled: with credits on, 100% is no longer a wall. Showing it + // as one would be a lie, so the flag travels up. ExtraUsageEnabled bool } -// Il grezzo, com'e' davvero. I campi non elencati qui (tangelo, iguana_necktie, -// nimbus_quill, seven_day_cowork, ...) sono feature non annunciate e vengono -// ignorati di proposito: l'endpoint non e' documentato e ne aggiunge senza -// preavviso, quindi tutto cio' che non riconosciamo non deve rompere nulla. +// The raw shape, as it really is. Fields not listed here (tangelo, +// iguana_necktie, nimbus_quill, seven_day_cowork, ...) are unannounced +// features and are ignored on purpose: the endpoint is undocumented and adds +// them without notice, so anything unrecognised must not break anything. type rawUsage struct { Limits []struct { Kind string `json:"kind"` @@ -46,9 +46,9 @@ type rawUsage struct { } `json:"scope"` } `json:"limits"` - // Campi di primo livello: sopravvivono, restano allineati a limits[], ma - // non portano il breakdown per modello (seven_day_opus/sonnet arrivano - // null). Servono solo se limits[] sparisce. + // Top-level fields: still present, still consistent with limits[], but + // they carry no per-model breakdown (seven_day_opus and seven_day_sonnet + // come back null). They only matter if limits[] disappears. FiveHour *rawLegacyWindow `json:"five_hour"` SevenDay *rawLegacyWindow `json:"seven_day"` @@ -58,8 +58,8 @@ type rawUsage struct { } type rawLegacyWindow struct { - // Qui e' un float (30.0), mentre limits[].percent e' intero. Non e' una - // svista: sono due rappresentazioni diverse della stessa cosa. + // A float here (30.0), while limits[].percent is an integer. Not an + // oversight: they are two representations of the same thing. Utilization float64 `json:"utilization"` ResetsAt *string `json:"resets_at"` } @@ -86,15 +86,15 @@ func clampPercent(f float64) int { return p } -// ParseUsage normalizza la risposta grezza. +// ParseUsage normalises the raw response. // -// La fonte e' limits[]: e' l'unica che porta severity, is_active e il nome del -// modello delle finestre scoped. I campi di primo livello sono il fallback per -// quando limits[] manca o arriva vuoto. +// The source is limits[]: it is the only one carrying severity, is_active and +// the model name of scoped windows. The top-level fields are the fallback for +// when limits[] is missing or arrives empty. func ParseUsage(body []byte) (*Usage, error) { var raw rawUsage if err := json.Unmarshal(body, &raw); err != nil { - return nil, fmt.Errorf("risposta di usage illeggibile: %w", err) + return nil, fmt.Errorf("unreadable usage response: %w", err) } u := &Usage{} @@ -120,9 +120,9 @@ func ParseUsage(body []byte) (*Usage, error) { return u, nil } - // Fallback: limits[] assente. Ricostruiamo il minimo indispensabile. - // severity resta vuoto perche' non lo sappiamo, e inventarlo sarebbe - // peggio che ometterlo. + // Fallback: limits[] absent. Rebuild the bare minimum. Severity stays + // empty because we do not know it, and inventing one would be worse than + // omitting it. if raw.FiveHour != nil { u.Windows = append(u.Windows, Window{ Kind: KindSession, Group: GroupSession, @@ -138,13 +138,13 @@ func ParseUsage(body []byte) (*Usage, error) { }) } if len(u.Windows) == 0 { - return nil, fmt.Errorf("nessuna finestra di quota nella risposta") + return nil, fmt.Errorf("no quota window in the response") } return u, nil } -// Nomi noti. Qualunque altro kind viene comunque trasportato: non e' un elenco -// chiuso, e' il sottoinsieme su cui dipstick sa dire qualcosa in piu'. +// Known names. Any other kind is still carried through: this is not a closed +// set, only the subset dipstick can say something extra about. const ( KindSession = "session" KindWeeklyAll = "weekly_all" @@ -154,7 +154,7 @@ const ( GroupWeekly = "weekly" ) -// Find restituisce la prima finestra con il kind dato. +// Find returns the first window with the given kind. func (u *Usage) Find(kind string) *Window { for i := range u.Windows { if u.Windows[i].Kind == kind { @@ -164,7 +164,7 @@ func (u *Usage) Find(kind string) *Window { return nil } -// FetchUsage legge e normalizza in un colpo solo. +// FetchUsage reads and normalises in one go. func FetchUsage() (*Usage, error) { body, err := RawUsage() if err != nil { diff --git a/internal/anthropic/usage_test.go b/internal/anthropic/usage_test.go index 2533b27..bcf5094 100644 --- a/internal/anthropic/usage_test.go +++ b/internal/anthropic/usage_test.go @@ -5,8 +5,8 @@ import ( "testing" ) -// Il test gira contro la forma reale catturata dall'endpoint, non contro un -// JSON inventato: e' l'unico modo di accorgersi se il contratto cambia. +// The test runs against the real shape captured from the endpoint, not an +// invented JSON: it is the only way to notice if the contract changes. func loadFixture(t *testing.T) []byte { t.Helper() raw, err := os.ReadFile("testdata/usage.json") @@ -22,7 +22,7 @@ func TestParseUsageRealShape(t *testing.T) { t.Fatal(err) } if len(u.Windows) != 3 { - t.Fatalf("finestre = %d, attese 3", len(u.Windows)) + t.Fatalf("windows = %d, want 3", len(u.Windows)) } session := u.Find(KindSession) @@ -30,7 +30,7 @@ func TestParseUsageRealShape(t *testing.T) { t.Errorf("session = %+v", session) } if session.ResetsAt == nil { - t.Error("session senza resets_at") + t.Error("session has no resets_at") } weekly := u.Find(KindWeeklyAll) @@ -38,20 +38,20 @@ func TestParseUsageRealShape(t *testing.T) { t.Errorf("weekly_all = %+v", weekly) } - // Il punto che lo spike ha scoperto: il breakdown per modello non sta in - // seven_day_opus/sonnet (null) ma qui, col nome deciso dal server. + // What the spike uncovered: the per-model breakdown is not in + // seven_day_opus/sonnet (null) but here, with the name the server picks. scoped := u.Find(KindWeeklyScoped) if scoped == nil || scoped.Model != "Fable" || scoped.Percent != 9 { - t.Errorf("weekly_scoped = %+v, atteso model=Fable percent=9", scoped) + t.Errorf("weekly_scoped = %+v, want model=Fable percent=9", scoped) } if u.ExtraUsageEnabled { - t.Error("extra_usage risulta attivo, la fixture dice false") + t.Error("extra_usage reads as enabled, the fixture says false") } } -// I campi in codice (tangelo, iguana_necktie, nimbus_quill...) non devono -// rompere il parsing, e nemmeno finire fra le finestre. +// Code-named fields (tangelo, iguana_necktie, nimbus_quill...) must neither +// break parsing nor end up among the windows. func TestParseUsageIgnoresUnknownFields(t *testing.T) { u, err := ParseUsage([]byte(`{ "limits": [{"kind":"session","group":"session","percent":5,"severity":"normal","is_active":true}], @@ -66,8 +66,8 @@ func TestParseUsageIgnoresUnknownFields(t *testing.T) { } } -// Se limits[] sparisce si ricade sui campi di primo livello, dove utilization -// e' un float da arrotondare. +// If limits[] disappears we fall back to the top-level fields, where +// utilization is a float that needs rounding. func TestParseUsageFallsBackToTopLevel(t *testing.T) { u, err := ParseUsage([]byte(`{ "limits": [], @@ -78,16 +78,16 @@ func TestParseUsageFallsBackToTopLevel(t *testing.T) { t.Fatal(err) } if w := u.Find(KindSession); w == nil || w.Percent != 12 { - t.Errorf("session = %+v, atteso percent=12", w) + t.Errorf("session = %+v, want percent=12", w) } if w := u.Find(KindWeeklyAll); w == nil || w.Percent != 31 { - t.Errorf("weekly = %+v, atteso percent=31 (arrotondato)", w) + t.Errorf("weekly = %+v, want percent=31 (rounded)", w) } } func TestParseUsageRejectsEmpty(t *testing.T) { if _, err := ParseUsage([]byte(`{"limits": []}`)); err == nil { - t.Error("una risposta senza finestre deve essere un errore, non uno stato a zero") + t.Error("a response with no windows must be an error, not a zeroed state") } } @@ -97,7 +97,7 @@ func TestClampPercent(t *testing.T) { want int }{{-5, 0}, {0, 0}, {12.4, 12}, {30.6, 31}, {100, 100}, {140, 100}} { if got := clampPercent(tc.in); got != tc.want { - t.Errorf("clampPercent(%v) = %d, atteso %d", tc.in, got, tc.want) + t.Errorf("clampPercent(%v) = %d, want %d", tc.in, got, tc.want) } } } diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 09c7bfe..4562b6a 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -1,7 +1,7 @@ -// Package daemon tiene aggiornato state.json. +// Package daemon keeps state.json up to date. // -// Gira come systemd user unit, fuori da plasmashell: se qualcosa qui va male -// muore un servizio, non il panel dell'utente. +// It runs as a systemd user unit, outside plasmashell: if something goes wrong +// here a service dies, not the user's panel. package daemon import ( @@ -16,19 +16,20 @@ import ( ) type Config struct { - // Interval e' la cadenza a sessione attiva. Lato server utilizzation si - // muove ogni ~5 minuti: interrogare piu' spesso ripete la stessa risposta. + // Interval is the cadence while a session is active. Server-side, + // utilization moves every ~5 minutes: asking more often repeats the same + // answer. Interval time.Duration - // IdleInterval e' la cadenza quando i transcript non mostrano attivita'. + // IdleInterval is the cadence when the transcripts show no activity. IdleInterval time.Duration - // IdleAfter e' quanto silenzio serve per considerarsi fermi. + // IdleAfter is how much silence counts as being idle. IdleAfter time.Duration - // MaxBackoff limita l'attesa dopo errori ripetuti. + // MaxBackoff caps the wait after repeated failures. MaxBackoff time.Duration - // StaleAfter e' da quanto puo' essere vecchia l'ultima lettura buona prima - // che smettiamo di mostrarla. + // StaleAfter is how old the last good read may be before we stop showing + // it at all. StaleAfter time.Duration - // ProfileEvery e' ogni quanto rileggere l'identita' dell'account. + // ProfileEvery is how often to re-read the account identity. ProfileEvery time.Duration } @@ -46,23 +47,23 @@ func DefaultConfig() Config { type Daemon struct { cfg Config log *slog.Logger - root string // albero dei transcript + root string // transcript tree - // Ultima lettura riuscita, per poter degradare su "stale" invece di - // cadere direttamente su "nessun dato". + // The last successful read, so we can degrade to "stale" instead of + // dropping straight to "no data". lastGood *anthropic.Usage lastGoodAt time.Time - // Il profilo cambia solo con un logout/login: si rilegge di rado, e un - // suo fallimento non deve intaccare la quota, che e' il dato che conta. + // The profile only changes on logout/login: it is re-read rarely, and its + // failure must not affect the quota, which is the figure that matters. profile *anthropic.Profile profileAt time.Time failures int - // Iniettabili: il backoff e il degrado su dati vecchi sono la logica che - // si rompe in silenzio, quindi devono essere testabili senza rete ne' - // scritture su disco. + // Injectable: backoff and degradation onto old data are the logic that + // fails silently, so they must be testable without the network or disk + // writes. fetchUsage func() (*anthropic.Usage, error) fetchProfile func() (*anthropic.Profile, error) writeState func(*state.State) error @@ -77,11 +78,11 @@ func New(cfg Config, root string, log *slog.Logger) *Daemon { } } -// Run cicla finche' il contesto non viene cancellato. +// Run loops until the context is cancelled. func (d *Daemon) Run(ctx context.Context) error { for { wait := d.tick(time.Now()) - d.log.Debug("prossimo giro", "fra", wait) + d.log.Debug("next round", "in", wait) select { case <-ctx.Done(): @@ -91,20 +92,25 @@ func (d *Daemon) Run(ctx context.Context) error { } } -// tick fa un giro completo e restituisce quanto aspettare prima del prossimo. +// tick runs one full round and returns how long to wait before the next. func (d *Daemon) tick(now time.Time) time.Duration { - // I transcript si leggono sempre: costano poco, dicono se c'e' attivita' - // - da cui la cadenza - e restano l'unica cosa vera se la rete non risponde. + // The transcripts are always read: they are cheap, they say whether there + // is activity - which sets the cadence - and they remain the only true + // thing if the network does not answer. + // + // A partial scan still returns usable totals, so the error is logged and + // the activity is used anyway; ignoring the error would present an + // incomplete figure as a whole one. activity, err := d.scan(now) if err != nil { - d.log.Warn("scansione dei transcript fallita", "err", err) + d.log.Warn("transcript scan incomplete", "err", err) } st, ok := d.fetch(now) - st.WithLocal(activity).WithAccount(d.loadProfile(now, ok)) + st.WithLocal(activity).WithAccount(d.loadProfile(now, ok, st.Quota.NeedsAuth)) if err := d.writeState(st); err != nil { - d.log.Error("scrittura dello stato fallita", "err", err) + d.log.Error("writing the state failed", "err", err) } if !ok { @@ -124,8 +130,8 @@ func (d *Daemon) scan(now time.Time) (*transcript.Activity, error) { return transcript.Scan(d.root, now) } -// fetch legge la quota e costruisce lo stato. Il bool dice se la lettura e' -// riuscita: solo quello governa il backoff. +// fetch reads the quota and builds the state. The bool says whether the read +// succeeded: that alone drives the backoff. func (d *Daemon) fetch(now time.Time) (*state.State, bool) { usage, err := d.fetchUsage() if err == nil { @@ -133,25 +139,25 @@ func (d *Daemon) fetch(now time.Time) (*state.State, bool) { return state.FromUsage(usage, now), true } - // Senza token non c'e' stata nessuna chiamata di rete, quindi non c'e' - // niente da rallentare: e' l'utente che deve agire. + // With no token no network call happened, so there is nothing to slow + // down: it is the user who has to act. if errors.Is(err, anthropic.ErrNoAuth) { - d.log.Warn("non autenticato", "azione", "dipstick auth") + d.log.Warn("not authenticated", "action", "dipstick auth") return state.Unavailable(err, true, now), true } - d.log.Warn("lettura della quota fallita", "err", err) + d.log.Warn("reading the quota failed", "err", err) if d.lastGood != nil && now.Sub(d.lastGoodAt) < d.cfg.StaleAfter { return state.Stale(d.lastGood, d.lastGoodAt, err, now), false } - // Troppo vecchia per essere ancora spacciata per un dato. + // Too old to still be passed off as data. d.lastGood = nil return state.Unavailable(err, false, now), false } -// backoff raddoppia l'attesa a ogni fallimento consecutivo. L'endpoint non e' -// documentato: se sta male o ci sta limitando, insistere alla stessa cadenza -// e' esattamente la cosa da non fare. +// backoff doubles the wait on each consecutive failure. The endpoint is +// undocumented: if it is unwell, or throttling us, insisting at the same +// cadence is exactly the wrong move. func (d *Daemon) backoff() time.Duration { d.failures++ wait := d.cfg.Interval @@ -164,11 +170,15 @@ func (d *Daemon) backoff() time.Duration { return wait } -// loadProfile rilegge l'identita' solo quando serve. Non ha senso chiederla se -// la quota stessa non risponde: sarebbe una richiesta in piu' verso un endpoint -// che sappiamo gia' non stare bene. -func (d *Daemon) loadProfile(now time.Time, quotaOK bool) *anthropic.Profile { - if !quotaOK { +// loadProfile re-reads the identity only when needed. +// +// It is skipped when the quota itself did not come back, and equally when +// there is no token: in the first case it would be one more request to an +// endpoint we already know is unwell, in the second it would fail identically +// every round and log a warning every five minutes, forever, while the user is +// simply logged out. +func (d *Daemon) loadProfile(now time.Time, quotaOK bool, needsAuth bool) *anthropic.Profile { + if !quotaOK || needsAuth { return d.profile } if d.profile != nil && now.Sub(d.profileAt) < d.cfg.ProfileEvery { @@ -176,8 +186,8 @@ func (d *Daemon) loadProfile(now time.Time, quotaOK bool) *anthropic.Profile { } p, err := d.fetchProfile() if err != nil { - // Il profilo e' contorno: se manca si mostra la quota senza testata. - d.log.Warn("lettura del profilo fallita", "err", err) + // The profile is garnish: without it the quota shows with no header. + d.log.Warn("reading the profile failed", "err", err) return d.profile } d.profile, d.profileAt = p, now diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index e7b091b..8877ee1 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -17,7 +17,7 @@ func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } -// harness costruisce un demone che non tocca ne' rete ne' disco. +// harness builds a daemon that touches neither the network nor the disk. func harness(t *testing.T, fetch func() (*anthropic.Usage, error)) (*Daemon, *[]*state.State) { t.Helper() var written []*state.State @@ -45,30 +45,30 @@ func TestTickWritesFreshState(t *testing.T) { return usageAt(30, now.Add(24*time.Hour)), nil }) if wait := d.tick(now); wait != DefaultConfig().Interval { - t.Errorf("attesa = %v, atteso %v", wait, DefaultConfig().Interval) + t.Errorf("wait = %v, want %v", wait, DefaultConfig().Interval) } if len(*written) != 1 || (*written)[0].Quota.Status != state.StatusFresh { - t.Fatalf("stato scritto = %+v", *written) + t.Fatalf("written state = %+v", *written) } } -// Lo stato va scritto anche quando la lettura fallisce: il plasmoide deve -// poter distinguere "quota non leggibile" da "demone morto". +// The state must be written even when the read fails: the plasmoid has to be +// able to tell "quota unreadable" from "daemon dead". func TestTickWritesEvenOnFailure(t *testing.T) { d, written := harness(t, func() (*anthropic.Usage, error) { - return nil, errors.New("rete giu'") + return nil, errors.New("network down") }) d.tick(now) if len(*written) != 1 { - t.Fatalf("scritture = %d, attesa 1", len(*written)) + t.Fatalf("writes = %d, want 1", len(*written)) } if (*written)[0].Quota.Status != state.StatusUnavailable { t.Errorf("status = %q", (*written)[0].Quota.Status) } } -// Dopo una lettura buona, un fallimento degrada su "stale" invece di -// cancellare tutto. +// After a good read, a failure degrades to "stale" rather than wiping +// everything. func TestFailureAfterSuccessDegradesToStale(t *testing.T) { fail := false d, written := harness(t, func() (*anthropic.Usage, error) { @@ -83,19 +83,19 @@ func TestFailureAfterSuccessDegradesToStale(t *testing.T) { last := (*written)[len(*written)-1] if last.Quota.Status != state.StatusStale { - t.Fatalf("status = %q, atteso stale", last.Quota.Status) + t.Fatalf("status = %q, want stale", last.Quota.Status) } if last.Compact == nil || last.Compact.Primary.Percent != 30 { - t.Errorf("i numeri vecchi dovrebbero restare: %+v", last.Compact) + t.Errorf("the old numbers should have stayed: %+v", last.Compact) } - // L'istante deve essere quello dell'ultima lettura RIUSCITA, non di ora. + // The instant must be that of the last SUCCESSFUL read, not now. if last.Quota.FetchedAt == nil || !last.Quota.FetchedAt.Equal(now) { - t.Errorf("fetched_at = %v, atteso %v", last.Quota.FetchedAt, now) + t.Errorf("fetched_at = %v, want %v", last.Quota.FetchedAt, now) } } -// Una finestra gia' scaduta non e' stantia, e' falsa: direbbe "usato" di una -// finestra che nel frattempo e' tornata a zero. +// A window that already reset is not stale, it is false: it would claim +// "used" of a window that has since gone back to zero. func TestStaleDropsExpiredWindows(t *testing.T) { fail := false d, written := harness(t, func() (*anthropic.Usage, error) { @@ -106,18 +106,18 @@ func TestStaleDropsExpiredWindows(t *testing.T) { }) d.tick(now) fail = true - d.tick(now.Add(20 * time.Minute)) // il reset e' passato + d.tick(now.Add(20 * time.Minute)) // the reset has passed last := (*written)[len(*written)-1] if last.Quota.Status != state.StatusUnavailable { - t.Errorf("status = %q, atteso unavailable", last.Quota.Status) + t.Errorf("status = %q, want unavailable", last.Quota.Status) } if last.Compact != nil { - t.Errorf("compact = %+v, atteso nil", last.Compact) + t.Errorf("compact = %+v, want nil", last.Compact) } } -// Oltre StaleAfter si smette di spacciare i numeri vecchi per un dato. +// Past StaleAfter we stop passing the old numbers off as data. func TestStaleExpiresAfterStaleAfter(t *testing.T) { fail := false d, written := harness(t, func() (*anthropic.Usage, error) { @@ -131,23 +131,23 @@ func TestStaleExpiresAfterStaleAfter(t *testing.T) { d.tick(now.Add(DefaultConfig().StaleAfter + time.Minute)) if last := (*written)[len(*written)-1]; last.Quota.Status != state.StatusUnavailable { - t.Errorf("status = %q, atteso unavailable", last.Quota.Status) + t.Errorf("status = %q, want unavailable", last.Quota.Status) } } -// Senza token non parte nessuna richiesta, quindi non c'e' niente da -// rallentare: e' l'utente che deve agire. +// With no token no request goes out, so there is nothing to slow down: it is +// the user who has to act. func TestMissingAuthDoesNotBackOff(t *testing.T) { d, written := harness(t, func() (*anthropic.Usage, error) { return nil, anthropic.ErrNoAuth }) for i := 0; i < 3; i++ { if wait := d.tick(now); wait != DefaultConfig().Interval { - t.Fatalf("giro %d: attesa = %v, atteso nessun backoff", i, wait) + t.Fatalf("round %d: wait = %v, expected no backoff", i, wait) } } if last := (*written)[len(*written)-1]; !last.Quota.NeedsAuth { - t.Error("needs_auth non impostato: il popup non puo' dire cosa fare") + t.Error("needs_auth not set: the popup cannot say what to do") } } @@ -159,18 +159,18 @@ func TestBackoffDoublesAndIsCapped(t *testing.T) { want := []time.Duration{cfg.Interval, 2 * cfg.Interval, 4 * cfg.Interval} for i, w := range want { if got := d.tick(now); got != w { - t.Errorf("fallimento %d: attesa = %v, attesa %v", i+1, got, w) + t.Errorf("failure %d: wait = %v, want %v", i+1, got, w) } } for i := 0; i < 10; i++ { d.tick(now) } if got := d.tick(now); got != cfg.MaxBackoff { - t.Errorf("attesa = %v, atteso il tetto %v", got, cfg.MaxBackoff) + t.Errorf("wait = %v, want the cap %v", got, cfg.MaxBackoff) } } -// Una lettura riuscita azzera il backoff accumulato. +// A successful read clears the accumulated backoff. func TestSuccessResetsBackoff(t *testing.T) { fail := true d, _ := harness(t, func() (*anthropic.Usage, error) { @@ -183,15 +183,15 @@ func TestSuccessResetsBackoff(t *testing.T) { d.tick(now) fail = false if got := d.tick(now); got != DefaultConfig().Interval { - t.Errorf("attesa = %v, atteso il ritorno alla cadenza normale", got) + t.Errorf("wait = %v, expected a return to the normal cadence", got) } fail = true if got := d.tick(now); got != DefaultConfig().Interval { - t.Errorf("attesa = %v, il backoff doveva ripartire da capo", got) + t.Errorf("wait = %v, the backoff should have restarted from scratch", got) } } -// Il profilo e' contorno: se fallisce, la quota si mostra lo stesso. +// The profile is garnish: if it fails, the quota still shows. func TestProfileFailureDoesNotBreakState(t *testing.T) { d, written := harness(t, func() (*anthropic.Usage, error) { return usageAt(30, now.Add(24*time.Hour)), nil @@ -205,11 +205,11 @@ func TestProfileFailureDoesNotBreakState(t *testing.T) { t.Errorf("status = %q", last.Quota.Status) } if last.Account != nil { - t.Errorf("account = %+v, atteso nil", last.Account) + t.Errorf("account = %+v, want nil", last.Account) } } -// Il profilo cambia solo con un logout/login: non si rilegge a ogni giro. +// The profile only changes on logout/login: it is not re-read every round. func TestProfileIsCached(t *testing.T) { calls := 0 d, _ := harness(t, func() (*anthropic.Usage, error) { @@ -223,15 +223,15 @@ func TestProfileIsCached(t *testing.T) { d.tick(now.Add(time.Hour)) d.tick(now.Add(2 * time.Hour)) if calls != 1 { - t.Errorf("letture del profilo = %d, attesa 1", calls) + t.Errorf("profile reads = %d, want 1", calls) } d.tick(now.Add(DefaultConfig().ProfileEvery + time.Minute)) if calls != 2 { - t.Errorf("letture del profilo = %d, attese 2 dopo la scadenza", calls) + t.Errorf("profile reads = %d, want 2 after expiry", calls) } } -// Se la quota non risponde non ha senso insistere anche sul profilo. +// If the quota does not answer there is no point insisting on the profile. func TestProfileNotFetchedWhenQuotaFails(t *testing.T) { calls := 0 d, _ := harness(t, func() (*anthropic.Usage, error) { @@ -243,6 +243,29 @@ func TestProfileNotFetchedWhenQuotaFails(t *testing.T) { } d.tick(now) if calls != 0 { - t.Errorf("letture del profilo = %d, attesa 0", calls) + t.Errorf("profile reads = %d, want 0", calls) + } +} + +// With no token, asking for the profile would fail identically every round and +// log a warning every five minutes, forever, while the user is simply logged +// out and the widget already says so. +func TestProfileNotFetchedWhenNotAuthenticated(t *testing.T) { + calls := 0 + d, written := harness(t, func() (*anthropic.Usage, error) { + return nil, anthropic.ErrNoAuth + }) + d.fetchProfile = func() (*anthropic.Profile, error) { + calls++ + return &anthropic.Profile{}, nil + } + for i := 0; i < 5; i++ { + d.tick(now.Add(time.Duration(i) * time.Hour)) + } + if calls != 0 { + t.Errorf("profile reads = %d, want 0", calls) + } + if last := (*written)[len(*written)-1]; !last.Quota.NeedsAuth { + t.Error("needs_auth not set") } } diff --git a/internal/state/state.go b/internal/state/state.go index 984a220..1936038 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -1,13 +1,13 @@ -// Package state definisce il file che il demone scrive e il plasmoide legge. +// Package state defines the file the daemon writes and the plasmoid reads. // -// E' l'unico punto di contatto fra le due meta' del progetto, quindi lo schema -// e' il contratto: si versiona e si cambia con intenzione. Il plasmoide deve -// solo disegnare, percio' ogni scelta - quale finestra e' quella che stringe, -// se il dato e' fresco - viene decisa qui e non in QML. +// It is the only point of contact between the two halves of the project, so +// the schema is the contract: it is versioned and changed on purpose. The +// plasmoid only draws, so every decision - which window is the tightest, +// whether the data is fresh - is made here and not in QML. // -// Non contiene stringhe di interfaccia: solo `kind` semantici e il nome del -// modello. La localizzazione e' del plasmoide, che ha `i18n()` e segue la -// lingua della sessione; il demone gira senza contesto di locale. +// It carries no interface strings: only semantic `kind` values and the model +// name. Localisation belongs to the plasmoid, which has i18n() and follows the +// session language; the daemon runs with no locale context. package state import ( @@ -20,54 +20,65 @@ import ( "github.com/claudioquaglia/dipstick/internal/transcript" ) -// SchemaVersion cambia solo per modifiche incompatibili. Il plasmoide rifiuta -// uno schema che non conosce invece di disegnare numeri a caso. +// SchemaVersion changes only for incompatible changes. The plasmoid refuses a +// schema it does not know rather than draw arbitrary numbers. const SchemaVersion = 1 -// Stati di freschezza del dato di quota. +// Freshness of the quota data. const ( - StatusFresh = "fresh" // letto ora dall'endpoint - StatusStale = "stale" // l'ultima lettura riuscita e' vecchia - StatusUnavailable = "unavailable" // nessuna lettura riuscita + StatusFresh = "fresh" // just read from the endpoint + StatusStale = "stale" // the last successful read is old + StatusUnavailable = "unavailable" // no successful read at all ) type State struct { Schema int `json:"schema"` GeneratedAt time.Time `json:"generated_at"` Quota Quota `json:"quota"` - // Compact e' cio' che va nel panel, gia' scelto. nil quando non c'e' nulla - // da mostrare: il plasmoide disegna un trattino, non uno zero. + // Compact is what goes in the panel, already decided. nil when there is + // nothing to show: the plasmoid draws a dash, not a zero. Compact *Compact `json:"compact"` - // Windows e' il dettaglio per il popup, incluse le finestre per modello. + // Windows is the detail for the popup, per-model windows included. Windows []Window `json:"windows"` - // ExtraUsageEnabled: con i crediti attivi il 100% non blocca piu'. + // ExtraUsageEnabled: with credits on, 100% no longer blocks. ExtraUsageEnabled bool `json:"extra_usage_enabled"` - // Local e' quel che dicono i transcript sul disco. Non e' una quota - i - // token si conoscono, i limiti no - ma e' l'unica cosa vera che resta - // quando l'endpoint non risponde. + // Local is what the transcripts on disk say. It is not a quota - the + // tokens are known, the limits are not - but it is the only true thing + // left when the endpoint does not answer. Local *Local `json:"local,omitempty"` - // Account e' l'identita' del piano configurato. Cambia solo con un - // logout/login, quindi il demone lo rilegge di rado. + // Account is the identity of the configured plan. It only changes on + // logout/login, so the daemon re-reads it rarely. Account *Account `json:"account,omitempty"` } -type Account struct { - Email string `json:"email,omitempty"` - Name string `json:"name,omitempty"` - // Plan e' un nome di prodotto ("Max 20x"), non testo di interfaccia: non - // si traduce, quindi puo' stare qui. - Plan string `json:"plan,omitempty"` +type Quota struct { + Status string `json:"status"` + // FetchedAt is the moment of the last SUCCESSFUL read, not of this round: + // it is what tells how much the number on screen can be trusted. + FetchedAt *time.Time `json:"fetched_at,omitempty"` + Error string `json:"error,omitempty"` + // NeedsAuth separates "log in again" from "try later". The plasmoid must + // be able to tell the user which of the two applies. + NeedsAuth bool `json:"needs_auth,omitempty"` } -// WithAccount allega l'identita'. Puo' mancare - il profilo e' una richiesta -// in piu' che puo' fallire per conto suo - e in quel caso il popup semplicemente -// non mostra la testata. -func (s *State) WithAccount(p *anthropic.Profile) *State { - if s == nil || p == nil { - return s - } - s.Account = &Account{Email: p.Email, Name: p.Name, Plan: p.Plan} - return s +// Compact is the decision already made for the panel: Primary is the +// constraint that will be hit first, and the bar shows the same figure. +type Compact struct { + Primary Window `json:"primary"` + Secondary *Window `json:"secondary,omitempty"` +} + +type Window struct { + Kind string `json:"kind"` + Group string `json:"group"` + Percent int `json:"percent"` + Severity string `json:"severity,omitempty"` + ResetsAt *time.Time `json:"resets_at,omitempty"` + IsActive bool `json:"is_active"` + // Model is set only for scoped windows, with the name the server sends. + // It is not a closed set: render it as it arrives. + Model string `json:"model,omitempty"` } type Local struct { @@ -78,15 +89,45 @@ type Local struct { WeekTokens int64 `json:"week_tokens"` MonthTokens int64 `json:"month_tokens"` Messages int `json:"messages"` - // Models e' il consumo per modello sui 30 giorni, la stessa finestra di Daily. + // Models and Daily cover the same span, so the legend and the chart + // describe the same period. Models []transcript.ModelUsage `json:"models,omitempty"` - // Daily e' la serie giorno per giorno, suddivisa per modello. - Daily []transcript.DayUsage `json:"daily,omitempty"` + Daily []transcript.DayUsage `json:"daily,omitempty"` +} + +type Account struct { + Email string `json:"email,omitempty"` + Name string `json:"name,omitempty"` + // Plan is a product name ("Max 20x"), not interface text: it is not + // translated, so it belongs here. + Plan string `json:"plan,omitempty"` } -// WithLocal allega i dati locali. Vengono allegati sempre, non solo in -// degrado: sapere quando si e' lavorato l'ultima volta e' utile comunque, e -// il costo e' gia' pagato dalla scansione. +func fromAPI(w anthropic.Window) Window { + return Window{ + Kind: w.Kind, Group: w.Group, Percent: w.Percent, Severity: w.Severity, + ResetsAt: w.ResetsAt, IsActive: w.IsActive, Model: w.Model, + } +} + +// FromUsage builds the state from a successful read. +func FromUsage(u *anthropic.Usage, now time.Time) *State { + s := &State{ + Schema: SchemaVersion, + GeneratedAt: now, + Quota: Quota{Status: StatusFresh, FetchedAt: &now}, + ExtraUsageEnabled: u.ExtraUsageEnabled, + } + for _, w := range u.Windows { + s.Windows = append(s.Windows, fromAPI(w)) + } + s.Compact = pickCompact(s.Windows) + return s +} + +// WithLocal attaches the local data. It is attached always, not only when +// degraded: knowing when work last happened is useful anyway, and the scan has +// already paid for it. func (s *State) WithLocal(a *transcript.Activity) *State { if s == nil || a == nil { return s @@ -109,12 +150,38 @@ func (s *State) WithLocal(a *transcript.Activity) *State { return s } -// Stale e' lo stato quando la lettura e' fallita ma ne avevamo una buona di -// recente: si mostrano i numeri vecchi, dicendo che sono vecchi. +// WithAccount attaches the identity. It may be missing - the profile is an +// extra request that can fail on its own - and then the popup simply shows no +// account line. +func (s *State) WithAccount(p *anthropic.Profile) *State { + if s == nil || p == nil { + return s + } + s.Account = &Account{Email: p.Email, Name: p.Name, Plan: p.Plan} + return s +} + +// Unavailable is the state to write when the quota could not be read. This is +// not an error to hide: the plasmoid must be able to say explicitly that the +// number is missing, instead of showing an old one as if it were good. +func Unavailable(err error, needsAuth bool, now time.Time) *State { + msg := "" + if err != nil { + msg = err.Error() + } + return &State{ + Schema: SchemaVersion, + GeneratedAt: now, + Quota: Quota{Status: StatusUnavailable, Error: msg, NeedsAuth: needsAuth}, + } +} + +// Stale is the state when the read failed but we had a good one recently: show +// the old numbers, saying they are old. // -// Le finestre gia' scadute vengono scartate: dopo un reset la vecchia -// percentuale non e' solo stantia, e' falsa - direbbe "90% usato" di una -// finestra che nel frattempo e' tornata a zero. +// Windows that have already reset are dropped: after a reset the old +// percentage is not merely stale, it is false - it would claim "90% used" of a +// window that has since gone back to zero. func Stale(prev *anthropic.Usage, fetchedAt time.Time, err error, now time.Time) *State { s := &State{ Schema: SchemaVersion, @@ -134,86 +201,19 @@ func Stale(prev *anthropic.Usage, fetchedAt time.Time, err error, now time.Time) } } if len(s.Windows) == 0 { - // Non e' rimasto nulla di vero da mostrare. + // Nothing true is left to show. return Unavailable(err, false, now) } s.Compact = pickCompact(s.Windows) return s } -type Quota struct { - Status string `json:"status"` - // FetchedAt e' l'istante dell'ultima lettura riuscita, non di questo giro: - // e' quello che dice quanto ci si puo' fidare del numero a schermo. - FetchedAt *time.Time `json:"fetched_at,omitempty"` - Error string `json:"error,omitempty"` - // NeedsAuth distingue "rifai il login" da "riprova piu' tardi". Il - // plasmoide deve poter dire all'utente quale delle due cose fare. - NeedsAuth bool `json:"needs_auth,omitempty"` -} - -// Compact e' la decisione gia' presa per il panel: Primary e' il vincolo che si -// tocca per primo, Secondary l'altra finestra, resa come barra sottile. -type Compact struct { - Primary Window `json:"primary"` - Secondary *Window `json:"secondary,omitempty"` -} - -type Window struct { - Kind string `json:"kind"` - Group string `json:"group"` - Percent int `json:"percent"` - Severity string `json:"severity,omitempty"` - ResetsAt *time.Time `json:"resets_at,omitempty"` - IsActive bool `json:"is_active"` - // Model e' valorizzato solo per le finestre scoped, col nome che manda il - // server. Non e' un elenco chiuso: si rende come arriva. - Model string `json:"model,omitempty"` -} - -func fromAPI(w anthropic.Window) Window { - return Window{ - Kind: w.Kind, Group: w.Group, Percent: w.Percent, Severity: w.Severity, - ResetsAt: w.ResetsAt, IsActive: w.IsActive, Model: w.Model, - } -} - -// FromUsage costruisce lo stato da una lettura riuscita. -func FromUsage(u *anthropic.Usage, now time.Time) *State { - s := &State{ - Schema: SchemaVersion, - GeneratedAt: now, - Quota: Quota{Status: StatusFresh, FetchedAt: &now}, - ExtraUsageEnabled: u.ExtraUsageEnabled, - } - for _, w := range u.Windows { - s.Windows = append(s.Windows, fromAPI(w)) - } - s.Compact = pickCompact(s.Windows) - return s -} - -// Unavailable e' lo stato da scrivere quando la quota non si e' potuta leggere. -// Non e' un errore da nascondere: il plasmoide deve poter dire esplicitamente -// che il numero non c'e', invece di mostrarne uno vecchio come se fosse buono. -func Unavailable(err error, needsAuth bool, now time.Time) *State { - msg := "" - if err != nil { - msg = err.Error() - } - return &State{ - Schema: SchemaVersion, - GeneratedAt: now, - Quota: Quota{Status: StatusUnavailable, Error: msg, NeedsAuth: needsAuth}, - } -} - -// pickCompact sceglie cosa mostrare nel panel. +// pickCompact chooses what goes in the panel. // -// I candidati sono solo la sessione 5h e la settimana complessiva: sono i due -// muri veri. Le finestre per modello sono dettaglio da popup - una scoped alta -// non blocca, si cambia modello. Primary e' la piu' alta delle due, cioe' il -// vincolo che si tocca per primo. +// The candidates are only the 5-hour session and the overall week: those are +// the real walls. Per-model windows are popup detail - a high scoped window +// does not block, you switch model. Primary is the higher of the two, that is, +// the constraint hit first. func pickCompact(windows []Window) *Compact { var session, weekly *Window for i := range windows { @@ -233,15 +233,15 @@ func pickCompact(windows []Window) *Compact { return &Compact{Primary: *session} } primary, secondary := session, weekly - // A parita' vince la settimana: e' quella che ci mette giorni a scendere, - // mentre la sessione si ricarica da sola in poche ore. + // On a tie the week wins: it takes days to come down, while the session + // refills on its own within hours. if weekly.Percent >= session.Percent { primary, secondary = weekly, session } return &Compact{Primary: *primary, Secondary: secondary} } -// Path e' $XDG_CONFIG_HOME/dipstick/state.json, con ~/.config come fallback. +// Path is $XDG_CONFIG_HOME/dipstick/state.json, falling back to ~/.config. func Path() (string, error) { dir, err := os.UserConfigDir() if err != nil { @@ -258,12 +258,12 @@ func (s *State) Marshal() ([]byte, error) { return append(raw, '\n'), nil } -// Write scrive lo stato in modo atomico. +// Write stores the state atomically. // -// Il rename e' il punto: il plasmoide rilegge il file a intervallo e senza -// coordinamento: se scrivessimo in place, prima o poi leggerebbe meta' JSON. -// Con write-su-temporaneo + rename vede sempre o il vecchio o il nuovo, mai -// qualcosa a meta'. +// The rename is the point: the plasmoid re-reads the file on a timer, with no +// coordination. Writing in place would eventually hand it half a JSON +// document; with write-to-temp plus rename it always sees either the old one +// or the new one, never something in between. func (s *State) Write() error { path, err := Path() if err != nil { @@ -276,15 +276,27 @@ func (s *State) Write() error { if err != nil { return err } - tmp := path + ".tmp" - // 0644: qui non ci sono segreti - solo percentuali - e il plasmoide gira - // nella sessione dell'utente. Il token sta altrove, a 0600. - if err := os.WriteFile(tmp, raw, 0o644); err != nil { + + // A unique temporary name: the daemon is not the only writer - `dipstick + // state --write` exists too - and a shared temp file could be interleaved. + tmp, err := os.CreateTemp(filepath.Dir(path), "state-*.json") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + + // 0644: there are no secrets here, only percentages, and the plasmoid runs + // in the user's session. The token lives elsewhere, at 0600. + if err := tmp.Chmod(0o644); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(raw); err != nil { + tmp.Close() return err } - if err := os.Rename(tmp, path); err != nil { - os.Remove(tmp) + if err := tmp.Close(); err != nil { return err } - return nil + return os.Rename(tmp.Name(), path) } diff --git a/internal/state/state_test.go b/internal/state/state_test.go index 492f923..5ee8698 100644 --- a/internal/state/state_test.go +++ b/internal/state/state_test.go @@ -2,7 +2,9 @@ package state import ( "encoding/json" + "errors" "os" + "path/filepath" "testing" "time" @@ -30,17 +32,17 @@ func TestFromUsageRealShape(t *testing.T) { t.Errorf("schema=%d status=%q", s.Schema, s.Quota.Status) } if len(s.Windows) != 3 { - t.Errorf("windows = %d, attese 3 (le scoped restano per il popup)", len(s.Windows)) + t.Errorf("windows = %d, want 3 (scoped ones stay for the popup)", len(s.Windows)) } - // Settimana al 30 contro sessione al 12: nel panel va la settimana. + // Week at 30 against session at 12: the week goes in the panel. if s.Compact == nil || s.Compact.Primary.Kind != anthropic.KindWeeklyAll { t.Fatalf("compact.primary = %+v", s.Compact) } if s.Compact.Primary.Percent != 30 { - t.Errorf("primary.percent = %d, atteso 30", s.Compact.Primary.Percent) + t.Errorf("primary.percent = %d, want 30", s.Compact.Primary.Percent) } if s.Compact.Secondary == nil || s.Compact.Secondary.Percent != 12 { - t.Errorf("secondary = %+v, attesa la sessione al 12", s.Compact.Secondary) + t.Errorf("secondary = %+v, want the session at 12", s.Compact.Secondary) } } @@ -51,11 +53,11 @@ func TestPickCompactPrefersTheTighterWindow(t *testing.T) { wantKind string wantPrimaryPct int }{ - {"sessione piu' alta", 80, 30, anthropic.KindSession, 80}, - {"settimana piu' alta", 10, 55, anthropic.KindWeeklyAll, 55}, - // A parita' vince la settimana: la sessione si ricarica in ore, la - // settimana no. - {"parita'", 40, 40, anthropic.KindWeeklyAll, 40}, + {"session higher", 80, 30, anthropic.KindSession, 80}, + {"week higher", 10, 55, anthropic.KindWeeklyAll, 55}, + // On a tie the week wins: the session refills within hours, the week + // does not. + {"tie", 40, 40, anthropic.KindWeeklyAll, 40}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -64,33 +66,33 @@ func TestPickCompactPrefersTheTighterWindow(t *testing.T) { {Kind: anthropic.KindWeeklyAll, Percent: tc.weekly}, }) if c == nil || c.Primary.Kind != tc.wantKind || c.Primary.Percent != tc.wantPrimaryPct { - t.Fatalf("primary = %+v, atteso %s@%d", c, tc.wantKind, tc.wantPrimaryPct) + t.Fatalf("primary = %+v, want %s@%d", c, tc.wantKind, tc.wantPrimaryPct) } if c.Secondary == nil { - t.Error("secondary mancante: la barra sottile resta senza dato") + t.Error("secondary missing: the popup loses the other window") } }) } } -// Le finestre per modello non devono mai finire nel panel: una scoped alta non -// blocca, si cambia modello. +// Per-model windows must never end up in the panel: a high scoped window does +// not block, you switch model. func TestPickCompactIgnoresScopedWindows(t *testing.T) { c := pickCompact([]Window{ {Kind: anthropic.KindWeeklyScoped, Percent: 99, Model: "Fable"}, {Kind: anthropic.KindSession, Percent: 10}, }) if c == nil || c.Primary.Kind != anthropic.KindSession { - t.Fatalf("primary = %+v, attesa la sessione", c) + t.Fatalf("primary = %+v, want the session", c) } if c.Secondary != nil { - t.Errorf("secondary = %+v, atteso nil senza weekly_all", c.Secondary) + t.Errorf("secondary = %+v, want nil without weekly_all", c.Secondary) } } func TestPickCompactNoWindows(t *testing.T) { if c := pickCompact(nil); c != nil { - t.Errorf("compact = %+v, atteso nil per far disegnare un trattino", c) + t.Errorf("compact = %+v, want nil so a dash gets drawn", c) } } @@ -101,15 +103,15 @@ func TestUnavailableCarriesTheReason(t *testing.T) { t.Errorf("quota = %+v", s.Quota) } if s.Compact != nil { - t.Error("compact deve essere nil: senza dato non si mostra uno zero") + t.Error("compact must be nil: with no data we do not show a zero") } if s.Quota.Error == "" { - t.Error("errore perso: il plasmoide non puo' spiegare cosa non va") + t.Error("error lost: the plasmoid cannot explain what is wrong") } } -// Lo schema e' il contratto col plasmoide: se cambiano i nomi dei campi, QML -// smette di leggere. Questo test lo rende un cambiamento deliberato. +// The schema is the contract with the plasmoid: if the field names change, +// QML stops reading. This test makes that a deliberate change. func TestJSONFieldNames(t *testing.T) { now := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC) raw, err := FromUsage(fixtureUsage(t), now).Marshal() @@ -122,7 +124,7 @@ func TestJSONFieldNames(t *testing.T) { } for _, k := range []string{"schema", "generated_at", "quota", "compact", "windows", "extra_usage_enabled"} { if _, ok := m[k]; !ok { - t.Errorf("campo di primo livello mancante: %q", k) + t.Errorf("missing top-level field: %q", k) } } var c struct { @@ -139,6 +141,72 @@ func TestJSONFieldNames(t *testing.T) { t.Fatal(err) } if c.Primary.Kind == "" || c.Primary.Percent == nil || c.Secondary == nil { - t.Errorf("compact incompleto: %+v", c) + t.Errorf("incomplete compact: %+v", c) + } +} + +// The state file is read by a process that does not coordinate with the +// writer: it must never see a partial document, and it must be readable. +func TestWriteIsAtomicAndReadable(t *testing.T) { + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", dir) + + st := FromUsage(fixtureUsage(t), time.Now()) + if err := st.Write(); err != nil { + t.Fatal(err) + } + path, _ := Path() + + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if perm := info.Mode().Perm(); perm != 0o644 { + t.Errorf("permissions = %o, want 644", perm) + } + + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var back State + if err := json.Unmarshal(raw, &back); err != nil { + t.Fatalf("what was written is not valid JSON: %v", err) + } + if back.Schema != SchemaVersion || back.Compact == nil { + t.Errorf("round trip lost data: %+v", back) + } + + // No temporary file may survive: the plasmoid globs nothing, but a stray + // half-written state.json look-alike is still litter in the user's config. + entries, _ := os.ReadDir(filepath.Dir(path)) + for _, e := range entries { + if e.Name() != "state.json" { + t.Errorf("leftover file after the write: %s", e.Name()) + } + } +} + +// Rewriting must leave exactly one file, whatever the previous content was. +func TestWriteOverwritesCleanly(t *testing.T) { + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", dir) + now := time.Now() + + if err := FromUsage(fixtureUsage(t), now).Write(); err != nil { + t.Fatal(err) + } + if err := Unavailable(errors.New("boom"), true, now).Write(); err != nil { + t.Fatal(err) + } + + path, _ := Path() + raw, _ := os.ReadFile(path) + var back State + if err := json.Unmarshal(raw, &back); err != nil { + t.Fatal(err) + } + if back.Quota.Status != StatusUnavailable || back.Compact != nil { + t.Errorf("the second write did not replace the first: %+v", back.Quota) } } diff --git a/internal/transcript/transcript.go b/internal/transcript/transcript.go index a6d2143..70f89cc 100644 --- a/internal/transcript/transcript.go +++ b/internal/transcript/transcript.go @@ -1,18 +1,20 @@ -// Package transcript legge i log di sessione di Claude Code per stimare -// l'attivita' recente quando l'endpoint della quota non risponde. +// Package transcript reads Claude Code's session logs to estimate recent +// activity when the quota endpoint does not answer. // -// ~/.claude/projects/ e' SOLA LETTURA: sono i log veri dell'utente, e Claude -// Code ci sta scrivendo mentre dipstick li legge. Qui si apre in lettura e -// basta, e nessun file di stato o cache finisce mai dentro quell'albero. +// ~/.claude/projects/ is READ-ONLY: those are the user's real logs, and Claude +// Code is writing to them while dipstick reads. Files are opened for reading +// only, and no cache or state file ever lands inside that tree. // -// I dati locali non sono una quota: conoscono i token, non i limiti. Servono a -// sapere se c'e' stata attivita' di recente - da cui la cadenza adattiva del -// polling - e a mostrare qualcosa di onesto quando la percentuale manca. +// Local data is not a quota: it knows the tokens, not the limits. It exists to +// tell whether there has been recent activity - which drives the adaptive poll +// interval - and to show something honest when the percentage is missing. package transcript import ( "bufio" "encoding/json" + "errors" + "fmt" "io/fs" "os" "path/filepath" @@ -20,7 +22,7 @@ import ( "time" ) -// Root e' l'albero dei transcript. Sola lettura, sempre. +// Root is the transcript tree. Read-only, always. func Root() (string, error) { home, err := os.UserHomeDir() if err != nil { @@ -29,60 +31,77 @@ func Root() (string, error) { return filepath.Join(home, ".claude", "projects"), nil } -// Activity e' quanto si riesce a dire guardando solo i file locali. +// Activity is everything that can be said by looking at local files alone. type Activity struct { ScannedAt time.Time - LastActivity time.Time // zero se non si e' trovato nulla - SessionTokens int64 // ultime 5 ore - TodayTokens int64 // da mezzanotte locale - WeekTokens int64 // ultimi 7 giorni - MonthTokens int64 // ultimi 30 giorni - Messages int // messaggi distinti conteggiati - FilesScanned int - - // Models e' il consumo per modello sui 30 giorni, cioe' la stessa finestra - // del grafico giornaliero che sta sotto: legenda e barre devono parlare - // dello stesso periodo. + LastActivity time.Time // zero if nothing was found + SessionTokens int64 // last 5 hours + TodayTokens int64 // since local midnight + WeekTokens int64 // last 7 days + MonthTokens int64 // the same span the daily series covers + + Messages int // distinct messages counted + FilesScanned int + + // Models is per-model consumption over the same span as Daily, so that the + // legend and the chart describe the same period. Models []ModelUsage - // Daily e' il consumo giorno per giorno, suddiviso per modello. Ordinato - // dal piu' vecchio al piu' recente, un elemento per giorno anche quando e' - // a zero: un grafico con i giorni vuoti saltati mentirebbe sulla forma. + // Daily is day-by-day consumption, split by model. Oldest first, one entry + // per day even when it is zero: a chart that skips empty days would + // compress time and make intermittent work look steady. Daily []DayUsage } -// DayUsage e' un giorno di calendario locale. -type DayUsage struct { - Date string `json:"date"` // YYYY-MM-DD, fuso locale - Tokens int64 `json:"tokens"` - Models map[string]int64 `json:"models,omitempty"` -} - -// ModelUsage e' quanto e' costato un modello nella settimana. +// ModelUsage is what one model cost over the scanned span. type ModelUsage struct { - // ID e' l'identificatore cosi' come compare nei transcript - // ("claude-opus-5"). Non si normalizza qui: l'elenco non e' chiuso e i - // nomi li decide chi genera i log. + // ID is the identifier exactly as it appears in the transcripts + // ("claude-opus-5"). It is not normalised here: the set is not closed and + // the names are chosen by whoever writes the logs. ID string `json:"id"` Tokens int64 `json:"tokens"` Messages int `json:"messages"` } +// DayUsage is one local calendar day. +type DayUsage struct { + Date string `json:"date"` // YYYY-MM-DD, local time + Tokens int64 `json:"tokens"` + Models map[string]int64 `json:"models,omitempty"` +} + const ( sessionWindow = 5 * time.Hour weekWindow = 7 * 24 * time.Hour - monthWindow = 30 * 24 * time.Hour + + // dailyDays is how many calendar days the chart covers. + dailyDays = 30 + + // maxLine bounds one transcript line. Tool output makes these long, so the + // scanner's default buffer is far too small. + maxLine = 16 * 1024 * 1024 ) -// midnight e' l'inizio del giorno corrente nel fuso locale. "Oggi" e' un -// concetto di calendario, non una finestra scorrevole: alle 02:00 di notte -// "oggi" sono due ore, non ventiquattro. +// midnight is the start of the current day in local time. "Today" is a +// calendar notion, not a rolling window: at 02:00, today is two hours old, not +// twenty-four. func midnight(now time.Time) time.Time { y, m, d := now.Date() return time.Date(y, m, d, 0, 0, 0, 0, now.Location()) } -// Una riga di transcript, ridotta ai campi che servono. +// spanStart is the oldest instant every total covers. +// +// It is a calendar boundary, not a rolling one, because the daily series is +// made of calendar days. Using `now - 30*24h` for the totals while the chart +// started at a midnight left a sliver of up to a day whose messages counted +// towards the month and the per-model legend but belonged to no drawn column: +// they vanished from the chart without a trace. +func spanStart(now time.Time) time.Time { + return midnight(now).AddDate(0, 0, -(dailyDays - 1)) +} + +// One transcript line, reduced to the fields that matter. type line struct { Timestamp string `json:"timestamp"` RequestID string `json:"requestId"` @@ -103,9 +122,10 @@ func (l *line) tokens() int64 { return u.Input + u.CacheCreat + u.CacheRead + u.Output } -// dedupKey identifica un messaggio. Serve perche' lo stesso messaggio compare -// piu' volte nei transcript - misurato sull'albero reale: 3927 righe con usage -// per 2026 id distinti. Sommare senza deduplicare quasi raddoppia il totale. +// dedupKey identifies a message. It is needed because the same message appears +// several times in the transcripts - measured on a real tree: 3927 lines with +// usage for 2026 distinct ids. Summing without deduplicating nearly doubles +// the total. func (l *line) dedupKey() string { if l.Message.ID != "" { return l.Message.ID @@ -113,174 +133,208 @@ func (l *line) dedupKey() string { return l.RequestID } -// Scan attraversa i transcript e riassume l'attivita' fino a `window` fa. +// message is one deduplicated message. +type message struct { + at time.Time + model string + tokens int64 +} + +// Scan walks the transcripts and summarises recent activity. +// +// The mtime filter is not a heuristic: a file untouched for N cannot contain +// lines newer than N. On a real tree it takes the 5-hour window from ~850ms to +// ~23ms, and the full 30 days to under a second. // -// Il filtro per mtime non e' un'euristica: un file non toccato da N tempo non -// puo' contenere righe piu' recenti di N. Sull'albero reale porta la scansione -// della finestra 5h da ~850 ms a ~23 ms. +// The returned Activity is always usable, even when the error is non-nil: a +// file that could not be read fully is reported so the caller can say the +// totals are incomplete, rather than silently presenting them as whole. func Scan(root string, now time.Time) (*Activity, error) { act := &Activity{ScannedAt: now} - // Il filtro per mtime usa la finestra piu' ampia: un file non toccato da - // 30 giorni non puo' contenere righe piu' recenti. - cutoff := now.Add(-monthWindow) - w := windows{ - session: now.Add(-sessionWindow), - today: midnight(now), - week: now.Add(-weekWindow), - } - seen := make(map[string]struct{}, 16384) - models := map[string]*ModelUsage{} - days := map[string]*DayUsage{} + start := spanStart(now) + + // The mtime cutoff is deliberately the wider of the two bounds: it only + // decides which files to open, and skipping one that might hold relevant + // lines would lose data. + mtimeCutoff := now.Add(-(dailyDays + 1) * 24 * time.Hour) + + seen := make(map[string]message, 16384) + var problems []error err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err != nil { - // Una directory illeggibile non e' motivo per buttare via il - // resto della scansione: si salta e si prosegue. + // An unreadable directory is no reason to throw away the rest of + // the scan: skip it and carry on. return nil } if d.IsDir() || filepath.Ext(path) != ".jsonl" { return nil } info, err := d.Info() - if err != nil || info.ModTime().Before(cutoff) { + if err != nil || info.ModTime().Before(mtimeCutoff) { + return nil + } + if err := scanFile(path, start, seen); err != nil { + problems = append(problems, err) return nil } act.FilesScanned++ - scanFile(path, w, cutoff, seen, models, days, act) return nil }) if err != nil { - return nil, err - } - act.Messages = len(seen) - act.Models = sortedModels(models) - act.Daily = dailySeries(days, now, dailyDays) - return act, nil -} - -// dailyDays e' quanti giorni copre il grafico. -const dailyDays = 30 - -// dailySeries produce una serie continua dal piu' vecchio al piu' recente. -// I giorni senza attivita' restano nella serie con zero: saltarli -// comprimerebbe il tempo e farebbe sembrare continuo un lavoro a singhiozzo. -func dailySeries(days map[string]*DayUsage, now time.Time, n int) []DayUsage { - out := make([]DayUsage, 0, n) - start := midnight(now).AddDate(0, 0, -(n - 1)) - for i := 0; i < n; i++ { - key := start.AddDate(0, 0, i).Format("2006-01-02") - if d, ok := days[key]; ok { - out = append(out, *d) - continue - } - out = append(out, DayUsage{Date: key}) + return act, err } - return out -} -// sortedModels ordina dal piu' costoso al meno, che e' l'ordine in cui -// interessano. -func sortedModels(m map[string]*ModelUsage) []ModelUsage { - out := make([]ModelUsage, 0, len(m)) - for _, v := range m { - out = append(out, *v) + act.aggregate(seen, now) + if len(problems) > 0 { + return act, fmt.Errorf("%d transcript(s) read incompletely: %w", + len(problems), errors.Join(problems...)) } - sort.Slice(out, func(i, j int) bool { - if out[i].Tokens != out[j].Tokens { - return out[i].Tokens > out[j].Tokens - } - return out[i].ID < out[j].ID - }) - return out -} - -// windows raccoglie i confini delle finestre, per non passarne quattro in fila. -type windows struct { - session, today, week time.Time + return act, nil } -func scanFile(path string, w windows, cutoff time.Time, seen map[string]struct{}, models map[string]*ModelUsage, days map[string]*DayUsage, act *Activity) { - // os.Open apre in sola lettura: e' il vincolo del progetto, reso esplicito. +// scanFile folds one file into seen, keeping the largest usage per message. +func scanFile(path string, start time.Time, seen map[string]message) error { + // os.Open is read-only: the project's constraint, made explicit. f, err := os.Open(path) if err != nil { - return + return fmt.Errorf("%s: %w", path, err) } defer f.Close() sc := bufio.NewScanner(f) - // I transcript contengono righe molto lunghe (contenuto dei tool): - // il buffer di default va in errore e la scansione si fermerebbe a meta'. - sc.Buffer(make([]byte, 0, 64*1024), 16*1024*1024) + sc.Buffer(make([]byte, 0, 64*1024), maxLine) for sc.Scan() { var l line - // Claude Code sta scrivendo mentre leggiamo: l'ultima riga puo' essere - // tronca. Si salta, e al giro dopo sara' completa. + // Claude Code writes while we read: the last line can be truncated. + // Skip it; the next pass will find it complete. if json.Unmarshal(sc.Bytes(), &l) != nil { continue } if l.Message.Usage == nil { continue } - // non e' una chiamata al modello: non consuma quota. + // is not a call to the model: it consumes no quota. if l.Message.Model == "" { continue } - ts, err := time.Parse(time.RFC3339, l.Timestamp) - if err != nil || ts.Before(cutoff) { + at, err := time.Parse(time.RFC3339, l.Timestamp) + if err != nil || at.Before(start) { continue } key := l.dedupKey() if key == "" { continue } - if _, dup := seen[key]; dup { + + // Duplicates are not identical copies: they are progressive snapshots + // of the same message, so a later one can report more output tokens + // than an earlier one. Keeping the largest keeps the finished figure; + // keeping the first one seen understates it. + n := l.tokens() + if prev, ok := seen[key]; ok && prev.tokens >= n { continue } - seen[key] = struct{}{} + seen[key] = message{at: at, model: l.Message.Model, tokens: n} + } - if ts.After(act.LastActivity) { - act.LastActivity = ts + // Without this check a line over maxLine, or an I/O error, would stop the + // scan and lose the rest of the file with no trace: a figure too low, + // presented as if it were complete. + if err := sc.Err(); err != nil { + return fmt.Errorf("%s: %w", path, err) + } + return nil +} + +// aggregate turns deduplicated messages into the totals and the series. +func (a *Activity) aggregate(seen map[string]message, now time.Time) { + sessionStart := now.Add(-sessionWindow) + todayStart := midnight(now) + weekStart := now.Add(-weekWindow) + + models := map[string]*ModelUsage{} + days := map[string]*DayUsage{} + + for _, m := range seen { + if m.at.After(a.LastActivity) { + a.LastActivity = m.at } - n := l.tokens() - act.MonthTokens += n - if !ts.Before(w.week) { - act.WeekTokens += n + a.MonthTokens += m.tokens + if !m.at.Before(weekStart) { + a.WeekTokens += m.tokens + } + if !m.at.Before(todayStart) { + a.TodayTokens += m.tokens + } + if !m.at.Before(sessionStart) { + a.SessionTokens += m.tokens } - id := l.Message.Model - if id != "" { - m := models[id] - if m == nil { - m = &ModelUsage{ID: id} - models[id] = m + if m.model != "" { + mu := models[m.model] + if mu == nil { + mu = &ModelUsage{ID: m.model} + models[m.model] = mu } - m.Tokens += n - m.Messages++ + mu.Tokens += m.tokens + mu.Messages++ } - // Il giorno e' quello locale in cui il messaggio e' stato prodotto. - dayKey := ts.Local().Format("2006-01-02") - d := days[dayKey] + key := m.at.Local().Format("2006-01-02") + d := days[key] if d == nil { - d = &DayUsage{Date: dayKey, Models: map[string]int64{}} - days[dayKey] = d + d = &DayUsage{Date: key, Models: map[string]int64{}} + days[key] = d } - d.Tokens += n - if id != "" { - d.Models[id] += n + d.Tokens += m.tokens + if m.model != "" { + d.Models[m.model] += m.tokens } - if !ts.Before(w.today) { - act.TodayTokens += n + } + + a.Messages = len(seen) + a.Models = sortedModels(models) + a.Daily = dailySeries(days, now) +} + +// sortedModels orders from most expensive to least, which is the order they +// matter in. +func sortedModels(m map[string]*ModelUsage) []ModelUsage { + out := make([]ModelUsage, 0, len(m)) + for _, v := range m { + out = append(out, *v) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Tokens != out[j].Tokens { + return out[i].Tokens > out[j].Tokens } - if !ts.Before(w.session) { - act.SessionTokens += n + return out[i].ID < out[j].ID + }) + return out +} + +// dailySeries produces a continuous series, oldest first. Days without +// activity stay in the series with a zero: dropping them would compress time +// and make intermittent work look steady. +func dailySeries(days map[string]*DayUsage, now time.Time) []DayUsage { + out := make([]DayUsage, 0, dailyDays) + start := spanStart(now) + for i := 0; i < dailyDays; i++ { + key := start.AddDate(0, 0, i).Format("2006-01-02") + if d, ok := days[key]; ok { + out = append(out, *d) + continue } + out = append(out, DayUsage{Date: key}) } + return out } -// Idle dice da quanto non si vede attivita'. Con LastActivity a zero - nessun -// dato - torna false: meglio interrogare la rete che assumere di essere fermi. +// Idle says how long there has been no activity. With LastActivity at zero - +// no data at all - it returns false: better to ask the network than to assume +// we are idle. func (a *Activity) Idle(threshold time.Duration) bool { if a.LastActivity.IsZero() { return false diff --git a/internal/transcript/transcript_test.go b/internal/transcript/transcript_test.go index 5ae7a4a..4a29cc1 100644 --- a/internal/transcript/transcript_test.go +++ b/internal/transcript/transcript_test.go @@ -4,32 +4,33 @@ import ( "fmt" "os" "path/filepath" + "strings" "testing" "time" ) -var now = time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC) +// A fixed midday instant: far enough from midnight that "today" and a rolling +// 24 hours differ, which is exactly where the window bugs live. +var now = time.Date(2026, 8, 27, 12, 0, 0, 0, time.Local) func ago(d time.Duration) string { return now.Add(-d).Format(time.RFC3339) } -func msg(id, model, ts string, in, cc, cr, out int64) string { +func msg(id, model, ts string, in, cacheCreate, cacheRead, out int64) string { return fmt.Sprintf(`{"type":"assistant","timestamp":%q,"requestId":"req_%s","message":`+ `{"id":%q,"model":%q,"usage":{"input_tokens":%d,"cache_creation_input_tokens":%d,`+ - `"cache_read_input_tokens":%d,"output_tokens":%d}}}`, ts, id, id, model, in, cc, cr, out) + `"cache_read_input_tokens":%d,"output_tokens":%d}}}`, + ts, id, id, model, in, cacheCreate, cacheRead, out) } -// write crea un transcript e ne fissa l'mtime: il filtro per mtime e' il cuore -// della strategia, quindi i test devono poterlo controllare. +// write creates a transcript and pins its mtime: the mtime filter is the heart +// of the strategy, so tests must be able to control it. func write(t *testing.T, dir, name string, mtime time.Time, lines ...string) string { t.Helper() path := filepath.Join(dir, name) if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { t.Fatal(err) } - body := "" - for _, l := range lines { - body += l + "\n" - } + body := strings.Join(lines, "\n") + "\n" if err := os.WriteFile(path, []byte(body), 0o644); err != nil { t.Fatal(err) } @@ -39,99 +40,222 @@ func write(t *testing.T, dir, name string, mtime time.Time, lines ...string) str return path } -// Il caso che conta: sull'albero reale 3927 righe con usage danno 2026 id -// distinti. Senza deduplica il totale quasi raddoppia. +func scan(t *testing.T, dir string) *Activity { + t.Helper() + act, err := Scan(dir, now) + if err != nil { + t.Fatalf("scan failed: %v", err) + } + return act +} + +// The case that matters: on a real tree 3927 lines with usage yield 2026 +// distinct ids. Without deduplication the total nearly doubles. func TestScanDeduplicatesRepeatedMessages(t *testing.T) { dir := t.TempDir() dup := msg("msg_a", "claude-opus-5", ago(time.Hour), 100, 0, 0, 10) write(t, dir, "proj/a.jsonl", now, dup, dup, dup) - act, err := Scan(dir, now) - if err != nil { - t.Fatal(err) - } + act := scan(t, dir) if act.SessionTokens != 110 { - t.Errorf("SessionTokens = %d, atteso 110 (la riga vale una volta sola)", act.SessionTokens) + t.Errorf("SessionTokens = %d, want 110 (the line counts once)", act.SessionTokens) } if act.Messages != 1 { - t.Errorf("Messages = %d, atteso 1", act.Messages) + t.Errorf("Messages = %d, want 1", act.Messages) } } -// La deduplica deve valere anche fra file diversi: la stessa sessione puo' -// comparire in piu' transcript. +// Duplicates are progressive snapshots, not identical copies: the finished +// figure is the largest one, and keeping the first seen understates it. +func TestScanKeepsTheLargestUsagePerMessage(t *testing.T) { + dir := t.TempDir() + write(t, dir, "proj/a.jsonl", now, + msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 5), + msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 900), + msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 40)) + + act := scan(t, dir) + if act.SessionTokens != 1000 { + t.Errorf("SessionTokens = %d, want 1000 (the completed snapshot)", act.SessionTokens) + } + if act.Models[0].Tokens != 1000 { + t.Errorf("model total = %d, want 1000", act.Models[0].Tokens) + } + if act.Daily[len(act.Daily)-1].Tokens != 1000 { + t.Errorf("daily total = %d, want 1000", act.Daily[len(act.Daily)-1].Tokens) + } +} + +// Deduplication must hold across files too: the same session can show up in +// more than one transcript. func TestScanDeduplicatesAcrossFiles(t *testing.T) { dir := t.TempDir() m := msg("msg_shared", "claude-opus-5", ago(time.Hour), 50, 0, 0, 5) write(t, dir, "proj-a/x.jsonl", now, m) write(t, dir, "proj-b/y.jsonl", now, m) - act, _ := Scan(dir, now) - if act.SessionTokens != 55 { - t.Errorf("SessionTokens = %d, atteso 55", act.SessionTokens) + if act := scan(t, dir); act.SessionTokens != 55 { + t.Errorf("SessionTokens = %d, want 55", act.SessionTokens) } } func TestScanSplitsWindows(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, - msg("recente", "claude-opus-5", ago(2*time.Hour), 100, 0, 0, 0), // dentro le 5h - msg("vecchio", "claude-opus-5", ago(48*time.Hour), 200, 0, 0, 0), // solo nella settimana - msg("antico", "claude-opus-5", ago(10*24*time.Hour), 999, 0, 0, 0), // fuori da tutto - ) - act, _ := Scan(dir, now) + msg("recent", "claude-opus-5", ago(2*time.Hour), 100, 0, 0, 0), + msg("older", "claude-opus-5", ago(48*time.Hour), 200, 0, 0, 0), + msg("ancient", "claude-opus-5", ago(10*24*time.Hour), 999, 0, 0, 0)) + + act := scan(t, dir) if act.SessionTokens != 100 { - t.Errorf("SessionTokens = %d, atteso 100", act.SessionTokens) + t.Errorf("SessionTokens = %d, want 100", act.SessionTokens) } if act.WeekTokens != 300 { - t.Errorf("WeekTokens = %d, atteso 300", act.WeekTokens) + t.Errorf("WeekTokens = %d, want 300", act.WeekTokens) } if !act.LastActivity.Equal(now.Add(-2 * time.Hour)) { t.Errorf("LastActivity = %v", act.LastActivity) } } -// Un file con mtime vecchio non puo' contenere righe recenti: saltarlo e' -// esatto, non approssimato. Qui si verifica che venga davvero saltato. +// "Today" is a calendar day, not a rolling 24 hours: at midday, something from +// twenty hours ago happened yesterday. +func TestScanSplitsTodayWeekMonth(t *testing.T) { + dir := t.TempDir() + write(t, dir, "p/a.jsonl", now, + msg("this-morning", "claude-opus-5", ago(3*time.Hour), 10, 0, 0, 0), + msg("yesterday", "claude-opus-5", ago(20*time.Hour), 100, 0, 0, 0), + msg("this-week", "claude-opus-5", ago(4*24*time.Hour), 1000, 0, 0, 0), + msg("this-month", "claude-opus-5", ago(20*24*time.Hour), 10000, 0, 0, 0), + msg("too-old", "claude-opus-5", ago(40*24*time.Hour), 999999, 0, 0, 0)) + + act := scan(t, dir) + if act.TodayTokens != 10 { + t.Errorf("today = %d, want 10 (local midnight, not a rolling 24h)", act.TodayTokens) + } + if act.WeekTokens != 1110 { + t.Errorf("week = %d, want 1110", act.WeekTokens) + } + if act.MonthTokens != 11110 { + t.Errorf("month = %d, want 11110", act.MonthTokens) + } +} + +// The invariant the README promises: every message in the month total is drawn +// in the chart. A rolling boundary for the totals against a calendar boundary +// for the chart left a sliver of messages counted but never drawn. +func TestMonthTotalMatchesTheChart(t *testing.T) { + dir := t.TempDir() + // Just inside the oldest drawn day, and just outside it. + firstDay := spanStart(now) + write(t, dir, "p/a.jsonl", now, + msg("oldest-drawn", "claude-opus-5", firstDay.Add(time.Minute).Format(time.RFC3339), 1000, 0, 0, 0), + msg("just-before", "claude-opus-5", firstDay.Add(-time.Minute).Format(time.RFC3339), 7777, 0, 0, 0), + msg("today", "claude-opus-5", ago(time.Hour), 1, 0, 0, 0)) + + act := scan(t, dir) + + var charted int64 + for _, d := range act.Daily { + charted += d.Tokens + } + if charted != act.MonthTokens { + t.Errorf("chart = %d, month total = %d: some messages are counted but never drawn", + charted, act.MonthTokens) + } + if act.MonthTokens != 1001 { + t.Errorf("month = %d, want 1001 (the message before the first drawn day is out)", + act.MonthTokens) + } + + var perModel int64 + for _, m := range act.Models { + perModel += m.Tokens + } + if perModel != act.MonthTokens { + t.Errorf("legend = %d, month total = %d: they must describe the same span", + perModel, act.MonthTokens) + } +} + +// A file with an old mtime cannot contain recent lines: skipping it is exact, +// not approximate. This checks it really is skipped. func TestScanSkipsFilesByModTime(t *testing.T) { dir := t.TempDir() - // Oltre la finestra piu' ampia (30 giorni), non al suo confine. - write(t, dir, "p/vecchio.jsonl", now.Add(-60*24*time.Hour), - msg("dentro-un-file-vecchio", "claude-opus-5", ago(time.Hour), 1000, 0, 0, 0)) + write(t, dir, "p/old.jsonl", now.Add(-60*24*time.Hour), + msg("inside-an-old-file", "claude-opus-5", ago(time.Hour), 1000, 0, 0, 0)) - act, _ := Scan(dir, now) + act := scan(t, dir) if act.FilesScanned != 0 { - t.Errorf("FilesScanned = %d, atteso 0", act.FilesScanned) + t.Errorf("FilesScanned = %d, want 0", act.FilesScanned) } - if act.WeekTokens != 0 { - t.Errorf("WeekTokens = %d, atteso 0", act.WeekTokens) + if act.MonthTokens != 0 { + t.Errorf("MonthTokens = %d, want 0", act.MonthTokens) } } -// Claude Code scrive mentre dipstick legge: l'ultima riga puo' essere tronca, -// e non deve far perdere le righe buone che la precedono. +// Claude Code writes while dipstick reads: the last line can be truncated, and +// that must not cost the good lines before it. func TestScanToleratesTruncatedLastLine(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, - msg("buono", "claude-opus-5", ago(time.Minute), 42, 0, 0, 0), + msg("good", "claude-opus-5", ago(time.Minute), 42, 0, 0, 0), `{"type":"assistant","timestamp":"2026-08-27T11:5`) - act, _ := Scan(dir, now) + if act := scan(t, dir); act.SessionTokens != 42 { + t.Errorf("SessionTokens = %d, want 42", act.SessionTokens) + } +} + +// A line past the scanner's limit stops the read. Reporting it is the whole +// point: silently returning a smaller number looks exactly like a quiet day. +func TestScanReportsAnOversizedLine(t *testing.T) { + dir := t.TempDir() + huge := `{"padding":"` + strings.Repeat("x", maxLine+1024) + `"}` + write(t, dir, "p/a.jsonl", now, + msg("before", "claude-opus-5", ago(time.Minute), 42, 0, 0, 0), + huge, + msg("after", "claude-opus-5", ago(time.Minute), 1000, 0, 0, 0)) + + act, err := Scan(dir, now) + if err == nil { + t.Fatal("an unreadable file must be reported, not swallowed") + } + if act == nil { + t.Fatal("the partial result must still be usable") + } if act.SessionTokens != 42 { - t.Errorf("SessionTokens = %d, atteso 42", act.SessionTokens) + t.Errorf("SessionTokens = %d: the lines before the failure should survive", + act.SessionTokens) } } -// non e' una chiamata al modello e non consuma quota. +// One bad file must not cost the others. +func TestScanKeepsGoingAfterABadFile(t *testing.T) { + dir := t.TempDir() + write(t, dir, "p/bad.jsonl", now, + `{"padding":"`+strings.Repeat("x", maxLine+1024)+`"}`) + write(t, dir, "p/good.jsonl", now, + msg("good", "claude-opus-5", ago(time.Minute), 500, 0, 0, 0)) + + act, err := Scan(dir, now) + if err == nil { + t.Error("the failure must be reported") + } + if act.SessionTokens != 500 { + t.Errorf("SessionTokens = %d, want 500 from the readable file", act.SessionTokens) + } +} + +// is not a call to the model and consumes no quota. func TestScanIgnoresSyntheticModel(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, - msg("finto", "", ago(time.Minute), 500, 0, 0, 0), - msg("vero", "claude-opus-5", ago(time.Minute), 7, 0, 0, 0)) + msg("fake", "", ago(time.Minute), 500, 0, 0, 0), + msg("real", "claude-opus-5", ago(time.Minute), 7, 0, 0, 0)) - act, _ := Scan(dir, now) - if act.SessionTokens != 7 { - t.Errorf("SessionTokens = %d, atteso 7", act.SessionTokens) + if act := scan(t, dir); act.SessionTokens != 7 { + t.Errorf("SessionTokens = %d, want 7", act.SessionTokens) } } @@ -139,34 +263,21 @@ func TestScanCountsAllTokenKinds(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, msg("m", "claude-opus-5", ago(time.Minute), 1, 20, 300, 4000)) - act, _ := Scan(dir, now) - if act.SessionTokens != 4321 { - t.Errorf("SessionTokens = %d, atteso 4321", act.SessionTokens) + if act := scan(t, dir); act.SessionTokens != 4321 { + t.Errorf("SessionTokens = %d, want 4321", act.SessionTokens) } } func TestScanMissingRootIsNotFatal(t *testing.T) { - act, err := Scan(filepath.Join(t.TempDir(), "non-esiste"), now) + act, err := Scan(filepath.Join(t.TempDir(), "does-not-exist"), now) if err != nil { - t.Fatalf("una root assente non deve essere un errore: %v", err) + t.Fatalf("a missing root must not be an error: %v", err) } if act.FilesScanned != 0 { t.Errorf("FilesScanned = %d", act.FilesScanned) } -} - -func TestIdle(t *testing.T) { - a := &Activity{ScannedAt: now, LastActivity: now.Add(-2 * time.Hour)} - if !a.Idle(time.Hour) { - t.Error("due ore di silenzio con soglia a un'ora: dovrebbe essere idle") - } - if a.Idle(3 * time.Hour) { - t.Error("soglia a tre ore: non dovrebbe essere idle") - } - // Nessun dato non vuol dire fermo: meglio interrogare la rete. - empty := &Activity{ScannedAt: now} - if empty.Idle(time.Minute) { - t.Error("senza attivita' nota non si deve concludere che sia idle") + if len(act.Daily) != dailyDays { + t.Errorf("the series must still be complete: %d days", len(act.Daily)) } } @@ -178,99 +289,62 @@ func TestScanBreaksDownByModel(t *testing.T) { msg("m3", "claude-opus-5", ago(2*time.Hour), 50, 0, 0, 0), msg("m4", "", ago(time.Hour), 999, 0, 0, 0)) - act, _ := Scan(dir, now) + act := scan(t, dir) if len(act.Models) != 2 { - t.Fatalf("modelli = %+v, attesi 2 ( escluso)", act.Models) + t.Fatalf("models = %+v, want 2 ( excluded)", act.Models) } - // Ordinati dal piu' costoso: e' l'ordine in cui interessano. + // Most expensive first: that is the order they matter in. if act.Models[0].ID != "claude-opus-5" || act.Models[0].Tokens != 150 { - t.Errorf("primo = %+v, atteso opus con 150", act.Models[0]) + t.Errorf("first = %+v, want opus with 150", act.Models[0]) } if act.Models[0].Messages != 2 { - t.Errorf("messaggi opus = %d, attesi 2", act.Models[0].Messages) + t.Errorf("opus messages = %d, want 2", act.Models[0].Messages) } if act.Models[1].ID != "claude-sonnet-5" || act.Models[1].Tokens != 10 { - t.Errorf("secondo = %+v", act.Models[1]) - } -} - -// I duplicati non devono gonfiare nemmeno il breakdown per modello. -func TestModelBreakdownDeduplicates(t *testing.T) { - dir := t.TempDir() - d := msg("dup", "claude-opus-5", ago(time.Hour), 100, 0, 0, 0) - write(t, dir, "p/a.jsonl", now, d, d, d) - act, _ := Scan(dir, now) - if len(act.Models) != 1 || act.Models[0].Tokens != 100 { - t.Errorf("modelli = %+v, atteso opus con 100", act.Models) - } -} - -// Oggi e' un concetto di calendario, non una finestra scorrevole: alle 02:00 -// "oggi" sono due ore, non ventiquattro. -func TestScanSplitsTodayWeekMonth(t *testing.T) { - dir := t.TempDir() - write(t, dir, "p/a.jsonl", now, - msg("stamattina", "claude-opus-5", ago(3*time.Hour), 10, 0, 0, 0), - msg("ieri", "claude-opus-5", ago(20*time.Hour), 100, 0, 0, 0), - msg("settimana", "claude-opus-5", ago(4*24*time.Hour), 1000, 0, 0, 0), - msg("mese", "claude-opus-5", ago(20*24*time.Hour), 10000, 0, 0, 0), - msg("troppo-vecchio", "claude-opus-5", ago(40*24*time.Hour), 999999, 0, 0, 0)) - - act, _ := Scan(dir, now) - if act.TodayTokens != 10 { - t.Errorf("oggi = %d, atteso 10 (mezzanotte locale, non 24h scorrevoli)", act.TodayTokens) - } - if act.WeekTokens != 1110 { - t.Errorf("settimana = %d, atteso 1110", act.WeekTokens) - } - if act.MonthTokens != 11110 { - t.Errorf("mese = %d, atteso 11110", act.MonthTokens) + t.Errorf("second = %+v", act.Models[1]) } } -// Il breakdown per modello copre i 30 giorni, la stessa finestra del grafico -// giornaliero: legenda e barre devono parlare dello stesso periodo. -func TestModelBreakdownCoversTheMonth(t *testing.T) { - dir := t.TempDir() - write(t, dir, "p/a.jsonl", now, - msg("recente", "claude-opus-5", ago(2*24*time.Hour), 100, 0, 0, 0), - msg("vecchio", "claude-opus-5", ago(20*24*time.Hour), 5000, 0, 0, 0), - msg("fuori", "claude-opus-5", ago(40*24*time.Hour), 999999, 0, 0, 0)) - - act, _ := Scan(dir, now) - if len(act.Models) != 1 || act.Models[0].Tokens != 5100 { - t.Errorf("modelli = %+v, atteso opus con 5100", act.Models) - } -} - -// La serie giornaliera deve essere continua: un giorno senza attivita' resta -// nella serie a zero, o il grafico comprimerebbe il tempo. +// The daily series must be continuous, or the chart compresses time. func TestDailySeriesIsContinuous(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, - msg("oggi", "claude-opus-5", ago(time.Hour), 10, 0, 0, 0), - msg("tre-giorni-fa", "claude-sonnet-5", ago(3*24*time.Hour), 70, 0, 0, 0)) + msg("today", "claude-opus-5", ago(time.Hour), 10, 0, 0, 0), + msg("three-days-ago", "claude-sonnet-5", ago(3*24*time.Hour), 70, 0, 0, 0)) - act, _ := Scan(dir, now) + act := scan(t, dir) if len(act.Daily) != dailyDays { - t.Fatalf("giorni = %d, attesi %d", len(act.Daily), dailyDays) + t.Fatalf("days = %d, want %d", len(act.Daily), dailyDays) } - // Ordinati dal piu' vecchio al piu' recente. if act.Daily[0].Date >= act.Daily[len(act.Daily)-1].Date { - t.Errorf("serie non ordinata: %s -> %s", act.Daily[0].Date, act.Daily[len(act.Daily)-1].Date) + t.Errorf("series is not ordered: %s -> %s", + act.Daily[0].Date, act.Daily[len(act.Daily)-1].Date) } last := act.Daily[len(act.Daily)-1] if last.Tokens != 10 || last.Models["claude-opus-5"] != 10 { - t.Errorf("ultimo giorno = %+v, atteso 10 token di opus", last) + t.Errorf("last day = %+v, want 10 tokens of opus", last) } - // Il giorno fra i due deve esserci, a zero. - vuoti := 0 + empty := 0 for _, d := range act.Daily { if d.Tokens == 0 { - vuoti++ + empty++ } } - if vuoti != dailyDays-2 { - t.Errorf("giorni a zero = %d, attesi %d", vuoti, dailyDays-2) + if empty != dailyDays-2 { + t.Errorf("empty days = %d, want %d", empty, dailyDays-2) + } +} + +func TestIdle(t *testing.T) { + a := &Activity{ScannedAt: now, LastActivity: now.Add(-2 * time.Hour)} + if !a.Idle(time.Hour) { + t.Error("two hours of silence with a one-hour threshold should be idle") + } + if a.Idle(3 * time.Hour) { + t.Error("with a three-hour threshold it should not be idle") + } + // No data does not mean idle: better to ask the network. + if (&Activity{ScannedAt: now}).Idle(time.Minute) { + t.Error("with no known activity we must not conclude we are idle") } } diff --git a/packaging/dipstick.service.in b/packaging/dipstick.service.in index a132907..f47f523 100644 --- a/packaging/dipstick.service.in +++ b/packaging/dipstick.service.in @@ -1,7 +1,9 @@ [Unit] -Description=dipstick — tiene aggiornata la quota Claude Max per il plasmoide -# Il servizio e' inutile senza rete, ma non deve fallire se parte prima: -# il primo giro degrada e riprova da solo. +Description=dipstick — keeps the Claude Max quota up to date for the plasmoid +# The service is useless without the network but must not fail if it starts +# first: the first round degrades and retries on its own. Wants= is required +# alongside After=, or the ordering has nothing to order against. +Wants=network-online.target After=network-online.target [Service] @@ -10,8 +12,8 @@ ExecStart=@BINDIR@/dipstick run Restart=on-failure RestartSec=30s -# Il demone legge i transcript, scrive un file di stato e parla con un solo -# host. Non gli serve altro, quindi non glielo diamo. +# The daemon reads transcripts, writes a state file and talks to a single +# host. It needs nothing else, so it is given nothing else. NoNewPrivileges=yes PrivateDevices=yes ProtectControlGroups=yes diff --git a/packaging/dipstick.spec b/packaging/dipstick.spec index ab1a30b..db03423 100644 --- a/packaging/dipstick.spec +++ b/packaging/dipstick.spec @@ -1,8 +1,8 @@ -# Spec per Fedora. +# Spec for Fedora. # -# Compilato e verificato su Fedora 44 aarch64. Non e' mai passato per COPR, che -# builda anche per altre architetture e altre versioni: se un giorno servisse, -# quella e' la prova che manca. +# Built and verified on Fedora 44 aarch64. It has never been through COPR, +# which also builds for other architectures and releases: if that is ever +# needed, that is the proof still missing. Name: dipstick Version: 0.1.0 @@ -11,9 +11,8 @@ Summary: Plasma widget showing how much Claude Max quota is left Summary(it): Widget Plasma che mostra quanta quota Claude Max resta License: GPL-3.0-or-later -# Nessun URL: il progetto non e' pubblicato da nessuna parte, e mettere un -# indirizzo che non esiste e' peggio che non metterne. Il sorgente e' un -# tarball locale, prodotto da `make dist`. +# No URL: the project is not published anywhere, and an address that does not +# exist is worse than none. The source is a local tarball from `make dist`. Source0: %{name}-%{version}.tar.gz BuildRequires: golang >= 1.24 @@ -21,15 +20,15 @@ BuildRequires: gettext BuildRequires: make BuildRequires: systemd-rpm-macros -# In locale, se Go e' installato fuori da RPM (mise, tarball ufficiale), serve -# `make rpm RPMBUILD_FLAGS=--nodeps`. In COPR il BuildRequires si risolve. +# Locally, if Go is installed outside RPM (mise, the official tarball), use +# `make rpm RPMBUILD_FLAGS=--nodeps`. In COPR the BuildRequires resolves. -# Il plasmoide non serve a niente senza Plasma, e il demone non serve a niente -# senza il plasmoide: si installano insieme perche' sono una cosa sola. +# The plasmoid is useless without Plasma, and the daemon is useless without +# the plasmoid: they install together because they are one thing. Requires: plasma-workspace >= 6.0 -# Il binario e' statico rispetto a Go: niente librerie da tracciare, e i -# debuginfo di Go in un pacchetto cosi' piccolo non valgono il peso. +# The binary is statically linked as far as Go is concerned: no libraries to +# track, and Go debuginfo in a package this small is not worth the weight. %global debug_package %{nil} %description @@ -54,8 +53,8 @@ polling e parsing fuori da plasmashell. %autosetup %build -# COPR builda senza rete: il modulo non ha dipendenze esterne, quindi non c'e' -# niente da scaricare e non serve vendoring. +# COPR builds without network access: the module has no external dependencies, +# so there is nothing to download and no vendoring needed. export GOFLAGS="-mod=mod -trimpath" export GOPATH="%{_builddir}/gopath" export GOCACHE="%{_builddir}/gocache" @@ -69,7 +68,8 @@ export GOPROXY=off export GOPATH="%{_builddir}/gopath" export GOCACHE="%{_builddir}/gocache" export GOPROXY=off -# I test non toccano la rete ne' i file dell'utente: girano anche in buildroot. +# The tests touch neither the network nor the user's files: they run in a +# buildroot too. go test ./... %post @@ -81,9 +81,9 @@ go test ./... %postun %systemd_user_postun %{name}.service -# Niente %find_lang: il catalogo vive dentro il pacchetto del plasmoide, che e' -# dove Plasma lo cerca per un applet di terze parti. Installarlo anche in -# %{_datadir}/locale lo faceva elencare due volte. +# No %find_lang: the catalogue lives inside the plasmoid package, which is +# where Plasma looks for a third-party applet. Installing it into +# %{_datadir}/locale as well had it listed twice. %files %license LICENSE %doc README.md @@ -93,4 +93,4 @@ go test ./... %changelog * Thu Aug 27 2026 Claudio Quaglia - 0.1.0-1 -- Primo pacchetto. +- First package. diff --git a/plasmoid/contents/ui/CompactRepresentation.qml b/plasmoid/contents/ui/CompactRepresentation.qml index de44287..9dcfb2a 100644 --- a/plasmoid/contents/ui/CompactRepresentation.qml +++ b/plasmoid/contents/ui/CompactRepresentation.qml @@ -1,13 +1,13 @@ /* - * Quel che si vede nel panel: la percentuale del vincolo che si tocca per - * primo, e sotto una barra che mostra la STESSA finestra. + * What shows in the panel: the percentage of the constraint that will be hit + * first, with a bar underneath showing the SAME window. * - * La barra mostrava la seconda finestra, ed era sbagliato: un numero e una - * barra affiancati che dicono valori diversi si leggono come incoerenti, non - * come due informazioni. La seconda finestra vive nel tooltip e nel popup. + * The bar used to show the second window, and that was wrong: a number and a + * bar side by side reporting different values read as incoherent, not as two + * pieces of information. The second window lives in the tooltip and the popup. * - * Quale sia "il primo" lo ha gia' deciso il demone. Qui non si sceglie nulla: - * a ~34px di altezza si disegna e basta. + * Which one is "first" has already been decided by the daemon. Nothing is + * chosen here: at ~34px tall, this only draws. */ import QtQuick import QtQuick.Layouts @@ -48,36 +48,36 @@ MouseArea { PlasmaComponents.Label { Layout.alignment: Qt.AlignHCenter - // Senza dato un trattino, non uno zero: uno zero sarebbe una - // bugia rassicurante proprio quando non sappiamo nulla. + // A dash when there is no data, not a zero: a zero would be a + // reassuring lie at exactly the moment we know nothing. text: compact.hasData ? i18nc("percentage of quota used", "%1%", compact.compactState.primary.percent) : "—" color: compact.accent - // Tarato sul testo del pannello, non sull'altezza disponibile: - // riempire il panel rendeva il numero molto piu' pesante delle - // icone del vassoio accanto. + // Sized against the panel's text, not the available height: + // filling the panel made the number far heavier than the tray + // icons next to it. font.pixelSize: Math.min(Kirigami.Units.gridUnit, Math.round(compact.height * 0.42)) fontSizeMode: Text.Fit minimumPixelSize: 8 } - // La barra rende leggibile a colpo d'occhio quanto vale il numero: - // stesso dato, forma diversa. + // The bar makes the number readable at a glance: same data, other + // shape. Rectangle { id: track visible: compact.hasData - // fillWidth prende la larghezza della colonna, decisa dal numero. - // Prima era `Math.max(layout.width, ...)`: la larghezza del - // binario dipendeva dal layout che dipende dal binario. + // fillWidth takes the column's width, which the number sets. It + // used to be `Math.max(layout.width, ...)`: the track's width + // depended on the layout, which depends on the track. Layout.fillWidth: true Layout.preferredHeight: Math.max(2, Math.round(compact.height * 0.08)) radius: height / 2 - // La trasparenza sta nel colore, non in `opacity`: l'opacita' del - // genitore si moltiplica su quella dei figli, quindi il - // riempimento finiva anche lui al 25% - identico al binario, cioe' - // invisibile. La barra sembrava sempre vuota. + // The transparency lives in the colour, not in `opacity`: a + // parent's opacity multiplies into its children, so the fill ended + // up at 25% too - identical to the track, and therefore invisible. + // The bar always looked empty. color: Qt.rgba(Kirigami.Theme.textColor.r, Kirigami.Theme.textColor.g, Kirigami.Theme.textColor.b, 0.25) diff --git a/plasmoid/contents/ui/DailyChart.qml b/plasmoid/contents/ui/DailyChart.qml index 040d466..4a5f28b 100644 --- a/plasmoid/contents/ui/DailyChart.qml +++ b/plasmoid/contents/ui/DailyChart.qml @@ -1,11 +1,11 @@ /* - * Consumo giorno per giorno negli ultimi 30 giorni: una colonna per giorno, - * divisa verticalmente per modello. + * Day-by-day consumption over the last 30 days: one column per day, split + * vertically by model. * - * La serie arriva continua dal demone, giorni vuoti inclusi: saltarli - * comprimerebbe il tempo e farebbe sembrare regolare un lavoro a singhiozzo. - * Le altezze sono relative al giorno di picco, perche' la domanda e' "com'e' - * andata rispetto ai giorni forti", non "quanti token esatti". + * The series arrives continuous from the daemon, empty days included: dropping + * them would compress time and make intermittent work look steady. Heights are + * relative to the peak day, because the question is "how did this compare to + * the busy days", not "exactly how many tokens". */ import QtQuick import QtQuick.Layouts @@ -17,8 +17,8 @@ ColumnLayout { id: chart property var days: [] - // L'ordine dei modelli decide sia i colori sia l'impilamento, e coincide - // con quello della legenda. + // The model order drives both the colours and the stacking, and matches + // the legend. property var modelOrder: [] readonly property double peak: { @@ -36,8 +36,8 @@ ColumnLayout { spacing: Kirigami.Units.smallSpacing RowLayout { - // Altezza bloccata: dentro un layout con spazio in avanzo le colonne - // si allargherebbero fino a riempirlo. + // Pinned height: inside a layout with spare room the columns would + // grow to fill it. readonly property int plotHeight: Kirigami.Units.gridUnit * 3 Layout.fillWidth: true @@ -57,9 +57,9 @@ ColumnLayout { Layout.fillWidth: true Layout.fillHeight: true - // I segmenti del giorno, nell'ordine della legenda. I modelli - // a zero si saltano: un rettangolo alto zero con un bordo - // arrotondato lascerebbe comunque un puntino. + // The day's segments, in legend order. Models at zero are + // skipped: a zero-height rectangle with a rounded corner would + // still leave a dot behind. readonly property var segments: { var out = [] var byModel = modelData && modelData.models ? modelData.models : ({}) @@ -72,17 +72,17 @@ ColumnLayout { return out } - // La traccia del giorno. Serve perche' un giorno a zero non - // disegna segmenti: senza, la serie sembrerebbe piu' corta di - // quello che e' e non si capirebbe che sono 30 giorni. + // The day's track. It is needed because a zero day draws no + // segments: without it the series would look shorter than it + // is, and it would not read as thirty days. Rectangle { anchors.fill: parent color: Kirigami.Theme.textColor opacity: 0.07 } - // Ancorata in basso: le colonne crescono verso l'alto senza - // bisogno di calcolare uno spazio vuoto sopra. + // Anchored to the bottom: columns grow upwards with no need + // to compute empty space above them. Column { anchors { left: parent.left @@ -108,7 +108,8 @@ ColumnLayout { } } - // Gli estremi dell'asse: senza, non si sa che periodo si sta guardando. + // The ends of the axis: without them there is no telling what period is + // on screen. RowLayout { Layout.fillWidth: true diff --git a/plasmoid/contents/ui/FullRepresentation.qml b/plasmoid/contents/ui/FullRepresentation.qml index 2e8c76f..02ef64c 100644 --- a/plasmoid/contents/ui/FullRepresentation.qml +++ b/plasmoid/contents/ui/FullRepresentation.qml @@ -1,12 +1,13 @@ /* - * Il popup. + * The popup. * - * Gerarchia: testata con piano e account, poi le finestre di rate limit - - * il dato che conta - poi il consumo locale per modello, che e' contorno. + * Hierarchy: heading with the plan and the account, then the rate + * limit windows - the figure that matters - then local per-model + * consumption, which is garnish. * - * Quel che deliberatamente non c'e', perche' e' un non-goal del progetto: - * storico a 30 giorni, grafici per giorno, classifiche per progetto. E' un - * widget di panel, non un'applicazione di analytics. + * Deliberately absent, because they are project non-goals: trends, + * projected burn rate, per-project rankings, session lists. This is a + * panel widget, not an analytics application. */ import QtQuick import QtQuick.Layouts @@ -24,8 +25,9 @@ PlasmaExtras.Representation { readonly property var account: quota && quota.account ? quota.account : null readonly property bool hasData: windows.length > 0 - // Il conto alla rovescia deve muoversi, ma solo a popup aperto: un timer - // che gira dentro plasmashell a widget chiuso e' lavoro regalato. + // The countdown has to move, but only while the popup is open: a + // timer running inside plasmashell with the widget closed is + // free work given away. property double now: Date.now() Timer { interval: 30000 @@ -37,17 +39,18 @@ PlasmaExtras.Representation { Layout.minimumWidth: Kirigami.Units.gridUnit * 20 - // Altezza dinamica: il popup vale quanto il suo contenuto, senza scroll. + // Dynamic height: the popup is worth exactly its content, no scrolling. // - // Il padding sono margini di LAYOUT, non ancorati e non `padding` del - // Control: i primi entrano nell'implicitHeight del layout, gli ancorati no - // (e il contenuto traboccava), mentre `padding` qui viene sovrascritto - - // PlasmaExtras.Representation lo gestisce per conto suo. - // Tutti e tre legati al contenuto, non solo il preferito: nel panel Plasma - // stringe l'altezza fra minimo e massimo, quindi un `preferredHeight` da - // solo viene schiacciato dal minimo di default. plasmawindowed non lo - // mostra - li' la finestra riempie e i Layout hint non contano - percio' - // questo si verifica solo nel panel. + // The padding is made of LAYOUT margins - not anchored ones, and not the + // Control's `padding`. Layout margins count towards the layout's + // implicitHeight; anchored ones do not, which is how the content used to + // spill outside the popup's background. `padding` here would simply be + // overwritten: PlasmaExtras.Representation manages it itself. + // All three tied to the content, not just the preferred one: in the panel + // Plasma clamps the height between minimum and maximum, so a lone + // `preferredHeight` gets squashed by the default minimum. plasmawindowed + // does not show this - there the window just fills and the Layout hints do + // not matter - so it can only be verified in the panel. Layout.minimumHeight: implicitHeight Layout.preferredHeight: implicitHeight Layout.maximumHeight: implicitHeight @@ -56,7 +59,7 @@ PlasmaExtras.Representation { header: PlasmaExtras.PlasmoidHeading { id: headerItem visible: full.hasData - // Senza, il titolo sta appiccicato ai bordi della barra. + // Without it the title sits flush against the heading's edges. leftPadding: Kirigami.Units.largeSpacing rightPadding: Kirigami.Units.largeSpacing topPadding: Kirigami.Units.largeSpacing @@ -71,8 +74,8 @@ PlasmaExtras.Representation { source: "speedometer" } - // Solo il nome dell'applicazione. Cosa sta mostrando lo dice - // l'intestazione di sezione, dentro il contenuto. + // The application name only. What it is showing is stated by the + // section heading inside the content. PlasmaExtras.Heading { Layout.fillWidth: true level: 3 @@ -89,8 +92,8 @@ PlasmaExtras.Representation { Layout.fillWidth: true Layout.fillHeight: true Layout.margins: Kirigami.Units.gridUnit - // Senza dato il popup non ha un contenuto che ne detti l'altezza: - // gliene serve una sensata di suo. + // With no data the popup has no content to set its height, so it + // needs a sensible one of its own. Layout.minimumHeight: Kirigami.Units.gridUnit * 14 visible: !full.hasData iconName: "speedometer" @@ -125,8 +128,9 @@ PlasmaExtras.Representation { return "" } - // Quel che resta di vero quando la percentuale manca: i transcript sul - // disco. Non e' una quota - i token si sanno, i limiti no - e va detto. + // What is left that is still true when the percentage is + // missing: the transcripts on disk. Not a quota - the tokens + // are known, the limits are not - and that has to be said. ColumnLayout { Layout.alignment: Qt.AlignHCenter Layout.topMargin: Kirigami.Units.largeSpacing @@ -167,8 +171,9 @@ PlasmaExtras.Representation { spacing: Math.round(Kirigami.Units.gridUnit * 0.75) visible: full.hasData - // La sezione: quale fonte sono queste percentuali. Il piano le - // qualifica, quindi la pastiglia sta qui e non nella testata. + // The section: which source these percentages come from. The + // plan qualifies them, so the pill sits here, not in the + // heading. RowLayout { Layout.fillWidth: true spacing: Kirigami.Units.smallSpacing @@ -186,15 +191,15 @@ PlasmaExtras.Representation { implicitWidth: planLabel.implicitWidth + Kirigami.Units.gridUnit implicitHeight: planLabel.implicitHeight + Kirigami.Units.smallSpacing radius: height / 2 - // Pastiglia piena con testo in contrasto. Prima era - // highlightColor su highlightColor trasparente: lo stesso - // colore su se' stesso, quindi illeggibile. + // The transparency lives in the colour: it used to be + // highlightColor over a transparent highlightColor, the same + // colour on itself, and therefore unreadable. color: Kirigami.Theme.highlightColor PlasmaComponents.Label { id: planLabel anchors.centerIn: parent - // Nome di prodotto, non testo tradotto. + // A product name, not translated text. text: full.account ? full.account.plan : "" color: Kirigami.Theme.highlightedTextColor font.pointSize: Kirigami.Theme.smallFont.pointSize @@ -203,11 +208,11 @@ PlasmaExtras.Representation { } } - // A quale account si riferiscono le percentuali qui sotto. + // Which account the percentages below belong to. PlasmaComponents.Label { Layout.fillWidth: true - // Annulla quasi tutto lo spazio di sezione: titolo e account - // sono un blocco solo, non due voci separate. + // Cancels almost all the section spacing: the title and the + // account are one block, not two separate entries. Layout.topMargin: -sections.spacing + 2 visible: text !== "" elide: Text.ElideRight @@ -216,16 +221,17 @@ PlasmaExtras.Representation { text: full.account ? (full.account.email || full.account.name || "") : "" } - // La riga sotto il titolo e' quel che lo rende una sezione invece di - // un testo qualsiasi: separa l'etichetta dai contatori che governa. + // The rule under the title is what makes it a section rather + // than stray text: it separates the label from the counters + // it governs. Kirigami.Separator { Layout.fillWidth: true Layout.topMargin: -Kirigami.Units.smallSpacing Layout.bottomMargin: Kirigami.Units.smallSpacing } - // Le righe hanno bisogno di piu' aria fra loro che al loro interno, - // o le tre barre sottili si leggono come un blocco solo. + // The rows need more air between them than within them, or the + // three thin bars read as a single block. Repeater { model: full.windows delegate: QuotaRow { @@ -236,7 +242,7 @@ PlasmaExtras.Representation { } } - // Seconda sezione, stessa forma della prima: titolo, riga, contenuto. + // Second section, same shape as the first: title, rule, content. PlasmaExtras.Heading { Layout.fillWidth: true visible: full.local !== null @@ -252,9 +258,9 @@ PlasmaExtras.Representation { visible: full.local !== null } - // Il recap su una riga sua: sono i numeri che si guardano per primi - // qui dentro, quindi hanno il peso del testo normale e non quello - // delle note. Restano tre totali, non una serie storica. + // The recap on a line of its own: these are the numbers looked + // at first in this section, so they carry the weight of body + // text rather than of footnotes. Three totals, not a series. RowLayout { Layout.fillWidth: true visible: full.local !== null @@ -286,8 +292,8 @@ PlasmaExtras.Representation { Item { Layout.fillWidth: true } } - // Il grafico sopra la legenda: la legenda spiega i colori che il - // grafico usa, quindi viene dopo. + // The chart above the legend: the legend explains the colours + // the chart uses, so it comes second. DailyChart { Layout.fillWidth: true days: full.local && full.local.daily ? full.local.daily : [] @@ -306,8 +312,8 @@ PlasmaExtras.Representation { models: full.local ? full.local.models : [] } - // La freschezza del dato e' parte del dato: un numero vecchio senza - // dirlo e' peggio di nessun numero. + // Freshness is part of the data: an old number presented + // without saying so is worse than no number. PlasmaComponents.Label { Layout.fillWidth: true visible: full.quota && full.quota.quota.status !== "fresh" @@ -317,8 +323,8 @@ PlasmaExtras.Representation { text: i18n("Quota data may be out of date.") } - // Con i crediti attivi il 100% non blocca piu': mostrarlo come un muro - // sarebbe una bugia. + // With credits on, 100% no longer blocks: showing it as a wall + // would be a lie. PlasmaComponents.Label { Layout.fillWidth: true visible: full.quota && full.quota.extra_usage_enabled diff --git a/plasmoid/contents/ui/ModelBreakdown.qml b/plasmoid/contents/ui/ModelBreakdown.qml index 6f1bed9..c9c9af1 100644 --- a/plasmoid/contents/ui/ModelBreakdown.qml +++ b/plasmoid/contents/ui/ModelBreakdown.qml @@ -1,11 +1,10 @@ /* - * Dove sono finiti i token della settimana, per modello. + * Where the tokens went, grouped by model. * - * Una barra sola divisa in quote, non tre barre: la domanda e' "in proporzione - * dove e' andato", non "quanto vale ciascuno in assoluto". I colori sono - * gradazioni del colore di evidenziazione del tema, cosi' resta coerente con - * qualunque schema l'utente abbia scelto invece di introdurre una tavolozza - * che stona. + * One bar split into shares, not several bars: the question is "proportionally + * where did it go", not "what is each one worth in absolute terms". The chart + * above answers "when"; this answers "how much per model". Same data, two + * readings. */ import QtQuick import QtQuick.Layouts @@ -18,8 +17,8 @@ ColumnLayout { property var models: [] - // Piu' di quattro voci diventano schegge illeggibili nella barra e righe - // di rumore nella legenda. + // Past four entries they become unreadable slivers in the bar and rows of + // noise in the legend. readonly property int maxItems: 4 readonly property var shown: models ? models.slice(0, maxItems) : [] readonly property double total: { @@ -30,8 +29,8 @@ ColumnLayout { return sum } - // I colori vivono in format.js: il grafico giornaliero usa gli stessi - // indici, e tenerli in un posto solo e' l'unico modo perche' corrispondano. + // The colours live in format.js: the daily chart uses the same indices, + // and keeping them in one place is the only way they stay in step. function tint(i) { return Format.modelColor(i) } @@ -41,9 +40,9 @@ ColumnLayout { visible: shown.length > 0 && total > 0 RowLayout { - // L'altezza va bloccata: dentro un layout che ha spazio in avanzo i - // segmenti si allargano fino a riempirlo, e con radius = height/2 - // diventano un pallone invece di una barra. + // The height has to be pinned: inside a layout with spare room the + // segments grow to fill it, and with radius = height/2 they turn into + // a balloon rather than a bar. readonly property int barHeight: Math.round(Kirigami.Units.gridUnit * 0.35) Layout.fillWidth: true @@ -61,8 +60,8 @@ ColumnLayout { Layout.fillWidth: true Layout.fillHeight: true - // La larghezza e' la quota sul totale: e' l'unica cosa che la - // barra deve dire. + // Width is the share of the total: the only thing this bar + // has to say. Layout.preferredWidth: Format.share(modelData.tokens, breakdown.total) * 1000 radius: height / 2 color: breakdown.tint(index) diff --git a/plasmoid/contents/ui/QuotaRow.qml b/plasmoid/contents/ui/QuotaRow.qml index c92e4b8..a2c2d38 100644 --- a/plasmoid/contents/ui/QuotaRow.qml +++ b/plasmoid/contents/ui/QuotaRow.qml @@ -1,6 +1,5 @@ /* - * Una finestra di rate limit: etichetta, quando si resetta, la barra, la - * percentuale. + * One rate-limit window: label, when it resets, the bar, the percentage. */ import QtQuick import QtQuick.Layouts @@ -17,6 +16,7 @@ ColumnLayout { Layout.fillWidth: true spacing: Kirigami.Units.smallSpacing + // The server decides the thresholds: here they only become colour. readonly property color accent: { switch (Format.severityRank(window ? window.severity : "")) { case 0: return Kirigami.Theme.textColor @@ -33,11 +33,10 @@ ColumnLayout { Layout.fillWidth: true elide: Text.ElideRight text: Format.windowLabel(row.window, i18n) - // La finestra attiva e' quella su cui si sta consumando adesso. - // Tutti in grassetto: sono i titoli delle rispettive barre, e - // metterne in evidenza uno solo faceva sembrare gli altri - // secondari quando non lo sono. Quale finestra sta accumulando - // adesso si legge dal countdown, non dal peso del testo. + // All bold: these are the titles of their own bars, and singling + // one out made the others look secondary when they are not. Which + // window is accumulating right now is told by the countdown, not + // by the weight of the text. font.weight: Font.Bold } @@ -56,8 +55,8 @@ ColumnLayout { value: row.window ? row.window.percent : 0 } - // La percentuale in chiaro e' l'ancora visiva della riga: senza, tre barre - // sottili una sotto l'altra si leggono come un blocco unico. + // The plain percentage anchors the row: without it, three thin bars + // stacked up read as a single block. PlasmaComponents.Label { text: row.window ? i18nc("how much of a quota window is consumed", "%1% used", row.window.percent) diff --git a/plasmoid/contents/ui/StateSource.qml b/plasmoid/contents/ui/StateSource.qml index d79229e..7292e52 100644 --- a/plasmoid/contents/ui/StateSource.qml +++ b/plasmoid/contents/ui/StateSource.qml @@ -1,15 +1,15 @@ /* - * Legge state.json scritto dal demone. + * Reads state.json, written by the daemon. * - * La lettura passa per il motore "executable" e un `cat`, non per - * XMLHttpRequest: Qt 6 disabilita XHR sui file locali e lo sblocca solo con - * QML_XHR_ALLOW_FILE_READ=1 nell'ambiente, che significa allentare quella - * protezione per tutto il QML di plasmashell - non solo per dipstick - e - * mettere le mani nella sessione dell'utente. Un fork di `cat` ogni tanto - * costa meno di entrambe le cose. + * The read goes through the "executable" engine and a `cat`, not through + * XMLHttpRequest: Qt 6 disables XHR on local files and only unlocks it with + * QML_XHR_ALLOW_FILE_READ=1 in the environment, which would mean loosening + * that protection for all of plasmashell's QML - not just for dipstick - and + * reaching into the user's session. Forking `cat` now and then costs less than + * either. * - * Il demone riscrive il file con write-su-temporaneo + rename, quindi un `cat` - * vede sempre o il vecchio o il nuovo, mai meta' JSON. + * The daemon rewrites the file with write-to-temp plus rename, so a `cat` + * always sees either the old one or the new one, never half a JSON document. */ import QtQml import QtCore @@ -18,10 +18,10 @@ import org.kde.plasma.plasma5support as P5Support QtObject { id: source - // Il file cambia al massimo ogni 5 minuti - la cadenza con cui il demone - // interroga la rete - quindi rileggerlo piu' spesso e' solo un fork in - // piu' dentro plasmashell. 15 secondi tengono il widget reattivo dopo un - // `dipstick auth` senza pesare. + // The file changes at most every 5 minutes - the cadence at which the + // daemon queries the network - so re-reading it more often is just one + // more fork inside plasmashell. Fifteen seconds keeps the widget + // responsive right after a `dipstick auth` without weighing anything down. property int interval: 15000 readonly property string filePath: { @@ -29,23 +29,32 @@ QtObject { return stripScheme(dir) + "/dipstick/state.json" } - // Lo stato deserializzato, o null se non c'e' nulla di utilizzabile. + // The deserialised state, or null if there is nothing usable. property var state: null - // Perche' non c'e' nulla. Distinto da `state === null` perche' il popup - // deve poter dire all'utente cosa fare, e le risposte sono diverse. - // "": tutto bene - // "missing": nessun file leggibile - il demone probabilmente non gira - // "malformed": file illeggibile - // "schema": scritto da una versione incompatibile + // Why there is nothing. Distinct from `state === null` because the popup + // has to tell the user what to do, and the answers differ. + // "": all good + // "missing": no readable file - the daemon is probably not running + // "malformed": unreadable file + // "schema": written by an incompatible version property string problem: "missing" - // Lo schema e' il contratto: uno sconosciuto si rifiuta, invece di - // interpretare campi che potrebbero non esserci piu'. + // The schema is the contract: an unknown one is refused rather than + // interpreting fields that may no longer be there. readonly property int supportedSchema: 1 readonly property string command: "cat " + shellQuote(filePath) + // The last raw payload seen. Reassigning `state` hands out a brand new + // JavaScript object, which invalidates every binding downstream: the + // tooltip, the compact form and - once the popup has been opened - the + // thirty columns of the chart and every quota row get destroyed and + // rebuilt. Doing that every fifteen seconds for a file that changes every + // five minutes is exactly the kind of free work inside plasmashell this + // project exists to avoid. + property string _lastRaw: "" + property var _engine: P5Support.DataSource { engine: "executable" connectedSources: [source.command] @@ -56,6 +65,9 @@ QtObject { source._fail("missing") return } + if (data.stdout === source._lastRaw) { + return + } var parsed try { parsed = JSON.parse(data.stdout) @@ -67,6 +79,7 @@ QtObject { source._fail("schema") return } + source._lastRaw = data.stdout source.state = parsed source.problem = "" } @@ -74,10 +87,11 @@ QtObject { function _fail(reason) { if (problem !== reason) { - console.warn("dipstick: stato non leggibile (" + reason + "): " + filePath) + console.warn("dipstick: unreadable state (" + reason + "): " + filePath) } - // Lo stato vecchio si butta: mostrare i numeri di prima come se fossero - // di adesso e' peggio che non mostrarne affatto. + _lastRaw = "" + // Throw the old state away: showing the previous numbers as if they + // were current is worse than showing none. state = null problem = reason } @@ -86,9 +100,9 @@ QtObject { return url.indexOf("file://") === 0 ? url.substring(7) : url } - // Il percorso finisce in una riga di comando, quindi va citato. $HOME con - // uno spazio dentro e' raro ma non impossibile, e un widget che si rompe - // in silenzio per quello sarebbe difficilissimo da diagnosticare. + // The path ends up on a command line, so it has to be quoted. A $HOME with + // a space in it is rare but not impossible, and a widget that breaks + // silently over that would be very hard to diagnose. function shellQuote(path) { return "'" + path.replace(/'/g, "'\\''") + "'" } diff --git a/plasmoid/contents/ui/format.js b/plasmoid/contents/ui/format.js index bdb9be6..fbf1ebe 100644 --- a/plasmoid/contents/ui/format.js +++ b/plasmoid/contents/ui/format.js @@ -1,8 +1,8 @@ .pragma library -// Le etichette si costruiscono qui, dal `kind` semantico che manda il demone. -// Il file di stato non contiene stringhe di interfaccia di proposito: la lingua -// e' della sessione, e il demone non ne ha una. +// Labels are built here, from the semantic `kind` the daemon sends. The state +// file deliberately carries no interface strings: the language belongs to the +// session, and the daemon has none. function windowLabel(win, i18n) { if (!win) { return "" @@ -13,20 +13,20 @@ function windowLabel(win, i18n) { case "weekly_all": return i18n("This week (all models)") case "weekly_scoped": - // Il nome del modello arriva dal server e non e' un elenco chiuso: - // si rende come arriva, senza tradurlo. + // The model name comes from the server and is not a closed set: + // render it as it arrives, untranslated. return win.model ? i18n("This week — %1", win.model) : i18n("This week (scoped)") default: - // Un kind che non conosciamo si mostra comunque: l'endpoint non e' - // documentato e ne aggiunge senza preavviso. Meglio grezzo che assente. + // An unknown kind is shown anyway: the endpoint is undocumented and + // adds them without notice. Raw beats absent. return win.kind || i18n("Unknown limit") } } -// Il server classifica gia' la gravita', quindi dipstick non inventa soglie. -// Il vocabolario esatto non e' documentato: "normal" e' l'unico valore -// osservato, percio' tutto cio' che non e' "normal" viene trattato come -// qualcosa che merita attenzione, invece di essere ignorato. +// The server already classifies severity, so dipstick invents no thresholds. +// The exact vocabulary is undocumented: "normal" is the only observed value, +// so anything that is not "normal" is treated as deserving attention rather +// than being ignored. function severityRank(severity) { switch ((severity || "").toLowerCase()) { case "": @@ -41,7 +41,7 @@ function severityRank(severity) { } } -// Conto alla rovescia fino al reset. Ritorna "" se non sappiamo quando sia. +// Countdown to the reset. Returns "" when we do not know when that is. function untilReset(isoString, now, i18n) { if (!isoString) { return "" @@ -66,12 +66,12 @@ function untilReset(isoString, now, i18n) { return i18n("resets in %1d %2h", Math.floor(hours / 24), hours % 24) } -// I token locali sono numeri enormi e senza un limite a cui rapportarli: si -// abbreviano, perche' la cifra esatta non aiuta nessuno. +// Local token counts are huge numbers with no limit to compare them against: +// abbreviate them, because the exact figure helps nobody. function humanTokens(n) { - // Un campo assente non e' uno zero: significa che il demone e' di una - // versione che non lo scrive. Mostrarlo come "0" nasconderebbe il - // disallineamento facendolo sembrare un dato vero. + // A missing field is not a zero: it means the daemon is a version that + // does not write it. Showing "0" would hide the mismatch by making it look + // like real data. if (n === undefined || n === null) { return "\u2014" } @@ -79,8 +79,8 @@ function humanTokens(n) { return "0" } if (n >= 1e9) { - // "B" per miliardi, non "G": qui si contano token, e il prefisso giga - // si legge come un'unita' di byte. + // "B" for billions, not "G": these are tokens, and the giga prefix + // reads as a unit of bytes. return (n / 1e9).toFixed(1) + "B" } if (n >= 1e6) { @@ -92,7 +92,7 @@ function humanTokens(n) { return String(n) } -// Da quanto non si lavora. Ritorna "" se non lo sappiamo. +// How long since any work happened. Returns "" when we do not know. function sinceActivity(isoString, now, i18n) { if (!isoString) { return "" @@ -116,15 +116,15 @@ function sinceActivity(isoString, now, i18n) { } // "claude-opus-5" -> "Opus 5", "claude-haiku-4-5-20251001" -> "Haiku 4.5". -// I nomi arrivano dai transcript e non sono un elenco chiuso: si abbellisce -// quel che si riconosce e si lascia passare il resto, invece di mappare su una -// tabella che invecchia. +// The names come from the transcripts and are not a closed set: prettify what +// is recognisable and let the rest through, rather than mapping against a +// table that goes stale. function modelName(id) { if (!id) { return "" } var parts = (id.indexOf("claude-") === 0 ? id.substring(7) : id).split("-") - // La data di rilascio in coda non aggiunge nulla: "Haiku 4.5" basta. + // The trailing release date adds nothing: "Haiku 4.5" is enough. if (parts.length > 1 && /^\d{8}$/.test(parts[parts.length - 1])) { parts.pop() } @@ -132,8 +132,8 @@ function modelName(id) { if (name.length > 0 && name[0] >= "a" && name[0] <= "z") { name = name[0].toUpperCase() + name.substring(1) } - // Le cifre di versione sono separate da trattini nell'id ma si leggono - // come un numero solo: "4-5" e' la 4.5. + // Version digits are hyphen-separated in the id but read as a single + // number: "4-5" is 4.5. var version = parts.filter(function(p) { return p.length > 0 }) if (version.length === 0) { return name @@ -143,24 +143,24 @@ function modelName(id) { : version.join(" ")) } -// Quota di un modello sul totale della settimana, come frazione 0..1. +// One model's share of the total, as a fraction from 0 to 1. function share(tokens, total) { return total > 0 ? Math.max(0, tokens) / total : 0 } -// Tinte per modello, dalla tavolozza Breeze. +// Per-model hues, from the Breeze palette. // -// Sono colori fissi, non derivati dall'accent dell'utente: e' il prezzo della -// distinguibilita'. Gradazioni di una stessa tinta si leggono come "piu' o -// meno la stessa cosa", che e' cio' che una legenda non deve fare. Stanno qui -// e non nei componenti perche' legenda e grafico devono usare lo stesso indice -// per lo stesso modello, altrimenti i colori non corrispondono. +// These are fixed colours, not derived from the user's accent: that is the +// price of telling them apart. Shades of one hue read as "more or less the +// same thing", which is what a legend must not do. They live here rather than +// in the components because the legend and the chart must map the same index +// to the same model, or the colours stop matching. var MODEL_PALETTE = [ - "#3daee9", // blu - "#27ae60", // verde - "#f67400", // arancio - "#9b59b6", // viola - "#da4453", // rosso + "#3daee9", // blue + "#27ae60", // green + "#f67400", // orange + "#9b59b6", // purple + "#da4453", // red "#c9ce3b" // lime ] @@ -168,7 +168,7 @@ function modelColor(i) { return MODEL_PALETTE[i % MODEL_PALETTE.length] } -// "2026-07-29" -> "29 Jul", nel formato della locale dell'utente. +// "2026-07-29" -> "29 Jul", in the user's locale format. function shortDate(iso) { if (!iso) { return "" diff --git a/plasmoid/contents/ui/main.qml b/plasmoid/contents/ui/main.qml index 3df0338..7e5fb43 100644 --- a/plasmoid/contents/ui/main.qml +++ b/plasmoid/contents/ui/main.qml @@ -1,9 +1,9 @@ /* - * dipstick — quota Claude Max nel panel di Plasma. + * dipstick — Claude Max quota in the Plasma panel. * - * Il plasmoide non decide nulla: legge lo stato che il demone ha gia' ridotto - * a "cosa mostrare" e lo disegna. Gira dentro plasmashell, dove un errore non - * costa un widget rotto ma il panel dell'utente. + * The plasmoid decides nothing: it reads the state the daemon has already + * reduced to "what to show" and draws it. It runs inside plasmashell, where a + * mistake costs not a broken widget but the user's panel. */ import QtQuick import org.kde.plasma.core as PlasmaCore @@ -25,12 +25,12 @@ PlasmoidItem { ? PlasmaCore.Types.ActiveStatus : PlasmaCore.Types.PassiveStatus - // Una finestra riassunta in una riga sola, completa di reset. + // One window summarised on a single line, reset included. // - // Sta qui e non in format.js perche' quello e' `.pragma library` e non - // vede `i18nc`. Le altre funzioni la' dentro ricevono `i18n` come - // parametro; per il contesto servirebbe passarne un secondo, e a quel - // punto tanto vale comporre dove il contesto c'e' gia'. + // It lives here rather than in format.js because that file is a + // `.pragma library` and cannot see `i18nc`. The functions in there take + // `i18n` as a parameter; carrying a second one for the context would be + // silly when the context is already in scope here. function windowSummary(win, now) { if (!win) { return "" @@ -44,11 +44,11 @@ PlasmoidItem { "%1: %2% — %3", label, win.percent, reset) } - // Il tooltip: una riga per finestra, ognuna completa. + // The tooltip: one line per window, each one self-contained. // - // Prima il reset stava su una riga sua, sotto entrambe le finestre, e si - // leggeva come se appartenesse all'ultima. Un dato giusto attribuito alla - // riga sbagliata e' peggio di un dato assente. + // The reset used to sit on a line of its own, below both windows, and read + // as if it belonged to the last one. A correct figure attached to the + // wrong row is worse than a missing one. toolTipMainText: quotaState && quotaState.compact ? i18n("Claude usage") : i18n("Claude quota unavailable") diff --git a/translations/extract.sh b/translations/extract.sh index 2d80cac..aeaef3d 100755 --- a/translations/extract.sh +++ b/translations/extract.sh @@ -1,11 +1,11 @@ #!/bin/sh -# Rigenera dipstick.pot dalle sorgenti QML e aggiorna i cataloghi esistenti. +# Regenerate dipstick.pot from the QML sources and update existing catalogues. # -# I flag `javascript-format` vengono rimossi: xgettext li deduce vedendo `%1d` -# o `%1h`, ma quelli sono i segnaposto di KDE (`%1`, `%2`) seguiti da una -# lettera che e' l'unita' di misura, non una conversione printf. Lasciandoli, -# msgfmt rifiuta traduzioni che cambiano la lettera - "%1d" -> "%1g" per -# giorni in italiano. +# The `javascript-format` flags are stripped: xgettext infers them from `%1d` +# or `%1h`, but those are KDE's placeholders (`%1`, `%2`) followed by a letter +# that is a unit of measure, not a printf conversion. Left in place, msgfmt +# rejects translations that change the letter - "%1d" becoming "%1g" for days +# in Italian. set -eu cd "$(dirname "$0")/.." -- knotmirror 0.0.1