agents: Pi's row picks the protocol magpie's models are asked on (xiaomanweiman on X)

magpie writes Pi's ~/.pi/agent/models.json with api "openai-completions".
xiaomanweiman found that T3 Code's pi plugin then puts all 71 tools in the
context, while on "openai-responses" only 3 core tools load and the rest
come lazily. v0.1.4039 kept an api set by hand; this adds a choice so no
one has to edit the file.

Pi's opened row in Agents has a Protocol row, picked in the app's menu
(no native select): Each model's own (today's default, unchanged),
OpenAI Chat Completions, OpenAI Responses, Anthropic Messages. These are
the KnownApi names in pi-ai 1.4.0 (/opt/homebrew/bin/pi) that magpie's
gateway serves (dshAPIs). The choice is stashed as pi.protocol and written
into the magpie provider block (piProviderOn/piModelOn). Anthropic
Messages also gives each model the gateway root as its baseUrl, since
Anthropic's SDK adds /v1 itself. Effort levels and prompt caching follow
the api actually written. An api typed in models.json by hand still wins
(piAPIsKept) and shows as the picked value. The CLI has
`magpie pi protocol <api|default>`. It is Pi only: not its forks (OmO,
Prime Agent, ...) or Aside. It is hidden while the pi-magpie extension
serves the models, and it reads nothing at a stopped WSL distro (#3896).

Tests:
- internal/agent/pi_protocol_test.go: TestPiProtocolPicked.
- internal/gui/tests/pi-protocol.test.cjs: Chromium and WebKit, en, zh,
  zh-TW, ja, de. It checks the row, the menu (4 items, no select, the
  current one ticked) and what /api/set gets.
- Strings in i18n.js in every language.

Broken by hand: with the protocol not written, TestPiProtocolPicked goes
red. With the menu label left untranslated, pi-protocol.test.cjs goes
16 of 20 red.

Real use: a nogui build ran in a sandbox HOME on 127.0.0.1:3562, against
a fake OpenAI Chat upstream, with the real pi 1.4.0 `-p "say pong"` and a
logging tap:
- completions: POST /v1/chat/completions
- responses: POST /v1/responses
- anthropic-messages: POST /v1/messages?beta=true
- default: /v1/chat/completions
Each answered PONG-FROM-FAKE. An api typed by hand (openai-responses)
survived `magpie sync`, and `magpie pi protocol` showed it.

Run at this head (rebased on origin/main 459d668b3):
- mote: gofmt -l clean; go vet of internal/agent, internal/gui and
  internal/cli ok; go test -count=1 of those three packages ok (an
  earlier run there found TestWSLColdPlaceOpensNothing and
  TestCoreScriptBudget red, both fixed here; the budget is met by
  trimming this change's code, not by raising it).
- mote at the pre-rebase tree: GOOS=linux go vet -tags nogui ./..., a
  windows vet, and go build, all ok.
- mica: pi-protocol.test.cjs 20/20, and the 65 agent-*, pi-*, i18n-* and
  connect-* GUI files. Their only reds are 55 in agent-details-ready,
  agent-switch-accounts and agent-menu-label. The same 55 fail on
  origin/main 459d668b3 alone, and are filed as #6373, #6369, #5925,
  #6029 and #6371.

Not run: the full `go test ./...` and the whole GUI suite. Both machines'
suite locks were queued behind other sessions' suites for hours. Not
tried: Pi forks, or a real vendor upstream behind each protocol (the
upstream was a fake).
This commit is contained in:
yetone
2026-11-13 21:41:05 +08:00
parent f798b4eb7a
commit 9a82192375
7 changed files with 480 additions and 22 deletions
+1
View File
@@ -63,6 +63,7 @@ something else shows up as drift.
- 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, Mistral Vibe, Kimi, MiniMax, Mothx, omp, OpenChamber, OpenClaw, OpenMausBot, Avibe, Kun, 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.
- Pi's models.json (Pi, its forks and Aside) keeps an `api` the user set by hand on magpie's provider or on one of its models (`piAPIsKept` in [`pi_api_kept.go`](../../internal/agent/pi_api_kept.go)): T3 Code's Pi puts all 71 tools in the context on `openai-completions` and 3 on `openai-responses`, and a sync wrote the user's `openai-responses` back (xiaomanweiman on X). The stash records the APIs magpie wanted per file (`api:<path>:wanted`), and one in the file that is none of them is the user's; a model's keeps its `baseUrl` and `compat`, and a model left on a provider the user put on Responses gets `compat.supportsStrictMode` (#3055). With no record the provider's is taken as `openai-completions`, the only value magpie wrote there; an `api` the file lacks is magpie's. magpie's own default stays Chat for models whose provider speaks Chat, relayed as sent. `TestPiKeepsAnAPISetByHand`.
- Pi's opened row on the Agents page has a Protocol row (`piProtocolField` in [`pi_protocol.go`](../../internal/agent/pi_protocol.go), `protocolButton` in app.js; `magpie pi protocol <api>` in the CLI), in place of typing that `api` by hand (xiaomanweiman on X). It lists each model's own (unpicked, as before) and pi-ai's APIs the gateway serves (`dshAPIs`): `openai-completions`, `openai-responses` and `anthropic-messages`. A pick, kept in the stash per place (`pi.protocol`), puts the provider and every one of magpie's models on it (`piProviderOn`, `piModelOn`): on Responses each gets `compat.supportsStrictMode`, on Messages its own `api` and `baseUrl` at the gateway's root (Anthropic's SDK adds `/v1`) while the provider's stays `/v1`. An `api` the user typed on the provider still wins and shows as picked; a pick made after it records that value as magpie's (`piAPIWanted`), so the pick replaces it. Pi alone: its forks and Aside keep each model's own. With the pi-magpie extension serving the provider the row has no options and is hidden. `TestPiProtocolPicked`, `pi-protocol.test.cjs`.
- `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.
- Air comes in two forms that read different files, both wired by `airAt` in [`air.go`](../../internal/agent/air.go). The Air app (`air`) reads `acp.json` in its own config folder. The Air plugin in JetBrains IDEs (`air-ide`; bundled from 2026.3, from Marketplace in 2026.2) reads `~/.jetbrains/acp.json` on every system, the file AI Assistant's custom agents are in too (`AcpConfigurationLoader` in the plugin's `intellij.air.backend.acp.runtime`, checked in air-plugin 262.8665.521). Each gets its own Magpie entry and `magpie-opencode.json` beside its `acp.json`. `air-ide` shows for an IDE config folder of 2026.2 or later, or with its entry already there (`TestAirIDEDetectedByIDEVersion`). Neither has a base URL for its own agents (JetBrains AI, the agent's login, or an Anthropic, OpenAI, Gemini or OpenRouter key); The plugin's Codex on its own login runs this computer's `codex` (the terminal's `PATH`, else the `@openai/codex` it installs) as `codex app-server` with the user's `CODEX_HOME` or `~/.codex`, and sets no `model_provider` (`CodexAppServerProcessKt`); its menu is Codex's `model/list` and its default `config/read`'s model. Its Claude Agent runs `claude` with only Air's hooks in `--settings`. So both go through magpie while Codex and Claude Code are connected here. The Air app's Codex runs with a `CODEX_HOME` of its own and JetBrains' gateway (`codexRuntimeEnvironment`, `[model_providers.air-gateway]`), and never does. The model on either Air row is the Magpie agent's alone, and the opened row says which of Air's own agents go through magpie (`airSaid` in `app.js`, `agent-air-own.test.cjs`; jumy_18634 on Discord).
+38 -20
View File
@@ -701,22 +701,7 @@ func magpieProviderJSONAt(shape, catalog, gw string) any {
}
return map[string]any{"type": "openai", "name": "magpie", "base_url": gw + "/v1", "api_key": keyAt(gw), "models": ms}
case "pi":
var ms []map[string]any
for _, m := range models {
ms = append(ms, piModelJSON(piAsked(catalog, m), gw, true))
}
if ms == nil {
ms = []map[string]any{}
}
// Pi names its session to a provider only when asked to:
// sendSessionAffinityHeaders has it send it on Chat
// (x-session-affinity, session_id) and Anthropic's Messages API
// (x-session-affinity). On Responses it sends session_id anyway.
// Without it a turn of Pi's on Chat or Messages reached the gateway
// with no session: its usage had none and "Record gateway
// conversations" kept none of it (akic404 on Discord).
return map[string]any{"name": "magpie", "baseUrl": gw + "/v1", "api": "openai-completions", "apiKey": keyAt(gw),
"compat": map[string]any{"sendSessionAffinityHeaders": true}, "models": ms}
return piProviderOn(catalog, models, gw, "")
}
return nil
}
@@ -882,6 +867,15 @@ func piAsked(agentID string, m catalog.Model) catalog.Model {
// baseUrl); without it the model is left on the provider's
// openai-completions (Pencil, pencil.go).
func piModelJSON(m catalog.Model, gw string, native bool) map[string]any {
return piModelOn(m, gw, native, "")
}
// piModelOn is piModelJSON for a provider block whose api the user picked
// in Pi's row (piProtocolField): on is that api, every model asked on it,
// "" for each on its own as piModelJSON has it. A model on the provider's
// api names none of its own; on anthropic-messages each names the gateway's
// root, as Anthropic's SDK adds the /v1 the provider's baseUrl has.
func piModelOn(m catalog.Model, gw string, native bool, on string) map[string]any {
// reasoning lets Pi offer its thinking levels for the model: as
// /v1/models says it (provider.Entry.Thinks), so one that thinks with
// no levels magpie knows (Trae CN's kimi-k3-max, #2380) is offered
@@ -898,6 +892,14 @@ func piModelJSON(m catalog.Model, gw string, native bool) map[string]any {
// told so: Pi would otherwise ask it for a thinking budget,
// which it turns away.
switch {
case on == "openai-completions":
case on == "openai-responses":
e["compat"] = map[string]any{"supportsStrictMode": true}
case on == "anthropic-messages":
e["api"], e["baseUrl"] = on, gw
if gateway.AdaptiveThinking(m.ID) {
e["compat"] = map[string]any{"forceAdaptiveThinking": true}
}
case !native:
case slices.Contains(m.APIs, string(provider.Responses)):
// strict left out of a tool of a turn asked there is taken as a
@@ -917,7 +919,12 @@ func piModelJSON(m catalog.Model, gw string, native bool) map[string]any {
if m.Images {
e["input"] = []string{"text", "image"}
}
if levels := piThinkingLevels(m.Efforts, e["api"] == "anthropic-messages" && gateway.ThinksOnlyWhenAsked(m.ID)); levels != nil {
// the api it is asked on, its own or the provider's
api := e["api"]
if api == nil && on != "" {
api = on
}
if levels := piThinkingLevels(m.Efforts, api == "anthropic-messages" && gateway.ThinksOnlyWhenAsked(m.ID)); levels != nil {
// on google-generative-ai Pi resolves a level through the map to
// one of Gemini's four (pi-ai's resolveGoogleThinkingLevel) and
// throws before sending on any other name, so a level the model
@@ -946,9 +953,9 @@ func piModelJSON(m catalog.Model, gw string, native bool) map[string]any {
if m.Price != nil {
e["cost"] = map[string]any{"input": m.Price.Input, "output": m.Price.Output, "cacheRead": m.Price.CacheRead, "cacheWrite": m.Price.CacheWrite}
}
if c := piPromptCache(e["api"], m.ID); c != nil {
if c := piPromptCache(api, m.ID); c != nil {
e["promptCache"] = c
} else if native && e["api"] == nil {
} else if native && (api == nil || api == "openai-completions") {
// a routing group has no api of its own (a Messages-only group stays
// on Chat, provider.GroupAPI), and went out with no promptCache, which
// stops Pi's cacheWarming with "cache lifetime unavailable" (#5037)
@@ -1553,6 +1560,12 @@ func piLikeKeyed(at place, id, name, dir string, key func() string) *Agent {
startup := func() string { return piStartup(path, pairGet(get, "defaultProvider", "defaultModel")()) }
block := piBlockKept(modelsPath, func() any {
b := magpieProviderJSONAt("pi", id, at.gw()).(map[string]any)
if id == "pi" {
// the protocol picked in its row (pi_protocol.go)
if on := piProtocol(at); on != "" {
b = piProviderOn(id, magpieModels(id), at.gw(), on)
}
}
b["apiKey"] = key()
return b
})
@@ -1590,7 +1603,7 @@ func piLikeKeyed(at place, id, name, dir string, key func() string) *Agent {
if id == "pi" {
telemetry = piTelemetry(at, path)
}
return &Agent{
a := &Agent{
Telemetry: telemetry,
ID: id, Name: name, Icon: id, Bin: id, Dir: dir, Path: path, Spelled: prefixed,
Restore: before.restore,
@@ -1710,6 +1723,11 @@ func piLikeKeyed(at place, id, name, dir string, key func() string) *Agent {
},
},
}
// the protocol it asks magpie's models on (pi_protocol.go)
if id == "pi" {
a.Fields = append(a.Fields, piProtocolField(at, modelsPath, writeMagpie, viaExt))
}
return a
}
func goose(home, cfg string) *Agent { return gooseIn(here(home), cfg) }
+155
View File
@@ -0,0 +1,155 @@
package agent
import (
"encoding/json"
"fmt"
"slices"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/edit"
)
// The protocol Pi asks magpie's models on, picked in Pi's row
// (xiaomanweiman on X): T3 Code's Pi puts all 71 of its tools in the
// context on openai-completions and 3 on openai-responses, loading the
// rest when asked, and they had to set providers.magpie.api by hand
// (pi_api_kept.go keeps that). The gateway serves each of pi-ai's APIs
// below, every model on each, so any of them can be asked for all of
// magpie's models. Unpicked, it is as before: the provider on
// openai-completions, each model on the API its provider serves natively
// (piModelJSON). An api the user typed in models.json still wins, and the
// row shows it; a pick made after it is the newer word and replaces it.
// piProtocols are the APIs of pi-ai's (KnownApi, pi-ai 1.4.0) the gateway
// serves, as dshAPIs: Chat at /v1/chat/completions, Responses at
// /v1/responses, Messages at /v1/messages. google-generative-ai is left
// out, as piAsked leaves it out of Pi's folder.
var piProtocols = dshAPIs
// piProtocolNames are the protocols as the row's picker lists them.
var piProtocolNames = map[string]string{
"openai-completions": "OpenAI Chat Completions",
"openai-responses": "OpenAI Responses",
"anthropic-messages": "Anthropic Messages",
}
// piProtocolKey is where the stash keeps the protocol picked for Pi at a
// place, "" for each model's own.
func piProtocolKey(at place) string { return at.key("pi.protocol") }
// piProtocol is the protocol picked for Pi at a place.
func piProtocol(at place) string {
v := stashShared()[piProtocolKey(at)]
if !slices.Contains(piProtocols, v) {
return ""
}
return v
}
// piProviderOn is magpie's provider block for Pi's models.json, every
// model asked on the api on, or each on its own for "".
func piProviderOn(agentID string, models []catalog.Model, gw, on string) map[string]any {
ms := []map[string]any{}
for _, m := range models {
ms = append(ms, piModelOn(piAsked(agentID, m), gw, true, on))
}
api := "openai-completions"
if on != "" {
api = on
}
// Pi names its session to a provider only when asked to:
// sendSessionAffinityHeaders has it send it on Chat
// (x-session-affinity, session_id) and Anthropic's Messages API
// (x-session-affinity). On Responses it sends session_id anyway.
// Without it a turn of Pi's on Chat or Messages reached the gateway
// with no session: its usage had none and "Record gateway
// conversations" kept none of it (akic404 on Discord).
return map[string]any{"name": "magpie", "baseUrl": gw + "/v1", "api": api, "apiKey": keyAt(gw),
"compat": map[string]any{"sendSessionAffinityHeaders": true}, "models": ms}
}
// piProtocolField is Pi's protocol, the api magpie's provider has in the
// models.json at modelsPath; write rewrites the block when it is there,
// and off says magpie doesn't write the block (the pi-magpie extension
// serves the provider), so there is nothing to pick.
func piProtocolField(at place, modelsPath string, write func() error, off func() bool) Field {
return Field{
Key: "protocol", Label: "protocol", Quiet: true,
Get: func() string {
picked := piProtocol(at)
if at.cold {
// a stopped distro's files start it (#3896)
return picked
}
file, _ := edit.GetJSON(modelsPath, "providers."+magpieID+".api")
if file == "" {
return picked
}
want := picked
if want == "" {
want = "openai-completions"
}
// one the user typed there is what Pi asks on
if file != want && !slices.Contains(piAPIsWanted(modelsPath), file) {
return file
}
return picked
},
Set: func(v string) error {
if v != "" && !slices.Contains(piProtocols, v) {
return fmt.Errorf("protocol is one of %v or empty (each model's own), not %q", piProtocols, v)
}
// the api in the file now, the user's own included, gives way
// to the pick
if file, _ := edit.GetJSON(modelsPath, "providers."+magpieID+".api"); file != "" {
piAPIWanted(modelsPath, file)
}
stash(map[string]string{piProtocolKey(at): v})
if _, has := edit.GetJSON(modelsPath, "providers."+magpieID); !has || off() {
return nil
}
return write()
},
Options: func(map[string]string) []Option {
if at.cold || off() {
return nil
}
out := []Option{{Value: "", Label: "Each model's own", Note: "each model on the API its provider serves"}}
for _, p := range piProtocols {
out = append(out, Option{Value: p, Label: piProtocolNames[p], Note: p})
}
return out
},
}
}
// piAPIsWanted are the APIs magpie has handed its provider in the Pi
// models.json at path (piAPIsKept's record).
func piAPIsWanted(path string) []string {
rec := map[string][]string{}
if s := stashShared()[apisWantedKey(path)]; s != "" && json.Unmarshal([]byte(s), &rec) != nil {
return nil
}
if _, known := rec[piProviderAPI]; !known {
return []string{"openai-completions"}
}
return rec[piProviderAPI]
}
// piAPIWanted takes api, the provider's in the Pi models.json at path
// as a pick is made, for magpie's alone: the pick replaces it, the
// user's own included, and an older value magpie wrote that the user
// types there later is theirs again.
func piAPIWanted(path, api string) {
stashMu.Lock()
defer stashMu.Unlock()
m := stashLoad()
rec := map[string][]string{}
if s := m[apisWantedKey(path)]; s != "" && json.Unmarshal([]byte(s), &rec) != nil {
rec = map[string][]string{}
}
rec[piProviderAPI] = []string{api}
b, _ := json.Marshal(rec)
m[apisWantedKey(path)] = string(b)
stashWrite(m)
}
+151
View File
@@ -0,0 +1,151 @@
package agent
import (
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// xiaomanweiman on X: Pi's row picks the protocol magpie's models are
// asked on, in place of typing providers.magpie.api into models.json.
// Unpicked it is as before (Chat for the provider, each model on its
// native API); a pick puts every model on it; an api typed by hand still
// shows and wins until a pick is made after it.
func TestPiProtocolPicked(t *testing.T) {
home := syncHome(t)
if err := provider.Save(provider.Provider{ID: "oa", Name: "OA", Key: "k", Responses: "http://127.0.0.1:1/v1", Models: []string{"gpt-6.1-sol"}}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "an", Name: "An", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"claude-opus-5"}}); err != nil {
t.Fatal(err)
}
piModels := filepath.Join(home, ".pi", "agent", "models.json")
writeFile(t, filepath.Join(home, ".pi", "agent", "settings.json"), `{"defaultProvider":"magpie","defaultModel":"relay/glm-4.6"}`)
writeFile(t, piModels, `{"providers":{"magpie":{"name":"magpie","api":"openai-completions","models":[]}}}`)
setUpInMagpie("pi")
SyncCatalog()
pi, err := Find("pi")
if err != nil {
t.Fatal(err)
}
var f *Field
for i := range pi.Fields {
if pi.Fields[i].Key == "protocol" {
f = &pi.Fields[i]
}
}
if f == nil {
t.Fatal("Pi has no protocol field")
}
get := func(k string) string {
v, _ := edit.GetJSON(piModels, "providers.magpie."+k)
return strings.Trim(v, `"`)
}
model := func(id string) (api, base string) {
for i := 0; ; i++ {
got := get("models." + strconv.Itoa(i) + ".id")
if got == "" {
t.Fatalf("no model %s\n%s", id, readFile(piModels))
}
if got == id {
return get("models." + strconv.Itoa(i) + ".api"), get("models." + strconv.Itoa(i) + ".baseUrl")
}
}
}
gw := strings.TrimSuffix(get("baseUrl"), "/v1")
// unpicked: as before
if v := f.Get(); v != "" {
t.Fatalf("unpicked protocol = %q, want each model's own", v)
}
if got := get("api"); got != "openai-completions" {
t.Fatalf("provider api = %s, want openai-completions", got)
}
if a, _ := model("oa/gpt-6.1-sol"); a != "openai-responses" {
t.Fatalf("a Responses model unpicked is on %q\n%s", a, readFile(piModels))
}
opts := f.Options(nil)
var vals []string
for _, o := range opts {
vals = append(vals, o.Value)
}
if strings.Join(vals, ",") != ",openai-completions,openai-responses,anthropic-messages" {
t.Fatalf("options = %v", vals)
}
// Responses picked: the provider's, every model on it
if err := f.Set("openai-responses"); err != nil {
t.Fatal(err)
}
SyncCatalog()
if got := get("api"); got != "openai-responses" {
t.Fatalf("provider api = %s, want openai-responses\n%s", got, readFile(piModels))
}
for _, id := range []string{"relay/glm-4.6", "oa/gpt-6.1-sol", "an/claude-opus-5"} {
if a, b := model(id); a != "" || b != "" {
t.Fatalf("%s on Responses has api %q at %q of its own\n%s", id, a, b, readFile(piModels))
}
}
if v := f.Get(); v != "openai-responses" {
t.Fatalf("protocol = %q", v)
}
// Messages: each model at the gateway's root
if err := f.Set("anthropic-messages"); err != nil {
t.Fatal(err)
}
for _, id := range []string{"relay/glm-4.6", "oa/gpt-6.1-sol", "an/claude-opus-5"} {
if a, b := model(id); a != "anthropic-messages" || b != gw {
t.Fatalf("%s on Messages = %q at %q, want anthropic-messages at %s\n%s", id, a, b, gw, readFile(piModels))
}
}
if got := get("baseUrl"); got != gw+"/v1" {
t.Fatalf("provider baseUrl = %s, want %s/v1", got, gw)
}
// Chat: every model on Chat, the Responses one too
if err := f.Set("openai-completions"); err != nil {
t.Fatal(err)
}
SyncCatalog()
if a, b := model("oa/gpt-6.1-sol"); a != "" || b != "" {
t.Fatalf("a Responses model on Chat has %q at %q\n%s", a, b, readFile(piModels))
}
if v := f.Get(); v != "openai-completions" {
t.Fatalf("protocol = %q", v)
}
// back to each model's own
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if a, _ := model("oa/gpt-6.1-sol"); a != "openai-responses" || get("api") != "openai-completions" {
t.Fatalf("each model's own: %q, provider %s\n%s", a, get("api"), readFile(piModels))
}
// typed by hand: it shows, and stays
if err := edit.SetJSON(piModels, edit.KV{Path: "providers.magpie.api", Value: "openai-responses"}); err != nil {
t.Fatal(err)
}
SyncCatalog()
if v := f.Get(); v != "openai-responses" || get("api") != "openai-responses" {
t.Fatalf("an api typed by hand shows %q, file %s", v, get("api"))
}
// a pick after it is the newer word
if err := f.Set(""); err != nil {
t.Fatal(err)
}
SyncCatalog()
if v := f.Get(); v != "" || get("api") != "openai-completions" {
t.Fatalf("picked after a hand value: shows %q, file %s", v, get("api"))
}
if err := f.Set("google-generative-ai"); err == nil {
t.Fatal("a protocol the gateway doesn't serve to Pi was taken")
}
}
+16 -2
View File
@@ -516,7 +516,7 @@ function renderAgents() {
const wide = (f) => f.label === "model" || f.label === "large" || f.label === "executor" || f.label === "planner";
// a field with nothing to pick and nothing set isn't drawn (#1499)
const none = (f) => (f.key === "effort" || toggled(f) || f.label === "subagents" || f.label === "gateway" || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === AUTO_MODE || f.label === ADVISOR || f.label === MEMORIES || f.label === COMPACT_MODEL || f.label === "sign-in" || f.key === "small" || asideAccount(a, f)) && !f.options.length && !f.value;
const shownFields = a.fields.filter((f) => !grouped(a, f) && !none(f) && !codexOwnSub(a, f) && !codexRowed(a, f) && !hermesBot(f) && !ompAdvisorKey(f));
const shownFields = a.fields.filter((f) => !grouped(a, f) && !none(f) && !codexOwnSub(a, f) && !codexRowed(a, f) && !hermesBot(f) && !ompAdvisorKey(f) && !protocolField(f));
const tiers = tierMenu(a);
if (tiers) shownFields.push(tiers);
const sorted = shownFields.sort((x, y) => wide(y) - wide(x) || extra(x) - extra(y));
@@ -2275,6 +2275,17 @@ function connectPanel(a, { fields, fieldBtn }) {
// an agent whose list doesn't take magpie's names has none
if (!a.noNames) { const v = kv(t("Provider in model names")), put = () => v.append(line(agentSuffixPick(a))); window.agentSuffixPick ? put() : import("./agentsuffix.js").then(put, () => {}); }
}
// which API magpie's models are asked on, in the app's menu; an api
// typed in its file by hand shows as it is (xiaomanweiman on X)
const f = a.fields.find(protocolField);
if (f?.options.length) {
const b = el("button", "field ag-pick ag-protocol"), c = el("span", "chev");
b.append(el("span", "v" + (f.value ? "" : " empty"), t(optionFor(f, f.value)?.label || f.value)), c);
c.append(svg(CHEV, 11, 1.7));
b.dataset.key = f.key;
b.onclick = (ev) => openPicker(a, f, b, ev);
kv(t("Protocol"), line(b));
}
// what a new session starts on: optional, the agent's own last pick
// unset; Codex's is the very value its /model picks, so one choice
// the model it starts on is on the row; what goes with it here
@@ -3959,6 +3970,9 @@ const codexSub = (a) => kindOf(a) === "codex" && a.fields.some((f) => f.label ==
const codexOwnSub = (a, f) => f.label === "subagents" && codexSub(a);
// named rows in Codex's settings: no square too (the owner, 10-25)
const hermesBot = (f) => f.key.startsWith("profile:");
// Pi's protocol, the api magpie's models are asked on (pi_protocol.go): a
// row of its own in the opened row, not a control on the row
const protocolField = (f) => f.label === "protocol";
const codexRowed = (a, f) => a.id === "codex" && !gatewayMode && (f.label === SUB_MODEL || f.label === MEMORIES);
// Lead's pick ("") takes the model the lead names; Same as the lead holds
// every subagent to the lead's own (cleverpigo on X)
@@ -5380,7 +5394,7 @@ function renderList() {
if (hasIcons) li.append(optionIcon(o));
const words = el("span", "option-words");
// a choice of magpie's own (Codex's sign-in) reads in the page's language
const own = pick.field.label === "sign-in";
const own = pick.field.label === "sign-in" || protocolField(pick.field);
words.append(el("span", "v", own ? t(o.label || o.value) : o.label || o.value));
const tell = tellTag(o.tell);
if (tell) words.append(tell);
+4
View File
@@ -1474,6 +1474,7 @@ const I18N = {
"{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.": "{agent} 在 272K 或选定的大小时压缩;完整窗口更慢更贵。只作用于 magpie 的模型,订阅自带的模型不受影响。",
"Long conversations in {agent}": "{agent} 的长对话",
"Each model's own": "各模型自己的",
"each model on the API its provider serves": "各模型走其服务商原生的 API",
"Other size…": "其他大小…",
"Set a model apart": "单独设置一个模型",
"Full window": "完整窗口",
@@ -6721,6 +6722,7 @@ const I18N = {
"{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.": "{agent} 在 272K 或選定的大小時壓縮;完整視窗更慢更貴。只作用於 magpie 的模型,訂閱自帶的模型不受影響。",
"Long conversations in {agent}": "{agent} 的長對話",
"Each model's own": "各模型自己的",
"each model on the API its provider serves": "各模型走其服務商原生的 API",
"Other size…": "其他大小…",
"Set a model apart": "單獨設定一個模型",
"Full window": "完整視窗",
@@ -11928,6 +11930,7 @@ const I18N = {
"{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.": "{agent} は 272K か選んだサイズで圧縮します。ウィンドウ全体は遅く高価です。対象は magpie のモデルのみで、サブスクリプション自身のモデルは影響を受けません。",
"Long conversations in {agent}": "{agent} の長い会話",
"Each model's own": "各モデルのまま",
"each model on the API its provider serves": "各モデルをそのプロバイダーの API で",
"Other size…": "ほかのサイズ…",
"Set a model apart": "モデルを個別に設定",
"Full window": "ウィンドウ全体",
@@ -17170,6 +17173,7 @@ const I18N = {
"{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.": "{agent} komprimiert bei 272K oder der gewählten Größe; das volle Fenster ist langsamer und teurer. Nur für magpie-Modelle: Modelle eines Abos bleiben unverändert.",
"Long conversations in {agent}": "Lange Unterhaltungen in {agent}",
"Each model's own": "Je Modell sein eigenes",
"each model on the API its provider serves": "Jedes Modell über die API seines Anbieters",
"Other size…": "Andere Größe…",
"Set a model apart": "Ein Modell eigens einstellen",
"Full window": "Volles Fenster",
+115
View File
@@ -0,0 +1,115 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// xiaomanweiman on X: Pi's opened row has a Protocol row, the API magpie's
// models are asked on, picked in the app's menu (never a native select):
// each model's own (as before), OpenAI Chat Completions, OpenAI Responses
// or Anthropic Messages. The pick posts the protocol field; an api the user
// typed in models.json comes back as the value and shows as picked. The
// field is not a control on the row itself. In Chromium and WebKit, in
// every language. No backend: the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const protocols = [
{ value: "", label: "Each model's own", note: "each model on the API its provider serves" },
{ value: "openai-completions", label: "OpenAI Chat Completions", note: "openai-completions" },
{ value: "openai-responses", label: "OpenAI Responses", note: "openai-responses" },
{ value: "anthropic-messages", label: "Anthropic Messages", note: "anthropic-messages" },
];
const models = [{ value: "magpie/relay/m1", label: "m1", ref: "relay/m1", note: "Relay · via magpie" }];
const pi = (proto) => ({
id: "pi", name: "Pi", icon: "generic", path: "/fixture/pi", wired: true,
fields: [
{ key: "model", label: "model", value: "magpie/relay/m1", options: models },
{ key: "protocol", label: "protocol", value: proto, options: protocols },
],
});
function server(lang, proto, sets) {
let cur = { agents: [pi(proto)], profiles: [] };
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ ...cur, settings: { lang, theme: "light" } });
if (url.pathname === "/api/set") {
const body = req.postDataJSON();
sets.push(body);
cur = JSON.parse(JSON.stringify(cur));
cur.agents[0].fields.find((f) => f.key === body.field).value = body.value;
return json({ ...cur, settings: { lang, theme: "light" } });
}
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const row = '.row.agent[data-id="pi"]';
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const proto of ["", "openai-responses"]) {
test(`${engine} ${lang}: Pi's Protocol row ${proto ? "shows " + proto : "picks a protocol"}`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 1000, height: 800 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], sets = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, proto, sets));
await page.goto("http://magpie.test/?view=agents");
await page.locator(row).waitFor();
// the words as i18n.js has them in this language
const tr = (s) => page.evaluate(([l, s]) => (l === "en" ? s : I18N[l][s]), [lang, s]);
for (const s of ["Protocol", "Each model's own", "each model on the API its provider serves"]) {
assert.ok(await tr(s), `${s} has no ${lang}`);
}
// not a control on the row
assert.equal(await page.locator(`${row} > * .field[data-key="protocol"]:not(.ag-protocol)`).count(), 0);
await page.locator(`${row} .ag-link`).click();
await page.locator(`${row} .ag-exp`).waitFor();
const kv = page.locator(`${row} .ag-exp .ag-kv`, { has: page.locator(".ag-protocol") });
assert.equal(await kv.count(), 1, "no Protocol row");
assert.equal(await kv.locator(".ag-k").textContent(), await tr("Protocol"));
const b = kv.locator(".ag-protocol");
assert.equal(await b.locator(".v").textContent(), proto ? "OpenAI Responses" : await tr("Each model's own"));
const y = await page.evaluate(() => scrollY);
await b.click();
await page.locator("#pop:not([hidden]) #list li").first().waitFor();
assert.equal(await page.evaluate(() => scrollY), y, "a click scrolled the page");
const items = page.locator("#pop:not([hidden]) #list li");
assert.equal(await items.count(), 4, (await items.allTextContents()).join(" | "));
const texts = await items.allTextContents();
const own = await tr("Each model's own"), ownNote = await tr("each model on the API its provider serves");
assert.ok(texts.some((s) => s.includes(own) && s.includes(ownNote)), texts.join(" | "));
assert.equal(await page.locator("select").count(), 0, "a native select");
// the one shown as picked is the value, a hand-typed one too
assert.deepEqual((await page.evaluate(() => pick.options.map((o) => o.value))).sort(), ["", "anthropic-messages", "openai-completions", "openai-responses"]);
const on = page.locator("#pop:not([hidden]) #list li.cur");
assert.equal(await on.count(), 1, "one shown as picked");
assert.ok((await on.textContent()).includes(proto ? "OpenAI Responses" : await tr("Each model's own")), await on.textContent());
await items.filter({ hasText: "Anthropic Messages" }).click();
await page.waitForFunction(() => document.querySelector("#status")?.textContent);
assert.deepEqual(sets, [{ agent: "pi", field: "protocol", value: "anthropic-messages" }]);
await page.locator(`${row} .ag-protocol .v`, { hasText: "Anthropic Messages" }).waitFor();
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "the Agents view overflows");
assert.deepEqual(errors, []);
});
}
}
}