gui: providers can be picked and removed together (eiyuuzaki2333 on X)

Many API providers added meant removing them one at a time. Select, by
the Providers search box (shown with two or more), puts a box on every
row as Routing's groups and Library's lists have it: a click on a row
picks it rather than open its editor, Shift picks the rows shown
between, and the bar's box picks every row shown. Remove asks once, in
the app's own dialog, with the count and every name, then posts
POST /api/providers/delete {ids}. That runs provider.Delete for each
id, as the editor's Remove does, inside one agent.Reseat, so agents
move once, to where they end up. One it can't remove comes back in
`unremoved` with why, stays picked and is named in the status; the call
is refused only when nothing was removed. Done or Escape ends picking.

The rows, bar and removal are in pvpick.js, imported when Select is
first clicked. The core grows 270 bytes (pvSel, the button's click and
two lines in renderProviders), and coreScriptBudget is raised by that
with the reason. "{name} wasn't removed: {error}" moves from Library's
words into core i18n.js, since core code says it now.

Run (rebased on origin/main e6e0585bd, on mica; mote was over its 18
cores):
- go test -tags nogui ./internal/gui/ ./internal/provider/: ok
  (TestProvidersDeleteSeveral new; TestCoreScriptBudget ok after the raise).
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok; go build: ok.
- GUI, chromium + webkit: provider-bulk-remove (new: en, zh, zh-TW, ja,
  de at 420 and 1100px), provider-remove, provider-find, provider-order,
  providers-off-fold, provider-search, provider-list-off,
  group-bulk-remove, library-pick-remove, i18n-keys, i18n-en-no-cjk: ok.
  found-skill-pick-remove's ja/de 420px subtests are red, and red the
  same at origin/main e6e0585bd in a clean worktree (#5013).
Broken by hand: the handler deleting only ids[:1] turns
TestProvidersDeleteSeveral red ("listed after: [b c d]"); the page
posting only the first id turns provider-bulk-remove red in every
language. Restored, green.
Not run: the full Go suite and the full GUI suite (mote overloaded,
mica running another session's GUI suite); not tried in the real app
with real providers.
This commit is contained in:
yetone
2026-11-14 22:18:09 +08:00
parent e6e0585bd3
commit 90efddabae
11 changed files with 509 additions and 6 deletions
+1
View File
@@ -679,6 +679,7 @@ covers it in both engines, every language and a narrow window.
- In Usage → Allowances, Trends → Cycle offers each account's own recorded cycle menu beside its curve (`quotaCurve`, `quotaRecordedCycles` in [`app.js`](../../internal/gui/assets/app.js)). The longest window (usually weekly) owns the menu; shorter windows are drawn over the selected dates with their own reset breaks. `/api/usage/quotas/history?days=45` supplies all retained readings, including remote cards. Completed cycles come from observed boundaries, not seven-day arithmetic; an early reset ends the previous cycle at the vendor's new start if it fits between readings, otherwise at the first new reading. Each menu option gives its observed duration, so an early reset is not labelled as a full seven days. The selected meters, plot, legend, tooltip and dashed pace use that cycle's last readings, never today's percentages. A window without a reading in the selected interval says so instead of showing a current value. A local account's past cycle asks `/api/usage/quotas/history/holds?provider=&user=&from=&to=` once per selection (`quotaCycleHoldsOf`), which asks no vendor (#2009, NorethSea): `HistoricalWindowHolds` in [`window_holds_history.go`](../../internal/usage/window_holds_history.go) reckons each window's whole at its own last reading in that cycle, from the request log up to that reading, so the 5-hour figure is the cycle's last 5-hour window, never its short windows added up. Its tooltip names that window's start and the reading's time. It shows "Loading…" until the answer comes. A window it can't reckon says "not enough data" with the reason, as a current card does; a reply that comes after another cycle was picked is dropped, and a card's Refresh or an asked read reckons again. Historical meters show the cycle end and sampling time; current account actions, balances and policies are left out until returning to the current view. Accounts are independent, and a selection survives card refreshes in the same page. Trends → 2 days temporarily shows recent readings; Off removes the curves; the tray always shows its current cycle. See `quota-curve.test.cjs` and the [history limits and reset inference](providers-accounts.md#constraints-and-failure-behavior).
- The Usage page's cards are packed into columns, never all stretched to a row's height (`packUsage`, #860): each card in that order goes to the leftmost column that ends highest, on 1px grid rows, so short cards stack beside a tall one. Every card is as tall as what it holds, the last in a column too: ikunbots on X had each column's last reach down to the tallest's end, which left a card with no windows (OpenCode Zen) as tall as Claude's beside it, mostly empty, and jen_celeus on X asked for cards as tall as their content. A head with nothing under it keeps no margin below. The page's order (DOM, dragging, Alt+arrows) stays `UsageOrder`. The column count is the most 260px columns that fit, or one fewer when that leaves much less empty room; it is chosen again only when the cards change or the width fits another number of columns, so a card opened or folded stays where it is, even as the scrollbar comes in. See `usage-pack.test.cjs`.
- The Providers page has a search box over its list (#1614, `findProviders` in [`app.js`](../../internal/gui/assets/app.js)): the words typed keep the rows, on and off, whose text or data say them all: name, id, preset, addresses, every model's id and name, the account's user and plan and each login's, account names and key names. The Turned off fold stays open while searching; Escape or clearing the box shows every row and the fold as it was. A row that is on reorders by dragging its logo, Alt+↑/↓, Alt+Shift+↑/↓ (top, bottom) or its right-click menu (`openProviderMenu`: Move to top, Move up, Move down, Move to bottom). While searching, a step or a drop moves it among the rows shown (it takes the place of the row it passes, `stepProvider`, `shownToOn`) and the hidden ones keep their order; Move to top and Move to bottom go to the ends of the whole list. Every move saves the whole order through `POST /api/providers/arrange`. See `provider-find.test.cjs` and `provider-order.test.cjs`.
- Providers are removed several at once from Select, beside the search box (`#pvSelect`, shown with two providers or more; eiyuuzaki2333 on X). Picking (`pvSel` in [`app.js`](../../internal/gui/assets/app.js); `pickedProviderRow`, `pvSelBar` and `removePicked` in [`pvpick.js`](../../internal/gui/assets/pvpick.js), imported when Select is first clicked, so the core carries only the button and two lines in `renderProviders`) puts a box on every row, takes the handle and switch away and opens no editor: a click on a row picks it, Shift picks the rows shown between, and the bar's box picks every row shown (a search narrows it; the closed Turned off fold's rows are not shown). Remove asks once, in the app's own dialog (`confirmAction`), with the count and every name, and posts `POST /api/providers/delete {ids}` (`providerRoutes` in [`providers.go`](../../internal/gui/providers.go)). That runs `provider.Delete` for each id, as the editor's Remove does, inside one `agent.Reseat`, so agents move once, to where they end up. A provider it can't remove comes back in `unremoved` with why, stays picked and is named in the status; it is refused only when nothing was removed. Done, Escape or a removal that leaves nothing picked ends picking. See `provider-bulk-remove.test.cjs` and `TestProvidersDeleteSeveral`.
- Hide accounts (`window.hideAccounts` at the end of [`app.js`](../../internal/gui/assets/app.js)) masks every account name and address in the window's text and tooltips, its menus and dialogs too, by one switch for the whole window and the tray panel. Routing's, Usage's and Providers' buttons (`#rtMask`, `#usageMask`, `#pvMask` beside Providers' search box) and Settings › Privacy's row are that one switch, stored in `magpie.maskEmails`: turned on any page, every page is hidden and every button says so, and another window or the panel follows through the `storage` event (paultian in #feedback: Providers had a switch of its own, so one page was hidden while another wasn't). A `magpie.maskProviders` left by the versions that had Providers' own switch is folded in once and removed: hidden on either page then is hidden everywhere now. While it is not chosen, it follows Mask personal data, and turning that on turns it on (`provider-mask.test.cjs`). While it is on, an account's name on the provider editor's row (`accountNameButton`, and the one-account line) and on its Usage card (`quotaWho`), and on the tray panel's Usage card (`panelQuotaCard`'s `.pq-who`, in sight while the card is hovered), has an eye (`hideAccounts.eye`), in sight on hover or keyboard focus. A click shows that one account, its address and the name the user gave it together (`kin`), everywhere that page draws it, tooltips included, while the others stay hidden (yogurt36 on Discord, for a screen share). The accounts shown are a set held in memory that `hits()` skips; nothing stores them. The window and the panel are pages of their own, each with its own set: one shown in the window stays hidden in the panel and the other way round, so a screenshot of either shows only what was shown there. Closing the window hides them again: the page stays loaded while the window is hidden, so `hideMain` runs `mainClosedJS` (`hideAccounts.closed`) first. Putting the panel away hides the panel's again, from its `visibilitychange` (the one that drops `panelPeek`) (`account-eye.test.cjs`, `TestClosingHidesShownAccounts`). What it hides is the accounts: their addresses, their vendors' values (`user`, `account`, Routing's `who`) and a name that stands for one, a plugin's (`accountUsers`, a card's `alias` without `named`) or a seat's. The name the user gave an account (`AccountNames`; a card's `alias` with `named`, which `withAccountNames` sets) is no account and stays in sight, beside the account it names, hidden (faketrader in #3656: several accounts couldn't be told apart). A label is scoped by its element, never by its value: in the user's own name (`.own-name`), a plan (`.plan`, the Providers row's `.acct-plan`), a model (`.model-value`) and a Usage card's title (`.subscription-head > b`) only an address is hidden, so an Antigravity account whose value is "Google" leaves "Google AI Pro" readable while an address written in a plan is still hidden; the same holds for the tooltips of plans and models (`TIPS`), not for the own name's, which says the account (`LABELS` in app.js, `account-mask-alias-plan.test.cjs`). The tray panel card's tooltip joins the account and the plan in one string, and still hides a plan's word that is an account's value.
- A new user's Agents page (the window's first page and the panel's Agents tab) has a *Get started* card above the agents in the welcome's place (wangye1644294 on X, `guideCard` in [`app.js`](../../internal/gui/assets/app.js)). Its three steps are: add a model source; connect an agent, where the agents magpie found that can be connected are named and each is connected in one click (`agents/connect`); and, optional, a routing group, with the most harmless starter template that can be made from the user's models (`provider.Templates`, Never stuck first) added in one click through `POST /api/groups/template`. Every tick comes from the state: the models magpie serves (`served` in `/api/state`, groups left out), an agent wired, or a group that isn't automatic. None comes from the card having been seen. The card goes once the first two steps are done. Its close button saves `settings.GuideHidden` through `POST /api/settings/guide`, so the panel, the window and a reload agree, and the Settings save keeps it. See `getting-started.test.cjs`.
- A connected agent's row in the window opens and closes on a click anywhere on it that isn't one of its controls, as a disclosure row does on the Mac (NG_shiyu on X, `connectRow` in [`app.js`](../../internal/gui/assets/app.js)): the click is handed to the row's *Models {n}* link (`expandLink`), which stays the control the keyboard and a screen reader use and keeps `aria-expanded`. Buttons, links, inputs, anything with a role, the grip and the opened sheet (`.ag-exp`) keep their own clicks, and a click that ends a text selection does nothing. The panel's rows did this already (`agent-row-disclose.test.cjs`).
+13
View File
@@ -2723,6 +2723,19 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.rt-mask svg { width: 13px; height: 13px; flex: none; }
.rt-mask[aria-pressed="true"] { color: var(--fg-2); }
#view-providers .pv-q { flex: 0 1 220px; min-width: 120px; }
/* Select (eiyuuzaki2333 on X): a box on every row, and over the list a bar
that stays in view as it scrolls: all or none, how many, Remove, Done.
While picking, a row neither opens nor drags, and nothing is added. */
#view-providers .pv-select { flex: none; }
#view-providers .pv-sel { position: sticky; top: 0; z-index: 3; display: flex; align-items: center; gap: 10px; min-height: 40px; margin: 0 0 8px; padding: 6px 8px 6px 11px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); flex: none; }
#view-providers .pv-sel .note { font-size: 12px; color: var(--fg-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
#view-providers .pv-sel input, #view-providers .pv-pickbox { margin: 0; flex: none; accent-color: var(--fg); }
#view-providers .row.pv-pick { cursor: default; user-select: none; -webkit-user-select: none; }
#view-providers .row.pv-pick.picked { background: var(--card-2); }
#view-providers.pv-picking .after-list, #view-providers.pv-picking #addSheet, #view-providers.pv-picking #providerDiscovery { display: none; }
/* a confirmation's list of what it removes, by name */
.action-confirm .confirm-names { margin: 12px 0 0; padding: 8px 12px; max-height: 168px; overflow-y: auto; list-style: none; border-radius: 8px; background: var(--card-2); color: var(--fg); font-size: 12.5px; line-height: 1.7; white-space: normal; }
.action-confirm .confirm-names li { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#view-providers .pv-none { margin: 18px 2px; }
#view-providers .off-head .fold:disabled { cursor: default; opacity: 1; }
@media (max-width: 520px) { #view-providers .pv-q { flex: 1 1 100%; } }
+10
View File
@@ -6238,6 +6238,9 @@ function renderProviders(quiet) {
if (open) dialog = renderEditor(p);
}
findProviders();
// while picking (pvpick.js), its rows and bar take the place of these
$("#pvSelect").hidden = !!pvSel || providers.providers.length < 2;
if (pvSel) pvSelBar();
renderExcluded();
renderFileError();
renderMovable();
@@ -6314,6 +6317,13 @@ function openProviderMenu(anchor, p, at) {
], at);
}
// Select (eiyuuzaki2333 on X: many providers added, removed one at a
// time), by the search box: the rows, the bar and the removal are in
// pvpick.js, imported when Select is first clicked, so they weigh nothing
// on the core. pvSel is the ids picked while picking, null otherwise.
let pvSel = null, pvSelLast = null;
$("#pvSelect").onclick = async () => (!providerDirty() || await confirmDiscard()) && import("./pvpick.js").then(() => startPicking(), statusErr);
// Providers' search (#1614): the rows saying every word, on and off, by their
// text, ids, addresses, users and keys; a word they don't say is a model's
// they serve, named under the row (frankdeng, Neo).
+28
View File
@@ -2556,6 +2556,13 @@ const I18N = {
"Select all": "全选",
"Import": "导入",
"{n} selected": "已选 {n} 个",
"Pick several providers to remove together": "勾选几个供应商,一起移除",
"Select every provider shown": "选择显示的所有供应商",
"Pick the providers to remove": "勾选要移除的供应商",
"Remove {n} providers?": "移除 {n} 个供应商?",
"Their saved configuration will be removed. Agents using them may switch to another provider or their default model.": "这将删除它们的已保存配置。使用它们的 Agent 可能切换到其他供应商或默认模型。",
"{n} providers removed": "已移除 {n} 个供应商",
"{name} wasn't removed: {error}": "{name} 未能删除:{error}",
"Reading other apps…": "正在读取其他应用…",
"magpie reads these apps' settings and changes nothing in them. Pick the providers to bring over.": "magpie 只读取这些应用的配置,不会改动它们。勾选要导入的供应商。",
"Not found on this computer": "这台电脑上没有找到",
@@ -7820,6 +7827,13 @@ const I18N = {
"Select all": "全選",
"Import": "匯入",
"{n} selected": "已選 {n} 個",
"Pick several providers to remove together": "勾選幾個供應商,一起移除",
"Select every provider shown": "選擇顯示的所有供應商",
"Pick the providers to remove": "勾選要移除的供應商",
"Remove {n} providers?": "移除 {n} 個供應商?",
"Their saved configuration will be removed. Agents using them may switch to another provider or their default model.": "這將刪除它們的已儲存設定。使用它們的 Agent 可能切換到其他供應商或預設模型。",
"{n} providers removed": "已移除 {n} 個供應商",
"{name} wasn't removed: {error}": "{name} 未能刪除:{error}",
"Reading other apps…": "正在讀取其他應用…",
"magpie reads these apps' settings and changes nothing in them. Pick the providers to bring over.": "magpie 只讀取這些應用的設定,不會改動它們。勾選要匯入的供應商。",
"Not found on this computer": "這臺電腦上沒有找到",
@@ -13059,6 +13073,13 @@ const I18N = {
"Select all": "すべて選択",
"Import": "インポート",
"{n} selected": "{n} 件選択中",
"Pick several providers to remove together": "複数のプロバイダーを選んでまとめて削除",
"Select every provider shown": "表示中のプロバイダーをすべて選択",
"Pick the providers to remove": "削除するプロバイダーを選択",
"Remove {n} providers?": "{n} 個のプロバイダーを削除しますか?",
"Their saved configuration will be removed. Agents using them may switch to another provider or their default model.": "保存した設定が削除されます。使用中のエージェントは別のプロバイダーまたは既定のモデルに切り替わる場合があります。",
"{n} providers removed": "{n} 個のプロバイダーを削除しました",
"{name} wasn't removed: {error}": "{name} を削除できませんでした:{error}",
"Reading other apps…": "他のアプリを読み込み中…",
"magpie reads these apps' settings and changes nothing in them. Pick the providers to bring over.": "magpie はこれらのアプリの設定を読むだけで、何も変更しません。取り込むプロバイダを選んでください。",
"Not found on this computer": "このコンピュータには見つかりません",
@@ -18329,6 +18350,13 @@ const I18N = {
"Select all": "Alle auswählen",
"Import": "Importieren",
"{n} selected": "{n} ausgewählt",
"Pick several providers to remove together": "Mehrere Anbieter auswählen und zusammen entfernen",
"Select every provider shown": "Alle angezeigten Anbieter auswählen",
"Pick the providers to remove": "Zu entfernende Anbieter auswählen",
"Remove {n} providers?": "{n} Anbieter entfernen?",
"Their saved configuration will be removed. Agents using them may switch to another provider or their default model.": "Ihre gespeicherte Konfiguration wird entfernt. Agenten, die sie verwenden, können zu einem anderen Anbieter oder ihrem Standardmodell wechseln.",
"{n} providers removed": "{n} Anbieter entfernt",
"{name} wasn't removed: {error}": "{name} wurde nicht entfernt: {error}",
"Reading other apps…": "Andere Apps werden gelesen…",
"magpie reads these apps' settings and changes nothing in them. Pick the providers to bring over.": "magpie liest die Einstellungen dieser Apps und ändert nichts daran. Wählen Sie die zu übernehmenden Anbieter.",
"Not found on this computer": "Auf diesem Computer nicht gefunden",
+2 -1
View File
@@ -138,7 +138,8 @@
<div class="who" role="status" aria-live="polite"><b id="providerDiscoveryCount"></b><span id="providerDiscoverySources"></span></div>
<div class="actions"><button class="text primary" id="reviewProviderDiscovery">Review and import…</button><button class="text" id="dismissProviderDiscovery" data-t data-tt="Hide these configurations until they change">Ignore</button></div>
</aside>
<div class="pv-head" id="pvHead" hidden><input class="sess-filter pv-q" id="pvQ" type="search" spellcheck="false" autocomplete="off" placeholder="Find a provider" aria-label="Find a provider" data-tp><button class="text rt-mask" id="pvMask" aria-pressed="false" data-tt="Mask the accounts on every page — email addresses and account names — for a screenshot to share"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.9 4.2A10.4 10.4 0 0 1 12 4c6.5 0 10 8 10 8a17.6 17.6 0 0 1-2.2 3.2M6.6 6.6C3.9 8.4 2 12 2 12s3.5 8 10 8a9.7 9.7 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2M2 2l20 20"/></svg><span data-t>Hide accounts</span></button></div>
<div class="pv-head" id="pvHead" hidden><input class="sess-filter pv-q" id="pvQ" type="search" spellcheck="false" autocomplete="off" placeholder="Find a provider" aria-label="Find a provider" data-tp><button class="text pv-select" id="pvSelect" type="button" hidden data-tt="Pick several providers to remove together" data-t>Select</button><button class="text rt-mask" id="pvMask" aria-pressed="false" data-tt="Mask the accounts on every page — email addresses and account names — for a screenshot to share"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.9 4.2A10.4 10.4 0 0 1 12 4c6.5 0 10 8 10 8a17.6 17.6 0 0 1-2.2 3.2M6.6 6.6C3.9 8.4 2 12 2 12s3.5 8 10 8a9.7 9.7 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2M2 2l20 20"/></svg><span data-t>Hide accounts</span></button></div>
<div class="pv-sel" id="pvSel" hidden></div>
<p class="set-none pv-none" id="pvNone" role="status" hidden></p>
<div class="list" id="providers"></div>
<div class="row-head off-head" id="offHead" hidden><button class="fold" id="foldOff" aria-expanded="false" aria-controls="offProviders"><span class="label" data-t>Turned off</span><span class="note" id="offCount"></span></button></div>
@@ -578,7 +578,6 @@ magpie.strings({
"{n} linked from folders of your own are only unlinked: those folders stay where they are.": "{n} 个链接自你文件夹的技能只取消链接,原文件夹保留。",
"Remove all {n}": "删除全部 {n} 个",
"{n} skills removed": "已删除 {n} 个技能",
"{name} wasn't removed: {error}": "{name} 未能删除:{error}",
"Stop picking servers": "结束多选",
"Copy config…": "复制配置…",
"As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here": "与 Claude Code 的 .mcp.json 格式相同。像 {ref} 这样引用变量的值,在这里仍然是变量名",
@@ -1625,7 +1624,6 @@ magpie.strings({
"{n} linked from folders of your own are only unlinked: those folders stay where they are.": "{n} 個連結自你資料夾的技能只取消連結,原資料夾保留。",
"Remove all {n}": "刪除全部 {n} 個",
"{n} skills removed": "已刪除 {n} 個技能",
"{name} wasn't removed: {error}": "{name} 未能刪除:{error}",
"Stop picking servers": "結束多選",
"Copy config…": "複製設定…",
"As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here": "與 Claude Code 的 .mcp.json 格式相同。像 {ref} 這樣引用變數的值,在這裡仍然是變數名稱",
@@ -2663,7 +2661,6 @@ magpie.strings({
"{n} linked from folders of your own are only unlinked: those folders stay where they are.": "自分のフォルダからリンクされた {n} 個はリンクが解除されるだけで、そのフォルダはそのまま残ります。",
"Remove all {n}": "{n} 個すべて削除",
"{n} skills removed": "{n} 個のスキルを削除しました",
"{name} wasn't removed: {error}": "{name} を削除できませんでした:{error}",
"Stop picking servers": "選択を終了",
"Copy config…": "設定をコピー…",
"As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here": "Claude Code の .mcp.json と同じ形式です。{ref} のように変数を参照する値は、ここでは変数名のままです",
@@ -3706,7 +3703,6 @@ magpie.strings({
"{n} linked from folders of your own are only unlinked: those folders stay where they are.": "Bei {n} aus eigenen Ordnern verlinkten wird nur der Link entfernt: Diese Ordner bleiben, wo sie sind.",
"Remove all {n}": "Alle {n} entfernen",
"{n} skills removed": "{n} Skills entfernt",
"{name} wasn't removed: {error}": "{name} wurde nicht entfernt: {error}",
"Stop picking servers": "Mehrfachauswahl beenden",
"Copy config…": "Konfiguration kopieren…",
"As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here": "So, wie es in Claude Codes .mcp.json steht. Ein Wert, der eine Variable nennt, etwa {ref}, bleibt hier ein Name",
+148
View File
@@ -0,0 +1,148 @@
// Picking providers to remove together (eiyuuzaki2333 on X: many
// providers added, removed one at a time), as Routing's groups and
// Library's lists have it: a box on every row, a click picks it (Shift
// picks the rows between it and the last one), and the bar over the list
// picks all or none of those shown, says how many, and removes them after
// one confirmation, each as its editor's Remove does (POST
// /api/providers/delete). Done or Escape ends it; the rows open, switch
// and drag again. app.js imports this when Select is first clicked and
// keeps pvSel, so it weighs nothing on the core.
// the list as it is when not picking: the bar gone, the rows' own parts
// shown again (renderProviders shows Select)
function unbar() {
$("#view-providers").classList.remove("pv-picking");
$("#pvSel").hidden = true;
$("#pvSel").replaceChildren();
}
// a search while picking: the bar's count and all box follow the rows it
// leaves (findProviders, app.js's own listener, runs first)
for (const k of ["input", "keydown"]) $("#pvQ").addEventListener(k, () => pvSel && pvSelSync());
// Escape ends picking, unless a dialog or the search box has it first
document.addEventListener("keydown", (e) => {
if (e.key !== "Escape" || !pvSel || view !== "providers" || confirmationPending || !$("#modal").hidden || e.defaultPrevented) return;
e.preventDefault();
endPicking();
});
window.pickedProviderRow = function (p) {
const row = el("div", "row provider pv-pick" + (p.off ? " off" : ""));
row.dataset.id = p.id;
const cb = el("input", "pv-pickbox");
cb.type = "checkbox";
cb.setAttribute("aria-label", p.name);
const who = el("div", "who");
const n = p.models.filter((m) => m.on).length;
who.append(el("div", "name", p.name), el("div", "sub", [p.account?.user || p.host, n ? t(n === 1 ? "{n} model" : "{n} models", { n }) : ""].filter(Boolean).join(" · ")));
row.append(cb, icon(p.icon || "generic"), who);
cb.onclick = (e) => { e.stopPropagation(); pickProvider(p.id, cb.checked, e.shiftKey); };
row.onclick = (e) => pickProvider(p.id, !pvSel.has(p.id), e.shiftKey);
return row;
};
// the rows shown, in the page's order: the search and the fold hide some
const pvShownRows = () => [...document.querySelectorAll("#providers > .row.provider, #offProviders > .row.provider")].filter((r) => !r.hidden && !r.parentElement.hidden);
window.pickProvider = function (id, on, range) {
if (!pvSel) return;
const ids = pvShownRows().map((r) => r.dataset.id), i = ids.indexOf(id), j = range ? ids.indexOf(pvSelLast) : -1;
for (const x of i >= 0 && j >= 0 ? ids.slice(Math.min(i, j), Math.max(i, j) + 1) : [id]) on ? pvSel.add(x) : pvSel.delete(x);
pvSelLast = id;
pvSelSync();
};
window.startPicking = function () {
pvSel = new Set();
pvSelLast = null;
editing = null;
draft = null;
renderProviders();
};
window.endPicking = function () {
pvSel = null;
pvSelLast = null;
unbar();
renderProviders();
};
// pvSelBar, after renderProviders drew the list: a provider gone is no
// longer picked, a list too short to pick from ends picking, and each row
// drawn is swapped for its picking row, shown or hidden as the search left
// it, before the bar is drawn
window.pvSelBar = function () {
for (const id of pvSel) if (!providers.providers.some((p) => p.id === id)) pvSel.delete(id);
if (providers.providers.length < 2 && !pvSel.size) {
pvSel = null;
$("#pvSelect").hidden = providers.providers.length < 2;
return unbar();
}
for (const r of document.querySelectorAll("#providers > .row.provider, #offProviders > .row.provider")) {
const p = providers.providers.find((x) => x.id === r.dataset.id);
if (!p) continue;
const n = pickedProviderRow(p);
n.hidden = r.hidden;
const hits = r.querySelector(".pv-hits");
if (hits) n.querySelector(".who").append(hits);
r.replaceWith(n);
}
const bar = $("#pvSel"), view = $("#view-providers");
view.classList.add("pv-picking");
bar.hidden = false;
const all = el("input", "pv-pickall");
all.type = "checkbox";
all.setAttribute("aria-label", t("Select every provider shown"));
all.onchange = () => {
for (const r of pvShownRows()) all.checked ? pvSel.add(r.dataset.id) : pvSel.delete(r.dataset.id);
pvSelSync();
};
const rm = el("button", "text danger pv-remove", t("Remove"));
rm.type = "button";
rm.onclick = () => removePicked(rm);
const done = el("button", "text pv-done", t("Done"));
done.type = "button";
done.onclick = endPicking;
bar.replaceChildren(all, el("span", "note"), el("span", "grow"), rm, done);
pvSelSync();
};
// the boxes, the bar's count and its Remove, as the picks are now
window.pvSelSync = function () {
if (!pvSel) return;
for (const r of document.querySelectorAll("#view-providers .row.pv-pick")) {
const on = pvSel.has(r.dataset.id);
r.classList.toggle("picked", on);
r.querySelector(".pv-pickbox").checked = on;
}
const shown = pvShownRows().map((r) => r.dataset.id), k = shown.filter((id) => pvSel.has(id)).length;
const all = $("#pvSel .pv-pickall");
if (!all) return;
all.checked = k > 0 && k === shown.length;
all.indeterminate = k > 0 && k < shown.length;
all.disabled = !shown.length;
$("#pvSel .note").textContent = pvSel.size ? t("{n} selected", { n: pvSel.size }) : t("Pick the providers to remove");
$("#pvSel .pv-remove").disabled = !pvSel.size;
};
// removePicked: the ones picked, named in one confirmation, then removed
// together. One that couldn't be stays picked, and the status says why.
window.removePicked = async function (b) {
const gone = providers.providers.filter((p) => pvSel?.has(p.id));
if (!gone.length || b.classList.contains("busy")) return;
const names = el("ul", "confirm-names");
for (const p of gone) names.append(el("li", "", p.name));
const why = document.createDocumentFragment();
why.append(t(gone.length === 1 ? "Its saved configuration will be removed. Agents using it may switch to another provider or their default model."
: "Their saved configuration will be removed. Agents using them may switch to another provider or their default model."), names);
if (!await confirmAction(gone.length === 1 ? t("Remove {name}?", { name: gone[0].name }) : t("Remove {n} providers?", { n: gone.length }), why, t("Remove"))) return;
const ids = gone.map((p) => p.id);
saving(b, t("Remove"));
try {
providers = await api("providers/delete", { ids });
} catch (e) {
doneSaving(b);
return statusErr(e); // nothing removed: every one stays picked
}
const left = providers.unremoved || [], removed = gone.filter((p) => !left.some((u) => u.id === p.id));
pvSel = left.length ? new Set(left.map((u) => u.id)) : null;
if (!pvSel) unbar();
renderProviders();
const okMsg = removed.length === 1 ? t("{name} removed", { name: removed[0].name }) : t("{n} providers removed", { n: removed.length });
if (left.length) {
const p = gone.find((x) => x.id === left[0].id);
status(okMsg + " · " + t("{name} wasn't removed: {error}", { name: p?.name || left[0].id, error: left[0].error }), "warn", 10000);
} else saidMoved(okMsg);
try { state = await api("state"); renderAgents(); } catch (e) { statusErr(e); }
};
File diff suppressed because one or more lines are too long
+56
View File
@@ -835,6 +835,9 @@ type providersJSON struct {
Had int `json:"had,omitempty"`
// Removed: of the keys removed at once (keys/remove-many), how many.
Removed int `json:"removed,omitempty"`
// Unremoved: of the providers removed at once (providers/delete), the
// ones left, each with why
Unremoved []unremovedJSON `json:"unremoved,omitempty"`
// FileError is why providers.json can't be read (provider.FileError):
// the page says so over what is listed, which is then the signed-in
// accounts alone, never "add your first provider".
@@ -844,6 +847,12 @@ type providersJSON struct {
Fetching bool `json:"fetching,omitempty"`
}
// unremovedJSON is a provider providers/delete couldn't remove, and why.
type unremovedJSON struct {
ID string `json:"id"`
Error string `json:"error"`
}
// agentModel is the model an agent is on, as magpie's catalog names it.
func agentModel(a *agent.Agent) string {
if len(a.Fields) == 0 {
@@ -1723,6 +1732,53 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
}
writeProvidersJSON(rw, providersState())
})
// several providers removed at once (eiyuuzaki2333 on X: many relays
// added, removed one at a time), each by provider.Delete as the
// editor's Remove does, with the agents on their models moved once,
// after the last (agent.Reseat), not through the others going too.
// One that can't be removed is left and named in Unremoved; none
// removed at all is refused as the editor's Remove is.
mux.HandleFunc("POST /api/providers/delete", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
IDs []string `json:"ids"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&in); err != nil {
fail(rw, err)
return
}
var ids []string
for _, id := range in.IDs {
if id != "" && !slices.Contains(ids, id) {
ids = append(ids, id)
}
}
if len(ids) == 0 {
fail(rw, errors.New("no provider picked"))
return
}
var unremoved []unremovedJSON
moved, err := agent.Reseat(func() error {
var first error
for _, id := range ids {
if err := provider.Delete(id); err != nil {
unremoved = append(unremoved, unremovedJSON{ID: id, Error: err.Error()})
first = cmp.Or(first, err)
}
}
if len(unremoved) == len(ids) {
return first
}
return nil
})
if err != nil {
fail(rw, err)
return
}
st := providersState()
st.Moved, st.Unremoved = moved, unremoved
writeJSON(rw, st)
keepProviders(st) // as a provider action's: the panel's switch draws it
})
// a picture for a provider, picked in the editor: kept by content before
// the provider is saved, which then points at it. The page sends it as
// base64 in JSON — the app's web view hands a scheme handler no body for
+103
View File
@@ -0,0 +1,103 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// providers/delete removes the providers picked together (eiyuuzaki2333 on
// X), each as the editor's Remove does: gone from the list and kept among
// the deleted, so their calls stay theirs. One not picked stays. One that
// can't be removed is named in unremoved while the rest go; none removed
// is refused.
func TestProvidersDeleteSeveral(t *testing.T) {
sandboxHome(t)
for _, id := range []string{"a", "b", "c", "d"} {
if err := provider.Save(provider.Provider{ID: id, Name: "Relay " + id, Key: "k" + id, Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
}
mux := http.NewServeMux()
providerRoutes(mux, nil)
del := func(body string) (int, providersJSON) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/providers/delete", strings.NewReader(body)))
var st providersJSON
if w.Code == http.StatusOK {
if err := json.Unmarshal(w.Body.Bytes(), &st); err != nil {
t.Fatal(err)
}
}
return w.Code, st
}
ids := func(st providersJSON) (out []string) {
for _, p := range st.Providers {
out = append(out, p.ID)
}
return out
}
have := func() (out []string) {
for _, p := range provider.All() {
out = append(out, p.ID)
}
return out
}
deleted := func() (out []string) {
b, err := os.ReadFile(provider.Path())
if err != nil {
t.Fatal(err)
}
var f struct{ Deleted []struct{ ID string } }
if err := json.Unmarshal(b, &f); err != nil {
t.Fatal(err)
}
for _, d := range f.Deleted {
out = append(out, d.ID)
}
return out
}
code, st := del(`{"ids":["a","c","a"]}`)
if code != http.StatusOK {
t.Fatalf("status %d", code)
}
if got := ids(st); slices.Contains(got, "a") || slices.Contains(got, "c") || !slices.Contains(got, "b") || !slices.Contains(got, "d") {
t.Fatalf("listed after: %v", got)
}
if got := have(); !slices.Equal(got, []string{"b", "d"}) {
t.Fatalf("saved after: %v", got)
}
if got := deleted(); !slices.Contains(got, "a") || !slices.Contains(got, "c") {
t.Fatalf("not kept among the deleted, as a single Remove keeps them: %v", got)
}
if len(st.Unremoved) != 0 {
t.Fatalf("unremoved: %+v", st.Unremoved)
}
// one not there: the rest go, it is named
code, st = del(`{"ids":["gone","b"]}`)
if code != http.StatusOK || len(st.Unremoved) != 1 || st.Unremoved[0].ID != "gone" || st.Unremoved[0].Error == "" {
t.Fatalf("status %d, unremoved %+v", code, st.Unremoved)
}
if got := have(); !slices.Equal(got, []string{"d"}) {
t.Fatalf("saved after: %v", got)
}
// none removed, or none picked: refused, d stays
for _, body := range []string{`{"ids":["gone"]}`, `{"ids":[]}`, `{}`} {
if code, _ := del(body); code == http.StatusOK {
t.Fatalf("%s: removed nothing and said ok", body)
}
}
if got := have(); !slices.Equal(got, []string{"d"}) {
t.Fatalf("saved after: %v", got)
}
}
@@ -0,0 +1,147 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Providers removed several at once (eiyuuzaki2333 on X: many API providers
// added, and removing them one at a time is tedious). Select, by the search
// box, puts a box on every row, on and off; a click on a row picks it
// rather than open its editor, and Shift picks the rows between. Remove
// asks once, in the app's own dialog, naming every provider it removes and
// how many, before it posts providers/delete {ids}; Cancel removes nothing.
// The ones not picked stay, and Escape ends picking. Every language,
// Chromium and WebKit, a narrow and a wide window; 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, off) => ({
id, name, off, icon: "generic", chat: "https://" + id + ".example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "m1", name: "m1", on: true }], agents: [], fallback: [], headers: {}, host: id + ".example.com",
key: { set: true, masked: "sk-…" + id }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
});
function serve(lang, posts) {
let list = [prov("a", "Relay A"), prov("b", "Relay B"), prov("c", "Relay C"), prov("d", "Relay D"), prov("e", "Relay E", true)];
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/providers/delete" || url.pathname === "/api/provider/delete") {
const body = route.request().postDataJSON();
posts.push([url.pathname, body]);
list = list.filter((p) => !(body.ids || [body.id]).includes(p.id));
return json(payload());
}
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: { select: "Select", cancel: "Cancel", picked: "3 selected", title: "Remove 2 providers?", done: "2 providers removed" },
zh: { select: "选择", cancel: "取消", picked: "已选 3 个", title: "移除 2 个供应商?", done: "已移除 2 个供应商" },
"zh-TW": { select: "選擇", cancel: "取消", picked: "已選 3 個", title: "移除 2 個供應商?", done: "已移除 2 個供應商" },
ja: { select: "選択", cancel: "キャンセル", picked: "3 件選択中", title: "2 個のプロバイダーを削除しますか?", done: "2 個のプロバイダーを削除しました" },
de: { select: "Auswählen", cancel: "Abbrechen", picked: "3 ausgewählt", title: "2 Anbieter entfernen?", done: "2 Anbieter entfernt" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: providers removed several at once`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const width of [420, 1100]) {
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { errors.push("native dialog: " + d.message()); d.dismiss(); });
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
const row = (name) => page.locator("#view-providers .row.provider", { hasText: name });
await row("Relay A").waitFor();
// a switched-off row's name carries its badge; the name itself leads
const names = async () => (await page.locator("#view-providers .row.provider .name").allTextContents()).map((n) => n.slice(0, 7));
const sel = page.locator("#pvSelect");
assert.equal((await sel.textContent()).trim(), w.select);
await sel.click();
const bar = page.locator("#pvSel");
await bar.waitFor();
assert.equal(await sel.isVisible(), false, "Select gives way to the bar");
assert.equal(await page.locator("#view-providers .row.pv-pick .pv-pickbox:visible").count(), 4, "a box on every row shown (the turned-off fold is closed)");
assert.equal(await page.locator("#view-providers .pv-handle, #view-providers .pswitch").count(), 0, "no handle or switch while picking");
const rm = bar.locator(".pv-remove");
assert.equal(await rm.isDisabled(), true, "nothing picked, nothing to remove");
// a row's click picks it, never opens its editor; Shift picks a run
await row("Relay A").click();
await row("Relay C").click({ modifiers: ["Shift"] });
await page.waitForFunction((s) => document.querySelector("#pvSel .note").textContent === s, w.picked);
assert.equal(await page.locator(".editor").count(), 0, "a click on a row doesn't open its editor");
await row("Relay B").locator(".pv-pickbox").uncheck();
assert.deepEqual(await page.locator("#view-providers .row.pv-pick.picked .name").allTextContents(), ["Relay A", "Relay C"]);
assert.equal(await bar.locator(".pv-pickall").evaluate((x) => x.indeterminate), true);
// asked once, with the count and every name; Cancel keeps them all
await rm.click();
const confirm = page.locator("dialog.action-confirm[open]");
await confirm.waitFor();
assert.equal((await confirm.locator("h2").textContent()).trim(), w.title);
assert.deepEqual(await confirm.locator(".confirm-names li").allTextContents(), ["Relay A", "Relay C"]);
assert.deepEqual(posts, [], "one click removes nothing");
await confirm.getByRole("button", { name: w.cancel, exact: true }).click();
await confirm.waitFor({ state: "detached" });
assert.deepEqual(posts, [], "Cancel keeps every provider");
assert.equal(await page.locator("#view-providers .row.pv-pick.picked").count(), 2, "Cancel keeps the picks");
await rm.click();
await confirm.locator("button").last().click();
await bar.waitFor({ state: "hidden" });
assert.deepEqual(posts, [["/api/providers/delete", { ids: ["a", "c"] }]]);
await page.waitForFunction((s) => document.querySelector("#status").textContent.includes(s), w.done);
assert.deepEqual(await names(), ["Relay B", "Relay D", "Relay E"], "the ones not picked stay");
assert.equal(await page.locator("#view-providers .row.pv-pick").count(), 0, "picking ends");
assert.equal(await page.locator("#view-providers .pv-handle").count(), 2, "the rows drag again");
// Escape ends picking, with nothing removed
await sel.click();
await bar.waitFor();
await row("Relay B").click();
await page.keyboard.press("Escape");
await bar.waitFor({ state: "hidden" });
assert.equal(posts.length, 1);
assert.deepEqual(await names(), ["Relay B", "Relay D", "Relay E"]);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth), true, "no sideways scroll");
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await sel.click();
await row("Relay B").click();
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-provider-bulk-remove.png`) });
}
assert.deepEqual(errors, []);
if (lang === "en" && width === 420) {
const missing = await page.evaluate(() => [
"Select", "Done", "{n} selected", "Pick several providers to remove together", "Select every provider shown", "Pick the providers to remove",
"Remove {n} providers?", "Their saved configuration will be removed. Agents using them may switch to another provider or their default model.",
"{n} providers removed", "{name} wasn't removed: {error}",
].flatMap((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]).map((l) => l + ": " + k)));
assert.deepEqual(missing, [], "every string in every language");
}
await page.context().close();
}
});
}
}