diff --git a/CLAUDE.md b/CLAUDE.md index 0088123..35d4760 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,8 +29,22 @@ 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. -## Da riempire +## Come si lavora -- [ ] Come si builda ed esegue (demone + pacchetto plasmoide) -- [ ] Layout del codice -- [ ] Come si testa +Build, installazione, layout del codice e comandi di diagnosi: `README.md`. +In breve: `make test` per i test (non toccano la rete), `make vet` prima di +committare, `plasmawindowed org.kde.plasma.dipstick` per provare il plasmoide +senza metterlo nel panel - i suoi errori QML finiscono nel journal utente, non +sul terminale. + +## Trappole gia' incontrate + +- **`XMLHttpRequest` su `file://` non funziona in QML.** Qt 6 lo disabilita. + La lettura dello stato passa da `Plasma5Support.DataSource` (`executable`). +- **I transcript contengono messaggi duplicati**, in quantita': ~3900 righe con + `usage` per ~2000 `message.id` distinti. Va deduplicato per `message.id`, o i + token quasi raddoppiano. Il modello `` non e' una chiamata reale. +- **`seven_day_opus` e `seven_day_sonnet` arrivano `null`.** Il breakdown per + modello sta in `limits[]`, col nome deciso dal server: non e' un elenco chiuso. +- **`state.json` non contiene stringhe di interfaccia.** La localizzazione e' del + plasmoide; il demone gira senza contesto di locale. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5af1588 --- /dev/null +++ b/Makefile @@ -0,0 +1,59 @@ +# 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. + +PREFIX ?= $(HOME)/.local +BINDIR ?= $(PREFIX)/bin +UNITDIR ?= $(HOME)/.config/systemd/user + +GOFLAGS ?= -trimpath +LDFLAGS ?= -s -w + +.PHONY: all build test vet fmt install install-daemon install-plasmoid \ + uninstall enable disable clean + +all: build + +build: + go build $(GOFLAGS) -ldflags '$(LDFLAGS)' -o dipstick ./cmd/dipstick + +test: + go test ./... + +vet: + go vet ./... + gofmt -l cmd internal + +install: install-daemon install-plasmoid + @echo + @echo "Installato. Restano due passi, che tocca a te:" + @echo + @echo " 1. dipstick auth (login OAuth)" + @echo " 2. systemctl --user enable --now dipstick" + @echo + @echo "Poi aggiungi 'Dipstick' al panel dal menu Aggiungi Widget." + +install-daemon: build + install -Dm755 dipstick $(BINDIR)/dipstick + install -Dm644 packaging/dipstick.service $(UNITDIR)/dipstick.service + systemctl --user daemon-reload + +install-plasmoid: + kpackagetool6 --type Plasma/Applet --install plasmoid \ + || kpackagetool6 --type Plasma/Applet --upgrade plasmoid + +# 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. +uninstall: + -systemctl --user disable --now dipstick + -rm -f $(BINDIR)/dipstick $(UNITDIR)/dipstick.service + -systemctl --user daemon-reload + -kpackagetool6 --type Plasma/Applet --remove org.kde.plasma.dipstick + +enable: + systemctl --user enable --now dipstick + +disable: + systemctl --user disable --now dipstick + +clean: + rm -f dipstick diff --git a/README.md b/README.md index 202dee0..4d84c2d 100644 --- a/README.md +++ b/README.md @@ -189,9 +189,54 @@ client non puo' posizionarsi liberamente ne' imporsi always-on-top. Nessuna: chiuse tutte al kickoff, vedi "Decisioni gia' prese". +## Come si builda, si installa, si testa + +``` +make # compila il demone +make test # test unitari, nessuna rete +make vet # go vet + gofmt +make install # demone in ~/.local/bin, unit in ~/.config/systemd/user, + # plasmoide via kpackagetool6 +``` + +Poi, e questi passi restano all'utente perche' dipstick non tocca la sessione: + +``` +dipstick auth # login OAuth (apre il browser) +systemctl --user enable --now dipstick # avvia il demone +``` + +e infine "Aggiungi Widget" -> Dipstick nel panel. + +Comandi utili per diagnosticare: + +``` +dipstick usage # JSON grezzo dell'endpoint, senza interpretazione +dipstick state # lo stato che leggerebbe il plasmoide, senza scriverlo +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. + +## Layout del codice + +``` +cmd/dipstick/ CLI e entry point del demone +internal/anthropic/ OAuth PKCE, endpoint quota/profilo, normalizzazione +internal/transcript/ lettura (SOLA LETTURA) dei transcript locali +internal/state/ lo schema di state.json e la scrittura atomica +internal/daemon/ il loop: cadenza adattiva, backoff, degrado +plasmoid/ il pacchetto QML +packaging/ la systemd user unit +``` + ## Stato -Domande aperte chiuse. Il contratto degli endpoint e' verificato contro l'endpoint -reale, non dedotto, e lo schema di `state.json` e' fissato: `dipstick state` lo -genera. Restano da fare il loop del demone (polling adattivo, systemd unit), il -fallback sui transcript locali e il plasmoide QML. +Funzionante da capo a fondo: demone, plasmoide, degrado e installazione. +Il contratto dell'endpoint e' verificato contro l'endpoint reale, non dedotto. + +Non ancora fatto: un pacchetto RPM/COPR per Fedora (il punto d'arrivo per la +distribuzione, che riusa il layout di `make install`), e i cataloghi di +traduzione - le stringhe del plasmoide sono in inglese e passano da `i18n()`, +quindi sono traducibili, ma nessun `.po` esiste ancora. diff --git a/cmd/dipstick/main.go b/cmd/dipstick/main.go index 55cda98..187c6cd 100644 --- a/cmd/dipstick/main.go +++ b/cmd/dipstick/main.go @@ -1,23 +1,31 @@ -// dipstick — spike di autenticazione. +// dipstick — quota Claude Max nel panel di Plasma. // -// Non e' ancora il demone: serve a rispondere a una sola domanda, cioe' se il -// contratto degli endpoint OAuth descritto nel README regge davvero. Per questo -// `usage` e `profile` stampano il JSON grezzo senza interpretarlo. +// `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. package main import ( "bufio" "bytes" + "context" "encoding/json" "errors" "fmt" + "log/slog" "os" "os/exec" + "os/signal" "strings" + "syscall" "time" "github.com/claudioquaglia/dipstick/internal/anthropic" + "github.com/claudioquaglia/dipstick/internal/daemon" "github.com/claudioquaglia/dipstick/internal/state" + "github.com/claudioquaglia/dipstick/internal/transcript" ) func main() { @@ -41,6 +49,8 @@ func run(args []string) error { return dump(anthropic.RawProfile) case "state": return cmdState(args[1:]) + case "run": + return cmdRun() case "logout": if err := anthropic.Logout(); err != nil { return err @@ -59,12 +69,13 @@ func run(args []string) error { func usage() { path, _ := anthropic.TokenPath() statePath, _ := state.Path() - fmt.Fprintf(os.Stderr, `dipstick — spike di autenticazione + 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). @@ -165,3 +176,45 @@ func cmdState(args []string) error { } return nil } + +// cmdRun e' il demone vero: gira sotto systemd finche' non gli si dice di +// smettere. +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. + log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ + Level: level, + ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { + if a.Key == slog.TimeKey { + return slog.Attr{} + } + return a + }, + })) + + 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) + root = "" + } + + // SIGTERM e' come systemd ferma il servizio: va onorato subito, non al + // prossimo giro - che puo' essere fra mezz\'ora. + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) + defer stop() + + path, _ := state.Path() + log.Info("avvio", "stato", path, "transcript", root) + + err = daemon.New(daemon.DefaultConfig(), root, log).Run(ctx) + if errors.Is(err, context.Canceled) { + log.Info("arresto") + return nil + } + return err +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go new file mode 100644 index 0000000..b0fe6bc --- /dev/null +++ b/internal/daemon/daemon.go @@ -0,0 +1,155 @@ +// Package daemon tiene aggiornato state.json. +// +// Gira come systemd user unit, fuori da plasmashell: se qualcosa qui va male +// muore un servizio, non il panel dell'utente. +package daemon + +import ( + "context" + "errors" + "log/slog" + "time" + + "github.com/claudioquaglia/dipstick/internal/anthropic" + "github.com/claudioquaglia/dipstick/internal/state" + "github.com/claudioquaglia/dipstick/internal/transcript" +) + +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 time.Duration + // IdleInterval e' la cadenza quando i transcript non mostrano attivita'. + IdleInterval time.Duration + // IdleAfter e' quanto silenzio serve per considerarsi fermi. + IdleAfter time.Duration + // MaxBackoff limita l'attesa dopo errori ripetuti. + MaxBackoff time.Duration + // StaleAfter e' da quanto puo' essere vecchia l'ultima lettura buona prima + // che smettiamo di mostrarla. + StaleAfter time.Duration +} + +func DefaultConfig() Config { + return Config{ + Interval: 5 * time.Minute, + IdleInterval: 30 * time.Minute, + IdleAfter: 30 * time.Minute, + MaxBackoff: 30 * time.Minute, + StaleAfter: 2 * time.Hour, + } +} + +type Daemon struct { + cfg Config + log *slog.Logger + root string // albero dei transcript + + // Ultima lettura riuscita, per poter degradare su "stale" invece di + // cadere direttamente su "nessun dato". + lastGood *anthropic.Usage + lastGoodAt 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. + fetchUsage func() (*anthropic.Usage, error) + writeState func(*state.State) error +} + +func New(cfg Config, root string, log *slog.Logger) *Daemon { + return &Daemon{ + cfg: cfg, log: log, root: root, + fetchUsage: anthropic.FetchUsage, + writeState: func(s *state.State) error { return s.Write() }, + } +} + +// Run cicla finche' il contesto non viene cancellato. +func (d *Daemon) Run(ctx context.Context) error { + for { + wait := d.tick(time.Now()) + d.log.Debug("prossimo giro", "fra", wait) + + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(wait): + } + } +} + +// tick fa un giro completo e restituisce quanto aspettare prima del prossimo. +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. + activity, err := d.scan(now) + if err != nil { + d.log.Warn("scansione dei transcript fallita", "err", err) + } + + st, ok := d.fetch(now) + st.WithLocal(activity) + + if err := d.writeState(st); err != nil { + d.log.Error("scrittura dello stato fallita", "err", err) + } + + if !ok { + return d.backoff() + } + d.failures = 0 + if activity != nil && activity.Idle(d.cfg.IdleAfter) { + return d.cfg.IdleInterval + } + return d.cfg.Interval +} + +func (d *Daemon) scan(now time.Time) (*transcript.Activity, error) { + if d.root == "" { + return nil, nil + } + 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. +func (d *Daemon) fetch(now time.Time) (*state.State, bool) { + usage, err := d.fetchUsage() + if err == nil { + d.lastGood, d.lastGoodAt = usage, now + 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. + if errors.Is(err, anthropic.ErrNoAuth) { + d.log.Warn("non autenticato", "azione", "dipstick auth") + return state.Unavailable(err, true, now), true + } + + d.log.Warn("lettura della quota fallita", "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. + 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. +func (d *Daemon) backoff() time.Duration { + d.failures++ + wait := d.cfg.Interval + for i := 1; i < d.failures; i++ { + wait *= 2 + if wait >= d.cfg.MaxBackoff { + return d.cfg.MaxBackoff + } + } + return wait +} diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go new file mode 100644 index 0000000..b545988 --- /dev/null +++ b/internal/daemon/daemon_test.go @@ -0,0 +1,189 @@ +package daemon + +import ( + "errors" + "io" + "log/slog" + "testing" + "time" + + "github.com/claudioquaglia/dipstick/internal/anthropic" + "github.com/claudioquaglia/dipstick/internal/state" +) + +var now = time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC) + +func quiet() *slog.Logger { + return slog.New(slog.NewTextHandler(io.Discard, nil)) +} + +// harness costruisce un demone che non tocca ne' rete ne' disco. +func harness(t *testing.T, fetch func() (*anthropic.Usage, error)) (*Daemon, *[]*state.State) { + t.Helper() + var written []*state.State + d := New(DefaultConfig(), "", quiet()) + d.fetchUsage = fetch + d.writeState = func(s *state.State) error { + written = append(written, s) + return nil + } + return d, &written +} + +func usageAt(percent int, resetsAt time.Time) *anthropic.Usage { + return &anthropic.Usage{Windows: []anthropic.Window{ + {Kind: anthropic.KindWeeklyAll, Group: anthropic.GroupWeekly, + Percent: percent, Severity: "normal", ResetsAt: &resetsAt, IsActive: true}, + }} +} + +func TestTickWritesFreshState(t *testing.T) { + d, written := harness(t, func() (*anthropic.Usage, error) { + 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) + } + if len(*written) != 1 || (*written)[0].Quota.Status != state.StatusFresh { + t.Fatalf("stato scritto = %+v", *written) + } +} + +// Lo stato va scritto anche quando la lettura fallisce: il plasmoide deve +// poter distinguere "quota non leggibile" da "demone morto". +func TestTickWritesEvenOnFailure(t *testing.T) { + d, written := harness(t, func() (*anthropic.Usage, error) { + return nil, errors.New("rete giu'") + }) + d.tick(now) + if len(*written) != 1 { + t.Fatalf("scritture = %d, attesa 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. +func TestFailureAfterSuccessDegradesToStale(t *testing.T) { + fail := false + d, written := harness(t, func() (*anthropic.Usage, error) { + if fail { + return nil, errors.New("503") + } + return usageAt(30, now.Add(24*time.Hour)), nil + }) + d.tick(now) + fail = true + d.tick(now.Add(5 * time.Minute)) + + last := (*written)[len(*written)-1] + if last.Quota.Status != state.StatusStale { + t.Fatalf("status = %q, atteso stale", last.Quota.Status) + } + if last.Compact == nil || last.Compact.Primary.Percent != 30 { + t.Errorf("i numeri vecchi dovrebbero restare: %+v", last.Compact) + } + // L'istante deve essere quello dell'ultima lettura RIUSCITA, non di ora. + if last.Quota.FetchedAt == nil || !last.Quota.FetchedAt.Equal(now) { + t.Errorf("fetched_at = %v, atteso %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. +func TestStaleDropsExpiredWindows(t *testing.T) { + fail := false + d, written := harness(t, func() (*anthropic.Usage, error) { + if fail { + return nil, errors.New("503") + } + return usageAt(90, now.Add(10*time.Minute)), nil + }) + d.tick(now) + fail = true + d.tick(now.Add(20 * time.Minute)) // il reset e' passato + + last := (*written)[len(*written)-1] + if last.Quota.Status != state.StatusUnavailable { + t.Errorf("status = %q, atteso unavailable", last.Quota.Status) + } + if last.Compact != nil { + t.Errorf("compact = %+v, atteso nil", last.Compact) + } +} + +// Oltre StaleAfter si smette di spacciare i numeri vecchi per un dato. +func TestStaleExpiresAfterStaleAfter(t *testing.T) { + fail := false + d, written := harness(t, func() (*anthropic.Usage, error) { + if fail { + return nil, errors.New("503") + } + return usageAt(30, now.Add(30*24*time.Hour)), nil + }) + d.tick(now) + fail = true + 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) + } +} + +// Senza token non parte nessuna richiesta, quindi non c'e' niente da +// rallentare: e' l'utente che deve agire. +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) + } + } + if last := (*written)[len(*written)-1]; !last.Quota.NeedsAuth { + t.Error("needs_auth non impostato: il popup non puo' dire cosa fare") + } +} + +func TestBackoffDoublesAndIsCapped(t *testing.T) { + cfg := DefaultConfig() + d, _ := harness(t, func() (*anthropic.Usage, error) { + return nil, errors.New("503") + }) + 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) + } + } + 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) + } +} + +// Una lettura riuscita azzera il backoff accumulato. +func TestSuccessResetsBackoff(t *testing.T) { + fail := true + d, _ := harness(t, func() (*anthropic.Usage, error) { + if fail { + return nil, errors.New("503") + } + return usageAt(10, now.Add(time.Hour)), nil + }) + d.tick(now) + d.tick(now) + fail = false + if got := d.tick(now); got != DefaultConfig().Interval { + t.Errorf("attesa = %v, atteso il ritorno alla cadenza normale", got) + } + fail = true + if got := d.tick(now); got != DefaultConfig().Interval { + t.Errorf("attesa = %v, il backoff doveva ripartire da capo", got) + } +} diff --git a/internal/state/state.go b/internal/state/state.go index 884621a..e930e4c 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -17,6 +17,7 @@ import ( "time" "github.com/claudioquaglia/dipstick/internal/anthropic" + "github.com/claudioquaglia/dipstick/internal/transcript" ) // SchemaVersion cambia solo per modifiche incompatibili. Il plasmoide rifiuta @@ -41,6 +42,71 @@ type State struct { Windows []Window `json:"windows"` // ExtraUsageEnabled: con i crediti attivi il 100% non blocca piu'. 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 *Local `json:"local,omitempty"` +} + +type Local struct { + ScannedAt time.Time `json:"scanned_at"` + LastActivity *time.Time `json:"last_activity,omitempty"` + SessionTokens int64 `json:"session_tokens"` + WeekTokens int64 `json:"week_tokens"` + Messages int `json:"messages"` +} + +// 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 (s *State) WithLocal(a *transcript.Activity) *State { + if s == nil || a == nil { + return s + } + l := &Local{ + ScannedAt: a.ScannedAt, + SessionTokens: a.SessionTokens, + WeekTokens: a.WeekTokens, + Messages: a.Messages, + } + if !a.LastActivity.IsZero() { + t := a.LastActivity + l.LastActivity = &t + } + s.Local = l + 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. +// +// 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. +func Stale(prev *anthropic.Usage, fetchedAt time.Time, err error, now time.Time) *State { + s := &State{ + Schema: SchemaVersion, + GeneratedAt: now, + Quota: Quota{Status: StatusStale, FetchedAt: &fetchedAt}, + } + if err != nil { + s.Quota.Error = err.Error() + } + if prev != nil { + s.ExtraUsageEnabled = prev.ExtraUsageEnabled + for _, w := range prev.Windows { + if w.ResetsAt != nil && w.ResetsAt.Before(now) { + continue + } + s.Windows = append(s.Windows, fromAPI(w)) + } + } + if len(s.Windows) == 0 { + // Non e' rimasto nulla di vero da mostrare. + return Unavailable(err, false, now) + } + s.Compact = pickCompact(s.Windows) + return s } type Quota struct { diff --git a/internal/transcript/transcript.go b/internal/transcript/transcript.go new file mode 100644 index 0000000..a03f9a3 --- /dev/null +++ b/internal/transcript/transcript.go @@ -0,0 +1,170 @@ +// Package transcript legge i log di sessione di Claude Code per stimare +// l'attivita' recente quando l'endpoint della quota non risponde. +// +// ~/.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. +// +// 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. +package transcript + +import ( + "bufio" + "encoding/json" + "io/fs" + "os" + "path/filepath" + "time" +) + +// Root e' l'albero dei transcript. Sola lettura, sempre. +func Root() (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(home, ".claude", "projects"), nil +} + +// Activity e' quanto si riesce a dire guardando solo i file locali. +type Activity struct { + ScannedAt time.Time + LastActivity time.Time // zero se non si e' trovato nulla + SessionTokens int64 // ultime 5 ore + WeekTokens int64 // ultimi 7 giorni + Messages int // messaggi distinti conteggiati + FilesScanned int +} + +const ( + sessionWindow = 5 * time.Hour + weekWindow = 7 * 24 * time.Hour +) + +// Una riga di transcript, ridotta ai campi che servono. +type line struct { + Timestamp string `json:"timestamp"` + RequestID string `json:"requestId"` + Message struct { + ID string `json:"id"` + Model string `json:"model"` + Usage *struct { + Input int64 `json:"input_tokens"` + CacheCreat int64 `json:"cache_creation_input_tokens"` + CacheRead int64 `json:"cache_read_input_tokens"` + Output int64 `json:"output_tokens"` + } `json:"usage"` + } `json:"message"` +} + +func (l *line) tokens() int64 { + u := l.Message.Usage + 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. +func (l *line) dedupKey() string { + if l.Message.ID != "" { + return l.Message.ID + } + return l.RequestID +} + +// Scan attraversa i transcript e riassume l'attivita' fino a `window` fa. +// +// 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. +func Scan(root string, now time.Time) (*Activity, error) { + act := &Activity{ScannedAt: now} + cutoff := now.Add(-weekWindow) + sessionCutoff := now.Add(-sessionWindow) + seen := make(map[string]struct{}, 16384) + + 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. + return nil + } + if d.IsDir() || filepath.Ext(path) != ".jsonl" { + return nil + } + info, err := d.Info() + if err != nil || info.ModTime().Before(cutoff) { + return nil + } + act.FilesScanned++ + scanFile(path, sessionCutoff, cutoff, seen, act) + return nil + }) + if err != nil { + return nil, err + } + act.Messages = len(seen) + return act, nil +} + +func scanFile(path string, sessionCutoff, cutoff time.Time, seen map[string]struct{}, act *Activity) { + // os.Open apre in sola lettura: e' il vincolo del progetto, reso esplicito. + f, err := os.Open(path) + if err != nil { + return + } + 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) + + 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. + if json.Unmarshal(sc.Bytes(), &l) != nil { + continue + } + if l.Message.Usage == nil { + continue + } + // non e' una chiamata al modello: non consuma quota. + if l.Message.Model == "" { + continue + } + ts, err := time.Parse(time.RFC3339, l.Timestamp) + if err != nil || ts.Before(cutoff) { + continue + } + key := l.dedupKey() + if key == "" { + continue + } + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + + if ts.After(act.LastActivity) { + act.LastActivity = ts + } + n := l.tokens() + act.WeekTokens += n + if !ts.Before(sessionCutoff) { + act.SessionTokens += n + } + } +} + +// 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. +func (a *Activity) Idle(threshold time.Duration) bool { + if a.LastActivity.IsZero() { + return false + } + return a.ScannedAt.Sub(a.LastActivity) > threshold +} diff --git a/internal/transcript/transcript_test.go b/internal/transcript/transcript_test.go new file mode 100644 index 0000000..a7fd68d --- /dev/null +++ b/internal/transcript/transcript_test.go @@ -0,0 +1,170 @@ +package transcript + +import ( + "fmt" + "os" + "path/filepath" + "testing" + "time" +) + +var now = time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC) + +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 { + 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) +} + +// write crea un transcript e ne fissa l'mtime: il filtro per mtime e' il cuore +// della strategia, quindi i test devono poterlo controllare. +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" + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, mtime, mtime); err != nil { + t.Fatal(err) + } + return path +} + +// Il caso che conta: sull'albero reale 3927 righe con usage danno 2026 id +// distinti. Senza deduplica il totale quasi raddoppia. +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) + } + if act.SessionTokens != 110 { + t.Errorf("SessionTokens = %d, atteso 110 (la riga vale una volta sola)", act.SessionTokens) + } + if act.Messages != 1 { + t.Errorf("Messages = %d, atteso 1", act.Messages) + } +} + +// La deduplica deve valere anche fra file diversi: la stessa sessione puo' +// comparire in piu' 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) + } +} + +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) + if act.SessionTokens != 100 { + t.Errorf("SessionTokens = %d, atteso 100", act.SessionTokens) + } + if act.WeekTokens != 300 { + t.Errorf("WeekTokens = %d, atteso 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. +func TestScanSkipsFilesByModTime(t *testing.T) { + dir := t.TempDir() + write(t, dir, "p/vecchio.jsonl", now.Add(-30*24*time.Hour), + msg("dentro-un-file-vecchio", "claude-opus-5", ago(time.Hour), 1000, 0, 0, 0)) + + act, _ := Scan(dir, now) + if act.FilesScanned != 0 { + t.Errorf("FilesScanned = %d, atteso 0", act.FilesScanned) + } + if act.WeekTokens != 0 { + t.Errorf("WeekTokens = %d, atteso 0", act.WeekTokens) + } +} + +// Claude Code scrive mentre dipstick legge: l'ultima riga puo' essere tronca, +// e non deve far perdere le righe buone che la precedono. +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), + `{"type":"assistant","timestamp":"2026-08-27T11:5`) + + act, _ := Scan(dir, now) + if act.SessionTokens != 42 { + t.Errorf("SessionTokens = %d, atteso 42", act.SessionTokens) + } +} + +// non e' una chiamata al modello e non consuma 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)) + + act, _ := Scan(dir, now) + if act.SessionTokens != 7 { + t.Errorf("SessionTokens = %d, atteso 7", act.SessionTokens) + } +} + +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) + } +} + +func TestScanMissingRootIsNotFatal(t *testing.T) { + act, err := Scan(filepath.Join(t.TempDir(), "non-esiste"), now) + if err != nil { + t.Fatalf("una root assente non deve essere un errore: %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") + } +} diff --git a/packaging/dipstick.service b/packaging/dipstick.service new file mode 100644 index 0000000..ef04ad8 --- /dev/null +++ b/packaging/dipstick.service @@ -0,0 +1,29 @@ +[Unit] +Description=dipstick — tiene aggiornata la quota Claude Max per il plasmoide +Documentation=https://github.com/claudioquaglia/dipstick +# Il servizio e' inutile senza rete, ma non deve fallire se parte prima: +# il primo giro degrada e riprova da solo. +After=network-online.target + +[Service] +Type=simple +ExecStart=%h/.local/bin/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. +NoNewPrivileges=yes +PrivateDevices=yes +ProtectControlGroups=yes +ProtectKernelModules=yes +ProtectKernelTunables=yes +RestrictNamespaces=yes +RestrictRealtime=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +SystemCallFilter=@system-service +SystemCallErrorNumber=EPERM + +[Install] +WantedBy=default.target diff --git a/plasmoid/contents/ui/FullRepresentation.qml b/plasmoid/contents/ui/FullRepresentation.qml index d2b07f1..60cebfd 100644 --- a/plasmoid/contents/ui/FullRepresentation.qml +++ b/plasmoid/contents/ui/FullRepresentation.qml @@ -14,6 +14,7 @@ PlasmaExtras.Representation { readonly property var quota: root.quotaState readonly property var windows: quota && quota.windows ? quota.windows : [] + readonly property var local: quota && quota.local ? quota.local : null // Il conto alla rovescia deve muoversi, ma solo mentre il popup e' aperto: // un timer che gira dentro plasmashell a widget chiuso e' lavoro regalato. @@ -33,6 +34,7 @@ PlasmaExtras.Representation { // Nessun dato: si spiega cosa fare, invece di mostrare un popup vuoto. PlasmaExtras.PlaceholderMessage { + id: placeholder anchors.centerIn: parent width: parent.width - Kirigami.Units.gridUnit * 4 visible: full.windows.length === 0 @@ -67,6 +69,45 @@ PlasmaExtras.Representation { } return "" } + + // Quel che resta quando la percentuale manca: i transcript sul disco. + // Non e' una quota - i token si sanno, i limiti no - e va detto, + // altrimenti si legge come se lo fosse. + ColumnLayout { + Layout.alignment: Qt.AlignHCenter + Layout.topMargin: Kirigami.Units.largeSpacing + visible: full.local !== null + spacing: 2 + + PlasmaComponents.Label { + Layout.alignment: Qt.AlignHCenter + horizontalAlignment: Text.AlignHCenter + opacity: 0.7 + font: Kirigami.Theme.smallFont + text: full.local + ? i18n("From local transcripts (tokens, not quota):") + : "" + } + PlasmaComponents.Label { + Layout.alignment: Qt.AlignHCenter + horizontalAlignment: Text.AlignHCenter + font: Kirigami.Theme.smallFont + text: full.local + ? i18n("%1 in the last 5h · %2 this week", + Format.humanTokens(full.local.session_tokens), + Format.humanTokens(full.local.week_tokens)) + : "" + } + PlasmaComponents.Label { + Layout.alignment: Qt.AlignHCenter + opacity: 0.7 + font: Kirigami.Theme.smallFont + visible: text !== "" + text: full.local + ? Format.sinceActivity(full.local.last_activity, full.now, i18n) + : "" + } + } } contentItem: ColumnLayout { diff --git a/plasmoid/contents/ui/format.js b/plasmoid/contents/ui/format.js index c856e06..f5aad20 100644 --- a/plasmoid/contents/ui/format.js +++ b/plasmoid/contents/ui/format.js @@ -65,3 +65,44 @@ 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. +function humanTokens(n) { + if (typeof n !== "number" || n <= 0) { + return "0" + } + if (n >= 1e9) { + return (n / 1e9).toFixed(1) + "G" + } + if (n >= 1e6) { + return (n / 1e6).toFixed(1) + "M" + } + if (n >= 1e3) { + return Math.round(n / 1e3) + "k" + } + return String(n) +} + +// Da quanto non si lavora. Ritorna "" se non lo sappiamo. +function sinceActivity(isoString, now, i18n) { + if (!isoString) { + return "" + } + var then = new Date(isoString).getTime() + if (isNaN(then)) { + return "" + } + var mins = Math.round((now - then) / 60000) + if (mins < 2) { + return i18n("active just now") + } + if (mins < 60) { + return i18n("last active %1m ago", mins) + } + var hours = Math.round(mins / 60) + if (hours < 24) { + return i18n("last active %1h ago", hours) + } + return i18n("last active %1d ago", Math.round(hours / 24)) +}