agent: a renamed routing group moves its agents, and the Codex app reloads a changed catalog

lucis0116 on X: renaming a provider or a group in magpie didn't reach
every agent.

Display names already reached the agents' files: store and SaveGroup
drop the catalog, and SyncCatalog writes the new "<model> · <name>" and
"<group> · routing group" labels into Codex's model_catalog_json, Claude
Code's picker, OpenCode and Pi (checked in a sandbox HOME). Two gaps
were left:

- A routing group given another id (Routing page, `magpie groups
  rename`, TUI) left every agent on group/<old>, which magpie no longer
  has. The CLI even said "agents set to group/from need group/to now".
  agent.RenameGroup now moves each agent field on group/<old> to
  group/<new>, spelled as the agent spells it. It goes through
  renameRefs, the move RenameProvider already made, now shared by both,
  then SyncCatalog. The GUI, CLI and TUI call it in place of
  provider.RenameGroup.
- The Codex app's own app-server reads model_catalog_json only as it
  starts, and KeepCodexAppOnItsProvider restarts it only when
  codexAppRoute changes. The route named the catalog's path, not what
  the file holds, so a renamed provider or group, or a model added,
  stayed on the old list until the user quit the app. The route now
  carries a hash of the catalog's bytes (codexCatalogTag, read again
  only when the file's size or time changes). The restart goes through
  the existing idle gate: no Codex request in flight, 10s idle, no turn
  open. A write of the same bytes is no change.

Run, in a sandbox HOME only:
- TestRenameGroupMovesTheAgentsOnIt (new): Codex, Claude Code, OpenCode
  and Pi on group/smart, renamed to clever: each said moved and each
  file on group/clever, none naming group/smart.
- TestCodexAppRouteFollowsTheCatalog (new): the route changes when a
  renamed provider rewrites the catalog, and stays put when the same
  bytes are written again.
- Broken by hand: RenameGroup's match turned off makes the first test
  red (no agent moved, every file on group/smart). The catalog line
  dropped from codexAppRoute makes the second red ("a provider renamed
  left the Codex app's route as it was").
- At aded9beea (base ad3833512): go test -tags nogui -timeout 45m
  ./internal/agent ./internal/cli ./internal/gui ./internal/tui
  ./internal/provider -count=1: cli, gui and tui ok. agent red on
  TestFolderVarsAreListed (#3884, red on main since e4552cca9) and
  TestCodexDisconnectStaysWithAccountsOn/login=api, which passed 3 of 3
  alone and isn't on this path (filed #3891). provider crashed in
  TestUnreadLoginsWriteErrorsKeepCredentials with "close of synctest
  channel from outside bubble" in filememo.Forget (#3632, open on main).
- Rebased on 56de2d192 (a312bf3e3 adds a switched account's app-server
  to the same stale set; no overlap): go test -tags nogui -count=1
  ./internal/agent -run 'Rename|CodexApp|Sync|Group|Codex|Hermes' ok
  at this head; ./internal/provider -run
  'CodexApp|Group' ok at a312bf3e3 + this change. The disk was full (other sessions' suites), so the
  whole of each package wasn't run again at this head.
- GUI: group-id-dots, group-morph, agent-model-groups and i18n-keys,
  32 of 32. No GUI script changed, and the GUI tests answer the API in
  memory.
- gofmt -l clean. go vet -tags nogui on agent, cli, gui and tui for
  darwin, linux and windows: ok.

Not covered:
- Claude Desktop reads the gateway's model list only as it starts. It
  still needs its Restart button (AppBehind) after a rename, as after
  any other catalog change.
- Pi, omp and StepCode enabledModels: RenameRefs renames magpie/<old>/
  provider entries only. A group's magpie/group/<old> entry goes as
  scope-gone, and the pick of group/<new> is added again. Not checked
  entry by entry.
- Codex signed in beside magpie (models_cache.json aged by the catalog
  tag) was not run again here.
- No real Codex app restart was watched. The reporter's agent isn't
  named.
This commit is contained in:
yetone
2026-10-27 18:22:29 +08:00
parent 7f827b3b0b
commit ca8a6f346a
9 changed files with 275 additions and 57 deletions
+1 -1
View File
@@ -78,7 +78,7 @@ something else shows up as drift.
- Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default` is the route, and magpie does not set it: setting it to `"magpie"` makes the App drop its own sign-in (`ensure_independent_for_custom_route`). The route stays whatever the App had. Pressing Use on magpie under Accounts is what switches it. A magpie that already set the route puts the old one back once, on the next sync or connect (`grokAppReleased`); a Use after that stays. Disconnect drops only the channel, and puts the route back only when it is still `"magpie"`: the one stashed at connect, else the one `connect.was` holds. One of the App's own routes picked in magpie's model field is written as the route and takes magpie's channel out, as picking another provider does elsewhere. A sync with no channel and a route other than `"magpie"` writes nothing, magpie's stash included, and Check says so when the route is `"magpie"` with the channel gone. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. Shared mode keeps `GROK_HOME` at `~/.grok` (Grok Build's library row). Independent mode, which Use turns on, reads agent-home: the Library writes `AGENTS.md`, `[mcp_servers]` in the same `config.toml`, and `skills/` there, and Grok App also reads `~/.agents/skills`. RTK has no Grok hook, so the Library lists Grok App with the switch off. The notice, while the App runs, says magpie is a custom provider in Settings › Account, a chat can pick its models in the model picker, and the App stays on its current route until Use.
- JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`).
- A config that starts with a UTF-8 byte order mark (a Windows `settings.json` or `config.toml` saved by PowerShell, Notepad or a channel switcher, #1534) is read without it (`edit.Read`), and a write keeps it (`keepBOM` in `WriteAtomic`): the user's file keeps the encoding it was saved in. That covers every format `internal/edit` writes (JSON/JSONC and its arrays, TOML, YAML, env); Codex reads a TOML file through a BOM too, so magpie no longer refuses one. A file read some other way trims it with `edit.TrimBOM` (the Claude Code and CC Switch imports). A line an edit takes out of a CRLF file goes with its `\r\n`.
- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/<model>`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`.
- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/<model>`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`, and a hash of what the catalog file holds, `codexCatalogTag` in [`codex_app_route.go`](../../internal/agent/codex_app_route.go), read again only when its size or time changes; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out, a provider or group renamed or a model added. Without the catalog in it the app kept the names and models it started with until it was restarted (lucis0116 on X). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexAppRouteFollowsTheCatalog`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`.
- Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is.
- Claude Desktop applying a configLibrary profile other than magpie's is not drift when that profile is a gateway profile for this magpie's gateway (`desktopAppliedGateway` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)): Desktop's "Import configuration" adds a file exported on another computer, magpie's profile there with the user's connectors (`managedMcpServers`), as a new entry under a random id (aa86222 on Discord). magpie keeps it applied on Reconnect and through Sync, and writes in it only `inferenceGatewayApiKey` (with a missing auth scheme) when the gateway would refuse its key (`desktopKeyApplied`; magpie's own keys count as taken, `desktopKeyTaken`). A profile for another gateway, CC Switch's among them, is still drift, and Reconnect applies magpie's. The first switch-on still starts magpie's profile from an applied one (#2035). `TestClaudeDesktopImportedProfileIsOnMagpie`.
- A field that follows another while empty (`Follows`: Claude Code's tiers and subagents on its main model) is read by `Drift` as on that field's model. The main model moved, in Claude Code's own `/model`, onto the model magpie had set a tier to is not drift (#1050). The tier keeps that model as its own through the move and the next one (`tier_own` in the stash), whatever it would follow on the new main model: fable, which follows no model that is no Fable, and haiku, which follows a Claude model on its Haiku, read as following and lost their model on the next move (#2257).
File diff suppressed because one or more lines are too long
+9
View File
@@ -72,6 +72,15 @@ func codexAppRoute() (route string, out, known bool) {
}
t, _ := edit.GetTOMLTable(a.Path, "model_providers."+magpieID)
b.WriteString("magpie.base_url=" + t["base_url"] + "\n")
// and the list in that catalog, which the app-server also reads only
// as it starts: a provider or group renamed, or a model added, left
// the app on the names and models it started with (lucis0116 on X)
if c, _ := edit.GetTOMLTop(a.Path, "model_catalog_json"); c != "" {
if !filepath.IsAbs(c) {
c = filepath.Join(filepath.Dir(a.Path), c)
}
b.WriteString("catalog=" + codexCatalogTag(c) + "\n")
}
if out {
b.WriteString("out\n")
}
+45
View File
@@ -0,0 +1,45 @@
package agent
import (
"crypto/sha256"
"encoding/hex"
"os"
"sync"
"time"
)
// codexCatalogTag stands for what the catalog file at path holds now, for
// codexAppRoute: a hash of its bytes, "" when it can't be read. The route
// is looked at every few seconds (provider.KeepCodexAppOnItsProvider) and
// the catalog holds each model's instructions, a few MB with many models,
// so the file is read again only when its size or time changed. A rewrite
// to the same bytes (a Connect writes it again) is the same tag, and
// restarts nothing.
func codexCatalogTag(path string) string {
st, err := os.Stat(path)
if err != nil {
return ""
}
c := &codexCatalogSeen
c.Lock()
defer c.Unlock()
if c.path == path && c.size == st.Size() && c.mod.Equal(st.ModTime()) {
return c.tag
}
b, err := os.ReadFile(path)
if err != nil {
return ""
}
sum := sha256.Sum256(b)
c.path, c.size, c.mod, c.tag = path, st.Size(), st.ModTime(), hex.EncodeToString(sum[:12])
return c.tag
}
// codexCatalogSeen is the last catalog codexCatalogTag read.
var codexCatalogSeen struct {
sync.Mutex
path string
size int64
mod time.Time
tag string
}
+98 -51
View File
@@ -14,58 +14,14 @@ import (
func RenameProvider(from, to string) ([]string, error) {
from = strings.ToLower(strings.TrimSpace(from))
to = strings.ToLower(strings.TrimSpace(to))
type move struct {
a *Agent
key, val string
}
// what the agents are on is read before: the picker's options name
// the provider by the id it has
var moves []move
if from != to {
for _, a := range Detected() {
vals := a.Values()
for _, f := range a.Fields {
v := vals[f.Key]
if v == "" {
continue
}
// the agent's suffix after the model (SplitSuffix) stays; a
// list of models is the user's own, its names moved by
// RenameRefs where the agent has one
model, suffix, one := a.split(v)
if !one {
continue
}
nv := ""
if f.Options != nil {
for _, o := range f.Options(vals) {
if o.Value == model && strings.HasPrefix(o.Ref, from+"/") {
now := to + "/" + strings.TrimPrefix(o.Ref, from+"/")
nv = strings.Replace(model, o.Ref, now, 1) + suffix
break
}
}
}
if nv == "" && strings.HasPrefix(v, magpieID+"/"+from+"/") {
nv = magpieID + "/" + to + "/" + strings.TrimPrefix(v, magpieID+"/"+from+"/")
}
if nv != "" && nv != v {
moves = append(moves, move{a, f.Key, nv})
}
}
}
}
if err := provider.Rename(from, to); err != nil {
return nil, err
}
var moved []string
for _, m := range moves {
if err := m.a.Apply(m.key, m.val); err != nil {
return moved, err
}
if len(moved) == 0 || moved[len(moved)-1] != m.a.Name {
moved = append(moved, m.a.Name)
moved, err := renameRefs(func(ref string) (string, bool) {
if rest, ok := strings.CutPrefix(ref, from+"/"); ok && from != to {
return to + "/" + rest, true
}
return "", false
}, func() error { return provider.Rename(from, to) })
if err != nil {
return moved, err
}
if from != to {
for _, a := range Detected() {
@@ -85,6 +41,97 @@ func RenameProvider(from, to string) ([]string, error) {
return moved, nil
}
// RenameGroup gives a routing group another id (provider.RenameGroup) and
// moves the agents on it to group/<to>, as RenameProvider does a
// provider's: left on group/<from>, each agent named a group magpie no
// longer has, and the user had to pick the group again in every agent
// (lucis0116 on X). It answers the agents it moved.
func RenameGroup(from, to string) ([]string, error) {
from = strings.ToLower(strings.TrimSpace(from))
to = strings.ToLower(strings.TrimSpace(to))
old, now := provider.GroupPrefix+from, provider.GroupPrefix+to
moved, err := renameRefs(func(ref string) (string, bool) {
if ref == old && from != to {
return now, true
}
return "", false
}, func() error { return provider.RenameGroup(from, to) })
if err != nil {
return moved, err
}
SyncCatalog()
return moved, nil
}
// renameRefs runs rename and then moves every field of a detected agent
// that was on a model whose ref renamed maps, to that model's new ref,
// spelled as the agent spells it. What the agents are on is read before
// rename: the pickers' options name the model by the ref it has then.
func renameRefs(renamed func(ref string) (string, bool), rename func() error) ([]string, error) {
type move struct {
a *Agent
key, val string
}
var moves []move
for _, a := range Detected() {
vals := a.Values()
for _, f := range a.Fields {
v := vals[f.Key]
if v == "" {
continue
}
// the agent's suffix after the model (SplitSuffix) stays; a
// list of models is the user's own, its names moved by
// RenameRefs where the agent has one
model, suffix, one := a.split(v)
if !one {
continue
}
nv := ""
if f.Options != nil {
for _, o := range f.Options(vals) {
if o.Value != model {
continue
}
if now, ok := renamed(o.Ref); ok {
nv = strings.Replace(model, o.Ref, now, 1) + suffix
break
}
}
}
if ref, ok := strings.CutPrefix(v, magpieID+"/"); nv == "" && ok {
// the agent's value names magpie's model outright
// (magpie/<ref>), with its suffix after it
for _, r := range []string{ref, strings.TrimPrefix(model, magpieID+"/")} {
if !strings.HasPrefix(ref, r) {
continue
}
if now, ok := renamed(r); ok {
nv = magpieID + "/" + now + strings.TrimPrefix(ref, r)
break
}
}
}
if nv != "" && nv != v {
moves = append(moves, move{a, f.Key, nv})
}
}
}
if err := rename(); err != nil {
return nil, err
}
var moved []string
for _, m := range moves {
if err := m.a.Apply(m.key, m.val); err != nil {
return moved, err
}
if len(moved) == 0 || moved[len(moved)-1] != m.a.Name {
moved = append(moved, m.a.Name)
}
}
return moved, nil
}
// MoveOffAccountIDs moves each of the user's providers saved on a
// subscription's id (provider.OnAccountIDs) to a free one, the agents on it
// with it, so the subscription is listed once signed in: a "WorkBuddy" key
+113
View File
@@ -0,0 +1,113 @@
package agent
import (
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// A routing group given another id takes the agents on it along, as a
// provider's rename does: Codex, Claude Code (its model and tiers),
// OpenCode and Pi were left on group/<old>, a group magpie no longer had,
// and the user had to pick it again in each (lucis0116 on X).
func TestRenameGroupMovesTheAgentsOnIt(t *testing.T) {
home := syncHome(t)
if err := provider.SaveGroup(provider.Group{ID: "smart", Name: "Smart", Members: []string{"relay/glm-4.6"}}); err != nil {
t.Fatal(err)
}
codexCfg := filepath.Join(home, ".codex", "config.toml")
codexCat := filepath.Join(home, ".codex", "magpie-models.json")
writeFile(t, codexCfg, "model = \"group/smart\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = '"+codexCat+"'\n")
writeFile(t, codexCat, `{"models":[]}`)
piModels := filepath.Join(home, ".pi", "agent", "models.json")
piSettings := filepath.Join(home, ".pi", "agent", "settings.json")
writeFile(t, piModels, `{"providers":{"magpie":{"name":"magpie","models":[]}}}`)
writeFile(t, piSettings, `{"defaultProvider":"magpie","defaultModel":"group/smart"}`)
oc := filepath.Join(home, ".config", "opencode", "opencode.json")
writeFile(t, oc, `{"model":"magpie/group/smart"}`)
claudeCfg := filepath.Join(home, ".claude", "settings.json")
writeFile(t, claudeCfg, `{}`)
cc, err := Find("claude")
if err != nil {
t.Fatal(err)
}
if err := cc.Apply("model", "group/smart"); err != nil {
t.Fatal(err)
}
SyncCatalog()
moved, err := RenameGroup("smart", "clever")
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"Codex", "Claude Code", "OpenCode", "Pi"} {
if !slices.Contains(moved, name) {
t.Errorf("%s not said moved: %v", name, moved)
}
}
if v, _ := edit.GetTOMLTop(codexCfg, "model"); v != "group/clever" {
t.Errorf("codex model = %q", v)
}
if v, _ := edit.GetJSON(piSettings, "defaultModel"); v != "group/clever" {
t.Errorf("pi defaultModel = %v", v)
}
if v, _ := edit.GetJSON(oc, "model"); v != "magpie/group/clever" {
t.Errorf("opencode model = %v", v)
}
claude := readFile(claudeCfg)
if strings.Contains(claude, "group/smart") || !strings.Contains(claude, `"model": "group/clever"`) && !strings.Contains(claude, `"model":"group/clever"`) {
t.Errorf("claude settings still on the old id:\n%s", claude)
}
for _, f := range []string{codexCat, piModels, oc} {
if s := readFile(f); strings.Contains(s, "group/smart") || !strings.Contains(s, "group/clever") {
t.Errorf("%s lists the old id:\n%s", f, s)
}
}
}
// The Codex app's app-server reads its model catalog only as it starts,
// so the route it is restarted on (codex_app_server.go) follows what the
// catalog holds: a provider's name changed in magpie reached the file, and
// the app kept showing the old one (lucis0116 on X). The same bytes
// written again are no change.
func TestCodexAppRouteFollowsTheCatalog(t *testing.T) {
home := syncHome(t)
codexCat := filepath.Join(home, ".codex", "magpie-models.json")
writeFile(t, filepath.Join(home, ".codex", "config.toml"), "model = \"relay/glm-4.6\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = '"+codexCat+"'\n")
writeFile(t, codexCat, `{"models":[]}`)
SyncCatalog()
route := func() string {
t.Helper()
r, _, known := codexAppRoute()
if !known {
t.Fatal("route not known")
}
return r
}
before := route()
if !strings.Contains(readFile(codexCat), "GLM-4.6 · Relay") {
t.Fatalf("catalog:\n%s", readFile(codexCat))
}
if err := provider.Save(provider.Provider{ID: "relay", Name: "Renamed", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"glm-4.6"}}); err != nil {
t.Fatal(err)
}
SyncCatalog()
if !strings.Contains(readFile(codexCat), "GLM-4.6 · Renamed") {
t.Fatalf("catalog not rewritten:\n%s", readFile(codexCat))
}
renamed := route()
if renamed == before {
t.Fatal("a provider renamed left the Codex app's route as it was: its app-server keeps the old names")
}
// written again as it is (a Connect does): no restart for that
if err := writeOwnList(codexCat, []byte(readFile(codexCat))); err != nil {
t.Fatal(err)
}
if route() != renamed {
t.Error("the same catalog written again changed the route")
}
}
+5 -2
View File
@@ -807,10 +807,13 @@ func setGroup(ref string, pairs []string) (provider.Group, error) {
return g, err
}
if to != from {
if err := provider.RenameGroup(from, to); err != nil {
moved, err := agent.RenameGroup(from, to)
if err != nil {
return g, err
}
fmt.Println(amber.Render("!"), "agents set to "+provider.GroupPrefix+from+" need "+provider.GroupPrefix+to+" now")
for _, a := range moved {
fmt.Println(green.Render("✓"), a+" is on "+provider.GroupPrefix+to+" now")
}
}
return findGroup(to)
}
+2 -1
View File
@@ -418,7 +418,8 @@ func groupRoutes(mux *http.ServeMux) {
}
in.ID = body.From
if err = provider.SaveGroup(in); err == nil {
err = provider.RenameGroup(body.From, to)
// the agents on group/<from> move to group/<to>
_, err = agent.RenameGroup(body.From, to)
}
case "delete":
if len(body.IDs) > 0 {
+1 -1
View File
@@ -493,7 +493,7 @@ func (m model) updateGroup(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
hint: "agents pick it as group/<id>: those on it, and the groups that have it in them, follow",
onEnter: func(to string) tea.Cmd {
return func() tea.Msg {
if err := provider.RenameGroup(g.ID, to); err != nil {
if _, err := agent.RenameGroup(g.ID, to); err != nil {
return flashMsg{text: err.Error()}
}
return renamedMsg{from: g.ID, to: strings.ToLower(to)}