diff --git a/README.md b/README.md index 4d84c2d..ec9dcfa 100644 --- a/README.md +++ b/README.md @@ -153,12 +153,20 @@ quota: { status: "fresh" | "stale" | "unavailable", compact: null | { primary, secondary } <- gia' scelto dal demone windows: [ finestra, ... ] <- dettaglio per il popup extra_usage_enabled: bool +account: null | { email, name, plan } <- da /api/oauth/profile +local: null | { scanned_at, last_activity, session_tokens, + week_tokens, messages, models: [ {id, tokens, messages} ] } finestra: { kind, group, percent, severity, resets_at, is_active, model? } ``` 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' il consumo per modello della +settimana corrente, ricavato dai transcript - non uno storico. + - **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 diff --git a/cmd/dipstick/main.go b/cmd/dipstick/main.go index 187c6cd..7dcd07b 100644 --- a/cmd/dipstick/main.go +++ b/cmd/dipstick/main.go @@ -150,6 +150,12 @@ func cmdState(args []string) error { } now := time.Now() + root, _ := transcript.Root() + activity, err := transcript.Scan(root, now) + if err != nil { + fmt.Fprintln(os.Stderr, "dipstick: scansione dei transcript fallita:", err) + } + var st *state.State if u, err := anthropic.FetchUsage(); err != nil { // Un fallimento non e' motivo per non scrivere: il plasmoide deve @@ -159,7 +165,13 @@ func cmdState(args []string) error { st = state.Unavailable(err, errors.Is(err, 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) + } } + st.WithLocal(activity) raw, err := st.Marshal() if err != nil { diff --git a/internal/anthropic/profile.go b/internal/anthropic/profile.go new file mode 100644 index 0000000..0a657a9 --- /dev/null +++ b/internal/anthropic/profile.go @@ -0,0 +1,82 @@ +package anthropic + +import ( + "encoding/json" + "fmt" + "strings" +) + +// Profile e' l'identita' dell'account: cambia solo con un logout/login, quindi +// si legge di rado. +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 string +} + +type rawProfile struct { + Account struct { + Email string `json:"email"` + DisplayName string `json:"display_name"` + FullName string `json:"full_name"` + HasClaudeMax bool `json:"has_claude_max"` + 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. + RateLimitTier string `json:"rate_limit_tier"` + } `json:"organization"` +} + +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) + } + p := &Profile{Email: raw.Account.Email, Name: raw.Account.DisplayName} + if p.Name == "" { + p.Name = raw.Account.FullName + } + p.Plan = planLabel(raw.Organization.RateLimitTier, raw.Account.HasClaudeMax, raw.Account.HasClaudePro) + 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. +func planLabel(tier string, hasMax, hasPro bool) string { + if rest, ok := strings.CutPrefix(tier, "default_claude_"); ok && rest != "" { + words := strings.Split(rest, "_") + for i, w := range words { + if w == "" { + continue + } + // "max" -> "Max", ma "20x" resta "20x": maiuscolare una cifra non + // cambia nulla e maiuscolare la x la imbruttisce. + if w[0] >= 'a' && w[0] <= 'z' { + words[i] = strings.ToUpper(w[:1]) + w[1:] + } + } + return strings.Join(words, " ") + } + switch { + case hasMax: + return "Max" + case hasPro: + return "Pro" + default: + return "" + } +} + +func FetchProfile() (*Profile, error) { + body, err := RawProfile() + if err != nil { + return nil, err + } + return ParseProfile(body) +} diff --git a/internal/anthropic/profile_test.go b/internal/anthropic/profile_test.go new file mode 100644 index 0000000..fd9de2a --- /dev/null +++ b/internal/anthropic/profile_test.go @@ -0,0 +1,44 @@ +package anthropic + +import "testing" + +func TestPlanLabelFromTier(t *testing.T) { + for _, tc := range []struct { + tier string + want string + }{ + {"default_claude_max_20x", "Max 20x"}, + {"default_claude_max_5x", "Max 5x"}, + {"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) + } + } +} + +// Il tier non e' documentato: se cambia forma si ricade sui booleani invece di +// mostrare una stringa incomprensibile. +func TestPlanLabelFallsBackToBooleans(t *testing.T) { + if got := planLabel("", true, false); got != "Max" { + t.Errorf("got %q, atteso Max", got) + } + if got := planLabel("qualcosa_di_nuovo", false, true); got != "Pro" { + t.Errorf("got %q, atteso Pro", got) + } + if got := planLabel("", false, false); got != "" { + t.Errorf("got %q, atteso vuoto", got) + } +} + +func TestParseProfilePrefersDisplayName(t *testing.T) { + p, err := ParseProfile([]byte(`{"account":{"email":"a@b.it","display_name":"Claudio", + "full_name":"Claudio Q","has_claude_max":true}, + "organization":{"rate_limit_tier":"default_claude_max_20x"}}`)) + if err != nil { + t.Fatal(err) + } + if p.Email != "a@b.it" || p.Name != "Claudio" || p.Plan != "Max 20x" { + t.Errorf("profilo = %+v", p) + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index b0fe6bc..09c7bfe 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -28,6 +28,8 @@ type Config struct { // StaleAfter e' da quanto puo' essere vecchia l'ultima lettura buona prima // che smettiamo di mostrarla. StaleAfter time.Duration + // ProfileEvery e' ogni quanto rileggere l'identita' dell'account. + ProfileEvery time.Duration } func DefaultConfig() Config { @@ -37,6 +39,7 @@ func DefaultConfig() Config { IdleAfter: 30 * time.Minute, MaxBackoff: 30 * time.Minute, StaleAfter: 2 * time.Hour, + ProfileEvery: 12 * time.Hour, } } @@ -50,20 +53,27 @@ type Daemon struct { 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. + 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. - fetchUsage func() (*anthropic.Usage, error) - writeState func(*state.State) error + fetchUsage func() (*anthropic.Usage, error) + fetchProfile func() (*anthropic.Profile, 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() }, + fetchUsage: anthropic.FetchUsage, + fetchProfile: anthropic.FetchProfile, + writeState: func(s *state.State) error { return s.Write() }, } } @@ -91,7 +101,7 @@ func (d *Daemon) tick(now time.Time) time.Duration { } st, ok := d.fetch(now) - st.WithLocal(activity) + st.WithLocal(activity).WithAccount(d.loadProfile(now, ok)) if err := d.writeState(st); err != nil { d.log.Error("scrittura dello stato fallita", "err", err) @@ -153,3 +163,23 @@ 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 { + return d.profile + } + if d.profile != nil && now.Sub(d.profileAt) < d.cfg.ProfileEvery { + return d.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) + return d.profile + } + d.profile, d.profileAt = p, now + return p +} diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index b545988..e7b091b 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -23,6 +23,9 @@ func harness(t *testing.T, fetch func() (*anthropic.Usage, error)) (*Daemon, *[] var written []*state.State d := New(DefaultConfig(), "", quiet()) d.fetchUsage = fetch + d.fetchProfile = func() (*anthropic.Profile, error) { + return &anthropic.Profile{Email: "a@b.it", Plan: "Max 20x"}, nil + } d.writeState = func(s *state.State) error { written = append(written, s) return nil @@ -187,3 +190,59 @@ func TestSuccessResetsBackoff(t *testing.T) { t.Errorf("attesa = %v, il backoff doveva ripartire da capo", got) } } + +// Il profilo e' contorno: se fallisce, la quota si mostra lo stesso. +func TestProfileFailureDoesNotBreakState(t *testing.T) { + d, written := harness(t, func() (*anthropic.Usage, error) { + return usageAt(30, now.Add(24*time.Hour)), nil + }) + d.fetchProfile = func() (*anthropic.Profile, error) { + return nil, errors.New("403") + } + d.tick(now) + last := (*written)[0] + if last.Quota.Status != state.StatusFresh { + t.Errorf("status = %q", last.Quota.Status) + } + if last.Account != nil { + t.Errorf("account = %+v, atteso nil", last.Account) + } +} + +// Il profilo cambia solo con un logout/login: non si rilegge a ogni giro. +func TestProfileIsCached(t *testing.T) { + calls := 0 + d, _ := harness(t, func() (*anthropic.Usage, error) { + return usageAt(30, now.Add(24*time.Hour)), nil + }) + d.fetchProfile = func() (*anthropic.Profile, error) { + calls++ + return &anthropic.Profile{Plan: "Max 20x"}, nil + } + d.tick(now) + 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) + } + d.tick(now.Add(DefaultConfig().ProfileEvery + time.Minute)) + if calls != 2 { + t.Errorf("letture del profilo = %d, attese 2 dopo la scadenza", calls) + } +} + +// Se la quota non risponde non ha senso insistere anche sul profilo. +func TestProfileNotFetchedWhenQuotaFails(t *testing.T) { + calls := 0 + d, _ := harness(t, func() (*anthropic.Usage, error) { + return nil, errors.New("503") + }) + d.fetchProfile = func() (*anthropic.Profile, error) { + calls++ + return &anthropic.Profile{}, nil + } + d.tick(now) + if calls != 0 { + t.Errorf("letture del profilo = %d, attesa 0", calls) + } +} diff --git a/internal/state/state.go b/internal/state/state.go index e930e4c..70c466d 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -46,6 +46,28 @@ type State struct { // token si conoscono, i limiti no - ma e' l'unica cosa vera che resta // quando l'endpoint non risponde. 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 *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"` +} + +// 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 } type Local struct { @@ -54,6 +76,8 @@ type Local struct { SessionTokens int64 `json:"session_tokens"` WeekTokens int64 `json:"week_tokens"` Messages int `json:"messages"` + // Models e' il consumo per modello nella settimana corrente. + Models []transcript.ModelUsage `json:"models,omitempty"` } // WithLocal allega i dati locali. Vengono allegati sempre, non solo in @@ -68,6 +92,7 @@ func (s *State) WithLocal(a *transcript.Activity) *State { SessionTokens: a.SessionTokens, WeekTokens: a.WeekTokens, Messages: a.Messages, + Models: a.Models, } if !a.LastActivity.IsZero() { t := a.LastActivity diff --git a/internal/transcript/transcript.go b/internal/transcript/transcript.go index a03f9a3..70eff6c 100644 --- a/internal/transcript/transcript.go +++ b/internal/transcript/transcript.go @@ -16,6 +16,7 @@ import ( "io/fs" "os" "path/filepath" + "sort" "time" ) @@ -36,6 +37,21 @@ type Activity struct { WeekTokens int64 // ultimi 7 giorni Messages int // messaggi distinti conteggiati FilesScanned int + + // Models e' il consumo per modello nella settimana. E' la finestra + // corrente, non uno storico: sapere quanto e' andato in Opus e quanto in + // Sonnet aiuta adesso, un archivio di trenta giorni no. + Models []ModelUsage +} + +// ModelUsage e' quanto e' costato un modello nella settimana. +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 string `json:"id"` + Tokens int64 `json:"tokens"` + Messages int `json:"messages"` } const ( @@ -84,6 +100,7 @@ func Scan(root string, now time.Time) (*Activity, error) { cutoff := now.Add(-weekWindow) sessionCutoff := now.Add(-sessionWindow) seen := make(map[string]struct{}, 16384) + models := map[string]*ModelUsage{} err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err != nil { @@ -99,17 +116,34 @@ func Scan(root string, now time.Time) (*Activity, error) { return nil } act.FilesScanned++ - scanFile(path, sessionCutoff, cutoff, seen, act) + scanFile(path, sessionCutoff, cutoff, seen, models, act) return nil }) if err != nil { return nil, err } act.Messages = len(seen) + act.Models = sortedModels(models) return act, nil } -func scanFile(path string, sessionCutoff, cutoff time.Time, seen map[string]struct{}, act *Activity) { +// 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) + } + 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 +} + +func scanFile(path string, sessionCutoff, cutoff time.Time, seen map[string]struct{}, models map[string]*ModelUsage, act *Activity) { // os.Open apre in sola lettura: e' il vincolo del progetto, reso esplicito. f, err := os.Open(path) if err != nil { @@ -157,6 +191,15 @@ func scanFile(path string, sessionCutoff, cutoff time.Time, seen map[string]stru if !ts.Before(sessionCutoff) { act.SessionTokens += n } + if id := l.Message.Model; id != "" { + m := models[id] + if m == nil { + m = &ModelUsage{ID: id} + models[id] = m + } + m.Tokens += n + m.Messages++ + } } } diff --git a/internal/transcript/transcript_test.go b/internal/transcript/transcript_test.go index a7fd68d..575e4f7 100644 --- a/internal/transcript/transcript_test.go +++ b/internal/transcript/transcript_test.go @@ -168,3 +168,38 @@ func TestIdle(t *testing.T) { t.Error("senza attivita' nota non si deve concludere che sia idle") } } + +func TestScanBreaksDownByModel(t *testing.T) { + dir := t.TempDir() + write(t, dir, "p/a.jsonl", now, + msg("m1", "claude-sonnet-5", ago(time.Hour), 10, 0, 0, 0), + msg("m2", "claude-opus-5", ago(time.Hour), 100, 0, 0, 0), + 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) + if len(act.Models) != 2 { + t.Fatalf("modelli = %+v, attesi 2 ( escluso)", act.Models) + } + // Ordinati dal piu' costoso: e' l'ordine in cui interessano. + if act.Models[0].ID != "claude-opus-5" || act.Models[0].Tokens != 150 { + t.Errorf("primo = %+v, atteso opus con 150", act.Models[0]) + } + if act.Models[0].Messages != 2 { + t.Errorf("messaggi opus = %d, attesi 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) + } +} diff --git a/plasmoid/contents/ui/FullRepresentation.qml b/plasmoid/contents/ui/FullRepresentation.qml index 60cebfd..5df1dee 100644 --- a/plasmoid/contents/ui/FullRepresentation.qml +++ b/plasmoid/contents/ui/FullRepresentation.qml @@ -1,6 +1,12 @@ /* - * Il popup: tutte le finestre, incluse quelle per modello, con il conto alla - * rovescia fino al reset e lo stato di freschezza del dato. + * Il 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. + * + * 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. */ import QtQuick import QtQuick.Layouts @@ -15,9 +21,11 @@ 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 + 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 mentre il popup e' aperto: - // un timer che gira dentro plasmashell a widget chiuso e' lavoro regalato. + // Il conto alla rovescia deve muoversi, ma solo a popup aperto: un timer + // che gira dentro plasmashell a widget chiuso e' lavoro regalato. property double now: Date.now() Timer { interval: 30000 @@ -27,17 +35,63 @@ PlasmaExtras.Representation { } onVisibleChanged: if (visible) now = Date.now() - Layout.minimumWidth: Kirigami.Units.gridUnit * 18 + Layout.minimumWidth: Kirigami.Units.gridUnit * 20 Layout.minimumHeight: Kirigami.Units.gridUnit * 12 - collapseMarginsHint: true + header: PlasmaExtras.PlasmoidHeading { + visible: full.hasData + contentItem: RowLayout { + spacing: Kirigami.Units.smallSpacing + + Kirigami.Icon { + implicitWidth: Kirigami.Units.iconSizes.small + implicitHeight: Kirigami.Units.iconSizes.small + source: "speedometer" + } + + PlasmaExtras.Heading { + Layout.fillWidth: true + level: 4 + elide: Text.ElideRight + text: i18n("Claude usage") + } + + // Il piano come pastiglia: e' un'etichetta di stato, non un titolo. + Rectangle { + visible: full.account && full.account.plan + Layout.alignment: Qt.AlignVCenter + implicitWidth: planLabel.implicitWidth + Kirigami.Units.smallSpacing * 3 + implicitHeight: planLabel.implicitHeight + Kirigami.Units.smallSpacing + radius: height / 2 + // Il colore porta gia' la trasparenza: usare `opacity` sul + // rettangolo la moltiplicherebbe anche sul testo figlio, + // sbiadendolo. + color: Qt.rgba(Kirigami.Theme.highlightColor.r, + Kirigami.Theme.highlightColor.g, + Kirigami.Theme.highlightColor.b, 0.25) + + PlasmaComponents.Label { + id: planLabel + anchors.centerIn: parent + // Nome di prodotto, non testo tradotto. + text: full.account ? full.account.plan : "" + font.pointSize: Kirigami.Theme.smallFont.pointSize + font.weight: Font.Bold + } + } + } + } + + contentItem: Item { + // Il popup si dimensiona sul contenuto: senza questo userebbe sempre + // l'altezza minima, lasciando un vuoto sotto le sezioni. + implicitHeight: sections.implicitHeight // 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 + visible: !full.hasData iconName: "speedometer" text: { if (root.stateProblem === "missing") { @@ -70,9 +124,8 @@ 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. + // 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. ColumnLayout { Layout.alignment: Qt.AlignHCenter Layout.topMargin: Kirigami.Units.largeSpacing @@ -81,16 +134,12 @@ PlasmaExtras.Representation { 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):") - : "" + text: 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", @@ -110,64 +159,78 @@ PlasmaExtras.Representation { } } - contentItem: ColumnLayout { - spacing: Kirigami.Units.smallSpacing - visible: full.windows.length > 0 + ColumnLayout { + id: sections + anchors.fill: parent + spacing: Kirigami.Units.largeSpacing + visible: full.hasData + // Le righe hanno bisogno di piu' aria fra loro che al loro interno, + // o le tre barre sottili si leggono come un blocco solo. Repeater { model: full.windows - - delegate: ColumnLayout { - required property var modelData + delegate: QuotaRow { + Layout.topMargin: index > 0 ? Kirigami.Units.smallSpacing : 0 required property int index + required property var modelData + window: modelData + now: full.now + } + } - Layout.fillWidth: true - Layout.topMargin: index > 0 ? Kirigami.Units.smallSpacing : 0 - spacing: 2 + Kirigami.Separator { + Layout.fillWidth: true + visible: full.local !== null + } - RowLayout { - Layout.fillWidth: true - PlasmaComponents.Label { - Layout.fillWidth: true - elide: Text.ElideRight - text: Format.windowLabel(modelData, i18n) - // La finestra che sta accumulando e' quella su cui - // l'utente sta effettivamente consumando adesso. - font.weight: modelData.is_active ? Font.Bold : Font.Normal - } - PlasmaComponents.Label { - text: i18nc("percentage of quota used", "%1%", modelData.percent) - font.weight: Font.Bold - color: { - switch (Format.severityRank(modelData.severity)) { - case 0: return Kirigami.Theme.textColor - case 1: return Kirigami.Theme.neutralTextColor - default: return Kirigami.Theme.negativeTextColor - } - } - } - } + // I dati locali: token, non quota. L'etichetta lo dice, perche' due + // numeri accostati a delle percentuali si leggono come se fossero la + // stessa cosa. + ColumnLayout { + Layout.fillWidth: true + visible: full.local !== null + spacing: Kirigami.Units.smallSpacing - PlasmaComponents.ProgressBar { + RowLayout { + Layout.fillWidth: true + PlasmaComponents.Label { Layout.fillWidth: true - from: 0 - to: 100 - value: modelData.percent + text: i18n("Tokens used") + font.pointSize: Kirigami.Theme.smallFont.pointSize + font.weight: Font.Bold } - PlasmaComponents.Label { - text: Format.untilReset(modelData.resets_at, full.now, i18n) - visible: text !== "" + text: full.local + ? i18n("%1 in 5h · %2 this week", + Format.humanTokens(full.local.session_tokens), + Format.humanTokens(full.local.week_tokens)) + : "" opacity: 0.7 font: Kirigami.Theme.smallFont } } + + ModelBreakdown { + Layout.fillWidth: true + models: full.local ? full.local.models : [] + } + } + + // La freschezza del dato e' parte del dato: un numero vecchio senza + // dirlo e' peggio di nessun numero. + PlasmaComponents.Label { + Layout.fillWidth: true + visible: full.quota && full.quota.quota.status !== "fresh" + wrapMode: Text.Wrap + color: Kirigami.Theme.neutralTextColor + font: Kirigami.Theme.smallFont + text: i18n("Quota data may be out of date.") } Item { Layout.fillHeight: true } // Con i crediti attivi il 100% non blocca piu': mostrarlo come un muro - // sarebbe sbagliato, e l'utente deve saperlo. + // sarebbe una bugia. PlasmaComponents.Label { Layout.fillWidth: true visible: full.quota && full.quota.extra_usage_enabled @@ -176,17 +239,18 @@ PlasmaExtras.Representation { font: Kirigami.Theme.smallFont text: i18n("Extra usage credits are enabled: reaching 100% will not block you.") } + } - // La freschezza del dato e' parte del dato: un numero vecchio senza - // dirlo e' peggio di nessun numero. - PlasmaComponents.Label { - Layout.fillWidth: true - visible: full.quota && full.quota.quota.status !== "fresh" - wrapMode: Text.Wrap - opacity: 0.7 + } + + footer: PlasmaExtras.PlasmoidHeading { + position: PlasmaExtras.PlasmoidHeading.Position.Footer + visible: full.hasData && full.account && (full.account.email || full.account.name) + contentItem: PlasmaComponents.Label { + elide: Text.ElideRight + opacity: 0.6 font: Kirigami.Theme.smallFont - color: Kirigami.Theme.neutralTextColor - text: i18n("Quota data may be out of date.") + text: full.account ? (full.account.email || full.account.name) : "" } } } diff --git a/plasmoid/contents/ui/ModelBreakdown.qml b/plasmoid/contents/ui/ModelBreakdown.qml new file mode 100644 index 0000000..9e12720 --- /dev/null +++ b/plasmoid/contents/ui/ModelBreakdown.qml @@ -0,0 +1,111 @@ +/* + * Dove sono finiti i token della settimana, per modello. + * + * 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. + */ +import QtQuick +import QtQuick.Layouts +import org.kde.plasma.components as PlasmaComponents +import org.kde.kirigami as Kirigami +import "format.js" as Format + +ColumnLayout { + id: breakdown + + property var models: [] + + // Piu' di quattro voci diventano schegge illeggibili nella barra e righe + // di rumore nella legenda. + readonly property int maxItems: 4 + readonly property var shown: models ? models.slice(0, maxItems) : [] + readonly property double total: { + var sum = 0 + for (var i = 0; i < shown.length; i++) { + sum += shown[i].tokens + } + return sum + } + + function tint(i) { + // Gradazioni discendenti: il modello dominante e' il piu' pieno. + return Qt.rgba(Kirigami.Theme.highlightColor.r, + Kirigami.Theme.highlightColor.g, + Kirigami.Theme.highlightColor.b, + Math.max(0.25, 1.0 - i * 0.25)) + } + + Layout.fillWidth: true + spacing: Kirigami.Units.smallSpacing + 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. + readonly property int barHeight: Math.round(Kirigami.Units.gridUnit * 0.35) + + Layout.fillWidth: true + Layout.fillHeight: false + Layout.preferredHeight: barHeight + Layout.minimumHeight: barHeight + Layout.maximumHeight: barHeight + spacing: 2 + + Repeater { + model: breakdown.shown + delegate: Rectangle { + required property var modelData + required property int index + + Layout.fillWidth: true + Layout.fillHeight: true + // La larghezza e' la quota sul totale: e' l'unica cosa che la + // barra deve dire. + Layout.preferredWidth: Format.share(modelData.tokens, breakdown.total) * 1000 + radius: height / 2 + color: breakdown.tint(index) + } + } + } + + GridLayout { + Layout.fillWidth: true + columns: 2 + columnSpacing: Kirigami.Units.largeSpacing + rowSpacing: 2 + + Repeater { + model: breakdown.shown + delegate: RowLayout { + required property var modelData + required property int index + + Layout.fillWidth: true + spacing: Kirigami.Units.smallSpacing + + Rectangle { + Layout.alignment: Qt.AlignVCenter + implicitWidth: Kirigami.Units.smallSpacing + implicitHeight: Kirigami.Units.smallSpacing + radius: width / 2 + color: breakdown.tint(index) + } + PlasmaComponents.Label { + Layout.fillWidth: true + elide: Text.ElideRight + text: Format.modelName(modelData.id) + font: Kirigami.Theme.smallFont + } + PlasmaComponents.Label { + text: Format.humanTokens(modelData.tokens) + opacity: 0.6 + font: Kirigami.Theme.smallFont + } + } + } + } +} diff --git a/plasmoid/contents/ui/QuotaRow.qml b/plasmoid/contents/ui/QuotaRow.qml new file mode 100644 index 0000000..07289fd --- /dev/null +++ b/plasmoid/contents/ui/QuotaRow.qml @@ -0,0 +1,66 @@ +/* + * Una finestra di rate limit: etichetta, quando si resetta, la barra, la + * percentuale. + */ +import QtQuick +import QtQuick.Layouts +import org.kde.plasma.components as PlasmaComponents +import org.kde.kirigami as Kirigami +import "format.js" as Format + +ColumnLayout { + id: row + + property var window: null + property double now: 0 + + Layout.fillWidth: true + spacing: Kirigami.Units.smallSpacing / 2 + + readonly property color accent: { + switch (Format.severityRank(window ? window.severity : "")) { + case 0: return Kirigami.Theme.textColor + case 1: return Kirigami.Theme.neutralTextColor + default: return Kirigami.Theme.negativeTextColor + } + } + + RowLayout { + Layout.fillWidth: true + spacing: Kirigami.Units.smallSpacing + + PlasmaComponents.Label { + Layout.fillWidth: true + elide: Text.ElideRight + text: Format.windowLabel(row.window, i18n) + // La finestra attiva e' quella su cui si sta consumando adesso. + font.weight: row.window && row.window.is_active ? Font.Bold : Font.Normal + } + + PlasmaComponents.Label { + text: row.window ? Format.untilReset(row.window.resets_at, row.now, i18n) : "" + visible: text !== "" + opacity: 0.6 + font: Kirigami.Theme.smallFont + } + } + + PlasmaComponents.ProgressBar { + Layout.fillWidth: true + from: 0 + to: 100 + 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. + PlasmaComponents.Label { + text: row.window + ? i18nc("how much of a quota window is consumed", "%1% used", row.window.percent) + : "" + color: row.accent + opacity: row.accent === Kirigami.Theme.textColor ? 0.75 : 1.0 + font.pointSize: Kirigami.Theme.smallFont.pointSize + font.weight: Font.DemiBold + } +} diff --git a/plasmoid/contents/ui/format.js b/plasmoid/contents/ui/format.js index f5aad20..724b217 100644 --- a/plasmoid/contents/ui/format.js +++ b/plasmoid/contents/ui/format.js @@ -106,3 +106,36 @@ function sinceActivity(isoString, now, i18n) { } return i18n("last active %1d ago", Math.round(hours / 24)) } + +// "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. +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. + if (parts.length > 1 && /^\d{8}$/.test(parts[parts.length - 1])) { + parts.pop() + } + var name = parts.shift() || "" + 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. + var version = parts.filter(function(p) { return p.length > 0 }) + if (version.length === 0) { + return name + } + return name + " " + (version.every(function(p) { return /^\d+$/.test(p) }) + ? version.join(".") + : version.join(" ")) +} + +// Quota di un modello sul totale della settimana, come frazione 0..1. +function share(tokens, total) { + return total > 0 ? Math.max(0, tokens) / total : 0 +}