agent: Droid gets a GPT on openai and a Claude on anthropic, as droid asks, and keeps an entry edited by hand

ji233 on Discord: droid warned at session start that "ultrafast/gpt-6.1-sol
appears to be an OpenAI model, but is configured with provider
generic-chat-completion-api". magpie wrote every model on a Chat provider
as generic-chat-completion-api, whatever its name.

droid's own rule, read from its bundle (droid 0.231.0, xs and g2): a
custom model's "model" matching /\bgpt[-_.]?\d/i, /codex/i or
/\bo[1-9](?:[-_.]|$)/i on any provider but openai is warned about as
OpenAI's; then one matching /claude|haiku|sonnet|opus/i on neither
anthropic nor bedrock-converse as Claude's. droid first looks the name up
among its own models; every OpenAI one there matches the patterns except
gpt-image/gpt-transcribe, so the patterns alone are used (droidWants).
Such a model now goes on the provider droid asks for (openai on the
gateway's /v1, anthropic on its root), and the gateway translates
(Responses->Chat: TestResponsesClientChatUpstream; groups on Responses
as for Codex). Other models keep their native API as before.

A provider, displayName, maxContextLimit, maxOutputTokens or
noImageSupport the user changed in one of magpie's entries stays through
a sync and a new pick: what magpie last wrote is stashed
(droid:<path>:wrote), a value other than it is the user's. Keys magpie
doesn't write stay too (droid's index aside). baseUrl follows the
entry's provider; apiKey is wiring, put back at every sync. With no
record (entries an older magpie wrote, which each sync wrote over
anyway), magpie's values are taken, so ji233's entries move to openai on
the next sync. Disconnect forgets the record. Doc: agent-wiring.md.

Run (mote):
- go test ./internal/agent -run TestDroid: ok. Red on the old droid.go
  (TestDroidWantsItsOwnRule, TestDroidProviderByName,
  TestDroidKeepsAnEntryEditedByHand all FAIL); with droidMerge forced
  to magpie's values, TestDroidKeepsAnEntryEditedByHand FAILs.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/agent ok.
- go test -count=1 -timeout 45m ./... at 5be7d8ab7 (on 133493488): 79
  packages ok; internal/gui's real-window AppKit tests killed at their
  deadline (TestPanelCloseHidesIt and TestTrayCellClickReleasedPanel
  fail the same on origin/main b4cb946f9 on mote: #4125, #2645), and
  internal/update TestRelaunchOpenTriedAgain's TempDir cleanup (#3881;
  passes -count=3 alone at this head, and alone on b4cb946f9).
  After rebasing on b4cb946f9: go test ./internal/agent ok.
- Real droid 0.231.0 in a sandbox HOME on mote, no sign-in, against a
  sandbox `magpie serve` built from this tree with a Chat-only provider
  "ultrafast" (gpt-6.1-sol, claude-opus-4-7, kimi-k2.5) on a fake
  upstream: `magpie droid magpie/ultrafast/gpt-6.1-sol` wrote openai /
  anthropic / generic-chat-completion-api; `droid exec -m
  custom:magpie/ultrafast/<m> "say pong"` answered PONG for all three
  through /v1/responses, /v1/messages and /v1/chat/completions, the
  upstream got Chat each time, and no "appears to be" warning was in
  droid's sessions. The same droid on generic-chat-completion-api for
  gpt-6.1-sol stored the warning in its session; on openai it didn't.

Not tried: droid's interactive TUI (exec only); a real vendor upstream
(fake Chat upstream only); Windows/WSL droid; droid's built-in-name
lookup cases the patterns miss (gpt-image-*, gpt-transcribe).
This commit is contained in:
yetone
2026-10-30 19:34:45 +08:00
parent b4cb946f98
commit cf9ea977ca
3 changed files with 306 additions and 8 deletions
+1
View File
@@ -83,6 +83,7 @@ something else shows up as drift.
- NewMax (newmax.cc, an Electron app on the Claude Agent SDK) keeps its settings as JSON in the row `app` of the `settings` table of `newmax.db`, a SQLite database in WAL mode in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` on every system (`newMax` in [`newmax.go`](../../internal/agent/newmax.go); its main bundle's `configureAppDataPaths`, `loadPersistedAppSettings` and the renderer's `mergeProviders`, v1.1.22). magpie adds one entry to `providers` in the shape NewMax's own import writes, `id: magpie-gateway` (its own preset is `magpie`, its import's ids hold `%3A`), `apiFormat: anthropic` at the gateway's root (NewMax appends `/v1/messages`) with `ANTHROPIC_AUTH_TOKEN` and a key naming NewMax, at most 20 models (`MAX_MODELS`) as `models` and `enabledModels` with their context windows, and its id at the end of `providerOrder`. The row is edited in place in one immediate transaction, so every other byte stays; the user's `name` and `enabled` for magpie's entry and the fields NewMax adds to it stay through a sync, and a sync with nothing to change doesn't write. A row that isn't a JSON object, or whose `providers` or `providerOrder` isn't a list, is left alone. With no row (NewMax at its defaults), magpie writes one with its entry alone, as NewMax lays its defaults and presets under the row; with no database yet, it asks to open NewMax once. Disconnect takes the entry and the id out, sets a pick of it back to `default`, and takes the row out when only what magpie made is left. NewMax holds its settings in memory and writes the whole row back whenever one changes, so a change is refused while `NewMax` (`newmax` on Linux) runs (Windows can't be asked, so the notice says to quit it first). The model is picked in NewMax's model picker, so the field is whether magpie is in it (`ListsModels`). Detected by its data folder or `NewMax.app` (`cc.newmax.desktop`).
- DevEco Code (Huawei's OpenCode fork, #1885) is wired as OpenCode is (`deveco` in [`agents.go`](../../internal/agent/agents.go)): magpie's provider goes into the first of `deveco.jsonc`, `deveco.json` and `config.json` in `~/.config/deveco` (the one DevEco merges last, so the one that wins), or in `$DEVECO_CONFIG_DIR` when that is absolute, read after them. 0.2.3 sends `deveco/0.2.3 ai-sdk/…` to a provider of its config, but much of the OpenCode code it keeps still sends OpenCode's own User-Agent (`opencode/<version>`), so its provider's key is `magpie-deveco` (`openCodeKeyAt`), not the plain `magpie` OpenCode and MiMo Code send, and Check asks for that key. Its npm package has no Linux binary, so no install command is offered there (`cliSpec.only`).
- Grok Build keeps magpie's models as one `[model."magpie/<provider>/<model>"]` table each in `config.toml` under `$GROK_HOME`, else `~/.grok` (`grok` in [`grok.go`](../../internal/agent/grok.go)), each on the gateway's `/v1` with magpie's key. Grok Build takes `api_backend` per model table, `"chat_completions"` (its default), `"responses"` or `"messages"` (Anthropic Messages), and sends each to `base_url` joined with `/chat/completions`, `/responses` or `/messages` (the "Supported API Backends" page bundled in its binary; grok 1.0.67). magpie writes each model's native API (`grokBackend`, from `catalog.Model.APIs` as Pi, droid and dsh pick theirs; uk.jent on Discord), so the gateway relays the request as it is: Responses for a model served best there, Messages for a Claude on an Anthropic endpoint, Chat for the rest, a group whose members differ, or one not known. Each table's `context_window` "drives auto-compact timing" (Grok Build's config reference), so it is where Long conversations has Codex compact (`grokWindow`, codexcat's rule): a threshold set on the model or its provider, else `settings.Working` of the model's window, the whole window under Full window; Long conversations is in Grok Build's sheet on the Agents page (`AGENT_PREFS`). A `context_window` the user set in one of magpie's tables by hand stays through a sync and a new pick (uk.jent on Discord: dozens of 1M models set to 300K one by one): what magpie last gave each model is stashed (`grok:<path>:windows`), and a value other than it is the user's (`grokOwnWindow`). With no record yet (a config an older magpie wrote, which gave every model its whole window), a value other than the model's whole window and other than magpie's now is taken for the user's. Disconnect drops the record with the tables. `TestGrokKeepsAWindowSetByHand`, `TestGrokKeepsAWindowSetBeforeTheRecord`, `TestGrokWindowFollowsLongConversations`.
- Droid keeps magpie's models as `customModels` entries in `~/.factory/settings.json` (`droidIn` in [`droid.go`](../../internal/agent/droid.go)), each with `provider` `openai` (Responses, `baseUrl` the gateway's `/v1`), `anthropic` (the gateway root) or `generic-chat-completion-api` (Chat, `/v1`). droid reads a custom model's `model` itself and, at every session start, warns about one whose name looks like OpenAI's (`/\bgpt[-_.]?\d/i`, `/codex/i`, `/\bo[1-9](?:[-_.]|$)/i`) on any provider but `openai`, or like a Claude (`/claude|haiku|sonnet|opus/i`) on neither `anthropic` nor `bedrock-converse` (droid 0.231.0's bundle, `xs` and `g2`; ji233 on Discord: `ultrafast/gpt-6.1-sol` on Chat). So `droidWants` puts such a model on the provider droid asks for, whatever its provider speaks, and the gateway translates; any other model goes on its `APIs`, as Pi, omp and dsh pick theirs. A `provider`, `displayName`, `maxContextLimit`, `maxOutputTokens` or `noImageSupport` the user changed in one of magpie's entries stays through a sync and a new pick (`droidMerge`): what magpie last gave each entry is stashed (`droid:<path>:wrote`), and a value other than it is the user's; keys magpie doesn't write stay too, droid's `index` aside. `baseUrl` follows the entry's provider and `apiKey` is the wiring, both put back at every sync. With no record (entries an older magpie wrote, which every sync wrote over anyway), magpie's values are taken. Disconnect drops the record with the entries. `TestDroidWantsItsOwnRule`, `TestDroidProviderByName`, `TestDroidKeepsAnEntryEditedByHand`.
- 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`). An edit's result is checked as the apps read JSONC (`edit.ValidJSONC`: jsonc-parser with `allowTrailingComma`, as OpenCode, VS Code and Zed parse; a trailing comma after a value is fine, one with nothing before it, `{,}` or `},,`, is not), and an edit that would turn a file the app reads into one it can't is refused, nothing written (`checkJSONC`). A delete takes the last member's own trailing comma with it, an insert into an object of comments only adds no comma, and a lone comma an older magpie left (`"mcp": {,}` after the hub was toggled for OpenCode, chenxiang0010 on Discord) is dropped by the next edit of that file (`dropLoneCommas`).
- 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`.
+172 -8
View File
@@ -19,10 +19,22 @@ package agent
// sets sessionDefaultSettings.model; the user's entries stay as they were
// and in front, so their own ids don't move, and the default they had is
// stashed and put back when magpie steps out.
//
// droid judges a custom model by its "model" too: one whose name reads as
// OpenAI's on another provider, or as a Claude off "anthropic", gets a
// warning at every session start (droidWants). Such a model is written on
// the provider droid asks for, and the gateway translates.
//
// A field of one of magpie's entries the user changed in settings.json
// stays theirs (droidKept): what magpie last wrote is stashed, and a value
// other than it is the user's. baseUrl and apiKey are the wiring, put back
// at every sync.
import (
"encoding/json"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
@@ -65,15 +77,20 @@ func droidEntries() []droidEntry { return droidEntriesAt(gateway.URL()) }
func droidEntriesAt(gw string) []droidEntry {
var out []droidEntry
for _, m := range magpieModels("droid") {
e := droidEntry{Model: m.ID, ID: droidID + m.ID, BaseURL: gw + "/v1", APIKey: keyAt(gw),
e := droidEntry{Model: m.ID, ID: droidID + m.ID, APIKey: keyAt(gw),
Provider: "generic-chat-completion-api", MaxContextLimit: m.Context, MaxOutputTokens: maxTokens(m), NoImageSupport: !m.Images}
switch {
switch want := droidWants(m.ID); {
case want != "":
// droid warns at every session start about a model whose name
// it reads as OpenAI's or Claude's on any other provider
// (ji233 on Discord: ultrafast/gpt-6.1-sol on Chat)
e.Provider = want
case slices.Contains(m.APIs, string(provider.Responses)):
e.Provider = "openai"
case slices.Contains(m.APIs, string(provider.Anthropic)):
// Anthropic's SDK adds the /v1 itself
e.Provider, e.BaseURL = "anthropic", gw
e.Provider = "anthropic"
}
e.BaseURL = droidBase(gw, e.Provider)
// the catalog's own label ("pro · DeepSeek") is what the picker
// shows; droid finds the model by its id, whatever its name
if e.DisplayName = m.Name; e.DisplayName == "" {
@@ -84,6 +101,135 @@ func droidEntriesAt(gw string) []droidEntry {
return out
}
// droidBase is the baseUrl droid sends a provider's requests to: the
// OpenAI SDKs join their path to /v1, Anthropic's adds the /v1 itself.
func droidBase(gw, prov string) string {
if prov == "anthropic" {
return gw
}
return gw + "/v1"
}
// droid's own reading of a custom model's name (droid 0.231.0, xs and g2
// in its bundle): one that isn't on "openai" while its name matches
// droidGPT is warned about as OpenAI's, and then one on neither
// "anthropic" nor "bedrock-converse" whose name matches droidClaude as
// Claude's. Before the patterns, droid looks the name up among its own
// models (gpt-* are OpenAI's, the rest not); every OpenAI one of those
// matches droidGPT, bar gpt-image and gpt-transcribe, which no chat
// catalog lists.
var (
droidGPT = []*regexp.Regexp{
regexp.MustCompile(`(?i)\bgpt[-_.]?\d`),
regexp.MustCompile(`(?i)codex`),
regexp.MustCompile(`(?i)\bo[1-9](?:[-_.]|$)`),
}
droidClaude = regexp.MustCompile(`(?i)claude|haiku|sonnet|opus`)
)
// droidWants is the provider droid asks for a custom model by its "model",
// or "" when it asks for none.
func droidWants(model string) string {
for _, re := range droidGPT {
if re.MatchString(model) {
return "openai"
}
}
if droidClaude.MatchString(model) {
return "anthropic"
}
return ""
}
// droidKept are the fields of magpie's entries a value the user set stays
// in. baseUrl follows the provider; apiKey is the wiring.
var droidKept = []string{"provider", "displayName", "maxContextLimit", "maxOutputTokens", "noImageSupport"}
// droidWrote is what magpie gave the droidKept fields of an entry, as JSON,
// a field it left out missing.
func droidWrote(e droidEntry) map[string]json.RawMessage {
b, _ := json.Marshal(e)
r := gjson.ParseBytes(b)
out := map[string]json.RawMessage{}
for _, k := range droidKept {
if v := r.Get(k); v.Exists() {
out[k] = json.RawMessage(v.Raw)
}
}
return out
}
// droidMerge is magpie's entry e over the one the file has (had): a
// droidKept field whose value there isn't what magpie last wrote (last)
// keeps the file's, and keys magpie doesn't write stay, droid's "index"
// aside. With no record of the entry, magpie's values are taken: before
// the record, every sync wrote them over anyway.
func droidMerge(gw string, e droidEntry, had gjson.Result, last map[string]json.RawMessage) json.RawMessage {
b, _ := json.Marshal(e)
if last == nil {
return b
}
type kv struct {
k string
v json.RawMessage
}
var out []kv
ours := map[string]bool{}
gjson.ParseBytes(b).ForEach(func(k, v gjson.Result) bool {
ours[k.String()] = true
out = append(out, kv{k.String(), json.RawMessage(v.Raw)})
return true
})
same := func(a json.RawMessage, b gjson.Result) bool {
if a == nil || !b.Exists() {
return a == nil && !b.Exists()
}
return reflect.DeepEqual(gjson.ParseBytes(a).Value(), b.Value())
}
user := map[string]gjson.Result{}
for _, k := range droidKept {
if v := had.Get(k); !same(last[k], v) {
user[k] = v
}
}
prov := e.Provider
if v, ok := user["provider"]; ok && v.Exists() {
prov = v.String()
}
var kept []kv
for _, p := range out {
switch v, ok := user[p.k]; {
case p.k == "baseUrl":
p.v, _ = json.Marshal(droidBase(gw, prov))
case ok && !v.Exists():
// the user took it out
continue
case ok:
p.v = json.RawMessage(v.Raw)
}
kept = append(kept, p)
}
had.ForEach(func(k, v gjson.Result) bool {
if n := k.String(); !ours[n] && n != "index" {
kept = append(kept, kv{n, json.RawMessage(v.Raw)})
}
return true
})
var sb strings.Builder
sb.WriteByte('{')
for i, p := range kept {
if i > 0 {
sb.WriteByte(',')
}
k, _ := json.Marshal(p.k)
sb.Write(k)
sb.WriteByte(':')
sb.Write(p.v)
}
sb.WriteByte('}')
return json.RawMessage(sb.String())
}
// droidSlug is droid's own spelling of a display name in a model id.
func droidSlug(s string) string {
return strings.Join(strings.FieldsFunc(strings.TrimSpace(s), unicode.IsSpace), "-")
@@ -141,6 +287,9 @@ func droidIn(at place) *Agent {
path := filepath.Join(dir, "settings.json")
legacy := filepath.Join(dir, "config.json")
key := "droid:" + path + ":" + droidModel
// keyWrote is what magpie last gave the droidKept fields of each of
// its entries, so a value other than it is the user's
keyWrote := "droid:" + path + ":wrote"
// raw is the model droid starts on as written: sessionDefaultSettings'
// or, while that is unset, the top-level one it moves there
raw := func() string {
@@ -162,20 +311,35 @@ func droidIn(at place) *Agent {
// magpie's after them; none left takes the key out
setModels := func(with bool) error {
var ms []any
var had bool
had := map[string]gjson.Result{}
for _, c := range droidCustoms(path, droidModels) {
if strings.HasPrefix(c.id, droidID) {
had = true
had[c.id] = gjson.ParseBytes(c.raw)
continue
}
ms = append(ms, c.raw)
}
if with {
saved := stashLoad()[keyWrote]
var last map[string]map[string]json.RawMessage
json.Unmarshal([]byte(saved), &last)
wrote := map[string]map[string]json.RawMessage{}
gw := at.gw()
for _, e := range droidEntries() {
ms = append(ms, e)
wrote[e.ID] = droidWrote(e)
if h, ok := had[e.ID]; ok {
ms = append(ms, droidMerge(gw, e, h, last[e.ID]))
} else {
ms = append(ms, e)
}
}
} else if !had {
if b, _ := json.Marshal(wrote); string(b) != saved {
stash(map[string]string{keyWrote: string(b)})
}
} else if len(had) == 0 {
return nil
} else {
forget(keyWrote)
}
if len(ms) > 0 {
return edit.SetJSON(path, edit.KV{Path: droidModels, Value: ms})
+133
View File
@@ -282,3 +282,136 @@ func TestDroidOverrideAndLegacy(t *testing.T) {
t.Fatal(err)
}
}
// droidWants holds droid's own reading of a model's name (droid 0.231.0's
// xs and g2): /\bgpt[-_.]?\d/i, /codex/i, /\bo[1-9](?:[-_.]|$)/i for
// OpenAI, then /claude|haiku|sonnet|opus/i for Claude.
func TestDroidWantsItsOwnRule(t *testing.T) {
for m, want := range map[string]string{
"ultrafast/gpt-6.1-sol": "openai",
"x/GPT5": "openai",
"x/gpt_4o": "openai",
"codex/gpt-5.5": "openai",
"x/gpt-5.3-codex": "openai",
"x/my-codex-proxy-model": "openai",
"x/o3": "openai",
"x/o4-mini": "openai",
"x/o1.preview": "openai",
"x/gpt-oss-120b": "",
"x/proto1": "",
"x/o10x": "",
"x/claude-opus-4-7": "anthropic",
"or/anthropic/sonnet-next": "anthropic",
"x/HAIKU": "anthropic",
"deepseek/pro": "",
"x/kimi-k2.5": "",
} {
if got := droidWants(m); got != want {
t.Errorf("%s: %q, want %q", m, got, want)
}
}
}
// A GPT or a Claude served on Chat is written on the provider droid asks
// for, so droid doesn't warn about it at every session start (ji233 on
// Discord: "ultrafast/gpt-6.1-sol appears to be an OpenAI model"), and an
// entry an older magpie wrote on Chat is moved on the next sync.
func TestDroidProviderByName(t *testing.T) {
_, path := droidHome(t)
provider.Save(provider.Provider{ID: "ultrafast", Name: "Ultrafast", Key: "k", Chat: "http://127.0.0.1:1/v1",
Models: []string{"gpt-6.1-sol", "o3", "claude-opus-4-7", "kimi-k2.5"}})
a := droid(os.Getenv("HOME"))
if err := a.Apply("model", "magpie/ultrafast/gpt-6.1-sol"); err != nil {
t.Fatal(err)
}
want := map[string][2]string{
"custom:magpie/ultrafast/gpt-6.1-sol": {"openai", gatewayV1()},
"custom:magpie/ultrafast/o3": {"openai", gatewayV1()},
"custom:magpie/ultrafast/claude-opus-4-7": {"anthropic", gateway.URL()},
"custom:magpie/ultrafast/kimi-k2.5": {"generic-chat-completion-api", gatewayV1()},
"custom:magpie/deepseek/pro": {"generic-chat-completion-api", gatewayV1()},
"custom:magpie/anth/claude-sonnet-5": {"anthropic", gateway.URL()},
"custom:magpie/resp/grok-5": {"openai", gatewayV1()},
}
check := func(when string) {
t.Helper()
ms, _, _ := droidFile(t, path)
for id, w := range want {
if e := ms[id]; e == nil || e["provider"] != w[0] || e["baseUrl"] != w[1] {
t.Errorf("%s: %s: %v", when, id, e)
}
}
if d := a.Check(); d != "" {
t.Errorf("%s: check: %s", when, d)
}
}
check("apply")
// as an older magpie left it: every Chat model on
// generic-chat-completion-api, and no record of what it wrote
old := strings.ReplaceAll(readFile(path), `"provider": "openai"`, `"provider": "generic-chat-completion-api"`)
old = strings.Replace(old, `"model": "ultrafast/claude-opus-4-7",`, `"model": "ultrafast/claude-opus-4-7", "x": 1,`, 1)
os.WriteFile(path, []byte(old), 0o644)
forget("droid:" + path + ":wrote")
if err := a.Sync(); err != nil {
t.Fatal(err)
}
check("sync over an older magpie's")
}
// A field of one of magpie's entries the user changed stays as they set
// it through a sync and a new pick; the rest follows the catalog, and the
// baseUrl follows the provider they picked.
func TestDroidKeepsAnEntryEditedByHand(t *testing.T) {
_, path := droidHome(t)
provider.Save(provider.Provider{ID: "ultrafast", Name: "Ultrafast", Key: "k", Chat: "http://127.0.0.1:1/v1",
Models: []string{"gpt-6.1-sol", "kimi-k2.5"}})
a := droid(os.Getenv("HOME"))
if err := a.Apply("model", "magpie/ultrafast/kimi-k2.5"); err != nil {
t.Fatal(err)
}
var f map[string]any
json.Unmarshal([]byte(readFile(path)), &f)
for _, m := range f["customModels"].([]any) {
e := m.(map[string]any)
switch e["id"] {
case "custom:magpie/ultrafast/gpt-6.1-sol":
// back on Chat, by their own choice
e["provider"] = "generic-chat-completion-api"
e["maxContextLimit"] = 300000
e["extraArgs"] = map[string]any{"reasoning_effort": "high"}
e["index"] = 7
case "custom:magpie/ultrafast/kimi-k2.5":
e["provider"] = "anthropic"
e["displayName"] = "Kimi (mine)"
delete(e, "noImageSupport")
}
}
b, _ := json.MarshalIndent(f, "", " ")
os.WriteFile(path, b, 0o644)
for _, step := range []func() error{a.Sync, func() error { return a.Apply("model", "magpie/deepseek/pro") }} {
if err := step(); err != nil {
t.Fatal(err)
}
ms, _, _ := droidFile(t, path)
g := ms["custom:magpie/ultrafast/gpt-6.1-sol"]
if g["provider"] != "generic-chat-completion-api" || g["baseUrl"] != gatewayV1() || g["maxContextLimit"] != float64(300000) ||
g["extraArgs"] == nil || g["index"] != nil || g["apiKey"] != gateway.Token || g["displayName"] == nil {
t.Errorf("gpt: %v", g)
}
k := ms["custom:magpie/ultrafast/kimi-k2.5"]
if _, ok := k["noImageSupport"]; ok || k["provider"] != "anthropic" || k["baseUrl"] != gateway.URL() || k["displayName"] != "Kimi (mine)" {
t.Errorf("kimi: %v", k)
}
if p := ms["custom:magpie/deepseek/pro"]; p["provider"] != "generic-chat-completion-api" || p["displayName"] != "pro · DeepSeek" {
t.Errorf("an entry not edited: %v", p)
}
}
// disconnecting drops them with the record
if err := a.Apply("model", ""); err != nil {
t.Fatal(err)
}
if _, ok := stashLoad()["droid:"+path+":wrote"]; ok {
t.Error("record kept after disconnect")
}
}