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 builds a daemon that touches neither the network nor the disk. 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.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 } 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("wait = %v, want %v", wait, DefaultConfig().Interval) } if len(*written) != 1 || (*written)[0].Quota.Status != state.StatusFresh { t.Fatalf("written state = %+v", *written) } } // The state must be written even when the read fails: the plasmoid has to be // able to tell "quota unreadable" from "daemon dead". func TestTickWritesEvenOnFailure(t *testing.T) { d, written := harness(t, func() (*anthropic.Usage, error) { return nil, errors.New("network down") }) d.tick(now) if len(*written) != 1 { t.Fatalf("writes = %d, want 1", len(*written)) } if (*written)[0].Quota.Status != state.StatusUnavailable { t.Errorf("status = %q", (*written)[0].Quota.Status) } } // After a good read, a failure degrades to "stale" rather than wiping // everything. 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, want stale", last.Quota.Status) } if last.Compact == nil || last.Compact.Primary.Percent != 30 { t.Errorf("the old numbers should have stayed: %+v", last.Compact) } // The instant must be that of the last SUCCESSFUL read, not now. if last.Quota.FetchedAt == nil || !last.Quota.FetchedAt.Equal(now) { t.Errorf("fetched_at = %v, want %v", last.Quota.FetchedAt, now) } } // A window that already reset is not stale, it is false: it would claim // "used" of a window that has since gone back to 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)) // the reset has passed last := (*written)[len(*written)-1] if last.Quota.Status != state.StatusUnavailable { t.Errorf("status = %q, want unavailable", last.Quota.Status) } if last.Compact != nil { t.Errorf("compact = %+v, want nil", last.Compact) } } // Past StaleAfter we stop passing the old numbers off as data. 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, want unavailable", last.Quota.Status) } } // With no token no request goes out, so there is nothing to slow down: it is // the user who has to act. 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("round %d: wait = %v, expected no backoff", i, wait) } } if last := (*written)[len(*written)-1]; !last.Quota.NeedsAuth { t.Error("needs_auth not set: the popup cannot say what to do") } } 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("failure %d: wait = %v, want %v", i+1, got, w) } } for i := 0; i < 10; i++ { d.tick(now) } if got := d.tick(now); got != cfg.MaxBackoff { t.Errorf("wait = %v, want the cap %v", got, cfg.MaxBackoff) } } // A successful read clears the accumulated backoff. 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("wait = %v, expected a return to the normal cadence", got) } fail = true if got := d.tick(now); got != DefaultConfig().Interval { t.Errorf("wait = %v, the backoff should have restarted from scratch", got) } } // The profile is garnish: if it fails, the quota still shows. 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, want nil", last.Account) } } // The profile only changes on logout/login: it is not re-read every round. 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("profile reads = %d, want 1", calls) } d.tick(now.Add(DefaultConfig().ProfileEvery + time.Minute)) if calls != 2 { t.Errorf("profile reads = %d, want 2 after expiry", calls) } } // If the quota does not answer there is no point insisting on the profile. 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("profile reads = %d, want 0", calls) } } // With no token, asking for the profile would fail identically every round and // log a warning every five minutes, forever, while the user is simply logged // out and the widget already says so. func TestProfileNotFetchedWhenNotAuthenticated(t *testing.T) { calls := 0 d, written := harness(t, func() (*anthropic.Usage, error) { return nil, anthropic.ErrNoAuth }) d.fetchProfile = func() (*anthropic.Profile, error) { calls++ return &anthropic.Profile{}, nil } for i := 0; i < 5; i++ { d.tick(now.Add(time.Duration(i) * time.Hour)) } if calls != 0 { t.Errorf("profile reads = %d, want 0", calls) } if last := (*written)[len(*written)-1]; !last.Quota.NeedsAuth { t.Error("needs_auth not set") } }