providers, sign-in, tray, plugins: four of StringKe's reports on Discord — (1) Removing a provider left its editor open and listed, and a second Remove said there was no such provider: the removal had been made, but moving the agents off its models failed on one agent whose config couldn't be written, and Reseat returned that as the change's error; now such an agent is a move with its error ("still on X, not moved: …", a warning in the panel, a line in the CLI and TUI), the others are moved, and the panel, told a delete failed, re-reads the list and closes the editor when the provider is gone. (2) The sign-in waiting sheet shows the sign-in link itself, selected whole on a click, with a copy button, for a browser other than the one that opens. (3) A subscription with several accounts offers "Account in use" among the menu bar's usages, following the account the gateway goes to first. (4) The Antigravity plugin's sign-in never started: magpie called every plugin's authorize with an inputs object, the way OpenCode's CLI does, and opencode-antigravity-auth then asked its Project ID on the terminal — magpie's stdin — until the minute ran out; inputs now go only to a method with prompts, as OpenCode's TUI passes them (checked against the real package under Bun in a sandbox: the Google sign-in URL comes back at once). TestReseatUnmovable, TestTrayInUse, TestInUseOf, TestAuthorizeNoPrompts, provider-remove.test.cjs, signin-link.test.cjs and tray-inuse.test.cjs fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; click-scroll, old-webkit, tray-usages, plugin-signin, signin-callback, factory-sub pass.

This commit is contained in:
yetone
2026-09-30 20:45:23 +08:00
parent 901ee08280
commit 52c8e838d2
18 changed files with 682 additions and 12 deletions
+14 -2
View File
@@ -21,10 +21,16 @@ type Move struct {
Field string `json:"field"` // model, or a tier (Claude Code's haiku …)
From string `json:"from"` // the catalog model it was on
To string `json:"to"` // the one it is on now; "" its own default
// Error is why the agent couldn't be moved (its file unwritable, say):
// it stays on From, which magpie no longer serves
Error string `json:"error,omitempty"`
}
// String is the move as the CLI and the TUI say it.
func (m Move) String() string {
if m.Error != "" {
return m.Agent + " " + m.Field + ": still on " + m.From + ", not moved: " + m.Error
}
to := m.To
if to == "" {
to = "its default"
@@ -66,6 +72,11 @@ func picks() []pick {
// Reseat makes a change to the providers (change) and moves every agent
// whose model it stopped serving: to that model from another provider
// that serves it, else to the agent's own default. It answers the moves.
// Its error is the change's alone: once the change is made, an agent that
// can't be moved is a move with its Error and the others are still moved.
// An error then would say the change failed when it was made — the panel,
// told so, kept a removed provider's editor open and listed, and a second
// Remove said there was no such provider.
func Reseat(change func() error) ([]Move, error) {
before := picks()
if err := change(); err != nil {
@@ -89,10 +100,11 @@ func Reseat(change func() error) ([]Move, error) {
if f.Options != nil {
to = sameModel(f.Options(vals), p.ref)
}
m := Move{Agent: p.a.Name, Field: f.Label, From: p.ref, To: to.Ref}
if err := p.a.Apply(p.key, to.Value); err != nil {
return moves, err
m.To, m.Error = "", err.Error()
}
moves = append(moves, Move{Agent: p.a.Name, Field: f.Label, From: p.ref, To: to.Ref})
moves = append(moves, m)
}
slices.Reverse(moves)
return moves, nil
+45
View File
@@ -3,6 +3,7 @@ package agent
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
@@ -132,3 +133,47 @@ func TestModelKey(t *testing.T) {
t.Error("gpt-5 = gpt-5-mini")
}
}
// An agent that can't be moved (its config unwritable) doesn't fail the
// change, which is made already: the others are moved and it is a move with
// its error. An error here kept a removed provider's editor open in the
// panel, the provider still listed, and a second Remove said "no provider".
func TestReseatUnmovable(t *testing.T) {
home := reseatHome(t)
c, h := mustFind(t, "claude"), mustFind(t, "hermes")
mustApply(t, c, "model", "cop/only-here")
mustApply(t, h, "model", "magpie/cop/only-here")
dir := filepath.Join(home, ".hermes")
if err := os.Chmod(dir, 0o555); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Chmod(dir, 0o755) })
if f, err := os.Create(filepath.Join(dir, "probe")); err == nil {
f.Close()
t.Skip("a read-only folder is writable here (root?)")
}
os.Chmod(filepath.Join(dir, "config.yaml"), 0o444)
moves, err := Reseat(func() error { return provider.Delete("cop") })
if err != nil {
t.Fatalf("the provider is removed, but Reseat said: %v", err)
}
if _, err := provider.Find("cop"); err == nil {
t.Fatal("cop still there")
}
if got := c.Field("model").Get(); got != "" {
t.Errorf("claude not moved: %q", got)
}
var stuck *Move
for i, m := range moves {
if m.Agent == "Hermes Agent" {
stuck = &moves[i]
}
}
if len(moves) != 2 || stuck == nil || stuck.Error == "" || stuck.To != "" || stuck.From != "cop/only-here" {
t.Fatalf("moves: %+v", moves)
}
if s := stuck.String(); !strings.Contains(s, "not moved") {
t.Errorf("String: %q", s)
}
}
+3
View File
@@ -1314,6 +1314,9 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.signing .acts .link { color: var(--fg-2); }
.signing .devcode { display: flex; align-items: center; gap: 6px; margin: 6px 0 2px; }
.signing .devcode code { font: 600 17px/1.2 var(--mono, ui-monospace, monospace); letter-spacing: .12em; padding: 4px 9px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); user-select: all; }
/* the sign-in link, one line, selected whole with a click */
.signing .signlink { display: flex; align-items: center; gap: 4px; margin: 5px 0 1px; min-width: 0; }
.signing .signlink code { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: 11px/1.3 var(--mono, ui-monospace, monospace); color: var(--fg-2); padding: 4px 7px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); user-select: all; -webkit-user-select: all; cursor: text; }
.signing .callback-form { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-top: 6px; }
.signing .callback-form input { flex: 1; min-width: 120px; width: 100%; padding: 6px 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); color: var(--fg); font-size: 12px; }
.signing .why { color: var(--red); }
+41 -8
View File
@@ -5164,12 +5164,19 @@ function renderSigning(sub) {
}
box.append(tt);
if (signing.url) {
// the link itself, to select or copy into another browser or profile
// than the one magpie opened it in
const link = el("span", "signlink");
const u = el("code", "", signing.url);
u.title = t("Open it in another browser or profile: copy it there");
const cp = copyBtn(signing.url, t("Sign-in link"));
cp.title = t("Copy link");
link.append(u, cp);
tt.append(link);
const acts = el("span", "acts");
const open = el("button", "link", t("Open again"));
open.onclick = () => api("open", { url: signing.url }).catch(() => {});
const cp = el("button", "link", t("Copy link"));
cp.onclick = () => copy(signing.url, t("Sign-in link"), cp);
acts.append(open, cp);
acts.append(open);
tt.append(acts);
}
if (signing.pasteCallback || signing.pasteCode) {
@@ -5888,6 +5895,19 @@ async function providerAction(action, body, okMsg, base = "provider/") {
renderAgents();
saidMoved(okMsg);
} catch (e) {
// a Remove may have gone through before what failed: the list as it is
// now, and the editor of a provider gone closes, rather than stay open
// on it for a second Remove to say there is no such provider
if (action === "delete" && typeof editing === "string") {
try {
providers = await api("providers");
if (!providers.providers.some((p) => p.id === editing)) {
editing = null; draft = null;
renderProviders();
return status(e.message, "err");
}
} catch { /* the error below says enough */ }
}
if (!editorError(e.message, "err")) status(e.message, "err");
document.querySelector(".editor .busy")?.classList.remove("busy");
}
@@ -5897,13 +5917,17 @@ async function providerAction(action, body, okMsg, base = "provider/") {
// took away (a provider switched off or removed, the last account signed
// out: #200), each to the same model elsewhere or back to its default.
function saidMoved(okMsg) {
// one magpie couldn't move (its file unwritable) is still on the model
// gone, and the change made all the same
let stuck = false;
const moved = (providers.moved || []).map((m) => {
const who = m.field === "model" ? m.agent : m.agent + " " + m.field;
if (m.error) { stuck = true; return t("{agent} is still on {model}, which magpie no longer serves: {error}", { agent: who, model: m.from, error: m.error }); }
return m.to ? t("{agent} moved to {model}", { agent: who, model: m.to })
: t("{agent} is back on its default", { agent: who });
});
const msg = [okMsg, ...moved].filter(Boolean).join(" · ");
if (msg) status(msg, "ok", moved.length ? 9000 : undefined);
if (msg) status(msg, stuck ? "warn" : "ok", stuck ? 12000 : moved.length ? 9000 : undefined);
}
// editorError shows what went wrong inside the open provider editor, by its
@@ -8764,6 +8788,9 @@ function importForm() {
// trayCardID names a Usage page card as settings.TrayUsage does: its
// provider, and the account when there is one.
const trayCardID = (q) => q.user ? q.provider + "|" + q.user : q.provider;
// IN_USE ends the id of a card that follows the subscription's account in
// use, the one the gateway goes to first, rather than naming one
const IN_USE = "|*";
// renderTrayUsage: the subscriptions and plans whose windows show beside
// the tray icon, side by side. The cards are the Usage page's, asked for
@@ -8785,7 +8812,7 @@ function renderTrayUsage(s, keep) {
const pill = el("button", "proto pick" + (ids.length ? " set" : ""));
pill.type = "button";
const paint = () => {
const card = (quotas || []).find((q) => trayCardID(q) === ids[0]);
const card = (quotas || []).find((q) => trayCardID(q) === ids[0] || q.provider + IN_USE === ids[0]);
pill.replaceChildren(el("span", "", !ids.length ? t("Off") : ids.length > 1 ? t("{n} subscriptions", { n: ids.length })
: card ? card.name : ids[0].split("|")[0]), svg(CHEV, 11, 1.6));
};
@@ -8796,11 +8823,17 @@ function renderTrayUsage(s, keep) {
if (pill.classList.contains("open")) return closeProtoMenu();
if (!quotas) { pill.classList.add("busy"); await loadQuotas(); pill.classList.remove("busy"); paint(); }
const cards = (quotas || []).filter((q) => !q.error && (q.windows?.length || q.balance));
const opts = [{ v: "", name: "Off", note: "" },
...cards.map((q) => ({ v: trayCardID(q), name: q.name, note: [q.plan, q.user].filter(Boolean).join(" · ") }))];
const opts = [{ v: "", name: "Off", note: "" }];
for (const q of cards) {
// a subscription with several accounts: the one in use, whichever
// it is now, before each by name
if (q.user && !opts.some((o) => o.v === q.provider + IN_USE) && cards.filter((c) => c.provider === q.provider).length > 1)
opts.push({ v: q.provider + IN_USE, name: q.name, note: "Account in use" });
opts.push({ v: trayCardID(q), name: q.name, note: [q.plan, q.user].filter(Boolean).join(" · ") });
}
// one ticked that isn't there now (signed out, or not answering) stays
// to be unticked
for (const id of ids) if (!opts.some((o) => o.v === id)) opts.push({ v: id, name: id.split("|")[0], note: id.split("|")[1] || "" });
for (const id of ids) if (!opts.some((o) => o.v === id)) opts.push({ v: id, name: id.split("|")[0], note: id.endsWith(IN_USE) ? "Account in use" : id.split("|")[1] || "" });
if (!cards.length) opts.push({ v: "\x00", name: "No subscriptions yet", note: "Sign in to one, or add a plan's key, and it shows on the Usage page" });
openProtoMenu(pill, opts, ids, (trayUsages) => savePrefs({ ...keep, trayUsages }), "Shown beside the icon");
};
+3
View File
@@ -269,6 +269,7 @@ const I18N = {
"{name} is off: agents no longer get its models": "{name} 已关闭:不再把它的模型写入 Agent",
"{agent} moved to {model}": "{agent} 已改用 {model}",
"{agent} is back on its default": "{agent} 已恢复为默认模型",
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} 仍在用 magpie 已不再提供的 {model}:{error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "已关闭:它的模型不会写入 Agent,也不会有请求发往它。密钥和设置都会保留,开启即可重新使用。",
"API key {masked}": "API 密钥 {masked}",
"Local servers need no key": "本地服务无需密钥",
@@ -408,6 +409,8 @@ const I18N = {
"Open again": "重新打开",
"Copy link": "复制链接",
"Sign-in link": "登录链接",
"Account in use": "正在使用的账号",
"Open it in another browser or profile: copy it there": "要用其他浏览器或浏览器配置登录,复制此链接到那里打开",
"If the browser cannot return to magpie, paste its final callback URL here.": "如果浏览器无法返回 magpie,请在此粘贴浏览器最终跳转的回调 URL。",
"Callback URL": "回调 URL",
"Finish sign-in": "完成登录",
+25 -1
View File
@@ -381,10 +381,34 @@ element is still there and hovered, its title shows the new total, the
chart still has 30 bars and the page has not scrolled. A metric picked after
that draws the latest numbers. The checks run in English and Chinese.
`provider-remove.test.cjs` checks Remove in a provider's editor. If the
delete fails after the provider is already gone (an agent's file could not
be rewritten), one click closes the editor, the provider's row disappears,
the other rows stay, and the status line shows the error; no second Remove
is needed. If the delete succeeds but leaves an agent on a model magpie no
longer serves, the status line warns about it and has no left-border
accent. If the delete fails while the provider is still there, the editor
stays open and shows the error. The checks run in English and Chinese, in
Chromium and WebKit.
`signin-link.test.cjs` checks a sign-in that is waiting (Factory's device
flow). Its link appears on one line inside the box and is selected whole
with a click, with no left-border accent. The copy button beside it
(titled Copy link) posts the whole link to /api/copy, and the status line
says it was copied. Open again is still there, and nothing scrolls. The
checks run in English and Chinese, in Chromium and WebKit.
`tray-inuse.test.cjs` checks Settings, Usage in the menu bar. A
subscription with two accounts lists "Account in use" before each account;
one with a single account does not. Ticking it saves `claude|*`, the pill
names the subscription, and reopening the menu shows it ticked. No click
moves the page. The checks run in English and Chinese, in Chromium and
WebKit.
With Node.js and Playwright available:
```sh
node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs
node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs
```
If Playwright is installed outside the repository, set `NODE_PATH` to the
+130
View File
@@ -0,0 +1,130 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Remove, in a provider's editor (StringKe on Discord: the dialog stayed
// open, a second Remove said there was no such provider, and the list
// wasn't refreshed). A Remove that fails once the provider is already gone
// closes the editor, drops its row and says what failed; a second one isn't
// needed. A Remove that goes through but leaves an agent it couldn't move on
// a model gone says so, as a warning, rather than failing. One that fails
// with the provider still there keeps the editor open on the error. No
// click moves the page. English and Chinese, Chromium and WebKit; 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 prov = (id, name) => ({
id, name, icon: "generic", chat: "https://" + id + ".example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "m1", name: "m1", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
});
// mode: "gone" — the delete fails after the provider went; "stuck" — it goes
// through, Hermes left behind; "kept" — it fails, the provider still there
function serve(lang, mode, deletes) {
let list = [prov("relay", "Relay"), prov("other", "Other")];
const payload = (extra) => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true }, ...extra });
return async (route) => {
const url = new URL(route.request().url());
const json = (data, status = 200) => route.fulfill({ status, 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({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json(payload());
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/provider/delete") {
const { id } = route.request().postDataJSON();
deletes.push(id);
if (mode === "kept") return json({ error: "disk full" }, 400);
const was = list.length;
list = list.filter((p) => p.id !== id);
if (list.length === was) return json({ error: `no provider "${id}"` }, 400);
if (mode === "gone") return json({ error: "open ~/.hermes/config.yaml: permission denied" }, 400);
return json(payload({ moved: [{ agent: "Hermes", field: "model", from: "relay/m1", error: "permission denied" }] }));
}
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 words = {
en: { remove: "Remove", stuck: "Relay removed · Hermes is still on relay/m1, which magpie no longer serves: permission denied" },
zh: { remove: "移除", stuck: "已移除 Relay · Hermes 仍在用 magpie 已不再提供的 relay/m1:permission denied" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
test(`${engine} ${lang}: Remove closes on a provider gone`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const pages = [];
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
for (const [i, p] of pages.entries()) await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-provider-remove-${i}.png`) });
}
await browser.close();
});
const open = async (mode) => {
const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
pages.push(page);
page.setDefaultTimeout(5000);
const errors = [], deletes = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, mode, deletes));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "Relay" }).click();
await page.locator(".editor").waitFor();
const del = page.locator(".editor .bar button.danger", { hasText: w.remove });
await del.scrollIntoViewIfNeeded();
await page.waitForTimeout(150);
const top = await del.evaluate((e) => e.getBoundingClientRect().top);
await del.click();
return { page, errors, deletes, top, del };
};
const rows = (page) => page.locator(".row.provider").allTextContents();
await t.test("gone", async () => {
const { page, errors, deletes } = await open("gone");
await page.locator(".editor").waitFor({ state: "detached" });
assert.deepEqual(deletes, ["relay"], "one Remove is enough");
await page.waitForFunction(() => ![...document.querySelectorAll(".row.provider")].some((r) => r.textContent.includes("Relay")));
assert((await rows(page)).some((r) => r.includes("Other")), "the rest of the list stays");
const st = page.locator("#status");
assert.equal(await st.textContent(), "open ~/.hermes/config.yaml: permission denied");
assert(/\berr\b/.test(await st.getAttribute("class")));
assert.deepEqual(errors, []);
});
await t.test("stuck", async () => {
const { page, errors } = await open("stuck");
await page.locator(".editor").waitFor({ state: "detached" });
const st = page.locator("#status");
await page.waitForFunction((s) => document.querySelector("#status").textContent === s, w.stuck);
assert(/\bwarn\b/.test(await st.getAttribute("class")), "a warning, not a plain ok");
const border = await st.evaluate((e) => getComputedStyle(e).borderLeftWidth);
assert(parseFloat(border) <= 1, "no left-border accent");
assert.deepEqual(errors, []);
});
await t.test("kept", async () => {
const { page, errors, deletes, top, del } = await open("kept");
await page.locator(".editor .editor-error").waitFor();
assert.equal(await page.locator(".editor .editor-error").textContent(), "disk full");
assert.equal(await del.evaluate((e) => e.getBoundingClientRect().top) <= top, true, "the Remove click didn't push the page down");
assert.deepEqual(deletes, ["relay"]);
assert((await rows(page)).some((r) => r.includes("Relay")), "still listed");
assert.deepEqual(errors, []);
});
const missing = await pages[0].evaluate(() => ["{agent} is still on {model}, which magpie no longer serves: {error}"].filter((k) => !I18N.zh[k]));
assert.deepEqual(missing, []);
});
}
}
+99
View File
@@ -0,0 +1,99 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The sign-in link in sight (StringKe on Discord: the sign-in page only
// opened in the default browser, with no link to take to another one).
// While a sign-in waits, its link shows on one line under the question,
// selectable whole, with a copy button beside it that copies the link;
// "Open again" still opens it. Neither click moves the page. English and
// Chinese, Chromium and WebKit; 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 LINK = "https://factory.example/device?code=WDJB-MJHT&state=" + "x".repeat(120);
function server(lang, copied, opened) {
return async (route) => {
const url = new URL(route.request().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:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
const signing = { id: "s1", agent: "factory", state: "waiting", url: LINK, code: "WDJB-MJHT" };
if (url.pathname === "/api/signin" || url.pathname.startsWith("/api/signin/")) return json(signing);
if (url.pathname === "/api/copy") { copied.push(route.request().postDataJSON().text); return json({}); }
if (url.pathname === "/api/open") { opened.push(route.request().postDataJSON()); return json({}); }
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 W = {
en: { anyway: "Sign in anyway", copy: "Copy link", again: "Open again", copied: "Sign-in link copied" },
zh: { anyway: "仍然登录", copy: "复制链接", again: "重新打开", copied: "已复制登录链接" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: the sign-in link can be copied`, async (t) => {
const w = W[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width: 900, height: 800 }, reducedMotion: "reduce" })).newPage();
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-signin-link.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
const errors = [], copied = [], opened = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, copied, opened));
await page.goto("http://magpie.test/?view=providers");
await page.locator("#addProvider").click();
const sheet = page.locator("#addSheet");
await sheet.locator('.tile[data-pick="Factory"]').click();
const box = sheet.locator(".signing");
await box.locator("button", { hasText: w.anyway }).click();
const link = box.locator(".signlink");
await link.waitFor();
// the whole link, on one line inside the box
const code = link.locator("code");
assert.equal(await code.textContent(), LINK);
const fit = await link.evaluate((l) => {
const c = l.querySelector("code"), b = l.closest(".signing").getBoundingClientRect(), r = c.getBoundingClientRect();
return { oneLine: r.height < 30, inside: r.right <= b.right + 0.5, sel: getComputedStyle(c).userSelect || getComputedStyle(c).webkitUserSelect };
});
assert(fit.oneLine && fit.inside, JSON.stringify(fit));
assert.equal(fit.sel, "all");
// no coloured stripe down its side: a left border no other than the rest
const stripes = await page.evaluate(() => [...document.querySelectorAll(".signlink, .signlink *")].filter((e) => {
const s = getComputedStyle(e);
return parseFloat(s.borderLeftWidth) > parseFloat(s.borderTopWidth) || (parseFloat(s.borderLeftWidth) && s.borderLeftColor !== s.borderTopColor);
}).map((e) => e.className));
assert.deepEqual(stripes, [], "no left-border accent");
const scrolls = () => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("#addSheet, #addSheet *")].filter((e) => e.scrollTop).map((e) => e.scrollTop)]);
const before = await scrolls();
const cp = link.locator("button.copy");
assert.equal(await cp.getAttribute("title"), w.copy);
await cp.click();
for (let i = 0; i < 40 && !copied.length; i++) await page.waitForTimeout(50);
assert.deepEqual(copied, [LINK]);
await page.waitForFunction((s) => document.querySelector("#status").textContent === s, w.copied);
assert.equal(await box.locator("button", { hasText: w.again }).count(), 1, "Open again is still there");
assert.deepEqual(await scrolls(), before, "nothing scrolled");
assert.deepEqual(errors, []);
});
}
}
+109
View File
@@ -0,0 +1,109 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// StringKe on Discord: the menu bar showed one account's use, never "the
// one in use". Settings → Usage in the menu bar lists, for a subscription
// with several accounts, "Account in use" before each account by name;
// ticked, it is saved as "claude|*" (the tray follows whichever account the
// gateway goes to first), and the pill names the subscription. One with a
// single account gets no such line. No click moves the page. English and
// Chinese, Chromium and WebKit; 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 quotas = [
{ provider: "claude", name: "Claude Code", icon: "claude-color", user: "a@b.c", plan: "Max", windows: [{ name: "5-hour", used: 42 }] },
{ provider: "claude", name: "Claude Code", icon: "claude-color", user: "d@e.f", plan: "Pro", windows: [{ name: "5-hour", used: 7 }] },
{ provider: "codex", name: "Codex", icon: "codex-color", user: "x@y.z", plan: "Plus", windows: [{ name: "5-hour", used: 8 }] },
];
function server(lang, posts) {
let cur = {
theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd",
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
trayUsage: "", trayUsages: [], trayUsageEvery: 3, vision: "", imageGen: "",
version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
proxyNow: "none", proxySource: "none", login: false,
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
};
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:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/settings") {
if (req.method() === "POST") {
const body = req.postDataJSON();
posts.push(body);
cur = { ...cur, ...body, trayUsage: (body.trayUsages || [])[0] || "" };
}
return json(cur);
}
if (url.pathname === "/api/usage/quotas") return json(quotas);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
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 W = { en: { off: "Off", inUse: "Account in use" }, zh: { off: "关闭", inUse: "正在使用的账号" } };
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: the menu bar follows the account in use`, async (t) => {
const w = W[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" })).newPage();
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-tray-inuse.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts));
await page.goto("http://magpie.test/?view=usage");
await page.locator("#prefs").click();
const pill = page.locator("#trayUsagePick button");
await pill.waitFor();
await pill.scrollIntoViewIfNeeded();
const top = () => page.locator("#view-settings").evaluate((v) => v.scrollTop);
const before = await top();
await pill.click();
const items = page.locator(".proto-menu .pm-item");
await items.first().waitFor();
const rows = await items.evaluateAll((bs) => bs.map((b) => [b.querySelector(".pm-name").textContent.trim(), b.querySelector(".pm-note").textContent.trim()]));
assert.deepEqual(rows, [
[w.off, ""], ["Claude Code", w.inUse], ["Claude Code", "Max · a@b.c"], ["Claude Code", "Pro · d@e.f"], ["Codex", "Plus · x@y.z"],
], "the account in use before Claude's two accounts; none for Codex's one");
await items.nth(1).click();
await page.keyboard.press("Escape");
await page.waitForFunction(() => document.querySelector("#trayUsagePick button").textContent.trim() === "Claude Code");
assert.deepEqual(posts.at(-1).trayUsages, ["claude|*"]);
// ticked when opened again
await pill.click();
await items.first().waitFor();
assert.deepEqual(await items.evaluateAll((bs) => bs.map((b) => b.getAttribute("aria-checked"))), ["false", "true", "false", "false", "false"]);
await page.keyboard.press("Escape");
await page.waitForTimeout(200);
assert.equal(await top(), before, "no click moved the page");
const missing = await page.evaluate(() => ["Account in use"].filter((k) => !I18N.zh[k]));
assert.deepEqual(missing, []);
assert.deepEqual(errors, []);
});
}
}
+42
View File
@@ -136,6 +136,12 @@ func trayUsageCards(ctx context.Context, ids []string) []provider.SubscriptionQu
func trayPick(cards []provider.SubscriptionQuota, ids []string) []provider.SubscriptionQuota {
var out []provider.SubscriptionQuota
for _, id := range ids {
if pid, ok := strings.CutSuffix(id, trayInUse); ok {
if q, ok := trayInUseCard(cards, pid); ok {
out = append(out, q)
}
continue
}
if i := slices.IndexFunc(cards, func(q provider.SubscriptionQuota) bool { return trayCardID(q) == id }); i >= 0 {
out = append(out, cards[i])
}
@@ -143,6 +149,42 @@ func trayPick(cards []provider.SubscriptionQuota, ids []string) []provider.Subsc
return out
}
// trayInUse ends a card id that follows a subscription's account in use
// ("claude|*") rather than naming one: with several accounts, the one the
// gateway goes to first is the one worth watching, whichever it is now.
const trayInUse = "|*"
// trayInUseAccount is the account of an agent's the gateway goes to first;
// a var for tests.
var trayInUseAccount = provider.InUseLogin
// trayInUseCard is the card of the provider's account in use, named with
// the account so the tooltip says which it is; the provider's first card
// when magpie can't tell (the account in use first among them).
func trayInUseCard(cards []provider.SubscriptionQuota, pid string) (provider.SubscriptionQuota, bool) {
var mine []provider.SubscriptionQuota
for _, q := range cards {
if q.Provider == pid {
mine = append(mine, q)
}
}
if len(mine) == 0 {
return provider.SubscriptionQuota{}, false
}
q := mine[0]
if len(mine) > 1 {
if user := trayInUseAccount(pid); user != "" {
if i := slices.IndexFunc(mine, func(q provider.SubscriptionQuota) bool { return strings.EqualFold(q.User, user) }); i >= 0 {
q = mine[i]
}
}
}
if q.User != "" {
q.Name += " · " + q.User
}
return q, true
}
// trayCell is a card as the Mac's menu bar draws it: its logo, and its
// label's parts stacked, the shortest window over the longer ("42%" over
// "18%"), or its balance alone.
+55
View File
@@ -0,0 +1,55 @@
package gui
import (
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// StringKe on Discord: the menu bar shows one account's use, picked in
// Settings, not the one in use. A card id "claude|*" follows the account
// the gateway goes to first, whichever that is now, and the tooltip names it.
func TestTrayInUse(t *testing.T) {
inUse := "b@x.y"
was := trayInUseAccount
trayInUseAccount = func(agent string) string {
if agent != "claude" {
t.Errorf("asked about %q", agent)
}
return inUse
}
t.Cleanup(func() { trayInUseAccount = was })
cards := []provider.SubscriptionQuota{
{Provider: "claude", Name: "Claude Code", User: "a@x.y", Windows: []provider.QuotaWindow{{Name: "5-hour", Used: 10}}},
{Provider: "claude", Name: "Claude Code", User: "B@x.y", Windows: []provider.QuotaWindow{{Name: "5-hour", Used: 70}}},
{Provider: "zcode", Name: "ZCode", User: "z@x.y", Windows: []provider.QuotaWindow{{Name: "5 小时", Used: 5}}},
{Provider: "deepseek", Name: "DeepSeek", Balance: "¥1.00"},
}
got := trayPick(cards, []string{"claude|*", "zcode|*", "deepseek", "claude|a@x.y", "gone|*"})
if len(got) != 4 {
t.Fatalf("cards: %+v", got)
}
if got[0].User != "B@x.y" || got[0].Name != "Claude Code · B@x.y" {
t.Errorf("in use: %+v", got[0])
}
if got[1].User != "z@x.y" || got[1].Name != "ZCode · z@x.y" {
t.Errorf("one account: %+v", got[1])
}
if got[2].Name != "DeepSeek" || got[3].User != "a@x.y" || got[3].Name != "Claude Code" {
t.Errorf("named ones as they were: %+v", got[2:])
}
if label, tip := trayUsageText(got[0], time.Now(), false); label != "70%" || tip != "Claude Code · B@x.y\n5-hour 70% used" {
t.Errorf("text: %q %q", label, tip)
}
// switched: the card follows
inUse = "a@x.y"
if got = trayPick(cards, []string{"claude|*"}); len(got) != 1 || got[0].User != "a@x.y" {
t.Errorf("after a switch: %+v", got)
}
// can't tell: the first, the one in use first among them
inUse = ""
if got = trayPick(cards, []string{"claude|*"}); len(got) != 1 || got[0].User != "a@x.y" {
t.Errorf("unknown: %+v", got)
}
}
+6 -1
View File
@@ -553,7 +553,12 @@ async function authorize({ provider, method, inputs, account }) {
if (!m) throw new Error(`no sign-in method ${method} for ${provider}`)
if (m.type !== "oauth") throw new Error("not an oauth method")
const key = signInKey(provider, account)
const a = await inScope(provider, key, () => m.authorize(inputs ?? {}))
// the inputs go only to a method that asks something, as OpenCode's TUI
// (/connect) passes them: an object with none is how its CLI (opencode
// auth login) calls, and a plugin told so asks its questions on the
// terminal, magpie's stdin here (opencode-antigravity-auth waited on its
// "Project ID" prompt, the sign-in never starting)
const a = await inScope(provider, key, () => m.authorize(m.prompts?.length ? inputs ?? {} : undefined))
const session = String(nextSession++)
sessions.set(session, { provider, key, a, inputs })
return { session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method }
+32
View File
@@ -0,0 +1,32 @@
package plugin
import (
"context"
"path/filepath"
"testing"
"time"
)
// StringKe on Discord: the Antigravity plugin can't sign in. An OAuth
// method that asks nothing is called with no inputs, as OpenCode's TUI
// calls it; opencode-antigravity-auth, handed an empty object, took it for
// OpenCode's CLI and waited on a "Project ID" prompt on magpie's stdin, the
// sign-in's page never given.
func TestAuthorizeNoPrompts(t *testing.T) {
sandbox(t)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("testdata/cliflow/index.js")
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
actx, acancel := context.WithTimeout(ctx, 15*time.Second)
defer acancel()
a, err := Authorize(actx, "cliflow", 0, map[string]string{}, NewAccount)
if err != nil || a.URL != "https://cliflow.invalid/auth" || a.Method != "code" {
t.Fatalf("Authorize = %+v, %v", a, err)
}
if got, err := Finish(ctx, a.Session, "good"); err != nil || got != (Saved{"cliflow", "cliflow"}) {
t.Fatalf("Finish = %+v, %v", got, err)
}
}
+27
View File
@@ -0,0 +1,27 @@
// A plugin whose OAuth method asks nothing and tells OpenCode's CLI from
// its TUI by the inputs, as opencode-antigravity-auth does: given an object
// (opencode auth login) it asks its questions on the terminal and answers
// only once signed in; given none (/connect) it gives the page to open.
export const CLIFlowPlugin = async () => ({
auth: {
provider: "cliflow",
methods: [
{
type: "oauth",
label: "OAuth",
authorize: async (inputs) => {
if (inputs) {
process.stderr.write("Project ID (leave blank to use your default project): ")
await new Promise(() => {}) // the terminal's answer, never coming
}
return {
url: "https://cliflow.invalid/auth",
instructions: "Paste the code",
method: "code",
callback: async (code) => (code === "good" ? { type: "success", refresh: "r", access: "a", expires: 0, accountId: "me@cliflow" } : { type: "failed" }),
}
},
},
],
},
})
+21
View File
@@ -550,6 +550,27 @@ func Logins(agent string) []Login {
return append(out, side...)
}
// InUseLogin is the account of an agent's the gateway goes to first: the
// one the agent is signed in to, unless it is paused, else the first other
// one on; "" when the agent has none.
func InUseLogin(agent string) string {
return inUseOf(Logins(agent))
}
func inUseOf(ls []Login) string {
for _, l := range ls {
if l.Active && !l.Paused {
return l.User
}
}
for _, l := range ls {
if l.On && !l.Paused {
return l.User
}
}
return ""
}
// SwitchLogin signs an agent in to a remembered account. Sessions of the
// agent that are already running keep the account they started with until
// they restart; so does Codex's background app-server, which new Codex
+22
View File
@@ -0,0 +1,22 @@
package provider
import "testing"
// The account in use, as the menu bar's "account in use" card follows it:
// the one the agent is signed in to, unless paused, else the first on.
func TestInUseOf(t *testing.T) {
for _, c := range []struct {
ls []Login
want string
}{
{[]Login{{User: "a", On: true}, {User: "b", Active: true, On: true}}, "b"},
{[]Login{{User: "b", Active: true, On: true, Paused: true}, {User: "c"}, {User: "d", On: true}}, "d"},
{[]Login{{User: "c"}, {User: "e", On: true}}, "e"},
{[]Login{{User: "c"}}, ""},
{nil, ""},
} {
if got := inUseOf(c.ls); got != c.want {
t.Errorf("%+v: %q, want %q", c.ls, got, c.want)
}
}
}
+4
View File
@@ -185,6 +185,10 @@ func reseatCmd(change func() error, done string) tea.Cmd {
return flashMsg{text: err.Error()}
}
for _, mv := range moved {
if mv.Error != "" {
done += "; " + mv.String()
continue
}
done += "; moved " + mv.String()
}
return flashMsg{text: done, ok: true}
+4
View File
@@ -849,6 +849,10 @@ func fetchedFrom(p provider.Provider) string {
// serving (agent.Reseat).
func printMoved(moved []agent.Move) {
for _, m := range moved {
if m.Error != "" {
fmt.Println("!", m.String())
continue
}
fmt.Println(green.Render("✓"), "moved", m.String())
}
}