Files
magpie/internal/cli/save_sync_behind_test.go
T
yetone 0911a65e7d agent: a catalog sync leaves a magpie provider the user wrote alone while the agent isn't connected
yyddbds on Discord: in Xiaomi MiMo they added a custom provider pointing
at magpie and picked a few models by hand. MiMo's switch on the Agents
page was off, yet after an update the provider held every one of
magpie's models. SyncCatalog runs at each start and update and on every
catalog change, and MiMo Code's Sync (openCodeLike) brought any
provider.magpie block up to the catalog whether magpie wrote it or not.
magpie's default went over a list the user set.

An Agent whose Sync does nothing but keep a block of magpie's name up
to the catalog is now ListOnly, and SyncCatalog runs it only while the
agent is Wired, which is what the Agents page's switch shows. The same
sync was in every sibling, so ListOnly is on all of them: openCodeLike
(OpenCode, MiMo Code and their WSL forms), piLikeKeyed (Pi and forks),
Goose, Crush, Air, AtomCode, Command Code, Droid, Fx, jcode, Kimi,
MiniMax, Mothx, omp, OpenChamber, OpenClaw, OpenPencil, Penguin, Qwen
Code and T3 Code. Left out on purpose: Codex, Claude, Grok and Hermes,
whose Syncs also repair while not connected (Hermes keeps its bots'
magpie provider current) and have their own gates.

Trade-off: a list magpie wrote while connected doesn't follow the
catalog while the agent runs a model of its own (switch off); it does
again once a model of magpie's is picked. Users whose list was already
written over: magpie keeps no copy of the old list, so it stays full;
from this release on it is left alone, and they trim it once by hand
(or connect the agent in magpie and use its model list's Pick).

Tests: TestCatalogSyncLeavesAHandWrittenMagpieBlock (MiMo, Pi and Crush
with a hand-written magpie block stay byte for byte; connected, MiMo's
list follows the catalog; disconnected and written by hand again, left
alone; a magpie model picked in MiMo, followed again).
TestListOnlyAgentsReadConnected: every ListOnly agent magpie connects
reads as Wired (n >= 15), so none of them loses catalog updates.
Fixtures of TestSyncCatalogRewritesAgentLists,
TestModelNameAndLevelsReachAgentFiles, TestSuffixModesReachAgentFiles
and TestPiKeepsTheirKeysInMagpiesProvider, and internal/cli's
TestSaveAnswersBeforeTheAgentsSync (its Pi settings were {}), now have
Pi connected (settings.json defaultProvider magpie), as a block magpie
wrote implies.
docs/subsystems/agent-wiring.md says the rule.

Run (mote, sandbox HOME via the tests' syncHome/codexHome):
- old code + the new test: red (MiMo, Pi, Crush written over; after
  Disconnect written over).
- broken by hand: ListOnly dropped from openCodeLike: red on MiMo
  (lines 52, 82); the Wired gate in SyncCatalog replaced with true: red
  on all three.
- go test -tags nogui -count=1 ./internal/agent: ok.
- gofmt -l clean; go vet ./... for darwin, GOOS=linux and GOOS=windows:
  ok.
- full suite, go test -tags nogui -count=1 -timeout 45m ./... at base
  3bebc3839 (logs kept in the worktree): every package ok but
  internal/cli (TestSaveAnswersBeforeTheAgentsSync, mine, fixture fixed
  above, then ok alone) and internal/gateway: TestAntigravityTurned*,
  TestAntigravityTurnsCodexsGPT5ThreadAwayOnce and
  TestCodexSpentGrokFailingIsTold, red the same on a fresh origin/main
  b26fa0903 copy, filed as #4362.
- rebased on e8d42c02d: vet (darwin, linux, windows) of internal/agent and
  internal/cli, and go test of internal/agent, internal/cli,
  internal/library and internal/gui: all ok. Pushed on 764a032f6,
  whose three commits since touch gateway, usage, provider and chat only.

Not tried: the real Xiaomi MiMo desktop app (the fixture is the OpenCode
shape MiMo Code writes; whether the reporter's provider id is literally
"magpie" is unconfirmed: a provider of another id was never touched).
Lists already written over are not restored.
2026-10-30 14:25:38 +08:00

132 lines
4.3 KiB
Go

//go:build !windows
package cli
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/gui"
"github.com/yetone/magpie/internal/provider"
)
// A routing group or a provider saved answers before the agents' model
// lists are rewritten. Every save ends in catalog.Changed, which rewrote
// each agent's files inside the request; on Windows each file an agent
// holds open cost half a second of retried renames, and a save took
// seconds now and then while an agent was at work (CyberCaius on Discord:
// 路由组和供应商编辑保存有时候保存会卡很久才保存成功).
//
// The slow sync is made here by Pi's models.json being a FIFO: the sync's
// read of it waits until the test opens the other end, as a write over a
// held file waits. The save must answer while it waits, and the sync must
// still run after.
func TestSaveAnswersBeforeTheAgentsSync(t *testing.T) {
home := t.TempDir()
for k, v := range map[string]string{"HOME": home, "USERPROFILE": home,
"XDG_CONFIG_HOME": filepath.Join(home, ".config"), "XDG_CACHE_HOME": filepath.Join(home, ".cache"),
"XDG_DATA_HOME": filepath.Join(home, ".local", "share"), "PI_CODING_AGENT_DIR": ""} {
t.Setenv(k, v)
}
was := catalog.Changed
catalog.Changed = nil
t.Cleanup(func() {
agent.SyncCatalogSettled()
catalog.Changed = was
})
if err := provider.Save(provider.Provider{ID: "a", Name: "a", Key: "ka",
Chat: "http://127.0.0.1:1/v1", Models: []string{"m1", "m2"}}); err != nil {
t.Fatal(err)
}
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
// Pi runs a model of magpie's: connected, so a sync writes its list
if err := os.WriteFile(filepath.Join(dir, "settings.json"), []byte(`{"defaultProvider":"magpie","defaultModel":"a/m1"}`), 0o600); err != nil {
t.Fatal(err)
}
fifo := filepath.Join(dir, "models.json")
h := gui.Handler(nil, nil)
post := func(path, body string) (int, string) {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
return rec.Code, rec.Body.String()
}
syncAgentsOnChange()
for _, c := range []struct{ name, path, body string }{
{"group", "/api/groups/save", `{"id":"g1","from":"g1","name":"G1","members":["a/m1"]}`},
{"provider", "/api/provider/save", `{"id":"a","from":"a","name":"A","key":"ka","chat":"http://127.0.0.1:1/v1","models":["m1"]}`},
} {
t.Run(c.name, func(t *testing.T) {
if err := syscall.Mkfifo(fifo, 0o600); err != nil {
t.Fatal(err)
}
// release opens the other end of the sync's held read, so the
// read gets {} and goes on. It waits up to 20s for a reader and
// says whether one was there; it never blocks past that, so
// nothing outlives the test, and the FIFO is gone after it.
released := false
release := func() bool {
if released {
return true
}
defer os.Remove(fifo)
for end := time.Now().Add(20 * time.Second); time.Now().Before(end); time.Sleep(10 * time.Millisecond) {
// ENXIO until a reader has it open
w, err := os.OpenFile(fifo, os.O_WRONLY|syscall.O_NONBLOCK, 0)
if err != nil {
continue
}
// a later read finds no file, as before the hold
os.Remove(fifo)
w.WriteString(`{}`)
w.Close()
released = true
return true
}
return false
}
defer release()
type answer struct {
code int
body string
}
done := make(chan answer, 1)
start := time.Now()
go func() {
code, body := post(c.path, c.body)
done <- answer{code, body}
}()
// generous: a loaded machine answers a save in well under this,
// while the held sync never ends until released
select {
case a := <-done:
if a.code != http.StatusOK {
t.Fatalf("save: %d %s", a.code, a.body)
}
case <-time.After(20 * time.Second):
held := release()
<-done
t.Fatalf("the %s save waited %s (sync held: %v): it answers only after the agents' files are written",
c.name, time.Since(start).Round(time.Millisecond), held)
}
// the sync did run, and is held on Pi's models.json
if !release() {
t.Fatalf("no sync ran after the %s save", c.name)
}
agent.SyncCatalogSettled()
})
}
}