Files
magpie/internal/agent/stash.go
T
yetoneandggbdpq 58651568b3 agent, sessions, provider: a state file that doesn't parse is kept aside, not written over as empty (#2263, ggbdpq)
applied.json, wsl.json and sessions-wsl.json were read as empty when they
didn't parse, and the next save wrote that emptiness over them. What
magpie had applied to each agent, the WSL distros and the WSL session
listing were lost with no copy. stash.json already kept a bad file aside
as .bad-<time>. Each of these now does the same through one helper,
lastgood.KeepUnparsed, instead of a copy per file:
- It does nothing when the file is missing or empty.
- When the file doesn't unmarshal into the reader's own type
  (lastgood.Into[T]), it copies the file aside (KeepBad).
- It stops the write when the copy can't be kept.

This also fixes the issue's claim about stash.json. Stash judged a file
with json.Valid, so `[]`, which a map reader takes as empty, was written
over unkept. Its failed copy was only logged, and the write went ahead
anyway. Both are fixed (TestUnreadStashArrayKeptAside), and
gateway-hidden.json uses the same helper.

Siblings found by going through every single-file JSON reader that takes
a bad file as empty and then writes it whole:
- stepfun-auth
- login-returns
- quota-history
- balance-history
- credits-daily
- Claude Desktop tiers
- plugin updates
- usage's computer id
- davsync's sync state

Each now keeps a bad copy. Caches that are rebuilt from the vendor are
left alone; docs/subsystems/providers-accounts.md lists them.

Run:
- gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui,
  GOOS=windows): clean.
- go test -tags nogui -p 4 -timeout 40m ./... with the other three
  commits of this push: see the last one's body.

Broken by hand: on the code before this, these fail:
- the issue's applied_keep_test.go and wsl_keep_test.go
- TestUnreadStashArrayKeptAside
- TestUnreadStateKeptAside (10 subtests)
- the gateway, usage, davsync and plugin _keep tests
TestKeepUnparsed and TestKeepUnparsedFailsWhenItCantBeKept cover the
helper.

I dropped a test, "not written when it can't be kept", for stash. It passed
on the old code too, because a read-only folder also stops the atomic
write.

Not tried: a real WSL distro.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 09:36:26 +08:00

103 lines
2.6 KiB
Go

package agent
import (
"encoding/json"
"errors"
"io/fs"
"log"
"os"
"path/filepath"
"sync"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/lastgood"
"github.com/yetone/magpie/internal/provider"
)
// The stash remembers what an agent's config said before magpie pointed it
// at the gateway, so switching back restores it instead of guessing.
//
// stash.json holds every agent's originals, so a change to it is read,
// changed and written under stashMu, and written whole (edit.WriteAtomic):
// two changes at once, or one cut short, never leave it half there, which
// the next change read as no stash and wrote back over every agent's. A
// file that doesn't parse (edited by hand, or half written by an older
// magpie) is copied aside before it is written over, so what it held can
// still be got back.
var stashMu sync.Mutex
func stashPath() string { return filepath.Join(filepath.Dir(provider.Path()), "stash.json") }
func stashLoad() map[string]string {
out := map[string]string{}
if b, err := os.ReadFile(stashPath()); err == nil {
json.Unmarshal(b, &out)
}
return out
}
// stashWrite writes m as the stash, a file there that doesn't parse kept
// aside first. The caller holds stashMu.
func stashWrite(m map[string]string) error {
b, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
p := stashPath()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
// stashLoad reads a file that doesn't unmarshal into the stash (a JSON
// array too, not only one cut short) as empty: it is copied aside, and
// one that can't be copied isn't written over
if err := lastgood.KeepUnparsed(p, lastgood.Into[map[string]string]); err != nil {
log.Printf("stash.json wasn't written over: %v", err)
return err
}
// made 0600 first: WriteAtomic keeps a file's mode, and the stash holds
// keys
if f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600); err == nil {
f.Close()
} else if !errors.Is(err, fs.ErrExist) {
return err
}
return edit.WriteAtomic(p, b)
}
func stash(kv map[string]string) {
stashMu.Lock()
defer stashMu.Unlock()
m := stashLoad()
for k, v := range kv {
if v == "" {
delete(m, k)
} else {
m[k] = v
}
}
stashWrite(m)
}
// forget drops stashed values without restoring them.
func forget(keys ...string) {
stashMu.Lock()
defer stashMu.Unlock()
m := stashLoad()
for _, k := range keys {
delete(m, k)
}
stashWrite(m)
}
func unstash(key string) string {
stashMu.Lock()
defer stashMu.Unlock()
m := stashLoad()
v := m[key]
if v != "" {
delete(m, key)
stashWrite(m)
}
return v
}