diff --git a/README.md b/README.md index ded6e1c..202dee0 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,40 @@ Fallback locale: `~/.claude/projects/**/*.jsonl`, un JSON per riga, campo `usage messaggio con `input_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`, `output_tokens`, `output_tokens_details.thinking_tokens`. +## Contratto fra demone e plasmoide + +`$XDG_CONFIG_HOME/dipstick/state.json` (0644), riscritto in modo atomico +(write su temporaneo + rename): il plasmoide rilegge senza coordinamento, quindi +deve vedere sempre o il vecchio o il nuovo, mai meta' JSON. + +``` +schema: intero, versionato. Il plasmoide rifiuta uno schema che non conosce + invece di disegnare numeri a caso. +quota: { status: "fresh" | "stale" | "unavailable", + fetched_at, <- ultima lettura RIUSCITA, non questo giro + error, needs_auth } <- "rifai il login" vs "riprova piu' tardi" +compact: null | { primary, secondary } <- gia' scelto dal demone +windows: [ finestra, ... ] <- dettaglio per il popup +extra_usage_enabled: bool + +finestra: { kind, group, percent, severity, resets_at, is_active, model? } +``` + +Due regole, entrambe per tenere il plasmoide stupido: + +- **Nessuna stringa di interfaccia.** Solo `kind` semantici e il nome del modello + come lo manda il server. La localizzazione e' del plasmoide, che ha `i18n()` e + segue la lingua della sessione; il demone gira senza contesto di locale e + andrebbe riavviato per cambiarla. +- **Le decisioni le prende il demone.** `compact.primary` e' gia' il vincolo che si + tocca per primo - la piu' alta fra sessione e settimana, con la settimana che + vince a parita' perche' la sessione si ricarica in poche ore e lei no. Le + finestre per modello non entrano mai nel panel: una scoped alta non blocca, + si cambia modello. QML disegna e basta. + +`compact: null` significa nessun dato: il plasmoide mostra un trattino, non uno zero. + + ## Assunzioni - L'abbonamento e' Claude Max (`rateLimitTier: default_claude_max_20x`). Il comportamento @@ -157,6 +191,7 @@ Nessuna: chiuse tutte al kickoff, vedi "Decisioni gia' prese". ## Stato -Domande aperte chiuse. Esiste uno spike di autenticazione funzionante -(`cmd/dipstick`, `internal/anthropic`) che ha verificato il contratto qui sopra -contro l'endpoint reale. Il demone e il plasmoide non esistono ancora. +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. diff --git a/cmd/dipstick/main.go b/cmd/dipstick/main.go index c5e76ed..55cda98 100644 --- a/cmd/dipstick/main.go +++ b/cmd/dipstick/main.go @@ -14,8 +14,10 @@ import ( "os" "os/exec" "strings" + "time" "github.com/claudioquaglia/dipstick/internal/anthropic" + "github.com/claudioquaglia/dipstick/internal/state" ) func main() { @@ -37,6 +39,8 @@ func run(args []string) error { return dump(anthropic.RawUsage) case "profile": return dump(anthropic.RawProfile) + case "state": + return cmdState(args[1:]) case "logout": if err := anthropic.Logout(); err != nil { return err @@ -54,16 +58,19 @@ func run(args []string) error { func usage() { path, _ := anthropic.TokenPath() + statePath, _ := state.Path() fmt.Fprintf(os.Stderr, `dipstick — spike di autenticazione 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 logout rimuove il token locale Il token vive in %s (0600). +Lo stato in %s (0644). ~/.claude/ non viene mai toccato. -`, path) +`, path, statePath) } // dump stampa la risposta indentata se e' JSON valido, grezza altrimenti: @@ -119,3 +126,42 @@ func cmdAuth(args []string) error { fmt.Printf("\nAutenticato. Token salvato in %s\nProva con: 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. +func cmdState(args []string) error { + write := false + for _, a := range args { + if a == "--write" { + write = true + } + } + + now := time.Now() + 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) + } else { + st = state.FromUsage(u, now) + } + + raw, err := st.Marshal() + if err != nil { + return err + } + fmt.Print(string(raw)) + + if write { + if err := st.Write(); err != nil { + return err + } + path, _ := state.Path() + fmt.Fprintln(os.Stderr, "scritto in", path) + } + return nil +} diff --git a/internal/anthropic/usage.go b/internal/anthropic/usage.go new file mode 100644 index 0000000..9305856 --- /dev/null +++ b/internal/anthropic/usage.go @@ -0,0 +1,174 @@ +package anthropic + +import ( + "encoding/json" + "fmt" + "math" + "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. +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 + IsActive bool + Model string // nome del modello per le finestre scoped, "" altrimenti +} + +// Usage e' la risposta di /api/oauth/usage ridotta a cio' che ci serve. +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 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. +type rawUsage struct { + Limits []struct { + Kind string `json:"kind"` + Group string `json:"group"` + Percent float64 `json:"percent"` + Severity string `json:"severity"` + ResetsAt *string `json:"resets_at"` + IsActive bool `json:"is_active"` + Scope *struct { + Model *struct { + DisplayName string `json:"display_name"` + } `json:"model"` + } `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. + FiveHour *rawLegacyWindow `json:"five_hour"` + SevenDay *rawLegacyWindow `json:"seven_day"` + + ExtraUsage *struct { + IsEnabled bool `json:"is_enabled"` + } `json:"extra_usage"` +} + +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. + Utilization float64 `json:"utilization"` + ResetsAt *string `json:"resets_at"` +} + +func parseTime(s *string) *time.Time { + if s == nil || *s == "" { + return nil + } + t, err := time.Parse(time.RFC3339, *s) + if err != nil { + return nil + } + return &t +} + +func clampPercent(f float64) int { + p := int(math.Round(f)) + if p < 0 { + return 0 + } + if p > 100 { + return 100 + } + return p +} + +// ParseUsage normalizza la risposta grezza. +// +// 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. +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) + } + + u := &Usage{} + if raw.ExtraUsage != nil { + u.ExtraUsageEnabled = raw.ExtraUsage.IsEnabled + } + + for _, l := range raw.Limits { + w := Window{ + Kind: l.Kind, + Group: l.Group, + Percent: clampPercent(l.Percent), + Severity: l.Severity, + ResetsAt: parseTime(l.ResetsAt), + IsActive: l.IsActive, + } + if l.Scope != nil && l.Scope.Model != nil { + w.Model = l.Scope.Model.DisplayName + } + u.Windows = append(u.Windows, w) + } + if len(u.Windows) > 0 { + return u, nil + } + + // Fallback: limits[] assente. Ricostruiamo il minimo indispensabile. + // severity resta vuoto perche' non lo sappiamo, e inventarlo sarebbe + // peggio che ometterlo. + if raw.FiveHour != nil { + u.Windows = append(u.Windows, Window{ + Kind: KindSession, Group: GroupSession, + Percent: clampPercent(raw.FiveHour.Utilization), + ResetsAt: parseTime(raw.FiveHour.ResetsAt), + }) + } + if raw.SevenDay != nil { + u.Windows = append(u.Windows, Window{ + Kind: KindWeeklyAll, Group: GroupWeekly, + Percent: clampPercent(raw.SevenDay.Utilization), + ResetsAt: parseTime(raw.SevenDay.ResetsAt), + }) + } + if len(u.Windows) == 0 { + return nil, fmt.Errorf("nessuna finestra di quota nella risposta") + } + 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'. +const ( + KindSession = "session" + KindWeeklyAll = "weekly_all" + KindWeeklyScoped = "weekly_scoped" + + GroupSession = "session" + GroupWeekly = "weekly" +) + +// Find restituisce la prima finestra con il kind dato. +func (u *Usage) Find(kind string) *Window { + for i := range u.Windows { + if u.Windows[i].Kind == kind { + return &u.Windows[i] + } + } + return nil +} + +// FetchUsage legge e normalizza in un colpo solo. +func FetchUsage() (*Usage, error) { + body, err := RawUsage() + if err != nil { + return nil, err + } + return ParseUsage(body) +} diff --git a/internal/anthropic/usage_test.go b/internal/anthropic/usage_test.go new file mode 100644 index 0000000..2533b27 --- /dev/null +++ b/internal/anthropic/usage_test.go @@ -0,0 +1,103 @@ +package anthropic + +import ( + "os" + "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. +func loadFixture(t *testing.T) []byte { + t.Helper() + raw, err := os.ReadFile("testdata/usage.json") + if err != nil { + t.Fatal(err) + } + return raw +} + +func TestParseUsageRealShape(t *testing.T) { + u, err := ParseUsage(loadFixture(t)) + if err != nil { + t.Fatal(err) + } + if len(u.Windows) != 3 { + t.Fatalf("finestre = %d, attese 3", len(u.Windows)) + } + + session := u.Find(KindSession) + if session == nil || session.Percent != 12 || session.Severity != "normal" { + t.Errorf("session = %+v", session) + } + if session.ResetsAt == nil { + t.Error("session senza resets_at") + } + + weekly := u.Find(KindWeeklyAll) + if weekly == nil || weekly.Percent != 30 || !weekly.IsActive { + 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. + scoped := u.Find(KindWeeklyScoped) + if scoped == nil || scoped.Model != "Fable" || scoped.Percent != 9 { + t.Errorf("weekly_scoped = %+v, atteso model=Fable percent=9", scoped) + } + + if u.ExtraUsageEnabled { + t.Error("extra_usage risulta attivo, la fixture dice false") + } +} + +// I campi in codice (tangelo, iguana_necktie, nimbus_quill...) non devono +// rompere il parsing, e nemmeno finire fra le finestre. +func TestParseUsageIgnoresUnknownFields(t *testing.T) { + u, err := ParseUsage([]byte(`{ + "limits": [{"kind":"session","group":"session","percent":5,"severity":"normal","is_active":true}], + "wildcard_feature": {"utilization": 99.0}, + "qualcosa_di_nuovo": [1,2,3] + }`)) + if err != nil { + t.Fatal(err) + } + if len(u.Windows) != 1 || u.Windows[0].Percent != 5 { + t.Errorf("windows = %+v", u.Windows) + } +} + +// Se limits[] sparisce si ricade sui campi di primo livello, dove utilization +// e' un float da arrotondare. +func TestParseUsageFallsBackToTopLevel(t *testing.T) { + u, err := ParseUsage([]byte(`{ + "limits": [], + "five_hour": {"utilization": 12.4, "resets_at": "2026-08-27T14:59:59Z"}, + "seven_day": {"utilization": 30.6, "resets_at": "2026-08-28T00:59:59Z"} + }`)) + if err != nil { + t.Fatal(err) + } + if w := u.Find(KindSession); w == nil || w.Percent != 12 { + t.Errorf("session = %+v, atteso percent=12", w) + } + if w := u.Find(KindWeeklyAll); w == nil || w.Percent != 31 { + t.Errorf("weekly = %+v, atteso percent=31 (arrotondato)", 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") + } +} + +func TestClampPercent(t *testing.T) { + for _, tc := range []struct { + in float64 + 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) + } + } +} diff --git a/internal/state/state.go b/internal/state/state.go new file mode 100644 index 0000000..884621a --- /dev/null +++ b/internal/state/state.go @@ -0,0 +1,192 @@ +// Package state definisce il file che il demone scrive e il plasmoide legge. +// +// 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. +// +// 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. +package state + +import ( + "encoding/json" + "os" + "path/filepath" + "time" + + "github.com/claudioquaglia/dipstick/internal/anthropic" +) + +// SchemaVersion cambia solo per modifiche incompatibili. Il plasmoide rifiuta +// uno schema che non conosce invece di disegnare numeri a caso. +const SchemaVersion = 1 + +// Stati di freschezza del dato di quota. +const ( + StatusFresh = "fresh" // letto ora dall'endpoint + StatusStale = "stale" // l'ultima lettura riuscita e' vecchia + StatusUnavailable = "unavailable" // nessuna lettura riuscita +) + +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 *Compact `json:"compact"` + // Windows e' il dettaglio per il popup, incluse le finestre per modello. + Windows []Window `json:"windows"` + // ExtraUsageEnabled: con i crediti attivi il 100% non blocca piu'. + ExtraUsageEnabled bool `json:"extra_usage_enabled"` +} + +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. +// +// 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. +func pickCompact(windows []Window) *Compact { + var session, weekly *Window + for i := range windows { + switch windows[i].Kind { + case anthropic.KindSession: + session = &windows[i] + case anthropic.KindWeeklyAll: + weekly = &windows[i] + } + } + switch { + case session == nil && weekly == nil: + return nil + case session == nil: + return &Compact{Primary: *weekly} + case weekly == nil: + 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. + 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. +func Path() (string, error) { + dir, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(dir, "dipstick", "state.json"), nil +} + +func (s *State) Marshal() ([]byte, error) { + raw, err := json.MarshalIndent(s, "", " ") + if err != nil { + return nil, err + } + return append(raw, '\n'), nil +} + +// Write scrive lo stato in modo atomico. +// +// 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'. +func (s *State) Write() error { + path, err := Path() + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + raw, err := s.Marshal() + 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 { + return err + } + if err := os.Rename(tmp, path); err != nil { + os.Remove(tmp) + return err + } + return nil +} diff --git a/internal/state/state_test.go b/internal/state/state_test.go new file mode 100644 index 0000000..492f923 --- /dev/null +++ b/internal/state/state_test.go @@ -0,0 +1,144 @@ +package state + +import ( + "encoding/json" + "os" + "testing" + "time" + + "github.com/claudioquaglia/dipstick/internal/anthropic" +) + +func fixtureUsage(t *testing.T) *anthropic.Usage { + t.Helper() + raw, err := os.ReadFile("../anthropic/testdata/usage.json") + if err != nil { + t.Fatal(err) + } + u, err := anthropic.ParseUsage(raw) + if err != nil { + t.Fatal(err) + } + return u +} + +func TestFromUsageRealShape(t *testing.T) { + now := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC) + s := FromUsage(fixtureUsage(t), now) + + if s.Schema != SchemaVersion || s.Quota.Status != StatusFresh { + 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)) + } + // Settimana al 30 contro sessione al 12: nel panel va la settimana. + 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) + } + if s.Compact.Secondary == nil || s.Compact.Secondary.Percent != 12 { + t.Errorf("secondary = %+v, attesa la sessione al 12", s.Compact.Secondary) + } +} + +func TestPickCompactPrefersTheTighterWindow(t *testing.T) { + cases := []struct { + name string + session, weekly int + 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}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := pickCompact([]Window{ + {Kind: anthropic.KindSession, Percent: tc.session}, + {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) + } + if c.Secondary == nil { + t.Error("secondary mancante: la barra sottile resta senza dato") + } + }) + } +} + +// Le finestre per modello non devono mai finire nel panel: una scoped alta non +// blocca, si cambia modello. +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) + } + if c.Secondary != nil { + t.Errorf("secondary = %+v, atteso nil senza 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) + } +} + +func TestUnavailableCarriesTheReason(t *testing.T) { + now := time.Now() + s := Unavailable(anthropic.ErrNoAuth, true, now) + if s.Quota.Status != StatusUnavailable || !s.Quota.NeedsAuth { + t.Errorf("quota = %+v", s.Quota) + } + if s.Compact != nil { + t.Error("compact deve essere nil: senza dato non si mostra uno zero") + } + if s.Quota.Error == "" { + t.Error("errore perso: il plasmoide non puo' spiegare cosa non va") + } +} + +// Lo schema e' il contratto col plasmoide: se cambiano i nomi dei campi, QML +// smette di leggere. Questo test lo rende un cambiamento deliberato. +func TestJSONFieldNames(t *testing.T) { + now := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC) + raw, err := FromUsage(fixtureUsage(t), now).Marshal() + if err != nil { + t.Fatal(err) + } + var m map[string]json.RawMessage + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatal(err) + } + 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) + } + } + var c struct { + Primary struct { + Kind string `json:"kind"` + Percent *int `json:"percent"` + Severity string `json:"severity"` + } `json:"primary"` + Secondary *struct { + Percent *int `json:"percent"` + } `json:"secondary"` + } + if err := json.Unmarshal(m["compact"], &c); err != nil { + t.Fatal(err) + } + if c.Primary.Kind == "" || c.Primary.Percent == nil || c.Secondary == nil { + t.Errorf("compact incompleto: %+v", c) + } +}