gui: the tray panel's Usage tab puts a vendor's account first from its count (RealZeroP27 on X)

RealZeroP27 asked to switch the Codex account in use from the menu bar
panel's quota page, not from the Providers page.

A vendor group with several accounts on the panel's Usage tab now draws
its count as a button (the count and a chevron). It opens the app menu
(openProtoMenu) with the accounts the provider editor can put first, the
first one ticked, and Manage accounts… at the foot, which opens the
window's Providers page. Picking one does what the editor's Make first
or Use does, through the same code: putFirst, now shared by the editor
and the panel. Kept signed in to one, that is provider/arrange with the
account first in the order; otherwise login/switch. The first account's
card gets a small tick. It works for any subscription with several
signed-in accounts (Codex, Claude, a plugin's), not only Codex.
Setup-token, access-only and lapsed accounts are left out, as in the
editor; kept signed in, so are paused or off ones. A vendor with one
account that can be first keeps its plain count.

The panel's provider list (panelAccts) is now also read when the Usage
tab has two accounts of one vendor, one read at a time. The menu reads
a fresh list first when only the kept one is drawn. pluginSubs falls
back to that list, since the panel has no window list (it threw on
null before).

Budget: the menu is in panelfirst.js, loaded when the count is pressed,
and the Allowances tab's arranging (panelArrange, hidePanelUsage) moved
out to panelarrange.js, loaded when Arrange is pressed. That pays for
the rest with no comments cut and no raise (#5918); the core is at
1,533,604 of 1,533,802. old-webkit's lazy list names both files.

Run (mote, at this change on origin/main 662546e78; rebased after onto
55b0d7c24, which changes only internal/gateway):
- GUI, chromium and webkit: panel-usage-first-account (5 languages x
  440/360px), panel-switch-accounts, panel-arrange, grip-inset,
  old-webkit, i18n-keys: 227 ok, 1 red: old-webkit's "the styles hold
  up in Safari 15.0" on main's .side-foot:has() from d374168d0, filed
  as #5919, the same at main.
- go test -run Budget ./internal/gui/ at this head: ok. The whole
  package before the rebase: the only red is
  TestGatewayModeStatsNameTheGatewaySessions, run at 00:22 local, which
  is #5690 (red in the first hour of a local day), untouched here.
- go vet ./internal/gui for darwin, GOOS=linux -tags nogui, GOOS=windows:
  ok. gofmt -l: clean.
- Before the rebase, 21 GUI files were run at this change and at main
  6a253f8af; the reds they share are the same on main under load. The
  two head-only reds (panel-switch-accounts' "reads the list once", a
  null box while the group redrew) were fixed here.

Broken by hand:
- The new test is red on origin/main's assets (no .pq-pick).
- putFirst with the kept branch turned off sends login/switch in the
  kept case: the kept test goes red.
- Dropping !l.accessOnly puts the access-only account in the menu: the
  menu's list check goes red.

Not tried: the whole GUI suite, a real account switch from the real
panel, the real Linux (WebKitGTK) app.
This commit is contained in:
yetone
2026-11-10 16:37:19 +08:00
parent 55b0d7c24e
commit 286e3b6d5f
7 changed files with 416 additions and 104 deletions
+7
View File
@@ -2030,6 +2030,13 @@ body.panel .profiles #save { height: 25px; } /* the field's: the line keeps its
.pq-gn { flex: 0 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* how many accounts: a quiet count set by the name, on its cap height */
.pq-count { flex: none; min-width: 16px; height: 15px; padding: 0 5px; box-sizing: border-box; border-radius: 999px; display: inline-grid; place-items: center; background: color-mix(in srgb, var(--fg) 7%, transparent); color: var(--muted); font-size: 9.5px; font-weight: 600; line-height: 1; letter-spacing: 0; font-variant-numeric: tabular-nums; }
/* with a vendor's accounts to put first: the count opens their menu */
.pq-pick { height: 17px; gap: 1px; padding: 0 3px 0 6px; display: inline-flex; align-items: center; cursor: default; transition: background .12s ease, color .12s ease, transform .12s cubic-bezier(.23, 1, .32, 1); }
.pq-pick svg { flex: none; opacity: .8; }
.pq-pick:is(:hover, .open) { background: color-mix(in srgb, var(--fg) 12%, transparent); color: var(--fg); }
.pq-pick:active { transform: scale(.97); }
/* the account used first: ticked before its name */
.pq-first { flex: none; display: inline-grid; place-items: center; width: 12px; height: 12px; margin-right: 3px; color: var(--accent); }
.pq-gnote { flex: none; margin-left: auto; font-size: 12px; font-weight: 400; letter-spacing: 0; text-transform: none; font-variant-numeric: tabular-nums; }
.pq-gnote.ends { color: var(--amber); }
/* used or left: a quiet pill at the right, over the rings; lit a moment
+84 -101
View File
@@ -1618,7 +1618,6 @@ function switchEntry(a) {
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(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);
@@ -1663,14 +1662,21 @@ async function switchAccountTo(a, p, user) {
renderAgents();
}
// the panel's list for it: the kept one, a fresh read only with none kept
// the panel's list for it and the Usage tab's: the kept one, a fresh read
// only with none kept, one read at a time
async function panelAccounts() {
if (!state.agents.some(switchesAccounts)) return;
const s = await api("providers?last=1").then((s) => s || api("providers")).catch(() => null);
if (!state.agents.some(switchesAccounts) && !panelSeveral()) return;
const s = await (panelAccounts.p ||= api("providers?last=1").then((s) => s || api("providers")).catch(() => null).finally(() => panelAccounts.p = 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();
renderPanelQuota(true);
}
function panelSeveral() {
const seen = new Set();
return (quotas || []).some((q) => q.user && !q.balance && (seen.has(q.provider) || !seen.add(q.provider)));
}
// agentsLead: above the window's list, what 「接入」 does, said once in a
@@ -12476,7 +12482,7 @@ function pluginMethod(sub, site) {
// Plugins), as subscriptions like the built-in ones. The plugin, not
// magpie, signs in and carries the requests.
function pluginSubs() {
return (providers.plugins || []).map((x) => ({
return ((providers || panelAccts)?.plugins || []).map((x) => ({
agent: x.id, pid: x.pid, name: x.name, icon: x.icon, plugin: x, own: true, single: !!x.single,
get plans() { return t("from the plugin {spec}", { spec: x.spec }); },
}));
@@ -12914,7 +12920,6 @@ function signInProxyLink(sub) {
// the whole address too, which a narrow sheet cuts short
b.title = proxyName(signing.proxy) + "\n" + t("The sign-in goes through this proxy, as the account's requests will. One picked here is kept as the account's.");
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
b.onclick = (e) => {
e.stopPropagation();
const flow = signing;
@@ -13353,6 +13358,29 @@ function loginsInOrder(a, p) {
return ls.sort((x, y) => (y.active ? 1 : 0) - (x.active ? 1 : 0));
}
// the editor's First, and its Make first or Use (putFirst), which the
// panel's Usage tab shares
function firstLogin(a, p) {
const ls = loginsInOrder(a, p);
return keptLogin(p) ? ls.find((l) => (l.active || l.on) && !l.paused && !l.lapsed)?.user : ls.find((l) => l.active)?.user;
}
function byQuotaOf(p, r = p?.routing || "") {
return p?.account && ["", "usage", "pace"].includes(r) ? ROUTINGS.find(([id]) => id === r)?.[1] : "";
}
function firstNoteOf(p, user) {
return t("{user} is first in the order; {routing} still goes by each account's quota, so the order only settles ties. In order uses the first first.", { user, routing: t(byQuotaOf(p)) });
}
function putFirst(a, p, l) {
const sub = subOf(a.agent), byQuota = byQuotaOf(p), on = !l.paused && (l.active || l.on);
if (keptLogin(p)) {
const ls = loginsInOrder(a, p);
return accountAction("provider/arrange", { id: p.id, accountOrder: [l.user, ...ls.filter((x) => x !== l).map((x) => x.user)] }, byQuota ? firstNoteOf(p, l.user) : t("The gateway now uses {user} first", { user: l.user }));
}
return accountAction("login/switch", { agent: a.agent, user: l.user }, on && byQuota ? (sub?.own ? "" : t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user }) + " ") + firstNoteOf(p, l.user) : sub?.own ? t("The gateway now uses {user} first", { user: l.user }) : t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user }));
}
function renderAccounts(a, p) {
const sub = subOf(a.agent);
const list = el("div", "accts");
@@ -13369,13 +13397,12 @@ function renderAccounts(a, p) {
const isOn = (l) => !unusable(l) && !l.paused && (l.active || l.on), wOf = (l) => Math.max(p?.accountWeights?.[String(l.user).toLowerCase()] || 0, 1), weights = ls.filter(isOn).reduce((n, l) => n + wOf(l), 0);
// kept signed in to one (#524): the first is the order's
const kept = keptLogin(p);
const firstUser = kept ? ls.find((l) => (l.active || l.on) && !l.paused && !l.lapsed)?.user : ls.find((l) => l.active)?.user;
const byQuota = p?.account && ["", "usage", "pace"].includes(p?.routing || "") ? ROUTINGS.find(([id]) => id === (p?.routing || ""))?.[1] : "";
const firstNote = (user) => t("{user} is first in the order; {routing} still goes by each account's quota, so the order only settles ties. In order uses the first first.", { user, routing: t(byQuota) });
const firstUser = firstLogin(a, p);
const byQuota = byQuotaOf(p);
const makeFirst = (l) => {
const b = el("button", "text", t("Make first"));
b.title = byQuota ? firstNote(l.user) : t("The gateway uses this account first; {agent} stays signed in to {user}", { agent: a.agentName, user: kept });
b.onclick = () => { b.classList.add("busy"); accountAction("provider/arrange", { id: p.id, accountOrder: [l.user, ...ls.filter((x) => x !== l).map((x) => x.user)] }, byQuota ? firstNote(l.user) : t("The gateway now uses {user} first", { user: l.user })); };
b.title = byQuota ? firstNoteOf(p, l.user) : t("The gateway uses this account first; {agent} stays signed in to {user}", { agent: a.agentName, user: kept });
b.onclick = () => { b.classList.add("busy"); putFirst(a, p, l); };
return b;
};
// pausable while another is on (#263)
@@ -13513,8 +13540,8 @@ function renderAccounts(a, p) {
line.append(forget, only);
} else {
const use = el("button", "text", on ? t("Make first") : t("Use"));
use.title = on && byQuota ? firstNote(l.user) : sub?.own ? t("The gateway uses this account first") : t("Sign {agent} in to this account", { agent: a.agentName });
use.onclick = () => { use.classList.add("busy"); accountAction("login/switch", { agent: a.agent, user: l.user }, on && byQuota ? (sub?.own ? "" : t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user }) + " ") + firstNote(l.user) : sub?.own ? t("The gateway now uses {user} first", { user: l.user }) : t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user })); };
use.title = on && byQuota ? firstNoteOf(p, l.user) : sub?.own ? t("The gateway uses this account first") : t("Sign {agent} in to this account", { agent: a.agentName });
use.onclick = () => { use.classList.add("busy"); putFirst(a, p, l); };
line.append(forget, use);
}
}
@@ -14278,7 +14305,6 @@ function windowCapMeter(m, p, user, w) {
: own ? t("{window} has a cap of its own: magpie counts this account as used up once {window} is at {n}%, until it renews. Click to change", { window: name, n: own })
: t("Click to give {window} a cap of its own, apart from this account's", { window: name })].filter(Boolean).join("\n");
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
const set = (v) => accountAction("provider/windowcap", { id: p.id, account: user, window: w.capId, ...w.tiers && { windows: ids }, cap: v },
v === 0 && !w.ownCap ? t("{window} of {who} follows the account's cap", { window: name, who: user })
: !(v % 100) ? t("{window} of {who} has no cap", { window: name, who: user })
@@ -15891,6 +15917,7 @@ function loadQuotas(asked, again) {
if (!same) renderQuotas(true);
if (view === "usage") loadUpstream();
if (reading && !quotasLater && ++quotasTries <= 20) quotasLater = setTimeout(() => { quotasLater = 0; loadQuotas(false, true); }, 1500);
if (mode === "panel" && state?.agents && !panelAccts) panelAccounts();
});
p.asked = asked;
quotasLoading = p;
@@ -17483,7 +17510,7 @@ function renderPanelUse() {
function renderPanelQuota(lazy) {
const box = $("#panelQuota");
if (mode !== "panel" || !box) return;
const drawn = JSON.stringify([quotas, quotaHistV, quotaLeft, quotaRange, [...panelOptsFolded], state?.settings, locale, panelTab, panelPeek, panelArranging, panelZeroOpen, usageArranging, Math.floor(Date.now() / 60e3)]);
const drawn = JSON.stringify([quotas, quotaHistV, quotaLeft, quotaRange, [...panelOptsFolded], state?.settings, locale, panelTab, panelPeek, panelArranging, panelZeroOpen, usageArranging, panelAcctsKey(), Math.floor(Date.now() / 60e3)]);
if (lazy && renderPanelQuota.drawn === drawn) return;
renderPanelQuota.drawn = drawn;
const subs = byUsageOrder(keyCards(quotas || []).filter((q) => q.balance || q.error || q.windows?.length));
@@ -17515,7 +17542,7 @@ function renderPanelQuota(lazy) {
fit();
return;
}
if (panelArranging) {
if (panelArranging && window.panelArrange) {
box.append(panelArrange(subs));
if (view && view.scrollTop !== keep) view.scrollTop = keep;
fit();
@@ -17550,11 +17577,14 @@ function renderPanelQuota(lazy) {
const { name, qs } = part;
if (qs.every((q) => zero.has(q)) && (atZero += qs.length) && !panelZeroOpen) continue;
const g = el("div", "pq-group");
g.dataset.provider = qs[0].provider;
const head = el("div", "pq-gh");
head.append(icon(qs[0].icon), el("span", "pq-gn", name));
// several accounts: how many, a quiet count by the name; one: its plan
// and until when, at the right
if (qs.length > 1) {
// several accounts: how many, a quiet count by the name, which puts one
// first; one: its plan and until when, at the right
const first = qs.length > 1 && panelFirstOf(qs);
if (first) head.append(panelFirstMenu(qs, first));
else if (qs.length > 1) {
const n = el("span", "pq-count", String(qs.length));
n.title = t("{n} accounts", { n: qs.length });
head.append(n);
@@ -17576,7 +17606,7 @@ function renderPanelQuota(lazy) {
// the accounts in full; none of them, the one in sight; folded, none
const shut = all && quotaAllFolded(qs[0].provider);
const full = qs.length > 1 ? qs.filter((q) => usageAcctOpen(q, qs)) : qs;
if (!shut) for (const q of full.length ? full : [usageShown(qs)]) g.append(panelQuotaCard(q));
if (!shut) for (const q of full.length ? full : [usageShown(qs)]) g.append(panelQuotaCard(q, first && sameUser(q.user, first.user)));
if (qs.length > 1 && !shut) g.append(usageMore(qs, "pq-more"));
box.append(g);
}
@@ -17585,7 +17615,7 @@ function renderPanelQuota(lazy) {
const arrange = el("button", "pq-more pq-arrange", t("Arrange"));
arrange.type = "button";
arrange.title = t("Choose which subscriptions this tab shows, and their order");
arrange.onclick = () => { panelArranging = true; panelPeek = ""; renderPanelQuota(); $("#panelQuota .pq-arow .pq-ahandle")?.focus(NO_SCROLL); };
arrange.onclick = () => import("./panelarrange.js").then(() => { panelArranging = true; panelPeek = ""; renderPanelQuota(); $("#panelQuota .pq-arow .pq-ahandle")?.focus(NO_SCROLL); }, statusErr);
foot.append(arrange);
if (atZero) {
const z = el("button", "pq-more pq-zero", panelZeroOpen ? t("Fold the ones at 0") : t("{n} at 0", { n: atZero }));
@@ -17605,6 +17635,31 @@ function renderPanelQuota(lazy) {
requestAnimationFrame(focusQuotaCard);
}
// a vendor's count on the panel's Usage tab puts an account first
// (RealZeroP27 on X); its menu is panelfirst.js
const sameUser = (a, b) => !!a && !!b && String(a).toLowerCase() === String(b).toLowerCase();
function panelAcctsKey() {
return panelAccts?.providers?.map((p) => p.account?.logins?.length > 1 && [p.id, p.routing, p.keepLogin, p.keepLoginAs, p.account.logins]);
}
function panelFirstOf(qs) {
const p = panelAccts?.providers?.find((x) => x.id === qs[0].provider && x.account?.logins?.length > 1);
if (!p) return null;
const a = p.account, kept = keptLogin(p), user = firstLogin(a, p);
const can = loginsInOrder(a, p).filter((l) => !l.token && !l.accessOnly && !l.lapsed && (!kept || (!l.paused && (l.active || l.on))));
return can.length > 1 && can.some((l) => l.user !== user) ? { p, a, user, can } : null;
}
function panelFirstMenu(qs, f) {
const b = el("button", "pq-count pq-pick");
b.type = "button";
b.title = t("{n} accounts", { n: qs.length });
b.setAttribute("aria-label", b.title);
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
b.append(el("span", "", String(qs.length)), svg(CHEV, 9, 1.8));
b.onclick = (e) => { e.stopPropagation(); if (b.classList.contains("open")) return closeProtoMenu(); import("./panelfirst.js").then(() => panelFirstOpen(b, qs, f), statusErr); };
return b;
}
// panelBalances is a run of balances on the Allowances tab, under their
// heading, as figures side by side.
function panelBalances(bals) {
@@ -17653,81 +17708,6 @@ function panelBalances(bals) {
return g;
}
// The Allowances tab's arranging (H20 on Discord): a row a subscription,
// in the order the Usage page's cards have, its logo the handle to move it
// (drag, or Alt+arrows) and a pill to hide it from this tab or show it
// again. Hiding is the panel's alone; routing and the rest still use it.
function panelArrange(subs) {
const g = el("div", "pq-group pq-arranging");
const head = el("div", "pq-gh");
head.append(el("span", "pq-gn", t("Arrange")));
const done = el("button", "pq-mode pq-done", t("Done"));
done.type = "button";
done.onclick = () => { panelArranging = false; renderPanelQuota(); };
head.append(done);
g.append(head, el("p", "pq-anote", t("Hiding is for this panel only: routing, the Usage page and the menu bar still use what's hidden. The order is the Usage page's too.")));
const hidden = new Set(state.settings?.panelUsageHidden || []);
const list = el("div", "pq-alist");
const seen = new Set();
for (const q of subs) {
if (seen.has(q.provider)) continue;
seen.add(q.provider);
const off = hidden.has(q.provider);
const row = el("div", "pq-arow" + (off ? " put-away" : ""));
row.dataset.key = q.provider;
const h = el("button", "ag-handle pq-ahandle");
h.type = "button";
h.setAttribute("aria-label", t("Arrange {agent}", { agent: q.name }));
h.title = t("Drag to reorder · Alt+arrow keys to move");
h.append(icon(q.icon || "generic"));
h.onkeydown = (e) => {
const step = { ArrowUp: -1, ArrowLeft: -1, ArrowDown: 1, ArrowRight: 1 }[e.key];
if (!e.altKey || !step) return;
e.preventDefault();
moveUsage(q.provider, usageKeys().indexOf(q.provider) + step);
$(`#panelQuota .pq-arow[data-key="${CSS.escape(q.provider)}"] .pq-ahandle`)?.focus(NO_SCROLL);
};
h.onpointerdown = (e) => {
if (usageArranging) return;
usageArranging = dragCards(e, h, row, list, [...list.children], (to) => moveUsage(q.provider, to), () => {
usageArranging = false;
if (usageRenderPending) { usageRenderPending = false; renderQuotas(); }
});
};
const pill = el("button", "pq-more pq-show", t(off ? "Show" : "Hide"));
pill.type = "button";
pill.setAttribute("aria-pressed", String(!off));
pill.title = t(off ? "Show {name} in this panel" : "Hide {name} from this panel", { name: q.name });
pill.onclick = () => hidePanelUsage(q.provider, !off);
row.append(h, el("span", "pq-aname", q.name), off ? el("span", "pq-hidden", t("Hidden")) : "", pill);
list.append(row);
}
g.append(list);
return g;
}
// hidePanelUsage hides a subscription from the panel's Allowances tab, or
// shows it again: drawn at once, put back if the save fails.
async function hidePanelUsage(key, hide) {
const prev = state.settings;
const cur = (prev.panelUsageHidden || []).filter((k) => k !== key);
const panelHidden = hide ? [...cur, key] : cur;
state.settings = { ...prev, panelUsageHidden: panelHidden };
const again = () => {
renderPanelQuota();
$(`#panelQuota .pq-arow[data-key="${CSS.escape(key)}"] .pq-show`)?.focus(NO_SCROLL);
};
again();
try {
const s = await api("usage/arrange", { panelHidden });
state.settings = { ...state.settings, panelUsageHidden: s.panelUsageHidden || [] };
} catch (e) {
state.settings = prev;
again();
statusErr(e);
}
}
// asOfText dates a cached allowance and distinguishes a deliberate skip
// from a failed read (such as the vendor rate limiting its usage endpoint).
function asOfText(q, short = false) {
@@ -17743,7 +17723,7 @@ function shortWindow(name) {
return m ? m[1] + { minute: "m", hour: "h", day: "d", week: "w", month: "mo" }[m[2].toLowerCase()] : t(name);
}
function panelQuotaCard(q) {
function panelQuotaCard(q, first = false) {
const card = el("div", "pq-card");
card.dataset.card = trayCardID(q);
if (q.balanceCard) card.dataset.balCard = q.balanceCard;
@@ -17751,6 +17731,13 @@ function panelQuotaCard(q) {
// in for (#1515), before the account itself
// and its eye while Hide accounts is on, as on the Usage page (yogurt36)
const who = el("span", "pq-who");
if (first) {
const tick = el("span", "pq-first");
tick.append(svg(CHECK, 10, 2.2));
tick.title = t("First");
who.append(tick);
card.classList.add("first");
}
who.append(el("span", "pq-user" + (q.alias && q.named ? " own-name" : ""), q.alias || q.user || q.name));
if ((q.user || q.alias) && window.hideAccounts) who.append(hideAccounts.eye(q.user || q.alias, q.provider));
card.append(who);
@@ -21650,7 +21637,6 @@ function sideEffortChip(val, levels, saved, now, cls, dflt, save) {
const b = el("button", "rt-cond on side-effort " + cls);
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
const shown = saved ? now || saved : "";
b.setAttribute("aria-label", t("Thinking") + ": " + (shown ? t(shown) : t("Default")));
b.title = t("How hard this model thinks");
@@ -21679,7 +21665,6 @@ function replyModelRow(s, keep) {
b.type = "button";
b.title = n;
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
b.append(el("span", "", t(cur[1])), svg(CHEV, 11, 1.6));
b.onclick = (e) => {
e.stopPropagation();
@@ -21989,7 +21974,6 @@ function pmPick(m, pick) {
const b = el("button", "sess-pick pm-model");
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
b.title = t("The local model");
b.append(el("span", "", (PM_MODELS[m.model] || [m.model])[0]), svg(CHEV, 11, 1.6));
b.onclick = (e) => {
@@ -22009,7 +21993,6 @@ function pmScore(m, pick) {
const b = el("button", "sess-pick pm-score");
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
b.title = t("Confidence threshold");
b.append(el("span", "", String(m.minScore)), svg(CHEV, 11, 1.6));
b.onclick = (e) => {
+77
View File
@@ -0,0 +1,77 @@
// The tray panel's arranging of its Allowances tab, loaded when Arrange is
// pressed (app.js's arrange button), so it weighs nothing on the core.
// The Allowances tab's arranging (H20 on Discord): a row a subscription,
// in the order the Usage page's cards have, its logo the handle to move it
// (drag, or Alt+arrows) and a pill to hide it from this tab or show it
// again. Hiding is the panel's alone; routing and the rest still use it.
window.panelArrange = function panelArrange(subs) {
const g = el("div", "pq-group pq-arranging");
const head = el("div", "pq-gh");
head.append(el("span", "pq-gn", t("Arrange")));
const done = el("button", "pq-mode pq-done", t("Done"));
done.type = "button";
done.onclick = () => { panelArranging = false; renderPanelQuota(); };
head.append(done);
g.append(head, el("p", "pq-anote", t("Hiding is for this panel only: routing, the Usage page and the menu bar still use what's hidden. The order is the Usage page's too.")));
const hidden = new Set(state.settings?.panelUsageHidden || []);
const list = el("div", "pq-alist");
const seen = new Set();
for (const q of subs) {
if (seen.has(q.provider)) continue;
seen.add(q.provider);
const off = hidden.has(q.provider);
const row = el("div", "pq-arow" + (off ? " put-away" : ""));
row.dataset.key = q.provider;
const h = el("button", "ag-handle pq-ahandle");
h.type = "button";
h.setAttribute("aria-label", t("Arrange {agent}", { agent: q.name }));
h.title = t("Drag to reorder · Alt+arrow keys to move");
h.append(icon(q.icon || "generic"));
h.onkeydown = (e) => {
const step = { ArrowUp: -1, ArrowLeft: -1, ArrowDown: 1, ArrowRight: 1 }[e.key];
if (!e.altKey || !step) return;
e.preventDefault();
moveUsage(q.provider, usageKeys().indexOf(q.provider) + step);
$(`#panelQuota .pq-arow[data-key="${CSS.escape(q.provider)}"] .pq-ahandle`)?.focus(NO_SCROLL);
};
h.onpointerdown = (e) => {
if (usageArranging) return;
usageArranging = dragCards(e, h, row, list, [...list.children], (to) => moveUsage(q.provider, to), () => {
usageArranging = false;
if (usageRenderPending) { usageRenderPending = false; renderQuotas(); }
});
};
const pill = el("button", "pq-more pq-show", t(off ? "Show" : "Hide"));
pill.type = "button";
pill.setAttribute("aria-pressed", String(!off));
pill.title = t(off ? "Show {name} in this panel" : "Hide {name} from this panel", { name: q.name });
pill.onclick = () => hidePanelUsage(q.provider, !off);
row.append(h, el("span", "pq-aname", q.name), off ? el("span", "pq-hidden", t("Hidden")) : "", pill);
list.append(row);
}
g.append(list);
return g;
};
// hidePanelUsage hides a subscription from the panel's Allowances tab, or
// shows it again: drawn at once, put back if the save fails.
async function hidePanelUsage(key, hide) {
const prev = state.settings;
const cur = (prev.panelUsageHidden || []).filter((k) => k !== key);
const panelHidden = hide ? [...cur, key] : cur;
state.settings = { ...prev, panelUsageHidden: panelHidden };
const again = () => {
renderPanelQuota();
$(`#panelQuota .pq-arow[data-key="${CSS.escape(key)}"] .pq-show`)?.focus(NO_SCROLL);
};
again();
try {
const s = await api("usage/arrange", { panelHidden });
state.settings = { ...state.settings, panelUsageHidden: s.panelUsageHidden || [] };
} catch (e) {
state.settings = prev;
again();
statusErr(e);
}
}
+26
View File
@@ -0,0 +1,26 @@
// The tray panel's Usage tab puts a vendor's account first (RealZeroP27
// on X: switch Codex's account there, not on the Providers page). app.js
// draws the vendor's count as a button (panelFirstMenu) and imports this
// when it is pressed, so the menu weighs nothing on the core. The menu
// lists the accounts the provider editor can put first, the first
// ticked; a pick does what the editor's Make first or Use does
// (putFirst), and Manage accounts… opens the window's Providers.
window.panelFirstOpen = async function open(b, qs, f) {
// the kept list drew it: the menu waits for a fresh read, as the
// Agents row's account menu does (switchEntry)
const s = panelAccts?.last && await api("providers").catch(() => null);
if (s) {
panelAccts = s;
renderAgents();
renderPanelQuota(true);
const again = [...document.querySelectorAll("#panelQuota .pq-pick")].find((x) => x.closest(".pq-group")?.dataset.provider === qs[0].provider);
return again?.click();
}
const opts = f.can.map((l) => ({ v: "u:" + l.user, name: l.user, literalName: true, note: accountPlan({ agent: f.a.agent, builtin: f.a.builtin, plan: l.plan }) }));
opts.push({ v: "manage", name: "Manage accounts…", note: "" });
openProtoMenu(b, opts, "u:" + (f.user || ""), (v) => {
const l = f.can.find((x) => "u:" + x.user === v);
if (v === "manage") api("window/main?view=providers", {}).catch(statusErr);
else if (l && l.user !== f.user) putFirst(f.a, f.p, l).then(() => renderPanelQuota(true));
}, "Use first", "sess-menu", "left");
};
File diff suppressed because one or more lines are too long
+4 -2
View File
@@ -163,10 +163,12 @@ test("compat.js is the first of the page's own scripts", async () => {
// balance, modellimits.js when it draws a model's row, notices.js when
// About's Open-source licenses opens, videogen.js when Settings draws
// Image generation, provlinks.js when Settings' search first wants its
// provider links, pageshare.js when a plugin's page shares a picture;
// provider links, pageshare.js when a plugin's page shares a picture,
// panelfirst.js when the panel's Usage tab's account count is pressed,
// panelarrange.js when its Allowances tab's Arrange is;
// the checks above
// still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
});
test("the styles hold up in Safari 15.0", async () => {
@@ -0,0 +1,217 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// RealZeroP27 on X: switch which Codex account is used from the tray
// panel's Usage tab, not only from the Providers page. A vendor with
// several accounts has its count in the group's heading open the app's
// menu (never a <select>) of the accounts the provider editor can put
// first, the first ticked; the first account's card is ticked too. A pick
// does what the editor's Make first or Use does: signs Codex in to it
// (/api/login/switch), or, kept signed in to one, puts it first in the
// order (/api/provider/arrange). A setup-token's, an access token's and a
// lapsed account are not offered; a vendor with nothing to choose keeps a
// plain count. 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 iso = (n) => new Date(n).toISOString();
const USERS = ["a@example.com", "b@example.com", "c@example.com", "d@example.com"];
function quotas() {
const now = Date.now(), readAt = iso(now - 60000), resetsAt = iso(now + 2 * 3600000);
return [
...USERS.map((user, i) => ({ provider: "codex", name: "Codex", icon: "openai", user, plan: "Pro", readAt, windows: [{ name: "5 hours", used: 10 + i * 10, resetsAt }] })),
// Claude: two accounts, the other a setup-token's, so nothing to choose
...["x@example.com", "y@example.com"].map((user) => ({ provider: "claude", name: "Claude", icon: "claude-color", user, plan: "Max", readAt, windows: [{ name: "5 hours", used: 5, resetsAt }] })),
];
}
// w: { active, order, kept (keepLoginAs or "") }
function providersOf(w) {
const logins = w.order.map((user) => ({
user, plan: "pro", active: user === w.active, on: user !== "c@example.com",
...(user === "d@example.com" ? { accessOnly: true } : {}),
}));
logins.push({ user: "e@example.com", plan: "plus", active: false, on: false, lapsed: "sign in again" });
const codex = {
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "order",
models: [], agents: [], fallback: [], headers: {}, keyList: [], keepLogin: !!w.kept, keepLoginAs: w.kept || "",
account: { agent: "codex", agentName: "Codex", user: w.active, plan: "pro", logins },
};
const claude = {
id: "claude", name: "Claude Code", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "order",
models: [], agents: [], fallback: [], headers: {}, keyList: [],
account: { agent: "claude", agentName: "Claude Code", user: "x@example.com", plan: "max", logins: [{ user: "x@example.com", plan: "max", active: true, on: true }, { user: "y@example.com", plan: "max", token: true, on: true }] },
};
return { providers: [codex, claude], presets: [], excluded: [], gateway: { running: true, window: true } };
}
function server(lang, w, log) {
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", guideHidden: true };
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 = {};" });
// Codex is connected, so the Agents tab has no account line to load the list for
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", icon: "generic", path: "/fixture/codex", source: "chatgpt", wired: true, fields: [] }], profiles: [], settings });
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(quotas());
if (url.pathname === "/api/usage/quotas/history") 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") {
log.push(url.searchParams.get("last") === "1" ? "kept" : "fresh");
return json(url.searchParams.get("last") === "1" ? { ...providersOf(w), last: true } : providersOf(w));
}
if (req.method() === "POST" && ["/api/login/switch", "/api/provider/arrange", "/api/window/main"].includes(url.pathname)) {
log.push(url.pathname + url.search + " " + (req.postData() || ""));
if (url.pathname === "/api/login/switch") {
const user = req.postDataJSON().user;
w.active = user;
w.order = [user, ...w.order.filter((u) => u !== user)];
return json(providersOf(w));
}
if (url.pathname === "/api/provider/arrange") {
w.order = req.postDataJSON().accountOrder.filter((u) => USERS.includes(u));
return json(providersOf(w));
}
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); }
catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const K = {
head: "Use first",
manage: "Manage accounts…",
count: "{n} accounts",
first: "First",
signed: "{agent} is now signed in as {user}",
gateway: "The gateway now uses {user} first",
};
const group = (id) => `#panelQuota .pq-group[data-provider="${id}"]`;
async function open(browser, lang, width, w) {
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
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('#ptabs [data-ptab="usage"]').click();
await page.locator(`${group("codex")} .pq-pick`).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 };
}
async function said(page, want) {
await page.waitForFunction((w) => document.querySelector("#status")?.textContent === w, want).catch(() => {});
assert.equal(await page.locator("#status").textContent(), want);
}
// waits out a redraw: the list read draws the group again
async function inside(page, sel, width) {
await page.waitForFunction(([s, w]) => { const r = document.querySelector(s)?.getBoundingClientRect(); return r?.width && r.x >= 0 && r.right <= w + 0.5; }, [sel, width], { timeout: 5000 }).catch(() => {});
const b = await page.locator(sel).boundingBox();
assert.ok(b && b.x >= 0 && b.x + b.width <= width + 0.5, `${sel} off the panel: ${JSON.stringify(b)}`);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the panel's Usage tab puts a Codex account first", 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 () => {
const w = { active: "a@example.com", order: [...USERS], kept: "" };
const { page, errors, log, tr } = await open(browser, lang, width, w);
for (const k of Object.values(K)) await tr(k);
const pick = page.locator(`${group("codex")} .pq-pick`);
assert.equal((await pick.textContent()).trim(), "4");
assert.equal(await pick.getAttribute("aria-haspopup"), "menu");
assert.equal(await pick.getAttribute("title"), await tr(K.count, { n: 4 }));
await inside(page, `${group("codex")} .pq-pick`, width);
// the first account's card is ticked
await page.locator(`${group("codex")} .pq-card.first .pq-first`).waitFor();
assert.equal(await page.locator(`${group("codex")} .pq-card.first .pq-user`).textContent(), "a@example.com");
assert.equal(await page.locator(`${group("codex")} .pq-first`).getAttribute("title"), await tr(K.first));
// Claude: its other account is a setup-token's, so a plain count
assert.equal(await page.locator(`${group("claude")} .pq-pick`).count(), 0);
assert.equal(await page.locator(`${group("claude")} span.pq-count`).textContent(), "2");
assert.equal(await page.locator("#panelQuota select").count(), 0);
await pick.click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
// the kept list drew it; the menu is a fresh read's
assert.ok(log.includes("fresh"), `no fresh read before the menu: ${log}`);
assert.equal(await menu.locator(".pm-head").textContent(), await tr(K.head));
// never an access token's (d) or one to sign in again (e)
assert.deepEqual(await menu.locator(".pm-item .pm-name").allTextContents(), ["a@example.com", "b@example.com", "c@example.com", await tr(K.manage)]);
assert.equal(await menu.locator(".pm-item.on .pm-name").allTextContents().then((x) => x.join()), "a@example.com");
await inside(page, ".proto-menu", width);
// an account that is off is signed in to, as the editor's Use does
await menu.locator(".pm-item", { hasText: "c@example.com" }).click();
for (let i = 0; i < 100 && !log.some((x) => x.startsWith("/api/login/switch")); i++) await page.waitForTimeout(20);
const sw = log.filter((x) => x.startsWith("/api/login/switch"));
assert.equal(sw.length, 1, `switches: ${log}`);
assert.deepEqual(JSON.parse(sw[0].slice(sw[0].indexOf(" ") + 1)), { agent: "codex", user: "c@example.com" });
await said(page, await tr(K.signed, { agent: "Codex", user: "c@example.com" }));
// the menu ticks the new first
await pick.click();
await menu.waitFor();
assert.equal(await menu.locator(".pm-item.on .pm-name").allTextContents().then((x) => x.join()), "c@example.com");
// Manage accounts… opens the window's Providers
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");
if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `panel-first-${engine}-${lang}-${width}.png`) });
assert.deepEqual(errors, []);
await page.context().close();
});
}
}
});
test(engine + ": kept signed in to one, the pick puts it first in the order", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
// Codex kept on b; a is first in the order; c is off, so not offered
const w = { active: "b@example.com", order: [...USERS], kept: "b@example.com" };
const { page, errors, log, tr } = await open(browser, "en", 360, w);
await page.locator(`${group("codex")} .pq-pick`).click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.deepEqual(await menu.locator(".pm-item .pm-name").allTextContents(), ["a@example.com", "b@example.com", await tr(K.manage)]);
assert.equal(await menu.locator(".pm-item.on .pm-name").allTextContents().then((x) => x.join()), "a@example.com");
await menu.locator(".pm-item", { hasText: "b@example.com" }).click();
for (let i = 0; i < 100 && !log.some((x) => x.startsWith("/api/provider/arrange")); i++) await page.waitForTimeout(20);
const ar = log.filter((x) => x.startsWith("/api/provider/arrange"));
assert.equal(ar.length, 1, `arranges: ${log}`);
const body = JSON.parse(ar[0].slice(ar[0].indexOf(" ") + 1));
assert.equal(body.id, "codex");
assert.equal(body.accountOrder[0], "b@example.com");
assert.ok(!log.some((x) => x.startsWith("/api/login/switch")), "kept signed in: Codex isn't signed in to another");
await said(page, await tr(K.gateway, { user: "b@example.com" }));
await page.locator(`${group("codex")} .pq-pick`).click();
await menu.waitFor();
assert.equal(await menu.locator(".pm-item.on .pm-name").allTextContents().then((x) => x.join()), "b@example.com");
assert.deepEqual(errors, []);
await page.context().close();
});
}