Files
magpie/internal/agent/lan_kept_test.go
T
yetone 93879515a0 agent: QwenPaw, each of its agents' active_model one of magpie's (pkh1585 on Discord)
pkh1585 asked for QwenPaw (AgentScope, github.com/agentscope-ai/QwenPaw)
on Discord. Read in its source, 2.2.2.post1, as data:

- Its folder is QWENPAW_WORKING_DIR, else ~/.copaw when that exists (the
  old name), else ~/.qwenpaw; WORKING_DIR/.env is loaded without
  overriding the environment. config.json's agents.profiles lists the
  agents, each with a workspace_dir whose agent.json holds active_model
  {provider_id, model}, read again on each message.
- Providers are no plain config: SECRET_DIR (QWENPAW_SECRET_DIR, else
  "<WORKING_DIR>.secret") holds providers/{builtin,custom}/<id>.json,
  read once at start. A plain api_key there is encrypted to "ENC:" at
  start, so that is the place QwenPaw itself keeps keys.

What magpie does now:

- `magpie qwenpaw <model>` and the GUI: a row per QwenPaw agent
  (qwenpaw#<id>, the default one as plain qwenpaw), skipping agents whose
  backend is ACP (another CLI runs those) and agents turned off.
- Connecting writes providers/custom/magpie.json (mode 600, the gateway's
  /v1 and the magpie-qwenpaw key, magpie's models as extra_models with
  their window, output and tool use) and sets that agent's active_model
  to {magpie, <provider>/<model>}. The old active_model is stashed as it
  was and put back verbatim on disconnect, absent and null included.
  The provider file is removed only when no QwenPaw agent still uses it.
- A sync after QwenPaw re-saved the provider (encrypted key, discovered
  models, its own defaults) keeps what QwenPaw wrote and changes only
  what magpie owns, so a second connect leaves the file as it is.
- The notice says QwenPaw reads providers at start-up: restart it once
  after connecting and after magpie's models change. New text in every
  locale.
- appdir: QWENPAW_WORKING_DIR and QWENPAW_SECRET_DIR take ~/ as QwenPaw's
  expanduser does; agentenv clears them in tests.
- README (en, zh), docs/reference.md, agent-wiring.md, the site's agent
  list and start pages (en, zh, ja), icon.

Run:
- internal/agent's QwenPaw tests (Connect, AgentsAreRows, SyncKeeps-
  WhatQwenPawChanged, Check, NotStartedYet, Folders, OwnModelAfter-
  Magpies, SyncAfterQwenPawSaved, NullModelRestored) on mote, and the
  all-agent tests (applied, rewire, lan_kept, proxy_kept, spelled) with
  a QwenPaw fixture.
- Broken by hand, each red: always rewriting the key
  (SyncKeepsWhatQwenPawChanged), removing the provider while another
  agent uses it (AgentsAreRows), no backend filter (AgentsAreRows lists
  qwenpaw#coder), dropping the keep of QwenPaw's own fields
  (SyncAfterQwenPawSaved), IsObject for Exists (NullModelRestored).
- Real QwenPaw 2.2.2.post1 (Python 3.12 via uv) in a sandbox HOME on
  the Linux box (WSL magpie-desktop), magpie on 3741, a fake OpenAI
  upstream on 3742: first start wrote config.json and agent.json;
  `magpie provider add fake …`, `magpie serve`, `magpie qwenpaw
  magpie/fake/echo-1`; after a restart QwenPaw encrypted the key (ENC:)
  and `qwenpaw agents chat` answered "PAWPAW-OK from the fake upstream",
  its log "built agent … model=magpie/fake/echo-1"; the upstream saw
  /v1/chat/completions model echo-1 streamed, magpie's usage.jsonl
  agent qwenpaw status 200. A second connect and `magpie models` left
  the provider file unchanged. `magpie qwenpaw default` took
  active_model back out (the only diff in agent.json) and removed the
  provider; QwenPaw started clean after.
- gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows -tags nogui.
- Full suite on mote (go test -tags nogui -count=1 -timeout 45m ./...)
  at 9554883db on d714c4216: 84 packages ok, internal/gui red on
  TestSettingsSaveKeepsWhatItDoesNotSend only (SearchAll from
  b09349d17, red on main, #4514). Rebased onto 15066f84f (an appdir
  change among the four new commits): appdir, agentenv, agent,
  filememo, gateway ok again, gui the same #4514 red; vet darwin,
  linux and windows of agent, appdir, agentenv ok. Rebased again onto
  dd7442f28 (edit, provider and agent changes): edit, provider, agent,
  appdir, agentenv ok, vet linux and windows of agent ok. Rebased onto
  6a23d9d75 (606743831's registry-following agent variables, which
  QWENPAW_WORKING_DIR and QWENPAW_SECRET_DIR now follow as agentenv
  vars): appdir, edit, agentenv, agent ok, vet linux and windows ok.
  Rebased onto 61b536d78 (provider's model lists): agent, appdir ok.
- GUI on mote, the files this reaches (i18n-keys, gui-de, gui-ja,
  gui-zh-tw, agent-connect, agent-layout, agent-notice-lang, brand,
  builtins, desktop-lang, header-relang, icon-tile, icon-url):
  Chromium 103/104, WebKit 59/60, the one red each gui-ja's ja for
  removing an agent's only account (a7b47d57e, #4580). The whole GUI
  suite wasn't run: mote had three other sessions' whole GUI suites
  running (load ~130) and WSL one more.

Not tried: Windows, the macOS desktop app, QwenPaw in WSL wired from
Windows magpie, the ACP backend, QwenPaw's web console after connecting,
a real legacy ~/.copaw.
2026-11-01 05:00:36 +08:00

175 lines
6.9 KiB
Go

package agent
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// An agent the user pointed at magpie on another machine (coeo91 on
// Discord: the LAN address, which went back to 127.0.0.1 after an update or
// a restart) keeps that address and the key it had there through the sync
// every start of magpie runs (SyncCatalog), for every agent magpie writes
// its models into; the sync still brings the models up to date.
func TestSyncKeepsAnAddressOnAnotherMachine(t *testing.T) {
t.Setenv("MAGPIE_ADDR", "")
home, _ := codexHome(t, "", "")
managed := claudeManaged
claudeManaged = func() string { return filepath.Join(home, "managed-settings.json") }
t.Cleanup(func() { claudeManaged = managed })
os.MkdirAll(filepath.Join(home, ".hanako", "agents", "hana"), 0o755)
os.WriteFile(filepath.Join(home, ".hanako", "agents", "hana", "config.yaml"), []byte("agent:\n name: Hana\n"), 0o644)
t.Setenv("ASTRBOT_ROOT", "")
writeFile(t, filepath.Join(home, ".astrbot", "data", "cmd_config.json"), astrbotConfig)
// QwenPaw, once it has written its agents' settings
qwenpawFixture(t, home)
setPort(t, 3591)
for _, a := range All() {
// Alma is told through its running app, and Cursor's local
// gateway is started by launchctl: neither is in the sandbox
if a.Check == nil || a.Launch != nil || a.WSL != "" || a.Native != nil || a.ID == "alma" || a.ID == "cursorlocal" {
continue
}
var key, want string
for _, g := range a.Fields {
for _, o := range g.Options(a.Values()) {
if want == "" && (o.Ref == "fake/m1" || o.Value == magpieID) {
key, want = g.Key, o.Value
}
}
}
if want == "" {
t.Fatalf("%s: no field takes magpie's models", a.ID)
}
if err := a.Apply(key, want); err != nil {
t.Fatalf("%s: %v", a.ID, err)
}
}
// the user points each file at the NAS's magpie, with its key
moved := filesWith(home, "127.0.0.1:3591")
if len(moved) < 20 {
t.Fatalf("only %d files have the gateway's address: %v", len(moved), moved)
}
keys := map[string]int{}
for _, p := range moved {
b, _ := os.ReadFile(p)
b = []byte(strings.ReplaceAll(string(b), "127.0.0.1:3591", "192.168.50.10:3591"))
kvs := keyValues(b)
for i := len(kvs) - 1; i >= 0; i-- {
if kv := kvs[i]; keeping().ours(kv.value) {
v := "nas-key"
if strings.HasPrefix(kv.value, "Bearer ") {
v = "Bearer nas-key"
}
b = append(b[:kv.start:kv.start], append([]byte(v), b[kv.end:]...)...)
}
}
keys[p] = strings.Count(string(b), "nas-key")
os.WriteFile(p, b, 0o644)
}
if err := provider.Save(provider.Provider{ID: "fake2", Name: "Fake2", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m2"}}); err != nil {
t.Fatal(err)
}
SyncCatalog()
synced := 0
for _, p := range moved {
b, _ := os.ReadFile(p)
s, name := string(b), strings.TrimPrefix(p, home)
if strings.Contains(s, "m2") {
synced++
}
if strings.Contains(s, "127.0.0.1:3591") {
t.Errorf("%s is back on this machine's gateway", name)
}
if !strings.Contains(s, "192.168.50.10:3591") {
t.Errorf("%s lost the NAS's address", name)
}
if n := strings.Count(s, "nas-key"); n < keys[p] {
t.Errorf("%s has the NAS's key %d times, not %d", name, n, keys[p])
}
for _, kv := range keyValues(b) {
if keeping().ours(kv.value) {
t.Errorf("%s has magpie's own key back: %q", name, kv.value)
}
}
}
if synced < len(moved)/2 {
t.Errorf("the sync wrote the new model into %d of %d files", synced, len(moved))
}
}
// What the sync writes is left as it is where the file says nothing sure of
// another machine: the gateway's address on this machine (another port, or
// localhost) follows the gateway, as does one a WSL distro reached Windows
// at; with two addresses gone, which went where can't be told.
func TestKeptAwayOnlyWhatIsSure(t *testing.T) {
syncHome(t)
t.Setenv("MAGPIE_ADDR", "127.0.0.1:3591")
dir := t.TempDir()
now := `{"p":{"baseUrl":"http://127.0.0.1:3591/v1","apiKey":"magpie"}}`
for _, c := range []struct{ name, was, want string }{
{"nas", `{"p":{"baseUrl":"http://192.168.1.20:3425/v1","apiKey":"nas-key"}}`,
`{"p":{"baseUrl":"http://192.168.1.20:3425/v1","apiKey":"nas-key"}}`},
{"nas, magpie's key", `{"p":{"baseUrl":"http://nas.local:3425/v1","apiKey":"magpie"}}`,
`{"p":{"baseUrl":"http://nas.local:3425/v1","apiKey":"magpie"}}`},
{"old port", `{"p":{"baseUrl":"http://127.0.0.1:3425/v1","apiKey":"magpie"}}`, now},
{"localhost", `{"p":{"baseUrl":"http://localhost:3591/v1","apiKey":"other"}}`, now},
{"two gone", `{"p":{"baseUrl":"http://192.168.1.20:3425/v1","apiKey":"a"},"q":{"baseUrl":"http://192.168.1.21:3425/v1"}}`, now},
{"wsl", `{"p":{"baseUrl":"http://172.29.0.1:3591/v1","apiKey":"lan"}}`, now},
} {
wsl.Lock()
wsl.seen = map[string]*distro{"Ubuntu": {Gateway: "172.30.0.1", Was: []string{"172.29.0.1"}}}
wsl.Unlock()
p := filepath.Join(dir, strings.ReplaceAll(c.name, " ", "-")+".json")
os.WriteFile(p, []byte(c.was), 0o644)
if got := string(keeping().away(p, []byte(now))); got != c.want {
t.Errorf("%s: %s, want %s", c.name, got, c.want)
}
}
// a model of the user's own on this machine (Ollama's) is no sign of
// magpie here
p := filepath.Join(dir, "ollama.json")
os.WriteFile(p, []byte(`{"o":{"baseUrl":"http://localhost:11434/v1"},"p":{"baseUrl":"http://192.168.1.20:3425/v1","apiKey":"nas-key"}}`), 0o644)
if got, want := string(keeping().away(p, []byte(`{"o":{"baseUrl":"http://localhost:11434/v1"},"p":{"baseUrl":"http://127.0.0.1:3591/v1","apiKey":"magpie"}}`))),
`{"o":{"baseUrl":"http://localhost:11434/v1"},"p":{"baseUrl":"http://192.168.1.20:3425/v1","apiKey":"nas-key"}}`; got != want {
t.Errorf("beside Ollama: %s, want %s", got, want)
}
// Qwen Code writes its key on its own, before the models
p = filepath.Join(dir, "qwen.json")
os.WriteFile(p, []byte(`{"env":{"MAGPIE_QWEN_API_KEY":"nas-key"},"m":{"baseUrl":"http://192.168.1.20:3425/v1"}}`), 0o644)
if got := string(keeping().away(p, []byte(`{"env":{"MAGPIE_QWEN_API_KEY":"magpie"},"m":{"baseUrl":"http://192.168.1.20:3425/v1"}}`))); !strings.Contains(got, `"nas-key"`) {
t.Errorf("the key alone went back to magpie's: %s", got)
}
wsl.Lock()
wsl.seen = nil
wsl.Unlock()
}
// The keys kept.away carries over are those a file keeps what the agent
// sends the gateway in, in each format magpie writes, and never a model's
// token limit.
func TestKeyValuesFormats(t *testing.T) {
in := strings.Join([]string{
`"apiKey": "magpie-qoder",`,
`api_key = "magpie"`,
` apiKey: magpie`,
`GEMINI_API_KEY=magpie`,
`"Authorization": "Bearer magpie"`,
`http_headers = { "x-openai-actor-authorization" = "magpie" }`,
`"max_tokens": 8192,`,
`"name": "magpie"`,
`"token": {"x": 1},`,
}, "\n")
var got []string
for _, kv := range keyValues([]byte(in)) {
got = append(got, in[kv.start:kv.end])
}
want := []string{"magpie-qoder", "magpie", "magpie", "magpie", "Bearer magpie", "magpie"}
if strings.Join(got, "|") != strings.Join(want, "|") {
t.Errorf("got %q, want %q", got, want)
}
}