agent: a provider named magpie written by hand is the user's, not connected (JFunfunfun on X)

Pi set up by hand on a provider of its own named magpie (magpie/<model>
at the gateway) read as connected in magpie: every catalog change wrote
magpie's list over that provider, RenameProvider rewrote its refs, Drift
offered Reconnect, and Disconnect took the provider out.

0911a65e7 (yyddbds, MiMo) already holds a ListOnly agent's sync until
it is Wired; that still let a hand-written config that names a magpie
model (JFunfunfun's Pi) read as Wired. Both gates now apply.
Its test's last case said a magpie model picked by hand on MiMo's own
magpie provider connects it; that is JFunfunfun's case, so it now
stays the user's until connected in magpie (listonly_test.go, and the
doc's ListOnly line says so).

An agent whose magpie is a provider of its own config (Spelled, not
Native) is now connected only when magpie set it up (setUp): a field in
applied.json, the new applied.Kept that Keep leaves instead of deleting
the record, or the <id>.connect.was stash Connect has written since
10-03. Otherwise (handWired) it isn't Wired, has no Drift, and
SyncCatalog, RenameProvider and renameRefs skip it; Disconnect is a
no-op as it is for any unwired agent. Connecting it in magpie takes it
on as before; Disconnect after that skips putting back "was" values
that were themselves magpie's (dsh errored on them). RenameLegacy
records the dial/ -> magpie/ values it writes, and moveEfforts (the
Cursor/Antigravity effort ids, at start-up) leaves a hand-written
magpie/<ref> alone. Aside keeps its own
key-based ownership. OpenCode's own-gateway-provider test now connects
through Apply as `magpie opencode` does.

Run (on mote, at this head, rebased on f2c6831a3): go test -tags nogui
-count=1 ./internal/agent ./internal/cli ./internal/library
./internal/gui; go vet darwin/linux/windows of internal/agent and
internal/cli; gofmt -l. internal/agent again after the ListOnly test
change: ok. Pushed on ceef9e943, whose five commits since touch usage,
sessions, library, provider movers and gui only.
New tests: TestPiHandWiredMagpieProviderIsTheirs (pi's literal
settings.json/models.json in a sandbox HOME, files byte-identical after
SyncCatalog, RenameProvider and Disconnect), TestPiConnectedBefore-
StaysConnected (applied record, gone model, connect.was, applied then
Keep), TestHandWiredMagpieProviderSiblings (29 Spelled agents). All fail
on the old code.
Tests that wrote a connected agent's files by hand (Pi, OpenCode,
Hermes, omp, dsh, the Kilo plugin, Cursor efforts, and the cli's
save-then-sync test) now also mark it as Connect leaves it
(setUpInMagpie, the connect.was stash); without it they read as
hand-written, which is what this change is about.

Broken by hand, each red: the Sync gate, the rename gates, the Drift
gate, Keep deleting the record, the was-skip in Disconnect, the
moveEfforts gate (TestMoveCursorEfforts' hand-wired case).

Not tried: a real pi binary against the gateway. Users connected
between 09-23 and 10-03 who pressed Keep (record deleted before this)
read as not connected; one Connect brings them back and pi keeps
working meanwhile. Agents without Spelled (Claude Code, Codex, Gemini
and others) decide by their own checks and are unchanged.
This commit is contained in:
yetone
2026-10-30 14:45:56 +08:00
parent ceef9e9438
commit 70a0c387cb
19 changed files with 350 additions and 15 deletions
+2 -2
View File
@@ -16,7 +16,7 @@ something else shows up as drift.
| Fields and options | A `Field` has `Get`, `Set` and `Options`. `Set("")` returns the field to the agent's default and takes magpie's wiring out. `Quiet` fields follow another field until set (`Follows`, such as Claude Code's tiers). An `Option` carries the picker's facts: `Direct`, `Via`, `Same`, `Alias`, `Rate` and `Context`. The GUI's and TUI's pickers list `Agent.Picks`: with the agent in settings' `ownModelsHidden` (the switch at the top of its model list, #1642), a field that offers catalog models (`Ref`) leaves out the agent's own (no `Ref`), but for its default and the value it is set to. The CLI still takes an own model by name. | [`agent.go`](../../internal/agent/agent.go), [`route.go`](../../internal/agent/route.go) |
| The list of agents | `All` lists every agent magpie knows, then the WSL agents (`wslAgents`). `Clients` lists every agent whose requests the gateway knows by name, which `usage.Agents` reads. One file per agent: `claude.go`, `codex.go`, `opencode` in `agents.go`, and so on. | [`agents.go`](../../internal/agent/agents.go) |
| Connect | `ConnectHow` picks the model an agent starts on and reports how. `How` is one of: `kept`, `again`, `joined`, `magpie`, `same`, `alike`, `default` or `first` (#726). With no models to give, it returns `NoModelsError` (code `no_models`). | [`applied.go`](../../internal/agent/applied.go) |
| What magpie set | `Apply` sets a field and records it in `applied.json`. `Wired` says whether magpie is in the config. `Drift` reports `unwired`, `replaced`, `unreachable`, `proxied` or `bypassed`. `Reapply` sets the record again. `Keep` accepts the config as it is now. | [`applied.go`](../../internal/agent/applied.go) |
| What magpie set | `Apply` sets a field and records it in `applied.json`. `Wired` says whether magpie is in the config. `Drift` reports `unwired`, `replaced`, `unreachable`, `proxied` or `bypassed`. `Reapply` sets the record again. `Keep` accepts the config as it is now, and keeps the agent connected (`applied.Kept`). An agent whose magpie is a provider of its own config (`Spelled`, not `Native`) is connected only when magpie set it up (`setUp`: a record, `Kept`, or a `<id>.connect.was` stash). A provider named magpie the user wrote by hand (`handWired`) is theirs: it isn't `Wired`, has no `Drift`, and neither `SyncCatalog`, `RenameProvider` nor `Disconnect` writes it; connecting in magpie takes it on (JFunfunfun on X, Pi on `magpie/<model>`; `TestPiHandWiredMagpieProviderIsTheirs`, `TestPiConnectedBeforeStaysConnected`, `TestHandWiredMagpieProviderSiblings`). | [`applied.go`](../../internal/agent/applied.go) |
| What came before | The stash (`stash.json`) remembers what the config said before magpie pointed it at the gateway, so Disconnect restores it rather than guessing. | [`stash.go`](../../internal/agent/stash.go) |
| Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. Last it runs `Restore`: Pi and its kin (`piLike`: Pi, OmO, Prime Agent; and MothX, its one `settings.json`) copy `settings.json` and `models.json` aside (`*.before-magpie`, `beforeMagpie`) before magpie's first write, and put that copy back byte for byte where what Disconnect left is the same JSON; a file that wasn't there goes again when only empty objects are left in it. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) |
| Uninstall | `magpie uninstall` and Settings › About › Uninstall magpie take magpie off this computer, because deleting magpie's folders by hand left Codex's `openai_base_url` on a gateway that was gone, and every turn failed with a 502 (Jevik_AI on X). `Run` goes in this order. `System` removes the service, opening at login, the Start menu shortcut, `magpie://` links and the privacy model's helper. `Agents` ends Codex's account failover, runs each connected agent's `Disconnect`, or its offline disconnect for a closed app, so the restore keeps what the user changed by hand since. It then ports Codex's rollouts and restarts the Codex app's app-server. `Data` deletes magpie's folders, but keeps the Library while it holds skills, servers or hooks. The executable stays where the user put it. The CLI refuses while another magpie runs, and asks first unless given `--yes`. The app runs `System` and `Agents` from `POST /api/uninstall`. If anything failed, nothing else is removed. Otherwise `POST /api/uninstall/finish` starts a detached `magpie uninstall --data-after <pid>`, which deletes the files once the app has quit, since WebView2 holds its folder open until then. magpie web refuses both routes (`TestUninstall*`, `uninstall-settings.test.cjs`). Every line magpie writes into a TOML, YAML or env config has a `# magpie:` note above it saying how to undo it, so a config left behind still names magpie (`edit.Mark`, `TestMarkedLinesEveryAgent`). | [`uninstall.go`](../../internal/uninstall/uninstall.go), [`uninstall_cli.go`](../../internal/cli/uninstall_cli.go), [`gui/uninstall.go`](../../internal/gui/uninstall.go) |
@@ -44,7 +44,7 @@ something else shows up as drift.
- magpie only removes what it wrote. Anything else in an agent's config stays as it was.
- agy's shell function (`update.ShellFunction`, [`shellfn.go`](../../internal/update/shellfn.go)) sits between `# >>> magpie agy >>>` and `# <<< magpie agy <<<`, the only lines magpie writes or takes out of a profile. The profiles are those `cliProfile` names (zsh's in `ZDOTDIR` when set, bash's, fish's `config.fish`), plus PowerShell 7's and Windows PowerShell's on Windows when their execution policy runs a profile. A missing profile is made only for the shell a terminal opens. Only a file inside the home is written, writes go through temp-and-rename, and a profile that can't be read is left alone. Picking one of magpie's models and every `Sync` on one put it there, which covers users wired before it existed. Stepping out and a `Sync` off magpie take it out. agy in a WSL distro gets the function in the distro's own profiles (`agyDistroProfiles` in [`agy.go`](../../internal/agent/agy.go), through `update.ShellFunctionAt`): `~/.bashrc`, `~/.zshrc` and `~/.config/fish/config.fish` where each is, and the profile of the login shell the distro's `/etc/passwd` names (bash when it names none) made where it isn't. The distro's `ZDOTDIR` and `XDG_CONFIG_HOME` aren't read. No magpie runs there, so the function (`agyDistroFunction`) reads `settings.json`'s model with `sed` and carries the gateway's address as the distro reaches it (`place.gw`, Windows' under NAT) and the key it takes from there (`agentKeyAt`, the WSL key under NAT). `Sync` writes it again, so an address WSL changed on a restart follows, and until then `Check` reports a function naming another address. A user's own `alias agy` still wins over it. A terminal opened before the change still needs the `Launch` command.
- A sync brings magpie's models up to date, not where the agent reaches magpie. Every `Sync` that `SyncCatalog` runs (each start and update of magpie, a provider added, and a plugin signed in to, out of or renewed, or listing other models than the last time: `plugin.OnChange` and `plugin.OnListed` call `catalog.Touched`, #2373) goes through `synced`, which passes each file written through `kept.away` (`edit.Filtered`, [`keptaway.go`](../../internal/agent/keptaway.go)). The filter sees every file written through `edit` while it is on, from any goroutine and under whatever lock the writer holds, so it takes none a writer may hold: the gateway's address and the LAN key are read before it is on (`keeping`), and magpie's own files (`magpieFile`: its folder as named or where its links lead, such as a `~/.config` linked into a dotfiles repo) are left as they are (ylorn on Discord: `settings.Save` under the settings' lock reached a filter that read the settings, and the app hung ~10s after every start; `TestOwnWritesDuringASyncWithALinkedConfig`). In a file without the gateway's own address, whose magpie the user pointed at an address on another machine (a NAS's, or this machine's LAN address), and with no address a WSL distro was seen at, that address stays in place of `gateway.URL()`, with the path before magpie's every URL at it had (`awayPath`: a reverse proxy's `/magpie`; on loopback, a local proxy's route where magpie answered or hasn't been asked), and so does the key that went with it in place of magpie's own (coeo91 on Discord: the base URL went back to 127.0.0.1 after an update or restart). An address on this machine's loopback follows the gateway; with more than one address or key gone, the write is left as it is. Picking a model in magpie still points the agent at this magpie, but for Claude Code at a proxy to it (above). ZCode and WorkBuddy keep such an address in their own writers too (`zcodeAddress`, `buddyWriteAt`).
- An agent whose `Sync` does nothing but bring a block of magpie's name up to the catalog is `ListOnly` (OpenCode, MiMo Code and the other OpenCode forms, Pi and its forks, Goose, Crush, Air, AtomCode, Command Code, Droid, Fx, jcode, Kimi, MiniMax, Mothx, omp, OpenChamber, OpenClaw, OpenPencil, Penguin, Qwen Code, T3 Code). `SyncCatalog` runs it only while the agent is connected (`Wired`), as its switch on the Agents page says: a custom provider the user named magpie in the agent, with a few models picked by hand, was written over with the whole catalog at every start (yyddbds on Discord, Xiaomi MiMo; `TestCatalogSyncLeavesAHandWrittenMagpieBlock`). A list magpie wrote while connected waits, while the agent runs a model of its own, until a model of magpie's is picked again. Every `ListOnly` agent magpie connects reads as `Wired` (`TestListOnlyAgentsReadConnected`). Agents whose `Sync` also repairs while not connected (Codex, Claude, Grok, Hermes' bots) are not `ListOnly`. magpie keeps no copy of a list it wrote over before this, so such a list stays full until the user trims it.
- An agent whose `Sync` does nothing but bring a block of magpie's name up to the catalog is `ListOnly` (OpenCode, MiMo Code and the other OpenCode forms, Pi and its forks, Goose, Crush, Air, AtomCode, Command Code, Droid, Fx, jcode, Kimi, MiniMax, Mothx, omp, OpenChamber, OpenClaw, OpenPencil, Penguin, Qwen Code, T3 Code). `SyncCatalog` runs it only while the agent is connected (`Wired`), as its switch on the Agents page says: a custom provider the user named magpie in the agent, with a few models picked by hand, was written over with the whole catalog at every start (yyddbds on Discord, Xiaomi MiMo; `TestCatalogSyncLeavesAHandWrittenMagpieBlock`). A list magpie wrote while connected waits, while the agent runs a model of its own, until a model of magpie's is picked again; a model of magpie's picked by hand on a provider the user wrote doesn't connect it (`handWired`, above). Every `ListOnly` agent magpie connects reads as `Wired` (`TestListOnlyAgentsReadConnected`). Agents whose `Sync` also repairs while not connected (Codex, Claude, Grok, Hermes' bots) are not `ListOnly`. magpie keeps no copy of a list it wrote over before this, so such a list stays full until the user trims it.
- `SyncCatalog` holds the catalog it builds (`provider.Hold`), the plugins' providers and sign-ins among it, for up to a second. Those `catalog.Touched` drops are told in the background, so a plugin change also drops what is held at once (`plugin.OnChangeNow`, [`hold.go`](../../internal/provider/hold.go)): the host's "auth" event is read before its reply to the sign-in that saved it, and a look at the accounts once the sign-in returns sees it (#2449: `magpie plugin login` found no account while a sync ran; `TestHeldGoesWithAPluginChange`).
- JetBrains Air's `magpie-opencode.json` keeps user-added fields in `provider.magpie`, including nested options, on sync and model picks (`air` in [`air.go`](../../internal/agent/air.go), using `theirsKept` in [`sync.go`](../../internal/agent/sync.go)). The gateway fields and complete model list are still replaced, so removed models leave the list.
- In every OpenCode-shaped config (OpenCode, DevEco, Air, OpenChamber; `openCodeKept` in [`agents.go`](../../internal/agent/agents.go)), a variant the user put on one of magpie's models stays through a sync, and so does one they wrote over under a name of magpie's. A variant exactly as magpie writes it under its name (`openCodeVariant`) is magpie's, so one the model no longer has goes (#2379, `TestOpenCodeCodexFastVariants`).
+77 -5
View File
@@ -33,6 +33,9 @@ var appliedMu sync.Mutex
type applied struct {
At time.Time `json:"at"`
Fields map[string]string `json:"fields"` // field key → value
// Kept: the user took the agent's config as it was (Keep) while magpie
// had it set up, which still says magpie set it up (setUp)
Kept bool `json:"kept,omitempty"`
}
func appliedPath() string { return filepath.Join(filepath.Dir(provider.Path()), "applied.json") }
@@ -180,6 +183,12 @@ func (a *Agent) Drift() *Drift {
break
}
}
// a provider named magpie the user wrote by hand is theirs to keep as
// they like: there is nothing magpie set to drift from, and Reapply
// would write magpie's over it
if onMagpie && a.handWired() {
return nil
}
if a.Check != nil {
if d := a.Check(); d != "" {
return &Drift{Kind: "unwired", Field: on.Key, Now: vals[on.Key], Want: vals[on.Key], Detail: d}
@@ -397,8 +406,24 @@ func (a *Agent) Reapply() error {
}
// Keep takes the agent's config as it is now: what magpie set before is
// forgotten, and no longer said to have been changed.
// forgotten, and no longer said to have been changed. The agent stays one
// magpie set up (setUp): an entry with no fields is kept for it, so one
// whose magpie is spelled as a provider of its own config still reads as
// connected.
func (a *Agent) Keep() {
appliedMu.Lock()
defer appliedMu.Unlock()
m := appliedLoad()
if _, ok := m[a.ID]; !ok {
return
}
m[a.ID] = applied{Kept: true}
appliedSave(m)
}
// forgetSetUp is Disconnect's Keep: what magpie set is forgotten, and so is
// that magpie set the agent up at all.
func (a *Agent) forgetSetUp() {
appliedMu.Lock()
defer appliedMu.Unlock()
m := appliedLoad()
@@ -409,20 +434,58 @@ func (a *Agent) Keep() {
appliedSave(m)
}
// setUp reports whether magpie put the agent on magpie and it hasn't been
// disconnected since: a Connect, which stashes what the agent was on
// (connect.was, since 10-03, which a Keep never took away), or a field
// magpie set to one of its models or to itself (applied.json, which Keep
// keeps an entry in). A field set in magpie to a model of the agent's own,
// or its thinking level, doesn't set it up.
func (a *Agent) setUp() bool {
if stashLoad()[a.ID+".connect.was"] != "" {
return true
}
rec := appliedOf(a.ID)
if rec.Kept {
return true
}
for k, v := range rec.Fields {
// magpie/<model> as magpie wrote it, its model since gone from the
// catalog too
if f := a.Field(k); f != nil && (v == magpieID || prefixed(v) || magpieValue(a, *f, v, rec.Fields)) {
return true
}
}
return false
}
// handWired: magpie is spelled as a provider of the agent's own config
// (Spelled: Pi's magpie/<model>, OpenCode's provider at the gateway), and
// magpie never set the agent up. A provider named magpie that the user
// wrote by hand is theirs (JFunfunfun on X): the agent isn't connected,
// and magpie neither syncs its list there, renames in it, nor takes it out
// on Disconnect.
//
// An app connected natively (Aside) keeps ownership its own way: its
// provider is magpie's by the key magpie wrote in it.
func (a *Agent) handWired() bool { return a.Native == nil && a.Spelled != nil && !a.setUp() }
// Wired reports whether magpie is in the agent's config: a field on one of
// magpie's models, or on magpie itself (an app whose one setting is magpie
// as its provider).
// as its provider). A model on a provider of the agent's own config named
// magpie counts only where magpie set the agent up (handWired).
func (a *Agent) Wired() bool {
if a.Native != nil {
return a.Native.Read().Provider == "connected"
}
// joined by a provider named magpie in the agent's own config (Hermes's
// providers.magpie, VS Code's magpie group), as a model on it is
if a.Joined != nil && a.Joined() || a.Beside != nil && a.Beside() {
return true
return !a.handWired()
}
vals := a.Values()
for _, f := range a.Fields {
if v := vals[f.Key]; v == magpieID || magpieValue(a, f, v, vals) || a.Routed != nil && setAsGroup(a.ID, f.Key, v) && a.Routed() {
return true
return !a.handWired()
}
}
return false
@@ -773,6 +836,15 @@ func (a *Agent) Disconnect() (err error) {
var was map[string]string
json.Unmarshal([]byte(unstash(a.ID+".connect.was")), &was)
after := a.Values()
// connected while on a provider named magpie it had by hand: what it
// was on then is magpie's route, its thinking level read off it too
// (dsh's), not the agent's own to put back
for _, f := range a.Fields {
if w := was[f.Key]; w == magpieID || magpieValue(a, f, w, was) {
was = nil
break
}
}
for _, f := range a.Fields {
if w := was[f.Key]; w != "" && after[f.Key] == "" && w != magpieID && !magpieValue(a, f, w, was) {
if err := f.Set(w); err != nil {
@@ -797,7 +869,7 @@ func (a *Agent) Disconnect() (err error) {
}
b, _ := json.Marshal(back)
stash(map[string]string{a.ID + ".reconnect": string(b)})
a.Keep()
a.forgetSetUp()
return nil
}
+1
View File
@@ -151,6 +151,7 @@ func TestDshApplyReplacesAKeyTheGatewayRefuses(t *testing.T) {
home, dir, web := dshRouteHome(t)
os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"), 0o644)
a := dsh(home)
setUpInMagpie(a.ID)
if err := a.Field("model").Set("magpie/deepseek/flash"); err != nil {
t.Fatal(err)
}
+206
View File
@@ -0,0 +1,206 @@
package agent
import (
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// JFunfunfun on X: Pi set by hand onto a provider of its own named magpie
// (magpie/<model>, at magpie's gateway) read as connected in magpie, which
// then wrote its own list over that provider's models on every catalog
// change, and Disconnect took the provider out. A provider named magpie
// that magpie didn't put there is the user's: the agent isn't connected,
// nothing drifts, and neither a sync, a rename nor Disconnect touches its
// files. Connecting it in magpie takes it on.
func TestPiHandWiredMagpieProviderIsTheirs(t *testing.T) {
syncHome(t)
a, err := Find("pi")
if err != nil {
t.Fatal(err)
}
dir := filepath.Dir(a.Path)
models := filepath.Join(dir, "models.json")
// Pi's own layout, as a person writes it (pi.dev docs: models.json
// providers, settings.json defaultProvider/defaultModel)
settingsJSON := `{
"defaultProvider": "magpie",
"defaultModel": "relay/glm-4.6",
"defaultThinkingLevel": "medium"
}
`
modelsJSON := `{
"providers": {
"magpie": {
"baseUrl": "` + gatewayV1() + `",
"api": "openai-completions",
"apiKey": "sk-a-gateway-key-of-mine",
"models": [{ "id": "relay/glm-4.6", "name": "my GLM" }]
}
}
}
`
hanakoWrite(t, a.Path, settingsJSON, 0o644)
hanakoWrite(t, models, modelsJSON, 0o644)
same := func(when string) {
t.Helper()
for p, want := range map[string]string{a.Path: settingsJSON, models: modelsJSON} {
if b, _ := os.ReadFile(p); string(b) != want {
t.Errorf("%s rewrote %s:\n%s", when, filepath.Base(p), b)
}
}
}
if v := a.Values()["model"]; v != "magpie/relay/glm-4.6" {
t.Fatalf("model reads %q", v)
}
if a.Wired() {
t.Fatal("a provider named magpie written by hand reads as connected")
}
if d := a.Drift(); d != nil {
t.Errorf("drift on a config magpie never set: %+v", d)
}
// a provider saved: the catalog changed, every agent's list is synced
if err := provider.Save(provider.Provider{ID: "relay2", Name: "Relay 2", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"glm-4.6"}}); err != nil {
t.Fatal(err)
}
SyncCatalog()
same("SyncCatalog")
if _, err := RenameProvider("relay", "relay3"); err != nil {
t.Fatal(err)
}
same("RenameProvider")
if err := a.Disconnect(); err != nil {
t.Fatal(err)
}
same("Disconnect")
if a.Wired() {
t.Fatal("connected after Disconnect")
}
// connected in magpie, it is magpie's: Keep (taking the config as it
// is) leaves it so, Disconnect gives it up
hanakoWrite(t, a.Path, `{}`, 0o644)
os.Remove(models)
if err := a.Connect(); err != nil {
t.Fatal(err)
}
if !a.Wired() {
t.Fatalf("not connected after Connect: %v", a.Values())
}
a.Keep()
if !a.Wired() {
t.Fatal("Keep took magpie's connection away")
}
if err := a.Disconnect(); err != nil {
t.Fatal(err)
}
if a.Wired() {
t.Fatalf("connected after Disconnect: %v", a.Values())
}
}
// Users who connected before this release read as connected still: an
// older magpie recorded the model it set (applied.json), or, where Keep
// took that record away, stashed what the agent was on at Connect.
func TestPiConnectedBeforeStaysConnected(t *testing.T) {
for _, c := range []struct {
name string
mark func(a *Agent)
}{
{"applied", func(a *Agent) { record(a.ID, "model", "magpie/relay/glm-4.6") }},
{"applied, model since gone", func(a *Agent) { record(a.ID, "model", "magpie/gone/model-x") }},
{"kept before", func(a *Agent) { stash(map[string]string{a.ID + ".connect.was": `{"model":""}`}) }},
{"applied, then kept", func(a *Agent) { record(a.ID, "model", "magpie/relay/glm-4.6"); a.Keep() }},
} {
t.Run(c.name, func(t *testing.T) {
syncHome(t)
a, err := Find("pi")
if err != nil {
t.Fatal(err)
}
// as magpie wrote it: the model field's Set, with nothing recorded
if err := a.Field("model").Set("magpie/relay/glm-4.6"); err != nil {
t.Fatal(err)
}
if a.Wired() {
t.Fatal("unrecorded reads as connected")
}
c.mark(a)
if !a.Wired() {
t.Fatalf("connected before, reads as not connected: %v", a.Values())
}
})
}
}
// Every agent whose magpie is a provider of its own config (Spelled) holds
// a provider magpie didn't put there as the user's, as Pi does.
func TestHandWiredMagpieProviderSiblings(t *testing.T) {
ids := []string{"agy", "opencode", "openchamber", "mimocode", "deveco", "pi", "aside", "omo", "prime-agent", "goose", "zed", "vscode",
"crush", "dsh", "commandcode", "fx", "omp", "hermes", "morph", "kimi", "empryo", "minimax-code", "droid",
"qoder", "qoder-cn", "grok", "atomcode", "cline", "snow"}
for _, id := range ids {
t.Run(id, func(t *testing.T) {
if id == "aside" {
// connected natively, Aside's provider named magpie is
// magpie's by the key magpie wrote in it; one with a key of
// the user's is theirs (asideConnection.provider)
settings, models := asideHome(t)
writeFile(t, settings, `{"defaultModel":{"provider":"magpie","modelId":"relay/glm-4.6"}}`)
writeFile(t, models, `{"providers":{"magpie":{"apiKey":"magpie","baseUrl":"`+gatewayV1()+`","api":"openai-completions","models":[{"id":"relay/glm-4.6"}]}}}`)
a, err := Find(id)
if err != nil {
t.Fatal(err)
}
if a.Wired() {
t.Fatal("Aside's provider named magpie, with the user's key, reads as connected")
}
return
}
syncHome(t)
a, err := Find(id)
if err != nil {
t.Fatal(err)
}
if a.Spelled == nil {
t.Fatal("no Spelled")
}
if id == "cline" {
hanakoWrite(t, a.Path, `{"version":1,"modes":{},"providers":{},"lastUsedProvider":"openrouter"}`, 0o600)
}
// written outside magpie: the field's own Set, nothing recorded
if err := a.Fields[0].Set("magpie/relay/glm-4.6"); err != nil {
t.Fatal(err)
}
if a.Wired() {
t.Fatalf("a provider named magpie magpie didn't set reads as connected: %v", a.Values())
}
if d := a.Drift(); d != nil {
t.Errorf("drift: %+v", d)
}
if err := a.Connect(); err != nil {
t.Fatal(err)
}
if !a.Wired() {
t.Fatalf("not connected after Connect: %v", a.Values())
}
if err := a.Disconnect(); err != nil {
t.Fatal(err)
}
if a.Wired() {
t.Fatalf("still connected after Disconnect: %v", a.Values())
}
})
}
}
// setUpInMagpie marks agents as connected in magpie, as Connect leaves them
// (its connect.was stash), for a test that writes a connected agent's files
// itself.
func setUpInMagpie(ids ...string) {
for _, id := range ids {
stash(map[string]string{id + ".connect.was": "{}"})
}
}
+3
View File
@@ -26,6 +26,7 @@ func TestHermes(t *testing.T) {
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil {
t.Fatal(err)
}
setUpInMagpie("hermes")
dir := appdir.HermesHomeIn(home)
path := filepath.Join(dir, "config.yaml")
read := func() (map[string]any, map[string]any, string) {
@@ -105,6 +106,7 @@ func TestHermes(t *testing.T) {
}
// Disconnect from magpie's model: back to what the user had
setUpInMagpie("hermes")
f.Set("magpie/deepseek/flash")
if err := a.Disconnect(); err != nil {
t.Fatal(err)
@@ -116,6 +118,7 @@ func TestHermes(t *testing.T) {
// a config with no provider of its own: none comes back
os.WriteFile(path, []byte("agent:\n max_turns: 60\n"), 0o644)
setUpInMagpie("hermes")
f.Set("magpie/deepseek/pro")
if err := a.Disconnect(); err != nil {
t.Fatal(err)
+9 -1
View File
@@ -38,7 +38,11 @@ func RenameLegacy() {
for i := range a.Fields {
f := &a.Fields[i]
if rest, ok := strings.CutPrefix(f.Get(), legacyID+"/"); ok {
_ = f.Set(magpieID + "/" + rest)
// dial/… is what magpie wrote under its old name: magpie set
// the agent up (setUp)
if f.Set(magpieID+"/"+rest) == nil {
record(a.ID, f.Key, f.Get())
}
}
}
switch a.ID {
@@ -91,6 +95,10 @@ func moveEfforts(pid string, base func(string) (string, string, bool)) {
v := f.Get()
pre, rest := "", v
if r, ok := strings.CutPrefix(v, magpieID+"/"); ok {
if a.handWired() {
// the user's own provider named magpie: not ours to move
continue
}
pre, rest = magpieID+"/", r
}
id, ok := strings.CutPrefix(rest, pid+"/")
+9
View File
@@ -132,6 +132,7 @@ func TestMoveCursorEfforts(t *testing.T) {
}
}
write(`{"defaultProvider": "magpie", "defaultModel": "curs/grok-4.7-low", "theme": "dark"}`)
setUpInMagpie("pi")
moveEfforts("curs", base)
for k, want := range map[string]string{"defaultProvider": "magpie", "defaultModel": "curs/grok-4.7", "defaultThinkingLevel": "low", "theme": "dark"} {
if v, _ := edit.GetJSON(pi, k); v != want {
@@ -149,4 +150,12 @@ func TestMoveCursorEfforts(t *testing.T) {
if v, _ := edit.GetJSON(pi, "defaultModel"); v != "curs/gone-low" {
t.Errorf("model %q", v)
}
// a provider named magpie the user wrote by hand is theirs: left as it is
stash(map[string]string{"pi.connect.was": ""})
mine := `{"defaultProvider": "magpie", "defaultModel": "curs/grok-4.7-low"}`
write(mine)
moveEfforts("curs", base)
if b, _ := os.ReadFile(pi); string(b) != mine {
t.Errorf("hand-wired Pi moved:\n%s", b)
}
}
+12 -4
View File
@@ -82,10 +82,18 @@ func TestCatalogSyncLeavesAHandWrittenMagpieBlock(t *testing.T) {
t.Errorf("after Disconnect, MiMo's own magpie provider written over:\n%s", got)
}
// a model of magpie's picked in MiMo connects it: the list is
// magpie's again
connected := strings.Replace(own, `"mimo/mimo-v2.5-pro"`, `"magpie/relay/glm-4.6"`, 1)
writeFile(t, mimo, connected)
// a model of magpie's picked in MiMo on that provider of its own
// doesn't connect it (JFunfunfun on X: handWired); connecting it in
// magpie does, and the list is magpie's again
picked := strings.Replace(own, `"mimo/mimo-v2.5-pro"`, `"magpie/relay/glm-4.6"`, 1)
writeFile(t, mimo, picked)
SyncCatalog()
if got := readFile(mimo); got != picked {
t.Errorf("a magpie model picked on MiMo's own magpie provider, written over:\n%s", got)
}
if err := a.Connect(); err != nil {
t.Fatal(err)
}
SyncCatalog()
if got := readFile(mimo); !strings.Contains(got, `"later/m3"`) {
t.Errorf("a connected MiMo's list not kept current:\n%s", got)
+1
View File
@@ -26,6 +26,7 @@ func TestModelNameAndLevelsReachAgentFiles(t *testing.T) {
writeFile(t, piModels, `{"providers":{"magpie":{"name":"magpie","models":[]}}}`)
// Pi runs a model of magpie's: connected, so its list follows
writeFile(t, filepath.Join(home, ".pi", "agent", "settings.json"), `{"defaultProvider":"magpie","defaultModel":"relay/glm-4.6"}`)
setUpInMagpie("pi")
codexDir := filepath.Join(home, ".codex")
codexCat := filepath.Join(codexDir, "magpie-models.json")
writeFile(t, filepath.Join(codexDir, "config.toml"), "model = \"relay/glm-4.6\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = '"+codexCat+"'\n")
+1
View File
@@ -175,6 +175,7 @@ task:
review: [magpie/deepseek/pro:low]
`
os.WriteFile(configPath, []byte(before), 0o644)
setUpInMagpie("omp")
if err := f.Set("magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
+1
View File
@@ -50,6 +50,7 @@ func kiloWired(t *testing.T) (string, string) {
if err != nil {
t.Fatal(err)
}
setUpInMagpie(a.ID)
if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
+6 -1
View File
@@ -25,7 +25,7 @@ func RenameProvider(from, to string) ([]string, error) {
}
if from != to {
for _, a := range Detected() {
if a.RenameRefs == nil {
if a.RenameRefs == nil || a.handWired() {
continue
}
ok, err := a.RenameRefs(from, to)
@@ -74,6 +74,11 @@ func renameRefs(renamed func(ref string) (string, bool), rename func() error) ([
}
var moves []move
for _, a := range Detected() {
// a provider named magpie written by hand is the user's, the
// models it names too (handWired)
if a.handWired() {
continue
}
vals := a.Values()
for _, f := range a.Fields {
v := vals[f.Key]
+1
View File
@@ -29,6 +29,7 @@ func TestRenameGroupMovesTheAgentsOnIt(t *testing.T) {
writeFile(t, piSettings, `{"defaultProvider":"magpie","defaultModel":"group/smart"}`)
oc := filepath.Join(home, ".config", "opencode", "opencode.json")
writeFile(t, oc, `{"model":"magpie/group/smart"}`)
setUpInMagpie("pi", "opencode")
claudeCfg := filepath.Join(home, ".claude", "settings.json")
writeFile(t, claudeCfg, `{}`)
cc, err := Find("claude")
+10 -1
View File
@@ -60,7 +60,9 @@ func TestOwnProviderNamedAsMagpies(t *testing.T) {
}
// OpenCode's own provider that sends to magpie's gateway is magpie's all
// the same (openCodeRef names a model there by it).
// the same (openCodeRef names a model there by it), once magpie set
// OpenCode up: before that, it is a provider the user wrote by hand and
// theirs (handWired, JFunfunfun on X).
func TestOpenCodeGatewayProviderIsMagpies(t *testing.T) {
syncHome(t)
a, err := Find("opencode")
@@ -68,6 +70,13 @@ func TestOpenCodeGatewayProviderIsMagpies(t *testing.T) {
t.Fatal(err)
}
hanakoWrite(t, a.Path, `{"provider":{"relay":{"options":{"baseURL":"`+gatewayV1()+`"},"models":{"relay/glm-4.6":{}}}},"model":"relay/relay/glm-4.6"}`, 0o644)
if a.Wired() {
t.Fatalf("its own provider at the gateway, written by hand, reads as connected: %v", a.Values())
}
// as magpie opencode relay/glm-4.6 sets it (9b1641a49)
if err := a.Apply("model", "relay/relay/glm-4.6"); err != nil {
t.Fatal(err)
}
if !a.Wired() {
t.Fatalf("a model through its own provider at the gateway isn't magpie's: %v (%s)", a.Values(), filepath.Base(a.Path))
}
+1
View File
@@ -34,6 +34,7 @@ func TestSuffixModesReachAgentFiles(t *testing.T) {
writeFile(t, piModels, `{"providers":{"magpie":{"name":"magpie","models":[]}}}`)
// Pi runs a model of magpie's: connected, so its list follows
writeFile(t, filepath.Join(home, ".pi", "agent", "settings.json"), `{"defaultProvider":"magpie","defaultModel":"relay/glm-4.6"}`)
setUpInMagpie("pi")
codexDir := filepath.Join(home, ".codex")
codexCat := filepath.Join(codexDir, "magpie-models.json")
writeFile(t, filepath.Join(codexDir, "config.toml"), "model = \"relay/glm-4.6\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = \""+tomlString(codexCat)+"\"\n")
+3 -1
View File
@@ -52,7 +52,9 @@ func SyncCatalog() {
unhold := filememo.Hold()
renaming := setToFoundGroups()
for _, a := range All() {
if a.Sync != nil && (!a.ListOnly || a.Wired()) {
// a provider named magpie written by hand is the user's, its
// model list too (handWired)
if a.Sync != nil && !a.handWired() && (!a.ListOnly || a.Wired()) {
_ = synced(a.Sync)
}
// a field magpie set to a found group's id before (autoref.go)
+1
View File
@@ -51,6 +51,7 @@ func TestPiKeepsTheirKeysInMagpiesProvider(t *testing.T) {
`)
// Pi runs a model of magpie's: connected, so its list follows
writeFile(t, filepath.Join(home, ".pi", "agent", "settings.json"), `{"defaultProvider":"magpie","defaultModel":"relay/glm-4.6"}`)
setUpInMagpie("pi")
SyncCatalog()
p := providerAt(t, piModels, "providers")
compat, _ := p["compat"].(map[string]any)
+1
View File
@@ -232,6 +232,7 @@ func TestSyncCatalogRewritesAgentLists(t *testing.T) {
// connected: a block of magpie's name in an agent not on magpie is the
// user's own (TestCatalogSyncLeavesAHandWrittenMagpieBlock)
writeFile(t, filepath.Join(home, ".pi", "agent", "settings.json"), `{"defaultProvider":"magpie","defaultModel":"relay/glm-4.6"}`)
setUpInMagpie("pi")
crushCfg := filepath.Join(home, ".config", "crush", "crush.json")
crushBody := `{"providers":{"mine":{"base_url":"http://x"}}}`
writeFile(t, crushCfg, crushBody)
+5
View File
@@ -54,6 +54,11 @@ func TestSaveAnswersBeforeTheAgentsSync(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "settings.json"), []byte(`{"defaultProvider":"magpie","defaultModel":"a/m1"}`), 0o600); err != nil {
t.Fatal(err)
}
// Pi as magpie connected it (Connect's connect.was stash): a sync
// writes only an agent connected in magpie
if err := os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "stash.json"), []byte(`{"pi.connect.was":"{}"}`), 0o600); err != nil {
t.Fatal(err)
}
fifo := filepath.Join(dir, "models.json")
h := gui.Handler(nil, nil)
post := func(path, body string) (int, string) {