Files
magpie/internal/agent/lists_models_test.go
T
yetone 9c39edb92c agent: Avibe, magpie as a model source through its Model Hub (alex_metacraft on X)
Avibe (avibe-bot/avibe, avibe-os on PyPI, the `vibe` CLI) runs its own
agent, Vibey, and Claude Code, Codex and OpenCode, all on models from its
Model Hub. Its sources live in model_hub.sources of config/config.json in
$AVIBE_HOME (else ~/.avibe, else a legacy ~/.vibe_remote), but a source
can't be written there by hand: its key is sealed in the hub's credential
store and Avibe puts it into its agents' route chains as it is made.

So the Avibe row adds "magpie" the way Avibe's Models page does, through
its internal API (POST /internal/model-hub on state/dispatch.sock, or on
Windows the loopback port + bearer of runtime/control-ipc/endpoint.json):
create_source with kind api_key, vendor custom, base_url the gateway's
/v1, key agentKey("avibe"), protocol openai_chat and save_unverified.
Avibe then lists the models from /v1/models and adds the source to
Vibey's, Claude's, Codex's and OpenCode's chains itself.

- openai_chat, not openai_responses: for a Responses source Avibe's
  CLIProxyAPI runs Codex's executor, which sends codex-tui headers the
  gateway would take for Codex.
- Off is delete_source with force, sent again with the would_remove_hops
  and would_interrupt Avibe answers, as its page confirms them. Sync is
  refresh_source the same way; on a moved gateway the source is made
  again (the key goes with the address; patch_source can't change it).
- The source id is stashed; a custom source at the gateway's /v1 counts
  as magpie's too and is stashed once seen.
- Every change needs Avibe running; otherwise the switch says to run
  `vibe start` (errAvibeDown). Nothing is written to config.json.
- A sync moves the source only from the gateway's own address on an
  older port (avibeMoved). One the user pointed at a NAS's or the LAN's
  magpie, a local proxy's route, or a WSL distro's way to Windows stays,
  as kept.away keeps every file-written agent's; a Rewire after a port
  move sets it again through the field's Set.
- Every test of the package but Avibe's own finds an Avibe running for
  each home (runningAvibe, served in-process), so the tests that connect
  every agent (gateway moved, LAN and proxy addresses kept, drift,
  ListOnly) take Avibe in too.
- The logo is a tile solid to its edges, so it joins app.css's tile rule
  (icon-tile.test.cjs went red without it).
- AVIBE_HOME joins agentenv and the ~-expanding path vars (Avibe expands
  it). Icon from Avibe's assets/logo.png (MIT), 64px.

Run:
- Real Avibe 3.2.5 (uv tool install avibe-os) in a sandbox HOME in WSL
  magpie-desktop, with a fake OpenAI server as the gateway: magpie's own
  code (a throwaway test, AVIBE_HOME + MAGPIE_ADDR) connected it, Avibe
  discovered both fake models with "Authorization: Bearer magpie-avibe"
  and put the source in vibey/claude/codex/opencode chains; Sync
  refreshed; a gateway move to :3592 made the source again there and
  stashed the new id; a second run found the source by address alone
  and still followed the move; off removed it (list_sources []).
  Earlier, by hand: Anthropic /v1/messages and /v1/responses through the
  hub reached the fake as chat completions.
- wsl-run, at this head rebased on origin/main 021a6e1fd (then 401187300, where the Avibe and all-agents tests, i18n-keys, icon-tile and the gui -run set were run again: ok on Linux and Windows): go test
  -tags nogui ./internal/agent ./internal/appdir ./internal/agentenv:
  appdir, agentenv ok; agent ok but TestGrokInstalled, red on WSL2 at
  main (#3548).
- win-run: the Avibe tests and the all-agents tests (drift, port move,
  LAN, proxy, ListOnly, pickers): ok. The whole internal/agent package
  on Windows (one commit earlier) has main's known Windows reds (#4115,
  #5068, #4846, #5130, #5344, ...); its two Avibe reds (drift, ListOnly)
  are what runningAvibe fixed.
- vet (on the Windows box): windows, GOOS=darwin, GOOS=linux nogui on
  agent/appdir/agentenv: ok.
  gofmt clean.
- GUI (chromium + webkit, win-run): i18n-keys, i18n-en-no-cjk,
  icon-one-tone, routing-client-icons, icon-tile: 63 of 63 ok; go test
  ./internal/gui -run 'Icon|Budget|CSS|I18n|Picker': ok.
- mote refused SSH all session, so everything ran on wsl-run/win-run.

Broken by hand:
- a sync moving any address that isn't the gateway's: the LAN- and
  proxy-kept tests red on Avibe's config.json.
- app.css without avibe in the tile rule: icon-tile.test.cjs red.
- protocol openai_responses: TestAvibeAddsMagpieAsAModelSource red.
- confirmed() not resending the echoed hops: the add, knows-its-source
  and follows-the-gateway tests red (source_in_route_chain).

Not tried: magpie on Windows wiring an Avibe that runs inside WSL; a
real Vibey turn against the real gateway (the fake stood in for it);
macOS with a real Avibe.
2026-11-10 19:36:59 +08:00

169 lines
6.6 KiB
Go

package agent
import (
"encoding/json"
"os"
"path/filepath"
"slices"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// listsSandbox is a HOME of its own with one provider of two models.
func listsSandbox(t *testing.T) (home, cfg string) {
t.Helper()
home = t.TempDir()
cfg = filepath.Join(home, ".config")
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", cfg)
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil {
t.Fatal(err)
}
return home, cfg
}
// An agent whose switch puts magpie's models in a picker of its own, with
// no field of its picking among them, lists only the ones picked for it on
// the Agents page, as every other agent does: ZCode was given every model,
// with no way to hide one (#1508, NovaTrailX). ListsModels is what gives
// its row that list.
func TestEveryPickerOfMagpiesModelsCanBeNarrowed(t *testing.T) {
home, cfg := listsSandbox(t)
var bare, menus []string
for _, a := range builtins(home, cfg) {
vals := a.Values()
refs, magpie := false, false
for _, f := range a.Fields {
if f.Options == nil {
continue
}
for _, o := range f.Options(vals) {
refs = refs || o.Ref != ""
magpie = magpie || o.Value == magpieID
}
}
switch {
// Claude Desktop's tier pickers list the catalog once it is
// connected (desktopTierFields), and the sandbox has no Desktop
case refs, a.ID == "claude-desktop":
// Kiro Crew's models are its harness's: the agent it runs (Codex,
// Claude Code…), whose own row narrows them
case a.ID == "kirocrew":
case a.ListsModels:
menus = append(menus, a.ID)
case magpie:
bare = append(bare, a.ID)
}
}
if len(bare) > 0 {
t.Errorf("magpie's models are put in these agents' pickers with no way to pick which: %v", bare)
}
for _, id := range []string{"zcode", "pencil", "openpencil", "openbot", "newmax", "liveagent", "t3code", "openmausbot", "avibe", "workbuddy", "workbuddy-ai", copilotJBID, CursorLocalID} {
if !slices.Contains(menus, id) {
t.Errorf("%s's row has no model list to pick in (ListsModels): %v", id, menus)
}
}
}
// The models taken out of ZCode's list on the Agents page are out of both
// files it reads, config.json and provider_config.json, and come back when
// they are put back; what the user set by hand stays: their own providers,
// rules and keys, and their manual rule for a model of magpie's (#1508).
func TestZCodeListsOnlyThePicked(t *testing.T) {
home, _ := listsSandbox(t)
dir := filepath.Join(home, ".zcode", "v2")
path, rules := filepath.Join(dir, "config.json"), filepath.Join(dir, "provider_config.json")
os.MkdirAll(dir, 0o755)
os.WriteFile(path, []byte(`{"provider":{"builtin:bigmodel":{"name":"Bigmodel","kind":"anthropic","enabled":true},"mine":{"name":"Mine","kind":"openai","models":{"m1":{"name":"M1"}}}},"theme":"dark"}`), 0o644)
os.WriteFile(rules, []byte(`{"schemaVersion":1,"config":{"providerConfigRules":{"providerRules":[{"providerId":"mine","enabled":true,"config":{"personalModelIds":["m1"]}}]},"modelConfigRules":{"providerModelRules":[{"providerId":"mine","modelId":"m1","config":{"properties":{"contextWindow":1000}}}],"manualProviderModelRules":[{"providerId":"magpie","modelId":"deepseek/pro","config":{"enabled":true,"properties":{"contextWindow":4242}}}]}},"ui":{"lang":"zh"}}`), 0o600)
a := zcode(home)
if err := a.Field("provider").Set("magpie"); err != nil {
t.Fatal(err)
}
type configDoc struct {
Theme string `json:"theme"`
Provider map[string]map[string]any `json:"provider"`
}
readConfig := func() configDoc {
var c configDoc
b, _ := os.ReadFile(path)
if err := json.Unmarshal(b, &c); err != nil {
t.Fatalf("%v\n%s", err, b)
}
if c.Theme != "dark" || c.Provider["builtin:bigmodel"] == nil || c.Provider["mine"]["models"].(map[string]any)["m1"] == nil {
t.Fatalf("the user's own config went: %s", b)
}
return c
}
type rulesDoc struct {
UI map[string]any `json:"ui"`
Config struct {
ProviderConfigRules struct {
ProviderRules []map[string]any `json:"providerRules"`
} `json:"providerConfigRules"`
ModelConfigRules struct {
ProviderModelRules []map[string]any `json:"providerModelRules"`
ManualProviderModelRules []map[string]any `json:"manualProviderModelRules"`
} `json:"modelConfigRules"`
} `json:"config"`
}
readRules := func() rulesDoc {
var d rulesDoc
b, _ := os.ReadFile(rules)
if err := json.Unmarshal(b, &d); err != nil {
t.Fatalf("%v\n%s", err, b)
}
pr, mr := d.Config.ProviderConfigRules.ProviderRules, d.Config.ModelConfigRules
if d.UI["lang"] != "zh" || len(pr) != 2 || pr[0]["providerId"] != "mine" ||
!slices.ContainsFunc(mr.ProviderModelRules, func(r map[string]any) bool { return r["providerId"] == "mine" && r["modelId"] == "m1" }) ||
len(mr.ManualProviderModelRules) != 1 || mr.ManualProviderModelRules[0]["modelId"] != "deepseek/pro" {
t.Fatalf("the user's own rules went: %s", b)
}
return d
}
listed := func() (config, personal, ruled []string) {
for id := range readConfig().Provider["magpie"]["models"].(map[string]any) {
config = append(config, id)
}
d := readRules()
for _, id := range d.Config.ProviderConfigRules.ProviderRules[1]["config"].(map[string]any)["personalModelIds"].([]any) {
personal = append(personal, id.(string))
}
for _, r := range d.Config.ModelConfigRules.ProviderModelRules {
if r["providerId"] == magpieID {
ruled = append(ruled, r["modelId"].(string))
}
}
slices.Sort(config)
slices.Sort(personal)
return config, personal, ruled
}
both := []string{"deepseek/flash", "deepseek/pro"}
if c, p, _ := listed(); !slices.Equal(c, both) || !slices.Equal(p, both) {
t.Fatalf("connected: config.json %v, provider_config.json %v", c, p)
}
// taken out on the Agents page: gone from both, at the next sync
if err := provider.SetHiddenModels("zcode", []string{"deepseek/flash"}); err != nil {
t.Fatal(err)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if c, p, r := listed(); !slices.Equal(c, []string{"deepseek/pro"}) || !slices.Equal(p, []string{"deepseek/pro"}) || len(r) != 0 {
t.Fatalf("hidden: config.json %v, provider_config.json %v, rules %v", c, p, r)
}
// and back
if err := provider.SetHiddenModels("zcode", nil); err != nil {
t.Fatal(err)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if c, p, r := listed(); !slices.Equal(c, both) || !slices.Equal(p, both) || !slices.Equal(r, []string{"deepseek/flash"}) {
t.Fatalf("shown again: config.json %v, provider_config.json %v, rules %v", c, p, r)
}
}