agent: an agent's own models say they go direct, and a pick of one asks before 接入 goes off (maxleebeta)

maxleebeta in #feedback: Pi 1.5.0 connected to magpie; picking one of
Pi's own OpenCode Go models (opencode-go/<model>) turned 「接入」 off at
once, with nothing said, while magpie's models kept it on.

The cause: the pick writes defaultProvider opencode-go, so Pi asks
OpenCode Go itself and magpie is no longer in its config, and Wired()
is rightly false. What was missing is that the model said so. Options
from ownProvider (every ownOptions agent: Pi, OpenCode, Crush, Goose,
Cline, Hermes, Morph, OpenChamber, Qoder, StepCode, plugged agents, the
WSL twins) and ompOwnOptions carried no Direct, unlike Claude Code's
and Codex's own models. So the picker neither tagged them "direct, not
via magpie" nor asked before a pick took the agent off magpie. Each
now carries Direct = its vendor's name. The GUI already does the rest
(pathTag, the leave-ask, direct options listed after magpie's).

Tests:
- internal/agent TestOwnModelsSayTheyGoDirect: Pi, OpenCode, Crush and
  omp, signed in to OpenCode Go, each give every opencode-go/ option
  Direct "OpenCode Go"; magpie's options have none. Picking one writes
  defaultProvider opencode-go.
- internal/gui/tests/agent-own-direct.test.cjs: the tags, magpie's
  first, the ask (Cancel keeps 接入 on, nothing written), magpie's other
  model not asked, confirmed → written and off. Run in chromium and
  webkit × en/zh/zh-TW/ja/de × 980/420.

Run at this head (rebased on 2c2d2a5e5, mote):
- gofmt -l clean
- CGO_ENABLED=0 GOOS=linux go vet -tags nogui and GOOS=windows go vet
  of ./internal/agent ./internal/gui: ok
- go test ./internal/agent (TestOwnModelsSayTheyGoDirect, Codex
  Own/Pi/Omp/Crush/OpenCode runs): ok
- GUI agent-own-direct, agent-leave-magpie, agent-own-path,
  agent-own-providers, claude-default-off, pi-default-note: 56/56
  pass, both engines

Before the rebase (base 4cd01c964), go test of ./internal/agent and its
importers (backup, cli, davsync, gui, library, profile, stats, tui,
uninstall): all ok except internal/gui's
TestMainWindowCorners/macOS_26_SDK, which is #3949 (red on mote's
macOS 27). This change doesn't touch it.

Broken by hand:
- Without Direct in agents.go/omp.go, the Go test goes red for all
  four agents.
- With `direct` stripped from the GUI fixture, the GUI test goes red.

Not tried: a real Pi 1.5.0 signed in to OpenCode Go.
This commit is contained in:
yetone
2026-11-03 10:08:44 +08:00
parent 2c2d2a5e51
commit 5573f79231
5 changed files with 216 additions and 5 deletions
File diff suppressed because one or more lines are too long
+8 -4
View File
@@ -484,10 +484,14 @@ func ownProvider(native func(p string) []catalog.Model, p string) []Option {
ms = codexServed(p)
}
opts := group(name, options(ms, p+"/"))
if ic := providerIcon(p); ic != "" {
for i := range opts {
opts[i].GroupIcon = ic
}
ic := providerIcon(p)
for i := range opts {
opts[i].GroupIcon = ic
// asked of the vendor on the agent's own sign-in or key: picked on
// a connected agent it takes the agent off magpie, which the
// picker says and asks first (maxleebeta: Pi's own OpenCode Go
// model turned 「接入」 off, with nothing said)
opts[i].Direct = name
}
return opts
}
+1 -1
View File
@@ -822,7 +822,7 @@ func ompOwnOptions(modelsFile, cur string) []Option {
}
for _, m := range f.Providers[p].Models {
if m.ID != "" {
opts = append(opts, Option{Value: p + "/" + m.ID, Note: m.Name, Icon: modelIcon(p, m.ID), Group: name, GroupIcon: providerIcon(p)})
opts = append(opts, Option{Value: p + "/" + m.ID, Note: m.Name, Icon: modelIcon(p, m.ID), Group: name, GroupIcon: providerIcon(p), Direct: name})
}
}
}
+72
View File
@@ -0,0 +1,72 @@
package agent
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/edit"
)
// maxleebeta in #feedback: Pi connected to magpie, picking one of Pi's own
// models in the OPENCODE GO section (opencode-go/<model>, Pi signed in to
// OpenCode Go itself) turned 「接入」 off, with nothing said. The pick
// writes defaultProvider opencode-go, so Pi asks OpenCode Go itself and
// magpie isn't in its config any more; what was missing is that the model
// said so. Each of an agent's own models now says who it asks (Direct), as
// Claude Code's and Codex's do, so the picker tags it "direct, not via
// magpie" and asks before a pick takes the agent off magpie. Every agent
// whose own models come from ownOptions shares this, so OpenCode, Crush
// and omp are held to it too; magpie's own models stay unmarked.
func TestOwnModelsSayTheyGoDirect(t *testing.T) {
home := syncHome(t)
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
if err := os.WriteFile(catalog.CachePath(), []byte(`{"opencode-go":{"name":"OpenCode Go","models":{
"glm-5.1":{"id":"glm-5.1","name":"GLM-5.1"},
"kimi-k2.6":{"id":"kimi-k2.6","name":"Kimi K2.6"}}}}`), 0o644); err != nil {
t.Fatal(err)
}
catalog.Reset()
t.Cleanup(catalog.Reset)
auth := `{"opencode-go": {"type": "api", "key": "test-key"}}`
piDir := filepath.Join(home, ".pi", "agent")
writeFile(t, filepath.Join(piDir, "auth.json"), auth)
writeFile(t, filepath.Join(piDir, "settings.json"), `{"defaultProvider": "magpie", "defaultModel": "deepseek/deepseek-v4.1-flash"}`)
writeFile(t, filepath.Join(home, ".local", "share", "opencode", "auth.json"), auth)
cfg := filepath.Join(home, ".config")
writeFile(t, filepath.Join(cfg, "crush", "crush.json"), `{"providers": {"opencode-go": {"api_key": "test-key"}}}`)
writeFile(t, filepath.Join(home, ".omp", "agent", "models.yml"), "providers:\n opencode-go:\n models:\n - id: glm-5.1\n name: GLM-5.1\n")
for _, a := range []*Agent{pi(home), opencode(home, cfg), crush(home, cfg), omp(home)} {
f := a.Field("model")
if f == nil {
t.Fatalf("%s has no model field", a.ID)
}
opts := f.Options(a.Values())
own := 0
for _, o := range opts {
if strings.HasPrefix(o.Value, "opencode-go/") {
own++
if o.Direct != "OpenCode Go" {
t.Errorf("%s: own model %s says it goes direct to %q, want OpenCode Go", a.ID, o.Value, o.Direct)
}
} else if o.Ref != "" && o.Direct != "" {
t.Errorf("%s: magpie's %s said to go direct to %q", a.ID, o.Value, o.Direct)
}
}
if own == 0 {
t.Errorf("%s offered none of its own OpenCode Go models: %v", a.ID, pickRows(opts, ""))
}
}
// what the tag says: picked, Pi asks OpenCode Go itself
if err := pi(home).Field("model").Set("opencode-go/glm-5.1"); err != nil {
t.Fatal(err)
}
if p, _ := edit.GetJSON(filepath.Join(piDir, "settings.json"), "defaultProvider"); p != "opencode-go" {
t.Fatalf("defaultProvider %q", p)
}
}
@@ -0,0 +1,134 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// maxleebeta in #feedback: Pi 1.5.0 connected to magpie, picking one of
// Pi's own OpenCode Go models (opencode-go/<model>, the OPENCODE GO section
// of its model list) turned 「接入」 off at once, with nothing said, while
// magpie's DeepSeek V4.1 Flash kept it on. The own model is asked of
// OpenCode Go by Pi itself, so the pick does take Pi off magpie; now the
// list says so (direct, not via magpie, listed after magpie's), and the
// pick is asked first, Cancel leaving Pi connected, as Claude Code's own
// models are (#726). The options are what /api/state sends since the fix:
// an own model carries direct. Every language, wide and narrow.
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 DS = "magpie/deepseek/deepseek-v4.1-flash";
const options = [
{ value: "opencode-go/glm-5.1", note: "GLM-5.1", group: "OpenCode Go", direct: "OpenCode Go" },
{ value: "opencode-go/kimi-k2.6", note: "Kimi K2.6", group: "OpenCode Go", direct: "OpenCode Go" },
{ value: DS, label: "DeepSeek V4.1 Flash", ref: "deepseek/deepseek-v4.1-flash", group: "DeepSeek", note: "DeepSeek · via magpie" },
{ value: "magpie/deepseek/deepseek-v4.1-pro", label: "DeepSeek V4.1 Pro", ref: "deepseek/deepseek-v4.1-pro", group: "DeepSeek", note: "DeepSeek · via magpie" },
];
function server(lang, posts) {
let cur = { agents: [{ id: "pi", name: "Pi", icon: "generic", path: "/fixture/pi", wired: true, fields: [{ key: "model", label: "model", value: DS, options }] }], profiles: [] };
const reply = (route) => route.fulfill({ json: { ...cur, settings: { lang, theme: "light" } } });
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 reply(route);
if (url.pathname === "/api/set") {
const body = JSON.parse(req.postData());
posts.push(body);
cur = JSON.parse(JSON.stringify(cur));
const a = cur.agents[0];
a.fields[0].value = body.value;
a.wired = body.value.startsWith("magpie/");
return reply(route);
}
if (url.pathname.startsWith("/api/agents/preview/")) return json({ changes: [] });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const row = '.row.agent[data-id="pi"]';
const KEYS = ["direct, not via magpie", "via magpie", "Take {agent} off magpie?", "Cancel", "Use {model}",
"{model} is {agent}'s own model: {agent} asks {vendor} for it itself, with its own sign-in, not through magpie. Picking it takes {agent} off magpie, and it starts on {model}."];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [980, 420]) {
test(`${engine} ${lang} ${width}: Pi's own OpenCode Go model says it goes direct and is asked before 接入 goes off`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [], dialogs = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { dialogs.push(d.message()); d.dismiss(); });
await page.route("**/*", server(lang, posts));
await page.goto("http://magpie.test/?view=agents");
await page.locator(`${row} .ag-conn`).waitFor();
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
const missing = await page.evaluate(([keys, lang]) => lang === "en" ? [] : keys.filter((k) => !I18N[lang]?.[k]), [KEYS, lang]);
assert.deepEqual(missing, [], `every string has its ${lang}`);
const tops = () => page.evaluate(() => [document.scrollingElement.scrollTop, document.querySelector("#view-agents")?.scrollTop]);
const top = await tops();
const start = page.locator(`${row} > .field.ag-start`);
const item = (text) => page.locator("#pop #list li", { hasText: text }).first();
const open = async () => { await start.click(); await page.locator("#pop:not([hidden]) #list li").first().waitFor(); };
const on = () => page.locator(`${row} .ag-conn`).getAttribute("aria-checked");
// each says which way it goes; magpie's are listed first
await open();
const tag = (li) => li.locator(".badge.path").textContent();
assert.equal(await tag(item("GLM-5.1")), await tr("direct, not via magpie"));
assert.equal(await tag(item("DeepSeek V4.1 Pro")), await tr("via magpie"));
const order = await page.locator("#pop #list li").allTextContents();
const at = (s) => order.findIndex((x) => x.includes(s));
assert.ok(at("DeepSeek V4.1 Pro") >= 0 && at("DeepSeek V4.1 Pro") < at("GLM-5.1"), `magpie's first: ${JSON.stringify(order)}`);
// the OpenCode Go model is asked first; Cancel leaves Pi connected
await item("GLM-5.1").click();
const ask = page.locator("#modal .leave-ask");
await ask.waitFor();
assert.equal((await ask.locator(".ehead b").textContent()).trim(), await tr("Take {agent} off magpie?", { agent: "Pi" }));
assert.ok((await ask.textContent()).includes("OpenCode Go"), "says who Pi asks instead");
assert.deepEqual(posts, [], "nothing written before it is confirmed");
const box = await ask.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= width, `the ask fits at ${width}px`);
await ask.locator("button", { hasText: await tr("Cancel") }).click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(posts, []);
assert.equal(await on(), "true");
// magpie's other model isn't asked, and Pi stays on
await open();
await item("DeepSeek V4.1 Pro").click();
await page.waitForFunction((r) => document.querySelector(r + " > .field.ag-start")?.textContent.includes("Pro"), row);
assert.equal(await page.locator("#modal:not([hidden]) .leave-ask").count(), 0);
assert.deepEqual(posts, [{ agent: "pi", field: "model", value: "magpie/deepseek/deepseek-v4.1-pro" }]);
assert.equal(await on(), "true");
// confirmed, it is written, and 「接入」 goes off as it said
await open();
await item("GLM-5.1").click();
await ask.waitFor();
await ask.locator("button", { hasText: await tr("Use {model}", { model: "opencode-go/glm-5.1" }) }).click();
await page.waitForFunction(() => document.querySelector("#modal").hidden);
await page.waitForFunction((r) => document.querySelector(r + " .ag-conn")?.getAttribute("aria-checked") === "false", row);
assert.deepEqual(posts.at(-1), { agent: "pi", field: "model", value: "opencode-go/glm-5.1" });
assert.equal(await page.locator("select").count(), 0, "no native select");
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth), 0, `no sideways scroll at ${width}px`);
assert.deepEqual(await tops(), top, "no click moved the page");
assert.deepEqual(dialogs, [], "no native dialog");
assert.deepEqual(errors, []);
});
}
}
}