// Package state defines the file the daemon writes and the plasmoid reads. // // It is the only point of contact between the two halves of the project, so // the schema is the contract: it is versioned and changed on purpose. The // plasmoid only draws, so every decision - which window is the tightest, // whether the data is fresh - is made here and not in QML. // // It carries no interface strings: only semantic `kind` values and the model // name. Localisation belongs to the plasmoid, which has i18n() and follows the // session language; the daemon runs with no locale context. package state import ( "encoding/json" "os" "path/filepath" "time" "github.com/claudioquaglia/dipstick/internal/anthropic" "github.com/claudioquaglia/dipstick/internal/transcript" ) // SchemaVersion changes only for incompatible changes. The plasmoid refuses a // schema it does not know rather than draw arbitrary numbers. const SchemaVersion = 1 // Freshness of the quota data. const ( StatusFresh = "fresh" // just read from the endpoint StatusStale = "stale" // the last successful read is old StatusUnavailable = "unavailable" // no successful read at all ) type State struct { Schema int `json:"schema"` GeneratedAt time.Time `json:"generated_at"` Quota Quota `json:"quota"` // Compact is what goes in the panel, already decided. nil when there is // nothing to show: the plasmoid draws a dash, not a zero. Compact *Compact `json:"compact"` // Windows is the detail for the popup, per-model windows included. Windows []Window `json:"windows"` // ExtraUsageEnabled: with credits on, 100% no longer blocks. ExtraUsageEnabled bool `json:"extra_usage_enabled"` // Local is what the transcripts on disk say. It is not a quota - the // tokens are known, the limits are not - but it is the only true thing // left when the endpoint does not answer. Local *Local `json:"local,omitempty"` // Account is the identity of the configured plan. It only changes on // logout/login, so the daemon re-reads it rarely. Account *Account `json:"account,omitempty"` } type Quota struct { Status string `json:"status"` // FetchedAt is the moment of the last SUCCESSFUL read, not of this round: // it is what tells how much the number on screen can be trusted. FetchedAt *time.Time `json:"fetched_at,omitempty"` Error string `json:"error,omitempty"` // NeedsAuth separates "log in again" from "try later". The plasmoid must // be able to tell the user which of the two applies. NeedsAuth bool `json:"needs_auth,omitempty"` } // Compact is the decision already made for the panel: Primary is the // constraint that will be hit first, and the bar shows the same figure. type Compact struct { Primary Window `json:"primary"` Secondary *Window `json:"secondary,omitempty"` } type Window struct { Kind string `json:"kind"` Group string `json:"group"` Percent int `json:"percent"` Severity string `json:"severity,omitempty"` ResetsAt *time.Time `json:"resets_at,omitempty"` IsActive bool `json:"is_active"` // Model is set only for scoped windows, with the name the server sends. // It is not a closed set: render it as it arrives. Model string `json:"model,omitempty"` } type Local struct { ScannedAt time.Time `json:"scanned_at"` LastActivity *time.Time `json:"last_activity,omitempty"` SessionTokens int64 `json:"session_tokens"` TodayTokens int64 `json:"today_tokens"` WeekTokens int64 `json:"week_tokens"` MonthTokens int64 `json:"month_tokens"` Messages int `json:"messages"` // Models and Daily cover the same span, so the legend and the chart // describe the same period. Models []transcript.ModelUsage `json:"models,omitempty"` Daily []transcript.DayUsage `json:"daily,omitempty"` } type Account struct { Email string `json:"email,omitempty"` Name string `json:"name,omitempty"` // Plan is a product name ("Max 20x"), not interface text: it is not // translated, so it belongs here. Plan string `json:"plan,omitempty"` } func fromAPI(w anthropic.Window) Window { return Window{ Kind: w.Kind, Group: w.Group, Percent: w.Percent, Severity: w.Severity, ResetsAt: w.ResetsAt, IsActive: w.IsActive, Model: w.Model, } } // FromUsage builds the state from a successful read. func FromUsage(u *anthropic.Usage, now time.Time) *State { s := &State{ Schema: SchemaVersion, GeneratedAt: now, Quota: Quota{Status: StatusFresh, FetchedAt: &now}, ExtraUsageEnabled: u.ExtraUsageEnabled, } for _, w := range u.Windows { s.Windows = append(s.Windows, fromAPI(w)) } s.Compact = pickCompact(s.Windows) return s } // WithLocal attaches the local data. It is attached always, not only when // degraded: knowing when work last happened is useful anyway, and the scan has // already paid for it. func (s *State) WithLocal(a *transcript.Activity) *State { if s == nil || a == nil { return s } l := &Local{ ScannedAt: a.ScannedAt, SessionTokens: a.SessionTokens, TodayTokens: a.TodayTokens, WeekTokens: a.WeekTokens, MonthTokens: a.MonthTokens, Messages: a.Messages, Models: a.Models, Daily: a.Daily, } if !a.LastActivity.IsZero() { t := a.LastActivity l.LastActivity = &t } s.Local = l return s } // WithAccount attaches the identity. It may be missing - the profile is an // extra request that can fail on its own - and then the popup simply shows no // account line. func (s *State) WithAccount(p *anthropic.Profile) *State { if s == nil || p == nil { return s } s.Account = &Account{Email: p.Email, Name: p.Name, Plan: p.Plan} return s } // Unavailable is the state to write when the quota could not be read. This is // not an error to hide: the plasmoid must be able to say explicitly that the // number is missing, instead of showing an old one as if it were good. func Unavailable(err error, needsAuth bool, now time.Time) *State { msg := "" if err != nil { msg = err.Error() } return &State{ Schema: SchemaVersion, GeneratedAt: now, Quota: Quota{Status: StatusUnavailable, Error: msg, NeedsAuth: needsAuth}, } } // Stale is the state when the read failed but we had a good one recently: show // the old numbers, saying they are old. // // Windows that have already reset are dropped: after a reset the old // percentage is not merely stale, it is false - it would claim "90% used" of a // window that has since gone back to zero. func Stale(prev *anthropic.Usage, fetchedAt time.Time, err error, now time.Time) *State { s := &State{ Schema: SchemaVersion, 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 { // Nothing true is left to show. return Unavailable(err, false, now) } s.Compact = pickCompact(s.Windows) return s } // pickCompact chooses what goes in the panel. // // The candidates are only the 5-hour session and the overall week: those are // the real walls. Per-model windows are popup detail - a high scoped window // does not block, you switch model. Primary is the higher of the two, that is, // the constraint hit first. func pickCompact(windows []Window) *Compact { var session, weekly *Window for i := range windows { 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 // On a tie the week wins: it takes days to come down, while the session // refills on its own within hours. if weekly.Percent >= session.Percent { primary, secondary = weekly, session } return &Compact{Primary: *primary, Secondary: secondary} } // Path is $XDG_CONFIG_HOME/dipstick/state.json, falling back to ~/.config. 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 stores the state atomically. // // The rename is the point: the plasmoid re-reads the file on a timer, with no // coordination. Writing in place would eventually hand it half a JSON // document; with write-to-temp plus rename it always sees either the old one // or the new one, never something in between. func (s *State) Write() error { path, err := Path() if err != nil { return err } if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err } raw, err := s.Marshal() if err != nil { return err } // A unique temporary name: the daemon is not the only writer - `dipstick // state --write` exists too - and a shared temp file could be interleaved. tmp, err := os.CreateTemp(filepath.Dir(path), "state-*.json") if err != nil { return err } defer os.Remove(tmp.Name()) // 0644: there are no secrets here, only percentages, and the plasmoid runs // in the user's session. The token lives elsewhere, at 0600. if err := tmp.Chmod(0o644); err != nil { tmp.Close() return err } if _, err := tmp.Write(raw); err != nil { tmp.Close() return err } if err := tmp.Close(); err != nil { return err } return os.Rename(tmp.Name(), path) }