gui: the tray panel switches a Claude Code's or Codex's account (shuizhuyu on X)

shuizhuyu asked for a global shortcut to switch accounts. v0.1.2143's
Quick panel shortcut opens the tray panel, but the panel had no account
switch: switchable() returned null there, because the panel reads no
provider list (a fresh /api/providers reads every sign-in, seconds after
a start, #1519).

Now a Claude Code or Codex not connected has an "account" line in its
opened panel row (switchEntry, the window's Switch accounts only menu).
The line is drawn from the list kept from the last read
(GET /api/providers?last=1, no keychain read; panelAccounts in app.js),
read fresh only when nothing is kept. Opening the menu does one fresh
read and opens on what it says. Manage accounts… and a lapsed pick open
the window's Providers (window/main?view=providers). The provider and
login actions now keep their answer as the last list (keepProviders), so
a switch made in the window or the panel is in the next kept read.

app.js stays under its budget with no raise: my own comments and two
older ones (the usage accounts note, the sidebar note) were cut down.

Run:
- GUI, Windows box (xiaomi-gpu, win-run), Chromium + WebKit: 31 files
  (panel-*, panel-switch-accounts, agent-switch-accounts, switch-only,
  claude-switch-only, keep-login, agent-failover, agent-row-disclose,
  getting-started, click-scroll, i18n-keys, gui-zh-tw, gui-ja, gui-de):
  503 of 503 pass. Not the whole GUI suite.
- mote: no browser could launch there (pboard down, #4125; every WebKit
  and later Chromium launch timed out at 180s), so the GUI runs there
  were cut short. agent-panel-name-width, red there in both engines, is
  red on origin/main too (#4304, #4203), and this change doesn't draw
  the closed rows it measures.
- mote: go vet ./internal/gui; go test -run 'TestKeptProvidersFollowActions|
  TestLastKnownProviders|Budget|TestProvider' ./internal/gui ok (includes
  TestCoreScriptBudget). gofmt -l clean. GOOS=windows go vet ./... ok.
  GOOS=linux go vet ./... fails only in wails/v3 pkg/application (cgo
  off when cross-compiling), the same on origin/main 32f5c3369 (#4406).

At the pushed head (rebased on origin/main 32f5c3369, whose switchEntry
now leaves setup-token logins out of the menu; kept): the Go run above
again ok, TestCoreScriptBudget at the new 1,536,586 included, app.js
1,314,856 of 1,315,316; on the Windows box, panel-switch-accounts,
agent-switch-accounts, switch-only, claude-switch-only, keep-login,
agent-failover, i18n-keys, panel-fold and panel-effort: 178 of 178.

Broken by hand:
- panel-switch-accounts on origin/main's assets: 12 of 12 red in
  Chromium (no account line).
- Panel always reading fresh (laziness removed): 11 of 12 red.
- keepProviders removed from the provider action:
  TestKeptProvidersFollowActions red.

Not tried: real Claude Code or Codex accounts; the real Wails panel
opened by the shortcut; the login/{action} keep has no test of its own.
This commit is contained in:
yetone
2026-10-30 15:26:03 +08:00
parent 643b525469
commit 46fb0c1b93
8 changed files with 296 additions and 32 deletions
+4 -1
View File
@@ -1824,7 +1824,10 @@ shows the account it is signed in to; click it, and the *Switch accounts
only* menu signs Claude Code in to another of them, with *Only switch
Claude Code's sign-in* and *Manage accounts…* beside. The button says
*Switched*, and a new Claude Code session uses the new account; one
already open keeps its account until it is started again.
already open keeps its account until it is started again. The tray panel
has it too: set a key under Settings › General › Quick panel shortcut, press
it from any app, open Claude Code's (or Codex's) row and click its
*account* line.
**How often an allowance is read.** Routing uses what was read last and
never waits for a reading, except the first one after magpie starts (3
+1 -1
View File
@@ -33,7 +33,7 @@ three.
6. The window opens as it was last left. Its settled size and whether it was maximised are kept in `settings.Window` and `settings.WindowMaximised` (`settle`; per machine, see `KeepOwn`). A maximised window keeps the size it restores to. `makeMain` opens it at that size (`openSize`). On its first show, `placeMain` maximises it again on the Mac and Windows (on Windows once the page has come). On Linux, `makeMain` makes it maximised with `StartState`. On Windows a size larger than the screen's work area is fitted and centred (`fitRoom`), and the larger size stays kept. The window's position is not kept.
7. The page's header is the window's title bar. `plainTitlebar` sets it up once the app has started, and again on a window lightweight mode made again (`madeAgain`). On Linux it hides GTK's title bar and keeps the shadow and the resize edges; GTK 3 leaves the corners square. On the Mac the traffic lights are inset into the header (`MacTitleBarHiddenInset`). In the design of macOS 26 a window with a toolbar has larger corners than one with a plain title bar, so `insetLights` ([`titlebar_darwin.go`](../../internal/gui/titlebar_darwin.go)) takes the toolbar off, and `MagpieLights` keeps the lights and the title bar's height where the toolbar had them: after a resize, a new title, light or dark, more contrast or less transparency, and leaving full screen. A sheet, such as the folder chooser, still begins below the title bar. A first press while another app is in front still moves the window from anywhere in that title bar (`firstPress`), as AppKit moved it with the toolbar; AppKit itself now does so only in a plain title bar's top 32pt. AppKit gives a program that design from macOS 26 when the program is linked against the macOS 26 SDK or a later one and its Info.plist doesn't ask for the earlier design (`UIDesignRequiresCompatibility`); `designOf26` reads each at run time, as the SDK depends on the toolchain that built magpie. The toolbar stays in the earlier design, where it doesn't change the corners, with the lights on the right (a right-to-left language), or when the title bar isn't laid out as expected; this is decided once, when the window is set up. In full screen the title bar is AppKit's own. Windows keeps its own title bar.
8. On the Mac, Settings › Show in Dock puts magpie in the Dock never (`DockNever`), while the window is open (the default; `DockWindow` records it chosen, for an older magpie that took none for never) or always (`Dock`, which wins). The default was never until ShouguangCao on X found the open window out of Command-Tab, so going back to it to paste a key copied elsewhere took the menu bar; a new install (no settings.json) reads With window, and Hide is a choice of its own (`inDock`, `dockChoice` in app.js, `TestDockFollowsWindowByDefault`, `dock-choice.test.cjs`). A file written before that has no `dockSettled`, and stored Hide as nothing, so a user who chose Hide can't be told from one who never chose: such a file with no Dock choice reads as Hide, and the first save writes it so with `dockSettled` (`settleDock`, `TestOlderSettingsKeepHide`, `TestNewInstallFollowsWindow`). A file nobody can read reads the same way. The page never sends `dockSettled`; the save keeps the file's (`TestSettingsSaveKeepsDockReading`). It is this computer's own, as the Dock choice is (`KeepOwn`). A full-screen window joins it whatever the setting (`inDock`, `dockOnFullscreen`). `openMain` joins before it shows the window (`setDock` runs on the main thread at once). An app activated out of the Dock (the quick panel's focus) that then joins it stays last in Command-Tab's order though it is in front, so joining to the front activates magpie by way of the Dock (`dockStep`, `activateAgain`; #1381, `TestDockStep`, `TestDockJoinLeadsCommandTab`). It does so without asking NSApp whether magpie is active: the Mac makes it the front app at once, and NSApp says so only once the main thread has taken that in, after the join on a busy Mac (#1651).
9. Settings › General › Quick panel shortcut binds a key combination that opens the tray's panel from any app (ben hanks on Discord); none is set by default. The page records the keys and posts them to `POST /api/settings/panel-shortcut`, which checks them (`panelShortcut`: a letter, digit, Space or F1–F20 with Ctrl, Alt/Option or Cmd/Super, or an F key alone, written as Wails' accelerator), has the running app bind them (`onPanelShortcut`, `bindPanelKey` through Wails' `GlobalShortcut`: Carbon's hot keys on the Mac, `RegisterHotKey` on Windows, `XGrabKey` on X11) and saves them only once bound. One the system refuses (on Windows and X11, another app holding it) is not saved and the old one stays bound; one saved but refused as magpie starts is retried after a handed-over magpie exits and else said in the row (`panelKeysJSON.Taken`). A pressed shortcut toggles the panel as a tray click does (`togglePanel`). The Mac's Carbon hot keys don't refuse a combination another app registered too, so there both are taken and magpie can't tell the user. The shortcut is per computer (`KeepOwn`), and the Mac's old process lets go of it as it hands over (`leaveMenuBar`). On Wayland no app may grab keys itself, so the field is off and the row says the command to bind in the desktop's own keyboard settings (`magpie panel`); Wails' GlobalShortcuts portal is not used, since the compositor decides its keys and Hyprland binds none unless configured.
9. Settings › General › Quick panel shortcut binds a key combination that opens the tray's panel from any app (ben hanks on Discord); none is set by default. The page records the keys and posts them to `POST /api/settings/panel-shortcut`, which checks them (`panelShortcut`: a letter, digit, Space or F1–F20 with Ctrl, Alt/Option or Cmd/Super, or an F key alone, written as Wails' accelerator), has the running app bind them (`onPanelShortcut`, `bindPanelKey` through Wails' `GlobalShortcut`: Carbon's hot keys on the Mac, `RegisterHotKey` on Windows, `XGrabKey` on X11) and saves them only once bound. One the system refuses (on Windows and X11, another app holding it) is not saved and the old one stays bound; one saved but refused as magpie starts is retried after a handed-over magpie exits and else said in the row (`panelKeysJSON.Taken`). A pressed shortcut toggles the panel as a tray click does (`togglePanel`). The Mac's Carbon hot keys don't refuse a combination another app registered too, so there both are taken and magpie can't tell the user. The shortcut is per computer (`KeepOwn`), and the Mac's old process lets go of it as it hands over (`leaveMenuBar`). On Wayland no app may grab keys itself, so the field is off and the row says the command to bind in the desktop's own keyboard settings (`magpie panel`); Wails' GlobalShortcuts portal is not used, since the compositor decides its keys and Hyprland binds none unless configured. From there a not-connected Claude Code's or Codex's opened row switches its account (shuizhuyu on X, [Switch accounts only](providers-accounts.md)).
## Constraints and failure behavior
File diff suppressed because one or more lines are too long
+1
View File
@@ -683,6 +683,7 @@ body.panel #agents > .row .ag-handle::before { left: -8px; }
.ag-who > svg { flex: none; }
.ag-who .v { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.ag-who.open { background: var(--pill); color: var(--fg); }
.ag-open .field.ag-who .ok { order: 2; }
.ag-who .ok { display: none; flex: none; align-items: center; gap: 3px; color: var(--green); font-weight: 600; }
.ag-who.done .ok { display: inline-flex; }
.ag-fix.busy svg > * { transform-box: view-box; transform-origin: 50% 50%; animation: spin .8s linear infinite; }
+40 -29
View File
@@ -682,6 +682,8 @@ function renderAgents() {
connectRow(a, row, who, { fields, extras, fieldBtn, sw, kind });
return row;
}
const acct = openBox && switchEntry(a);
if (acct) openBox.querySelector(".ag-body").prepend(acct.button);
if (sw && openBox) {
const line = el("div", "ag-conn-row");
line.append(el("span", "k", t("magpie")), el("span", "ag-conn-said", connectSaid(a)), sw);
@@ -1585,13 +1587,15 @@ function connectRow(a, row, who, { fields, extras, fieldBtn, sw, kind }) {
}
// Switch accounts only (the owner on X): a Claude Code or Codex not
// connected says its account, and its menu signs it in to another, as the
// account rows do; the window's, the panel reads no provider list
let accountSwitched = null;
// connected says its account, and its menu signs it in to another. The
// panel's (shuizhuyu on X) is drawn from the kept list (?last=1): a fresh
// read takes seconds after a start, so it waits for the menu
let accountSwitched = null, panelAccts = null;
const switchesAccounts = (a) => !a.wired && (a.id === "claude" || a.id === "codex");
function switchable(a) {
if (a.wired || mode === "panel" || (a.id !== "claude" && a.id !== "codex")) return null;
const p = (providers || providersEarly?.got)?.providers?.find((x) => x.id === a.id && x.account?.agent === a.id);
if (!switchesAccounts(a)) return null;
const p = (mode === "panel" ? panelAccts : providers || providersEarly?.got)?.providers?.find((x) => x.id === a.id && x.account?.agent === a.id);
return p && loginsInOrder(p.account, p)[0]?.user ? p : null;
}
@@ -1599,12 +1603,13 @@ function switchEntry(a) {
const p = switchable(a);
if (!p) return null;
const ls = loginsInOrder(p.account, p), cur = ls.find((l) => l.active)?.user || "", ag = { agent: a.name };
const b = el("button", "ag-acc ag-who"), cx = a.id === "codex";
// the panel's a line of its opened row
const pn = mode === "panel", b = el("button", pn ? "field ag-who" : "ag-acc ag-who"), cx = a.id === "codex";
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
if (cur) b.title = t("Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.", { ...ag, user: cur });
b.append(svg(EXTRA_GLYPH["sign-in"], 12, 1.5), el("span", "v", cur || t("Not signed in")));
b.append(pn ? el("span", "k", t("account")) : svg(EXTRA_GLYPH["sign-in"], 12, 1.5), el("span", "v", cur || t("Not signed in")));
const ago = performance.now() - (accountSwitched?.at || -1e9);
if (accountSwitched?.agent === a.id && accountSwitched.user === cur && ago < 5000) {
const ok = el("span", "ok");
@@ -1613,20 +1618,26 @@ function switchEntry(a) {
b.classList.add("done");
setTimeout(() => b.classList.remove("done"), 5000 - ago);
}
b.append(svg(CHEV, 10, 1.6));
b.append(pn ? el("span", "chev", svg(CHEV, 11, 1.7)) : svg(CHEV, 10, 1.6));
const opts = ls.filter((l) => !l.token).map((l) => ({ v: "u:" + l.user, name: l.user, literalName: true, note: l.lapsed ? "Sign-in required" : accountPlan({ agent: a.id, plan: l.plan }) }));
const on = cx ? t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag) : t("magpie serves no requests on these accounts");
// the Only switch setting, where the accounts page offers it
if (!cx || ls.filter((l) => !l.lapsed && (l.active || l.on)).length > 1) opts.push({ v: "only", name: t("Only switch {agent}'s sign-in", ag), literalName: true, ticked: !!p.switchOnly, note: on });
opts.push({ v: "manage", name: "Manage accounts…", note: "" });
b.onclick = (e) => {
b.onclick = async (e) => {
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
const s = pn && panelAccts?.last && await api("providers").catch(() => null);
if (s) {
panelAccts = s;
renderAgents();
return $(`.row.agent[data-id="${a.id}"] .ag-who`)?.click();
}
openProtoMenu(b, opts, "u:" + cur, (v) => {
const l = ls.find((x) => "u:" + x.user === v);
if (v === "only") accountAction("provider/switchonly", { id: p.id, switchOnly: !p.switchOnly }, !p.switchOnly ? on
: cx ? t("{agent}'s requests go through magpie to fail over to your other accounts again", ag) : t("magpie serves requests on these accounts again"));
else if (v === "manage" || l?.lapsed) openProvider(a.id);
else if (v === "manage" || l?.lapsed) pn ? api("window/main?view=providers", {}).catch((e) => status(e.message, "err")) : openProvider(a.id);
else if (l && l.user !== cur) switchAccountTo(a, p, l.user);
}, "Switch accounts only", "sess-menu", "right");
};
@@ -1641,6 +1652,16 @@ async function switchAccountTo(a, p, user) {
renderAgents();
}
// the panel's list for it: the kept one, a fresh read only with none kept
async function panelAccounts() {
if (!state.agents.some(switchesAccounts)) return;
const s = await api("providers?last=1").then((s) => s || api("providers")).catch(() => null);
const key = (l) => JSON.stringify(l?.providers?.filter((p) => p.account).map((p) => [p.id, p.account, p.switchOnly, p.keepLoginAs]));
if (!s || panelAccts === s || key(s) === key(panelAccts)) return;
panelAccts = s;
renderAgents();
}
// agentsLead: above the window's list, what 「接入」 does, said once in a
// line; while no agent is connected, as a welcome, with a way to add a
// provider when magpie has no models to give
@@ -4297,7 +4318,7 @@ async function load(again) {
loadInstalls();
// the Providers page made ready behind the one shown (#1519)
if (mode !== "panel" && !(view === "providers" || providersPage(view))) prefetchProviders();
if (mode === "panel") { renderPanelQuota(true); if (!early) panelQuotasNow(again); }
if (mode === "panel") { renderPanelQuota(true); if (!early) panelQuotasNow(again); panelAccounts(); }
// an open provider editor is someone typing: coming back to the window
// must not rebuild it under them
if ((view === "providers" || providersPage(view)) && !(editing || adding)) await loadProviders();
@@ -14392,6 +14413,7 @@ async function accountAction(path, body, okMsg, confirmed = false, say = (m) =>
"This account or key will stop being used for requests. You will need to add it again to use it.")) return false;
try {
providers = await api(path, body);
if (mode === "panel") panelAccts = providers;
renderProviders();
state = await api("state");
renderAgents();
@@ -15947,19 +15969,11 @@ function renderQuotas(lazy) {
requestAnimationFrame(focusQuotaCard);
}
// A subscription with several accounts shows each of them, one in full —
// the one that answered last, else the first — and the others in brief,
// their bars alone, a click opening one (whqtian on Discord: 只显示一个账号
// 即可,其他的可以点击展开; ARNO, 17 subscriptions and 29 accounts: 以前每个
// 账号所占的空间很小,基本能一页看到所有账号… 关了magpie后又得一个个展开).
// The tray panel, with less room, leaves the ones in brief out. Each
// account's full or brief is remembered by provider and account
// (magpie.usageAccounts), for the window and the panel alike; a provider
// opened before that (magpie.usageOpen) starts with every account in full.
// The accounts the card's button opened are remembered too
// (magpie.usageAcctsOpened), so that its fold puts those back in brief,
// and only those (WuSix on Discord: with both accounts in brief, 展开 opened
// both and 收起其余账号 folded only the second).
// A subscription's accounts: one in full (the last to answer, else the
// first), the others in brief, a click opening one (whqtian, ARNO on
// Discord); the panel leaves the brief out. Remembered per account
// (magpie.usageAccounts; magpie.usageOpen before it), and what the card's
// button opened (magpie.usageAcctsOpened) so its fold folds only those.
let usageOpen, usageAccts, usageByMore;
const usageFolds = () => { usageOpen = new Set(kept("usageOpen", [])); usageAccts = kept("usageAccounts", {}); usageByMore = new Set(kept("usageAcctsOpened", [])); };
usageFolds();
@@ -23619,11 +23633,8 @@ document.fonts?.addEventListener("loadingdone", fitTop);
// ("Work / Library / MCP servers"). Narrower, and magpie web on a phone,
// the pages go back into the header as tabs and each page shows its own
// tabs again, as iPadOS's sidebar turns into a tab bar when it has no room.
// It is the same #nav, its buttons and handlers, moved between the two.
// (app.css's side-nav rules hold at the same width): narrower, the page
// beside it would be narrower than Usage's requests with their columns left
// out (768 points), and the sidebar gives way to the header's tabs, as a Mac
// app's sidebar does in a narrow window
// It is the same #nav, moved between the two. (app.css's side-nav rules
// hold at the same width: narrower than Usage's requests, 768 points)
var SIDE_AT = 1024;
var sideQuery = matchMedia(`(min-width: ${SIDE_AT}px)`);
function sideNav() { return document.body.classList.contains("side-nav"); }
+50
View File
@@ -93,3 +93,53 @@ func TestLastKnownProviders(t *testing.T) {
t.Fatalf("another version's list served: %.200s", b)
}
}
// The tray panel's account switch (shuizhuyu on X) draws the kept list,
// so a change made through a provider or login action is kept at once,
// not only on the next GET /api/providers.
func TestKeptProvidersFollowActions(t *testing.T) {
sandboxHome(t)
forgetLastProviders()
t.Cleanup(forgetLastProviders)
if _, err := provider.Add(provider.Provider{ID: "own", Name: "Own", Chat: "http://127.0.0.1:1/v1", Key: "sk-own", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
srv := Handler(nil, nil)
do := func(method, path, body string) string {
t.Helper()
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%s %s: %d %s", method, path, rec.Code, rec.Body)
}
return rec.Body.String()
}
off := func() bool {
t.Helper()
var l struct {
Last bool `json:"last"`
Providers []struct {
ID string `json:"id"`
Off bool `json:"off"`
} `json:"providers"`
}
if err := json.Unmarshal([]byte(do("GET", "/api/providers?last=1", "")), &l); err != nil || !l.Last {
t.Fatalf("kept list: %+v %v", l, err)
}
for _, p := range l.Providers {
if p.ID == "own" {
return p.Off
}
}
t.Fatal("own is not in the kept list")
return false
}
do("GET", "/api/providers", "")
if off() {
t.Fatal("own kept as off before it was switched off")
}
do("POST", "/api/provider/off", `{"id":"own"}`)
if !off() {
t.Error("the kept list still has own on after it was switched off")
}
}
+4
View File
@@ -2121,6 +2121,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
st := providersState()
st.Moved = moved
writeJSON(rw, st)
// the tray panel's account switch draws the kept list: a change
// made here is in it at once
keepProviders(st)
})
// How much of its allowance each of an agent's accounts has used.
mux.HandleFunc("GET /api/login/usage", func(rw http.ResponseWriter, r *http.Request) {
@@ -2161,6 +2164,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
st := providersState()
st.Moved = moved
writeJSON(rw, st)
keepProviders(st) // as a provider action's: the panel's switch draws it
})
// Codex's background app-server, left on the account before a switch
// or on the model list before a change (the Agents row's Restart):
@@ -0,0 +1,195 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The tray panel switches accounts too (shuizhuyu on X: a global shortcut
// to switch accounts). The quick panel's shortcut opens it, and a Claude
// Code or Codex not connected has an Account line in its opened row, the
// account it is signed in to, whose menu signs it in to another, as the
// window's Agents row does (Switch accounts only). The line is drawn from
// the list kept from the last read (/api/providers?last=1, no sign-in
// read): the panel asks no fresh list until the menu is opened, and then
// opens it on what that read says. Nothing kept: one fresh read. A
// connected agent has no line; Manage accounts… opens the window's
// Providers. In every language, at two panel widths, Chromium and WebKit.
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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));
const own = [{ value: "sonnet", label: "Sonnet" }];
const agents = (claudeWired) => [
{ id: "claude", name: "Claude Code", icon: "generic", path: "/fixture/claude", source: "sub", wired: claudeWired, fields: [{ key: "model", label: "model", value: "sonnet", options: own }] },
{ id: "codex", name: "Codex", icon: "generic", path: "/fixture/codex", source: "chatgpt", fields: [{ key: "model", label: "model", value: "gpt-5.5", options: [{ value: "gpt-5.5", label: "gpt-5.5" }] }] },
];
function providersOf(active, last) {
const claude = {
id: "claude", name: "Claude Code", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "smart",
models: [], agents: [], fallback: [], headers: {}, keyList: [],
account: {
agent: "claude", agentName: "Claude Code", user: active, plan: "max",
logins: ["work@example.com", "home@example.com"].map((user) => ({ user, plan: user === "work@example.com" ? "max" : "pro", active: user === active, on: true })),
},
};
const codex = {
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "smart",
models: [], agents: [], fallback: [], headers: {}, keyList: [],
account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] },
};
return { ...(last ? { last: true } : {}), providers: [claude, codex], presets: [], excluded: [], gateway: { running: true, window: true } };
}
// w: { kept (the active account in the kept list, or null for none kept),
// active (the account a fresh read says), wired }
function server(lang, w, log) {
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({ agents: agents(!!w.wired), profiles: [], settings: { lang, theme: "light", guideHidden: true } });
if (url.pathname === "/api/agents/cli" && req.method() === "GET") return json({ agents: {}, pending: false });
if (url.pathname === "/api/agents/install") return json([]);
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/providers" && req.method() === "GET") {
if (url.searchParams.get("last") === "1") {
log.push("kept");
return json(w.kept ? providersOf(w.kept, true) : null);
}
log.push("fresh");
return json(providersOf(w.active));
}
if (req.method() === "POST" && ["/api/login/switch", "/api/window/main"].includes(url.pathname)) {
log.push(url.pathname + url.search + " " + (req.postData() || ""));
if (url.pathname === "/api/login/switch") {
w.active = w.kept = req.postDataJSON().user;
return json(providersOf(w.active));
}
return route.fulfill({ status: 204 });
}
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 K = {
account: "account",
head: "Switch accounts only",
manage: "Manage accounts…",
only: "Only switch {agent}'s sign-in",
switched: "Switched",
said: "{agent} is now signed in as {user}. New {agent} sessions use this account; one already open keeps its account until it is started again.",
};
const row = (id) => `.row.agent[data-id="${id}"]`;
async function open(browser, lang, width, w) {
const page = await (await browser.newContext({ viewport: { width, height: 640 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [], log = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, w, log));
await page.goto("http://magpie.test/?mode=panel");
await page.locator(`${row("claude")} .ag-sum`).waitFor();
const tr = async (k, vars = {}) => {
const s = await page.evaluate(([k, lang]) => (lang === "en" ? k : I18N[lang]?.[k]), [k, lang]);
assert.ok(s, `${lang} has ${k.slice(0, 40)}`);
return Object.entries(vars).reduce((s, [k, v]) => s.replaceAll(`{${k}}`, v), s);
};
return { page, errors, log, tr };
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the tray panel switches a Claude Code's account", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [440, 360]) {
await t.test(`${lang} ${width}px`, async () => {
// kept: work; signed in to home since (in a terminal)
const w = { kept: "work@example.com", active: "home@example.com" };
const { page, errors, log, tr } = await open(browser, lang, width, w);
const cc = { agent: "Claude Code" };
for (const k of Object.values(K)) await tr(k);
await page.locator(`${row("claude")} .ag-sum`).click();
const who = page.locator(`${row("claude")} .ag-open button.field.ag-who`);
await who.waitFor({ state: "visible" });
assert.equal(await who.locator(".k").textContent(), await tr(K.account));
assert.equal(await who.locator(".v").textContent(), "work@example.com");
// drawn from the kept list: no fresh read yet
assert.ok(log.includes("kept"), "the kept list is read");
assert.ok(!log.includes("fresh"), `a fresh list read before the menu was asked for: ${log}`);
const box = await who.boundingBox();
assert.ok(box && box.x >= 0 && box.x + box.width <= width, `button off the panel: ${JSON.stringify(box)}`);
// opened, the menu is the fresh read's
await who.click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.deepEqual(log.filter((x) => x === "fresh"), ["fresh"]);
assert.equal(await menu.locator(".pm-head").textContent(), await tr(K.head));
const items = menu.locator(".pm-item .pm-name");
assert.deepEqual(await items.allTextContents(), ["home@example.com", "work@example.com", await tr(K.only, cc), await tr(K.manage)]);
assert.equal(await menu.locator(".pm-item.on .pm-name").allTextContents().then((x) => x.join()), "home@example.com");
assert.equal(await page.locator(`${row("claude")} .ag-who .v`).textContent(), "home@example.com");
const mb = await menu.boundingBox();
assert.ok(mb.x >= 0 && mb.x + mb.width <= width, `menu off the panel: ${JSON.stringify(mb)}`);
await menu.locator(".pm-item", { hasText: "work@example.com" }).click();
await page.waitForFunction(() => document.querySelector('.row.agent[data-id="claude"] .ag-who .v')?.textContent === "work@example.com");
assert.ok(log.some((x) => x.startsWith("/api/login/switch") && x.includes('"user":"work@example.com"')), `no switch posted: ${log}`);
const now = page.locator(`${row("claude")} .ag-who`);
assert.ok(await now.locator(".ok").isVisible(), "Switched shows on the line");
assert.equal((await now.locator(".ok").textContent()).trim(), await tr(K.switched));
assert.equal(await page.locator("#status").textContent(), await tr(K.said, { ...cc, user: "work@example.com" }));
if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `panel-switch-${engine}-${lang}-${width}.png`) });
// the row stays open, the line in it
assert.equal(await page.locator(row("claude")).getAttribute("aria-expanded"), "true");
// Manage accounts… opens the window's Providers
await now.click();
await menu.waitFor();
await menu.locator(".pm-item", { hasText: await tr(K.manage) }).click();
for (let i = 0; i < 100 && !log.some((x) => x.startsWith("/api/window/main")); i++) await page.waitForTimeout(20);
assert.ok(log.some((x) => x.startsWith("/api/window/main?view=providers")), `Manage accounts… didn't open the window: ${log}`);
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth + 1), "the panel scrolls sideways");
assert.deepEqual(errors, []);
await page.context().close();
});
}
}
});
test(engine + ": nothing kept, the panel reads the list once; a connected Claude Code has no line", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const w = { kept: null, active: "work@example.com" };
const { page, errors, log } = await open(browser, "en", 440, w);
await page.locator(`${row("claude")} .ag-sum`).click();
const who = page.locator(`${row("claude")} .ag-open .ag-who`);
await who.waitFor({ state: "visible" });
assert.equal(await who.locator(".v").textContent(), "work@example.com");
assert.deepEqual(log.filter((x) => x === "fresh"), ["fresh"]);
// a fresh list in hand: the menu opens on it, no second read
await who.click();
await page.locator(".proto-menu").waitFor();
assert.deepEqual(log.filter((x) => x === "fresh"), ["fresh"]);
await page.keyboard.press("Escape");
// Codex, one account: its line says it
await page.locator(`${row("codex")} .ag-sum`).click();
await page.locator(`${row("codex")} .ag-open .ag-who .v`, { hasText: "me@example.com" }).waitFor({ state: "visible" });
assert.deepEqual(errors, []);
await page.context().close();
const c = await open(browser, "en", 440, { kept: "work@example.com", active: "work@example.com", wired: true });
await c.page.locator(`${row("claude")} .ag-sum`).click();
await c.page.locator(`${row("claude")}.open`).waitFor();
await c.page.locator(`${row("codex")} .ag-open .ag-who`).waitFor({ state: "attached" });
assert.equal(await c.page.locator(`${row("claude")} .ag-who`).count(), 0, "a connected Claude Code has an account line");
assert.deepEqual(c.errors, []);
await c.page.context().close();
});
}