Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
provider: a check-in file that can't be read or parsed stops the check-in
yetonea8ecf4020e3b
diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.mdindex fd9f0747f..f08b93796 100644--- a/docs/subsystems/provider-plugins.md+++ b/docs/subsystems/provider-plugins.md@@ -44,7 +44,7 @@ A plugin can press its vendor's daily check-in (签到) itself: its `auth` hookThe hook returns `{outcome, credit?, streak?, message?}`. `outcome` is one of `claimed` (checked in now), `done` (already in today), `ineligible`, `inactive` (no check-in event now), `captcha` or `failed`. A throw, or an outcome not in that list, is `failed` with the reason. `captcha` means the vendor wants a captcha: magpie never solves one, and says "check in in its own app" instead. A plugin must not solve captchas either.-[`plugin_checkin.go`](../../internal/provider/plugin_checkin.go) runs these through the same `checkiner` as the built-in check-ins ([`checkin.go`](../../internal/provider/checkin.go)): each signed-in, in-use account once a Beijing day, the first look 2 minutes after start and then every 30 minutes, a `failed` asked again after 30 minutes, every other outcome settled for the day. Results are kept in `plugin-checkin.json` by `provider|<sign-in key>` (`pluginCheckinKey`: the key `plugin-auth.json` keeps the sign-in under, `autoclaw` or `autoclaw#x1y2z3`), never by the display name: two sign-ins can share a name (AutoClaw's default can't be changed), and keyed by it only the first of them was ever checked in, by the loop or *Check in now* (plugins#254). The sign-in key holds over a refresh and over signing in to the same account again (`settle` in `host.js` puts it back under its key); a sign-in made after one was signed out the same day may take the freed key, and with it that day's result. An entry kept by `provider|<display name>` before then is carried over once the plugin's accounts are listed (`adoptLegacyPluginCheckins`): a check-in goes to the first sign-in in use of that name, the one the old key asked, and only to it, so its namesakes are asked and none twice; an `Off` in `settings.CheckinOff` goes to every sign-in of that name, since none of them was checked in while it was off. A `plugin-checkin.json` that can't be read or parsed is left as it is and carried over once it reads. A failure is recorded as failed and never resets an account, a key or a previous day's result. Each account's Usage card has the check-in row (`checkinBy: "plugin:<provider>"`), and Settings → Usage has a Plugins tab with a Daily check-in switch per provider (`settings.PluginCheckins`, `POST /api/settings/plugin-checkin {provider, on}`; *Check in now* is `POST /api/usage/plugin-checkin {provider}`). `magpie accounts checkin` and `c` on the TUI's Usage page include them. Every check-in, built-in or a plugin's, also skips an account listed in `settings.CheckinOff` by its file key (#1902): `checkinNow` asks nothing for it, by the loop or a press, `CheckinAccounts()` lists each account with its own `on` for Settings (`checkinAccounts`, a row each under the vendor's switch when it has two or more, `POST /api/settings/checkin-account {key, on}`), and its card carries `checkinOff`.+[`plugin_checkin.go`](../../internal/provider/plugin_checkin.go) runs these through the same `checkiner` as the built-in check-ins ([`checkin.go`](../../internal/provider/checkin.go)): each signed-in, in-use account once a Beijing day, the first look 2 minutes after start and then every 30 minutes, a `failed` asked again after 30 minutes, every other outcome settled for the day. Results are kept in `plugin-checkin.json` by `provider|<sign-in key>` (`pluginCheckinKey`: the key `plugin-auth.json` keeps the sign-in under, `autoclaw` or `autoclaw#x1y2z3`), never by the display name: two sign-ins can share a name (AutoClaw's default can't be changed), and keyed by it only the first of them was ever checked in, by the loop or *Check in now* (plugins#254). The sign-in key holds over a refresh and over signing in to the same account again (`settle` in `host.js` puts it back under its key); a sign-in made after one was signed out the same day may take the freed key, and with it that day's result. An entry kept by `provider|<display name>` before then is carried over once the plugin's accounts are listed (`adoptLegacyPluginCheckins`): a check-in goes to the first sign-in in use of that name, the one the old key asked, and only to it, so its namesakes are asked and none twice; an `Off` in `settings.CheckinOff` goes to every sign-in of that name, since none of them was checked in while it was off. A `plugin-checkin.json` that can't be read or parsed is left as it is and carried over once it reads; until then no plugin account is checked in, and each says why (`readCheckins`, as for every vendor's check-in file). A failure is recorded as failed and never resets an account, a key or a previous day's result. Each account's Usage card has the check-in row (`checkinBy: "plugin:<provider>"`), and Settings → Usage has a Plugins tab with a Daily check-in switch per provider (`settings.PluginCheckins`, `POST /api/settings/plugin-checkin {provider, on}`; *Check in now* is `POST /api/usage/plugin-checkin {provider}`). `magpie accounts checkin` and `c` on the TUI's Usage page include them. Every check-in, built-in or a plugin's, also skips an account listed in `settings.CheckinOff` by its file key (#1902): `checkinNow` asks nothing for it, by the loop or a press, `CheckinAccounts()` lists each account with its own `on` for Settings (`checkinAccounts`, a row each under the vendor's switch when it has two or more, `POST /api/settings/checkin-account {key, on}`), and its card carries `checkinOff`.The switch is off by default. For a provider whose vendor magpie checked in through the plugin's fetch before (WorkBuddy, Trae CN, MiniMax Code, Qoder), it follows that vendor's existing switch until set on its own, and magpie's own check-in leaves that provider's accounts to the plugin (`pluginChecksIn`), so an account is never checked in twice.diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.mdindex f95a3eda0..033014368 100644--- a/docs/subsystems/providers-accounts.md+++ b/docs/subsystems/providers-accounts.md@@ -216,7 +216,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.- An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider.- When `logins.json` cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, `lastgood.Keep` ([lastgood.go](../../internal/lastgood/lastgood.go)) keeps the file there now: as `logins.json.bak`, its last good generation, when it reads, or copied aside as `logins.json.bad-<time>` (`-2`, `-3`… for another within one second) when it doesn't, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the copy fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally.- A Windows machine that went down mid-write left `logins.json` and `plugin-auth.json` at their full length, every byte zero (#1505): the rename reached the disk before the data. Every write of magpie's own state goes through `steady.WriteFile` (or `edit.WriteAtomic`), which flushes the temp file before renaming it in, and the plugin host's `writeDurable` does the same. So does every write of an agent's own sign-in (#2239): `codexToken`'s rotated tokens into Codex's `auth.json` (`~/.codex`, or `$CODEX_HOME` when set; its keychain item instead when Codex keeps the sign-in there) and `writeClaudeCredential`'s `.credentials.json` go through `writePrivate`, never a truncating `os.WriteFile`, so a machine going down mid-write leaves the old sign-in whole, and on Windows a file another program holds for a moment is waited out (`steady.Rename`) instead of the rotation being dropped while the refresh token on the disk is spent. A file that is there but doesn't read on a cold start is read from its `.bak` (`lastgood.Read`/`Fallback`): `logins.json`, `providers.json`, `migrations.json`, `settings.json`, `profiles.json`, `plugins.json`, `plugin-auth.json` and `mcp-signins.json`. `caller-keys.json` is flushed the same way but never read from a `.bak`: a key revoked in the last write would come back, so a store that doesn't read still refuses every key. The recovery is logged and listed in `/api/state`'s `recovered`, which the window tells once (`recoveredOnce`). The `.bak` lags one write behind on purpose: a crash zeroes the latest write, so a copy made with it could be zeroed too. With no good `.bak` the file is unknown, never empty: a sign-out leaves `plugin-auth.json` or `mcp-signins.json` as it is (magpie's own returns the error), and a sign-in added copies the file aside before it writes.-- A state file whose reader takes one that doesn't unmarshal into its type as empty is copied aside before it is written over (`lastgood.KeepUnparsed` with `lastgood.Into[T]`, #2263): valid JSON of another shape, `[]` for a map, counts as not parsing. A copy that can't be made stops the write. These are `stash.json`, `applied.json`, `wsl.json` and Codex's `magpie-models.json` ([agent](../../internal/agent/), whose hand-added model keys `codexcat.Keep` can't hold when the file doesn't parse), `sessions-wsl.json` and `gateway-sessions-hidden.json` ([sessions](../../internal/sessions/)), `stepfun-auth.json`, `login-returns.json`, `quota-history.json`, `balance-history.json` and `credits-daily.json` ([provider](../../internal/provider/)), `claude-desktop.tiers.json`, `plugin-updates.json`, `usage-computer.json` and `sync-state.json`. Caches magpie fills again by itself (last quota readings, check-in and warm-up marks, plugin icons, npm and GitHub lookups, client shapes, seats, alert marks, `served.json`, `bun/state.json`) are still written over: losing one costs a refetch or a repeated notice.+- A state file whose reader takes one that doesn't unmarshal into its type as empty is copied aside before it is written over (`lastgood.KeepUnparsed` with `lastgood.Into[T]`, #2263): valid JSON of another shape, `[]` for a map, counts as not parsing. A copy that can't be made stops the write. These are `stash.json`, `applied.json`, `wsl.json` and Codex's `magpie-models.json` ([agent](../../internal/agent/), whose hand-added model keys `codexcat.Keep` can't hold when the file doesn't parse), `sessions-wsl.json` and `gateway-sessions-hidden.json` ([sessions](../../internal/sessions/)), `stepfun-auth.json`, `login-returns.json`, `quota-history.json`, `balance-history.json` and `credits-daily.json` ([provider](../../internal/provider/)), `claude-desktop.tiers.json`, `plugin-updates.json`, `usage-computer.json` and `sync-state.json`. A daily check-in's file (`workbuddy-checkin.json`, `trae-checkin.json`, `minimax-checkin.json`, `qoder-checkin.json`, `plugin-checkin.json`) that is there but can't be read or doesn't parse into entries is unknown (`readCheckins` in [`workbuddy_checkin.go`](../../internal/provider/workbuddy_checkin.go)): its vendor's check-in asks nothing and writes nothing, so no account is checked in twice in a day and no entry is lost, the file is left as it is, each account's result is `failed` with the reason (the loop tries again after 30 minutes, a press says why), and the cards show what last read from it in this process. A file not there is empty. `TestCheckinUnreadableFileLeftAlone` covers it. Caches magpie fills again by itself (last quota readings, warm-up marks, plugin icons, npm and GitHub lookups, client shapes, seats, alert marks, `served.json`, `bun/state.json`) are still written over: losing one costs a refetch or a repeated notice.- The gateway and a magpie run from a terminal change the same files (#1674). `loginsMu` is a [`filelock.Mutex`](../../internal/filelock/filelock.go): besides the mutex it holds an OS lock on `logins.json.lock` (flock, `LockFileEx` on Windows), and taking it has `logins.json` read afresh (`filememo.Look`), so every read a change is made from sees what another magpie wrote, and a refresh the gateway wrote is never written back over. `savedTokenMu` holds `logins.json.renew.lock` the same way, so two magpies never spend one refresh token. `caller-keys.json` (`access`) and `mcp-signins.json` (`mcpauth`, with `mcp-signins.json.renew.lock` around a renewal) are changed under such locks too; `plugin-auth.json` already was, under `plugin-auth.json.lock`, which `host.js` takes too. A lock another magpie holds is waited for up to `filelock.Wait` (10s), then gone on without, as before there was one. `rememberLogins` writes nothing when only `Seen` would move on and the saved one is less than `seenEvery` (10 minutes) old, so a run that only lists accounts (`magpie ls`, `providers`, `sessions`, `usage`) leaves `logins.json` as it is. [`logins_lock_test.go`](../../internal/provider/logins_lock_test.go) covers both, the second with another test process writing between this one's read and write.- The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came.- A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown.diff --git a/internal/provider/checkin.go b/internal/provider/checkin.goindex 10fc258c4..a016afc3f 100644--- a/internal/provider/checkin.go+++ b/internal/provider/checkin.go@@ -57,9 +57,14 @@ func (c checkiner) checkinNow(ctx context.Context, soon bool) []WorkBuddyCheckin}c.mu.Lock()defer c.mu.Unlock()- st := readCheckins(c.path)now := c.now()day := wbCheckinDay(now)+ st, err := readCheckins(c.path)+ if err != nil {+ // unknown, never empty: nothing is asked or written, the file+ // is left as it is, and each account says why+ return c.unread(now, err)+ }var out []WorkBuddyCheckinchanged := false// one account signed in twice (the built-in and the plugin) is@@ -104,12 +109,32 @@ func (c checkiner) checkinNow(ctx context.Context, soon bool) []WorkBuddyCheckinif b, err := json.MarshalIndent(st, "", " "); err == nil {if err := writePrivate(c.path, append(b, '\n')); err != nil {log.Printf("%s check-in: %v", c.label, err)+ } else {+ wroteCheckins(c.path, st)}}}return out}+// unread is how the accounts checkinNow would look at stand while its file+// can't be read (err, logged by readCheckins): each failed with err, at+// now, so the loop tries again after wbCheckinRetry and a press says why;+// none was asked.+func (c checkiner) unread(now time.Time, err error) []WorkBuddyCheckin {+ var out []WorkBuddyCheckin+ listed := map[string]bool{}+ off := checkinOff()+ for _, a := range c.accounts() {+ if !a.On || a.key == "" || listed[a.key] || off[a.key] {+ continue+ }+ listed[a.key] = true+ out = append(out, WorkBuddyCheckin{User: a.User, By: c.by, Day: wbCheckinDay(now), At: now, Outcome: CheckinFailed, Msg: err.Error()})+ }+ return out+}+// checkinOff are the accounts left out of their vendor's daily check-in// (settings.CheckinOff), by their entry in its file.func checkinOff() map[string]bool {diff --git a/internal/provider/checkin_unreadable_test.go b/internal/provider/checkin_unreadable_test.gonew file mode 100644index 000000000..6caa89764--- /dev/null+++ b/internal/provider/checkin_unreadable_test.go@@ -0,0 +1,118 @@+package provider++import (+ "bytes"+ "context"+ "os"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// A check-in file that is there but can't be read or parsed is unknown,+// never empty: neither the loop nor a press asks the vendor anything, the+// file is left byte for byte as it was, and each account says why. Read+// as empty, the next check-in asked again (a second check-in in a day) and+// wrote over the entries it couldn't read.+func TestCheckinUnreadableFileLeftAlone(t *testing.T) {+ bad := map[string][]byte{+ "cut short": []byte(`{"workbuddy|u1": {"day": "2026-10-21", "outc`),+ "zeroed": make([]byte, 512),+ "empty": {},+ "a list": []byte(`[]`),+ "null": []byte(`null`),+ }+ for name, b := range bad {+ t.Run(name, func(t *testing.T) {+ f := &fakeWBCheckin{active: true}+ srv := f.serve(t)+ now := time.Date(2026, 10, 21, 3, 0, 0, 0, time.UTC)+ c := wbCheckinFixture(t, srv, &now)+ if err := os.WriteFile(c.path, b, 0o600); err != nil {+ t.Fatal(err)+ }+ for _, soon := range []bool{false, true} {+ rs := c.checkinNow(context.Background(), soon)+ if len(rs) != 1 || rs[0].Outcome != CheckinFailed || rs[0].Asked || rs[0].User != "旅行者" ||+ !strings.Contains(rs[0].Msg, c.path) {+ t.Fatalf("soon %v: %+v", soon, rs)+ }+ }+ if s, cl := f.counts(); s != 0 || cl != 0 {+ t.Fatalf("asked WorkBuddy with its file unread: status %d, claims %d", s, cl)+ }+ if got, err := os.ReadFile(c.path); err != nil || !bytes.Equal(got, b) {+ t.Fatalf("the file became %q (%v), was %q", got, err, b)+ }+ })+ }++ // one that can't be read at all (a folder in its place)+ t.Run("unreadable", func(t *testing.T) {+ var asked atomic.Int32+ path := filepath.Join(t.TempDir(), "plugin-checkin.json")+ if err := os.Mkdir(path, 0o700); err != nil {+ t.Fatal(err)+ }+ c := checkiner{path: path, now: time.Now, mu: &pluginCheckinMu, by: "plugin:x", label: "x", recheck: true,+ accounts: func() []checkinAcct {+ return []checkinAcct{{User: "a", On: true, key: "x|a", do: func(context.Context) WorkBuddyCheckin {+ asked.Add(1)+ return WorkBuddyCheckin{Outcome: CheckinClaimed}+ }}}+ }}+ rs := c.checkinNow(context.Background(), true)+ if len(rs) != 1 || rs[0].Outcome != CheckinFailed || rs[0].By != "plugin:x" || asked.Load() != 0 {+ t.Fatalf("checked in %d times: %+v", asked.Load(), rs)+ }+ if fi, err := os.Stat(path); err != nil || !fi.IsDir() {+ t.Fatalf("its place was written over: %v", err)+ }+ })+}++// A file not there is still empty: the account is checked in.+func TestCheckinMissingFileIsEmpty(t *testing.T) {+ f := &fakeWBCheckin{active: true}+ srv := f.serve(t)+ now := time.Date(2026, 10, 21, 3, 0, 0, 0, time.UTC)+ c := wbCheckinFixture(t, srv, &now)+ rs := c.checkinNow(context.Background(), false)+ if len(rs) != 1 || rs[0].Outcome != CheckinClaimed || !rs[0].Asked {+ t.Fatalf("%+v", rs)+ }+}++// While a file doesn't parse, its cards keep what last read from it, and+// once it parses again the check-in goes on from what it holds.+func TestCheckinUnreadableKeepsLastGood(t *testing.T) {+ f := &fakeWBCheckin{active: true}+ srv := f.serve(t)+ now := time.Date(2026, 10, 21, 3, 0, 0, 0, time.UTC)+ c := wbCheckinFixture(t, srv, &now)+ ctx := context.Background()+ if rs := c.checkinNow(ctx, false); len(rs) != 1 || rs[0].Outcome != CheckinClaimed {+ t.Fatalf("first: %+v", rs)+ }+ good, err := os.ReadFile(c.path)+ if err != nil {+ t.Fatal(err)+ }+ os.WriteFile(c.path, good[:len(good)/2], 0o600)+ if st := shownCheckins(c.path); st["workbuddy|u1"].Outcome != CheckinClaimed {+ t.Fatalf("shown while unread: %+v", st)+ }+ if _, err := readCheckins(c.path); err == nil {+ t.Fatal("a file cut short read without an error")+ }+ // the file mended: today's claim read back, nothing asked again+ os.WriteFile(c.path, good, 0o600)+ if rs := c.checkinNow(ctx, false); len(rs) != 1 || rs[0].Outcome != CheckinClaimed || rs[0].Asked {+ t.Fatalf("mended: %+v", rs)+ }+ if s, cl := f.counts(); s != 1 || cl != 1 {+ t.Fatalf("status %d, claims %d", s, cl)+ }+}diff --git a/internal/provider/minimax_checkin.go b/internal/provider/minimax_checkin.goindex 770e95f03..83232175d 100644--- a/internal/provider/minimax_checkin.go+++ b/internal/provider/minimax_checkin.go@@ -241,7 +241,7 @@ func CheckInMiniMax(ctx context.Context) []WorkBuddyCheckin {// MiniMaxCheckins is each MiniMax Code account's last check-in, as kept,// by its name now; asks nothing.func MiniMaxCheckins() []WorkBuddyCheckin {- st := readCheckins(miniMaxCheckinPath())+ st := shownCheckins(miniMaxCheckinPath())var out []WorkBuddyCheckinlisted := map[string]bool{}for _, a := range miniMaxCheckinAccounts() {diff --git a/internal/provider/plugin_checkin.go b/internal/provider/plugin_checkin.goindex fc2643856..db220b216 100644--- a/internal/provider/plugin_checkin.go+++ b/internal/provider/plugin_checkin.go@@ -16,7 +16,6 @@ import ("context""encoding/json""log"- "os""path/filepath""slices""sort"@@ -169,17 +168,8 @@ func adoptLegacyPluginCheckins(ps []pluginCheckinProvider) {// path to its first heir that has none of its own, and drops it; it says// whether the file is as it should be now.func adoptLegacyCheckinFile(path string, order []string, heirs map[string][]string) bool {- b, err := os.ReadFile(path)- if os.IsNotExist(err) {- return true- }+ st, err := readCheckins(path)if err != nil {- log.Printf("plugin check-in: %v", err)- return false- }- st := map[string]WorkBuddyCheckin{}- if err := json.Unmarshal(b, &st); err != nil {- log.Printf("plugin check-in: %s: %v", path, err)return false}changed := false@@ -201,6 +191,9 @@ func adoptLegacyCheckinFile(path string, order []string, heirs map[string][]striif err == nil {err = writePrivate(path, append(out, '\n'))}+ if err == nil {+ wroteCheckins(path, st)+ }if err != nil {log.Printf("plugin check-in: %v", err)return false@@ -331,7 +324,7 @@ type PluginCheckin struct {// PluginCheckins are the plugins' providers that check in, each with its// accounts' last check-ins as kept; asks nothing.func PluginCheckins() []PluginCheckin {- st := readCheckins(pluginCheckinPath())+ st := shownCheckins(pluginCheckinPath())s := settings.Load()var out []PluginCheckinfor _, p := range pluginCheckinProviders() {@@ -360,7 +353,7 @@ func pluginCheckinMarks(qs []SubscriptionQuota) []SubscriptionQuota {if len(ps) == 0 {return qs}- st := readCheckins(pluginCheckinPath())+ st := shownCheckins(pluginCheckinPath())for _, p := range ps {var on []checkinCardfor _, a := range p.accounts {diff --git a/internal/provider/plugin_checkin_test.go b/internal/provider/plugin_checkin_test.goindex 593c6eb64..65cb56210 100644--- a/internal/provider/plugin_checkin_test.go+++ b/internal/provider/plugin_checkin_test.go@@ -306,7 +306,7 @@ func TestPluginCheckinTellsSignInsOfOneNameApart(t *testing.T) {if rs := loop.checkinNow(ctx, false); len(rs) != 4 || len(pressed(t, presses)) != 4 {t.Fatalf("a minute on: %+v, pressed %q", rs, pressed(t, presses))}- st := readCheckins(pluginCheckinPath())+ st := shownCheckins(pluginCheckinPath())for who, k := range keys {if r, ok := st[pluginCheckinKey("fakeco", k)]; !ok || r.Day != "2026-10-06" || r.Outcome != CheckinInactive {t.Errorf("%s (%s) kept as %+v, ok %v; file %+v", who, k, r, ok, st)@@ -408,7 +408,7 @@ func TestPluginCheckinCarriesOverDisplayNameEntries(t *testing.T) {if heir == "" || namesake == "" {t.Fatalf("A's sign-ins: %+v", ps[0].accounts)}- st := readCheckins(pluginCheckinPath())+ st := shownCheckins(pluginCheckinPath())if r, ok := st[heir]; !ok || r.Outcome != CheckinClaimed || r.Credit != 400 || r.Day != "2026-10-06" {t.Fatalf("A's check-in went to %s as %+v (ok %v): %+v", heir, r, ok, st)}@@ -473,7 +473,7 @@ func TestPluginCheckinCarriesNothingOverAnUnreadableFile(t *testing.T) {if !adoptLegacyCheckinFile(path, order, heirs) {t.Fatal("not carried once the file reads")}- st := readCheckins(path)+ st := shownCheckins(path)if _, ok := st["fakeco|fakeco"]; !ok || len(st) != 1 {t.Fatalf("carried as %+v", st)}diff --git a/internal/provider/qoder_checkin.go b/internal/provider/qoder_checkin.goindex 898bb5b92..3cff4d101 100644--- a/internal/provider/qoder_checkin.go+++ b/internal/provider/qoder_checkin.go@@ -223,7 +223,7 @@ func CheckInQoder(ctx context.Context) []WorkBuddyCheckin {// QoderCheckins is each Qoder account's last check-in, as kept, by its// name now; asks nothing.func QoderCheckins() []WorkBuddyCheckin {- st := readCheckins(qoderCheckinPath())+ st := shownCheckins(qoderCheckinPath())var out []WorkBuddyCheckinlisted := map[string]bool{}for _, a := range qoderCheckinAccounts() {diff --git a/internal/provider/qoder_checkin_test.go b/internal/provider/qoder_checkin_test.goindex bae98cf90..b84a61a05 100644--- a/internal/provider/qoder_checkin_test.go+++ b/internal/provider/qoder_checkin_test.go@@ -346,7 +346,7 @@ func TestQoderCheckinCampaignCache(t *testing.T) {if len(rs) != 1 || rs[0].Outcome != CheckinDone || rs[0].Day != wbCheckinDay(now) || !rs[0].Asked || gets != 4 || posts != claims {t.Fatalf("midnight kept yesterday's result: %+v, reads %d, claims %d", rs, gets, posts)}- if saved := readCheckins(c.path)[qoderCheckinKey(a)]; saved.Day != wbCheckinDay(now) {+ if saved := shownCheckins(c.path)[qoderCheckinKey(a)]; saved.Day != wbCheckinDay(now) {t.Fatalf("midnight didn't update the saved day: %+v", saved)}// A restart reads the same recent result from disk.diff --git a/internal/provider/trae_checkin.go b/internal/provider/trae_checkin.goindex da5cc20c0..cfb62b048 100644--- a/internal/provider/trae_checkin.go+++ b/internal/provider/trae_checkin.go@@ -201,7 +201,7 @@ func CheckInTrae(ctx context.Context) []WorkBuddyCheckin {// TraeCheckins is each Trae CN account's last check-in, as kept, by its// name now; asks nothing.func TraeCheckins() []WorkBuddyCheckin {- st := readCheckins(traeCheckinPath())+ st := shownCheckins(traeCheckinPath())var out []WorkBuddyCheckinlisted := map[string]bool{}for _, a := range traeCheckinAccounts() {diff --git a/internal/provider/workbuddy_checkin.go b/internal/provider/workbuddy_checkin.goindex 15a52cebd..947874749 100644--- a/internal/provider/workbuddy_checkin.go+++ b/internal/provider/workbuddy_checkin.go@@ -30,8 +30,11 @@ import ("context""encoding/json""errors"+ "fmt""io"+ "io/fs""log"+ "maps""net""net/http""os"@@ -169,10 +172,67 @@ func wbCheckinPath() string { return filepath.Join(filepath.Dir(Path()), "workbu// wbCheckinKey is an account's entry in the file: its site and id.func wbCheckinKey(a wbAccount) string { return a.site.id + "|" + a.creds.UID }-func readCheckins(path string) map[string]WorkBuddyCheckin {+// readCheckins is what a check-in file at path keeps, by entry. A file not+// there is empty. One there that can't be read or doesn't parse into+// entries (cut short, zeroed, `[]`) is unknown, never empty: the error+// says so, and what is given is what last read from it in this process,+// so a card still shows it. A check-in neither asks nor writes on an+// error, or it would check an account in twice in a day and write over+// the entries it couldn't read.+func readCheckins(path string) (map[string]WorkBuddyCheckin, error) {st := map[string]WorkBuddyCheckin{}- if b, err := os.ReadFile(path); err == nil {- json.Unmarshal(b, &st)+ b, err := os.ReadFile(path)+ switch {+ case errors.Is(err, fs.ErrNotExist):+ err = nil+ case err == nil:+ if err = json.Unmarshal(b, &st); err != nil || st == nil {+ if err == nil {+ err = errors.New("it holds null")+ }+ err = fmt.Errorf("%s doesn't parse (%v): magpie leaves it as it is and checks in no account of it until it does", path, err)+ }+ default:+ err = fmt.Errorf("%s can't be read (%v): magpie leaves it as it is and checks in no account of it until it can", path, err)+ }+ checkinsReadMu.Lock()+ defer checkinsReadMu.Unlock()+ if err != nil {+ // logged once while it stays the same, not on every card read+ if checkinsBad[path] != err.Error() {+ checkinsBad[path] = err.Error()+ log.Printf("check-in: %v", err)+ }+ return maps.Clone(checkinsRead[path]), err+ }+ delete(checkinsBad, path)+ checkinsRead[path] = maps.Clone(st)+ return st, nil+}++// checkinsRead is each check-in file's entries as last read, for+// readCheckins to give when the file can't be read now, and checkinsBad+// the error last logged for one that can't.+var (+ checkinsReadMu sync.Mutex+ checkinsRead = map[string]map[string]WorkBuddyCheckin{}+ checkinsBad = map[string]string{}+)++// wroteCheckins notes st as written to path: what last read from it.+func wroteCheckins(path string, st map[string]WorkBuddyCheckin) {+ checkinsReadMu.Lock()+ defer checkinsReadMu.Unlock()+ delete(checkinsBad, path)+ checkinsRead[path] = maps.Clone(st)+}++// shownCheckins is readCheckins for a reader that only shows the entries:+// on an error, what last read (logged by readCheckins).+func shownCheckins(path string) map[string]WorkBuddyCheckin {+ st, _ := readCheckins(path)+ if st == nil {+ st = map[string]WorkBuddyCheckin{}}return st}@@ -312,7 +372,7 @@ func CheckInWorkBuddy(ctx context.Context) []WorkBuddyCheckin {// WorkBuddyCheckins is each WorkBuddy (China) account's last check-in, as// kept, by its name now; asks nothing.func WorkBuddyCheckins() []WorkBuddyCheckin {- st := readCheckins(wbCheckinPath())+ st := shownCheckins(wbCheckinPath())var out []WorkBuddyCheckinlisted := map[string]bool{}for _, a := range wbCheckinAccounts() {@@ -334,10 +394,10 @@ func WorkBuddyCheckins() []WorkBuddyCheckin {// those in through the plugin's fetch. qs, which may be the usage cache,// is left as it is; nothing is asked.func WithCheckins(qs []SubscriptionQuota) []SubscriptionQuota {- qs = withCheckins(qs, wbCheckinAccounts(), readCheckins(wbCheckinPath()))- qs = markCheckins(qs, traeCards(traeCheckinAccounts()), readCheckins(traeCheckinPath()), "trae")- qs = markCheckins(qs, miniMaxCards(miniMaxCheckinAccounts()), readCheckins(miniMaxCheckinPath()), "minimax")- qs = markCheckins(qs, qoderCards(qoderCheckinAccounts()), readCheckins(qoderCheckinPath()), "qoder")+ qs = withCheckins(qs, wbCheckinAccounts(), shownCheckins(wbCheckinPath()))+ qs = markCheckins(qs, traeCards(traeCheckinAccounts()), shownCheckins(traeCheckinPath()), "trae")+ qs = markCheckins(qs, miniMaxCards(miniMaxCheckinAccounts()), shownCheckins(miniMaxCheckinPath()), "minimax")+ qs = markCheckins(qs, qoderCards(qoderCheckinAccounts()), shownCheckins(qoderCheckinPath()), "qoder")return pluginCheckinMarks(qs)}