Something went wrong. Try again.
A KDE Plasma panel widget showing how much Claude Max quota is left, at a glance.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220// Package daemon keeps state.json up to date.//// It runs as a systemd user unit, outside plasmashell: if something goes wrong// here a service dies, not the user's panel.package daemon
import ( "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 is the cadence while a session is active. Server-side, // utilization moves every ~5 minutes: asking more often repeats the same // answer. Interval time.Duration // IdleInterval is the cadence when the transcripts show no activity. IdleInterval time.Duration // IdleAfter is how much silence counts as being idle. IdleAfter time.Duration // MaxBackoff caps the wait after repeated failures. MaxBackoff time.Duration // StaleAfter is how old the last good read may be before we stop showing // it at all. StaleAfter time.Duration // ProfileEvery is how often to re-read the account identity. ProfileEvery 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, ProfileEvery: 12 * time.Hour, }}
type Daemon struct { cfg Config log *slog.Logger root string // transcript tree
// scanner remembers what earlier rounds read, so a round costs only what // Claude Code appended since. It is used from Run's loop alone. scanner *transcript.Scanner
// The last successful read, so we can degrade to "stale" instead of // dropping straight to "no data". lastGood *anthropic.Usage lastGoodAt time.Time
// The profile only changes on logout/login: it is re-read rarely, and its // failure must not affect the quota, which is the figure that matters. profile *anthropic.Profile profileAt time.Time
failures int
// Injectable: backoff and degradation onto old data are the logic that // fails silently, so they must be testable without the network or disk // writes. fetchUsage func() (*anthropic.Usage, error) fetchProfile func() (*anthropic.Profile, error) writeState func(*state.State) error}
func New(cfg Config, root string, log *slog.Logger) *Daemon { return &Daemon{ cfg: cfg, log: log, root: root, scanner: transcript.NewScanner(), fetchUsage: anthropic.FetchUsage, fetchProfile: anthropic.FetchProfile, writeState: func(s *state.State) error { return s.Write() }, }}
// Run loops until the context is cancelled.//// A send on wake cuts the wait short and starts a round immediately: it is how// the plasmoid's refresh button reaches a daemon that may be half an hour into// an idle sleep. A nil channel simply never fires.func (d *Daemon) Run(ctx context.Context, wake <-chan struct{}) error { for { wait := d.tick(time.Now()) d.log.Debug("next round", "in", wait)
timer := time.NewTimer(wait) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-wake: // The wait was cut short on request, so the backoff that produced // it is forgotten too: the user is telling us to try again now. timer.Stop() d.log.Info("refresh requested") d.failures = 0 case <-timer.C: } }}
// tick runs one full round and returns how long to wait before the next.func (d *Daemon) tick(now time.Time) time.Duration { // The transcripts are always read: after the first round they cost only // what was appended, they say whether there is activity - which sets the // cadence - and they remain the only true thing if the network does not // answer. // // A partial scan still returns usable totals, so the error is logged and // the activity is used anyway; ignoring the error would present an // incomplete figure as a whole one. activity, err := d.scan(now) if err != nil { d.log.Warn("transcript scan incomplete", "err", err) }
st, ok := d.fetch(now) st.WithLocal(activity).WithAccount(d.loadProfile(now, ok, st.Quota.NeedsAuth))
if err := d.writeState(st); err != nil { d.log.Error("writing the state failed", "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 } began := time.Now() act, err := d.scanner.Scan(d.root, now) if act != nil { d.log.Debug("transcripts scanned", "took", time.Since(began), "files", act.FilesScanned, "bytes", act.BytesRead) } return act, err}
// fetch reads the quota and builds the state. The bool says whether the read// succeeded: that alone drives the backoff.func (d *Daemon) fetch(now time.Time) (*state.State, bool) { usage, err := d.fetchUsage() if err == nil { d.lastGood, d.lastGoodAt = usage, now return state.FromUsage(usage, now), true }
// With no token no network call happened, so there is nothing to slow // down: it is the user who has to act. if errors.Is(err, anthropic.ErrNoAuth) { d.log.Warn("not authenticated", "action", "dipstick auth") return state.Unavailable(err, true, now), true }
d.log.Warn("reading the quota failed", "err", err) if d.lastGood != nil && now.Sub(d.lastGoodAt) < d.cfg.StaleAfter { return state.Stale(d.lastGood, d.lastGoodAt, err, now), false } // Too old to still be passed off as data. d.lastGood = nil return state.Unavailable(err, false, now), false}
// backoff doubles the wait on each consecutive failure. The endpoint is// undocumented: if it is unwell, or throttling us, insisting at the same// cadence is exactly the wrong move.func (d *Daemon) backoff() time.Duration { d.failures++ wait := d.cfg.Interval for i := 1; i < d.failures; i++ { wait *= 2 if wait >= d.cfg.MaxBackoff { return d.cfg.MaxBackoff } } return wait}
// loadProfile re-reads the identity only when needed.//// It is skipped when the quota itself did not come back, and equally when// there is no token: in the first case it would be one more request to an// endpoint we already know is unwell, in the second it would fail identically// every round and log a warning every five minutes, forever, while the user is// simply logged out.func (d *Daemon) loadProfile(now time.Time, quotaOK bool, needsAuth bool) *anthropic.Profile { if !quotaOK || needsAuth { return d.profile } if d.profile != nil && now.Sub(d.profileAt) < d.cfg.ProfileEvery { return d.profile } p, err := d.fetchProfile() if err != nil { // The profile is garnish: without it the quota shows with no header. d.log.Warn("reading the profile failed", "err", err) return d.profile } d.profile, d.profileAt = p, now return p}