gui: a provider's per-key proxy lines fold past eight keys (@NetRozee on X)

@NetRozee on X: a custom endpoint given a thousand keys froze magpie.

Cause. The editor's Advanced > Proxy drew a line for every key, each
with a Provider's proxy | Direct | Custom control. Each control, once in
the page, looked up its place among every .segs in the editor and slid
its thumb (segsPlace, slide): quadratic, with a layout read each. The
Accounts list above it already folded (keyFold); this list didn't.

Fix. proxyLines folds a provider's keys as keyFold does: past KEYS_FOLD,
the first KEYS_FIRST and those with a proxy of their own, then All N
keys; opened, a filter (keyMatches, as the Accounts list's) over
KEYS_PAGE lines and how many more, and Show fewer. Typing draws the
lines again under the filter, which stays in the page (#1055). A key not
drawn keeps its proxy: Save posts every key's own, drawn or not.
Subscription accounts' lines are unchanged. No new strings.

Measured (Playwright, the editor opened on a provider of N keys):
                1000 keys          5000 keys
  Chromium      1067ms -> 100ms    55.6s -> 93ms
  WebKit        4809ms -> 68ms     203s -> 81ms
  DOM           9388 -> 434 nodes  45388 -> 434 nodes

Tests: provider-many-keys-proxy.test.cjs (new, en and zh, Chromium and
WebKit): fails in all four on the old app.js (no All 300 keys). With
account-proxy, provider-many-keys, filter-ime, usage-keys-fold,
i18n-keys, click-scroll, provider-proxy, proxy-own-wording,
routing-proxy, plugin-proxy-page, signin-proxy and proxy-test: 221 of
221 pass in both engines.

Run: gofmt -l (clean); GOOS=linux and GOOS=windows go vet -tags nogui
./... (clean); go test -tags nogui -count=1 -timeout 45m ./... in a sandbox HOME (GOCACHE, GOMODCACHE pinned) on af601541e with this series: 66 packages ok, 18 without tests, no FAIL (gateway 468.5s, provider 215.9s, gui 122.8s).
provider-many-keys-proxy.test.cjs rerun after the suite: 4 of 4.
This commit is contained in:
yetone
2026-10-16 08:43:02 +08:00
parent 0bbb2f3ca4
commit 674b6ca288
4 changed files with 197 additions and 25 deletions
+3 -1
View File
@@ -27,7 +27,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) |
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, any case, or `re:` matching the whole id; a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. | [`keys.go`](../../internal/provider/keys.go) |
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`keys.go`](../../internal/provider/keys.go) |
| Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https://<host>/v1/projects/<project>/locations/<location>`, its host following the location (`vertexHost`). It speaks Gemini alone (`Speaks`, `Base`). It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider <id>` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) |
| Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) |
| Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) |
@@ -231,6 +231,8 @@ go test -tags nogui ./internal/provider -run 'TestClaudeSwitchTakesTheAccountsPr
go test -tags nogui ./internal/plugin -run TestPluginSignInProxy
node --test internal/gui/tests/signin-proxy.test.cjs internal/gui/tests/signin-close.test.cjs
go test -tags nogui ./internal/provider -run 'TestAccount|TestImport|TestCodex|TestGroup|TestQuota|TestLogin|TestSignIn|TestSeveralKeys|TestKeyProtocol|TestSetKeyWeight|TestReadSub2APIKeyLimits|TestSub2APIKeyLimitsOnItsCard|TestKeyAllowance|TestPlanKeyAllowance|TestPayAsYouGoKeyAskedSeldom|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestAllowancesReadOnlyWhenAsked|TestAllowancesReadByThemselvesByDefault|TestKeyReadsOnlyWhenAsked|TestAtAddress|TestProviderAtAddress|TestAddressOf'
go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui -run 'TestRestKeysIsRestKey|TestKeysOnDropsRepeats|TestServingReadsListsOnce|TestKeyReadsEightAtOnce|TestKeySlots|TestPerKeyReadsListsOnce|TestProviderInfoListsKeysOnce'
node --test internal/gui/tests/provider-many-keys.test.cjs internal/gui/tests/provider-many-keys-proxy.test.cjs
go test -tags nogui ./internal/provider -run 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap'
go test -tags nogui ./internal/netproxy ./internal/provider ./internal/gateway -run 'TestDispatchHTTP1|OverHTTP1|TestAccountProxy|TestUncheckedTLS|TestInsecureTLS'
go test -tags nogui ./internal/provider -run 'TestSeat|TestPlanOfASignedInAccountShownOnce|TestGLMPlanMatchesZCodePlugin|TestAccountName'
+5
View File
@@ -2815,6 +2815,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.editor .plugin-option .segs { flex: none; }
.editor .acct-proxy .who { font-size: 12px; font-weight: 500; color: var(--fg-2); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.editor .acct-proxies > .hint { margin-top: 0; }
/* past eight keys their lines fold behind All N keys, opened with a filter */
.editor .acct-proxy-tools { display: flex; align-items: center; gap: 6px; min-width: 0; }
.editor .acct-proxy-tools .acct-proxy-filter { flex: 1 1 auto; min-width: 0; }
.editor .acct-proxy-tools .text { flex: none; }
.editor .acct-proxies > .acct-proxy-more { justify-self: start; }
/* what a balance token's URL wants instead, and a balance checked in the form */
.editor .bal-fix { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin-top: 6px; font-size: 12px; line-height: 1.45; color: var(--muted); }
.editor .bal-fix:empty { display: none; }
+73 -24
View File
@@ -7806,37 +7806,86 @@ function accountProxyPicker(a) {
// Accounts list names it. null for a provider with one key.
const KEY_PROXY_HINT = "Each key can go through a proxy of its own; Provider's proxy is the one above";
function keyProxyPicker(p) {
return proxyLines((p?.keyList || []).map((k) => ({ k: k.id, name: k.name || k.masked, key: k.id })), KEY_PROXY_HINT);
return proxyLines((p?.keyList || []).map((k) => ({ k: k.id, name: k.name || k.masked, key: k.id, info: k })), KEY_PROXY_HINT, true);
}
function proxyLines(items, hint) {
// proxyLines: a line for each account or key. A provider's keys fold as
// its Accounts list folds them (keyFold): past KEYS_FOLD, the first
// KEYS_FIRST and those with a proxy of their own, or, opened, those the
// filter matches, KEYS_PAGE at most. A line for each of a thousand keys
// took the editor a minute to open, five thousand three (@NetRozee on X).
// A key not drawn keeps the proxy it has: only a line picked in changes it.
function proxyLines(items, hint, foldKeys) {
if (items.length < 2) return null;
draft.accountProxies = draft.accountProxies || {};
const box = el("div", "acct-proxies");
for (const it of items) {
const k = it.k;
const cur = draft.accountProxies[k] || { mode: "", url: "" };
const line = el("div", "acct-proxy");
if (it.user) line.dataset.user = it.user;
if (it.key) line.dataset.key = it.key;
const who = el("span", "who", it.name);
who.title = it.name;
const addr = input(cur.url || "", "http://127.0.0.1:7890");
addr.className = "proxy-url";
addr.classList.toggle("off", cur.mode !== "custom");
addr.oninput = () => { draft.accountProxies[k] = { ...(draft.accountProxies[k] || { mode: "custom" }), url: addr.value }; };
const seg = segs([["", t("Provider's proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], cur.mode || "", (v) => {
draft.accountProxies[k] = { ...(draft.accountProxies[k] || {}), mode: v };
addr.classList.toggle("off", v !== "custom");
});
seg.classList.add("proxy-mode");
const row = el("div", "proxy-row");
row.append(seg, addr);
line.append(who, row);
box.append(line);
const tail = el("div", "hint", t(hint));
if (!foldKeys || items.length <= KEYS_FOLD) {
for (const it of items) box.append(proxyLine(it));
box.append(tail);
return box;
}
box.append(el("div", "hint", t(hint)));
let q = null; // the filter's text while the whole list is open
let tools = null;
const draw = () => {
for (const n of [...box.childNodes]) if (n !== tools && n !== tail) n.remove();
const add = (n) => box.insertBefore(n, tail);
if (q === null) {
const own = (it) => !!draft.accountProxies[it.k]?.mode;
for (const it of items.filter((it, i) => i < KEYS_FIRST || own(it)).slice(0, KEYS_PAGE)) add(proxyLine(it));
const more = el("button", "text acct-proxy-more", t("All {n} keys", { n: items.length }));
more.type = "button";
more.onclick = () => { q = ""; openTools(); draw(); tools.querySelector("input").focus({ preventScroll: true }); };
add(more);
return;
}
const matched = items.filter((it) => keyMatches(it.info, q));
for (const it of matched.slice(0, KEYS_PAGE)) add(proxyLine(it));
if (!matched.length) add(el("div", "hint acct-proxy-none", t("No key matches")));
else if (matched.length > KEYS_PAGE) add(el("div", "hint acct-proxy-rest", t("{n} more — type to narrow them down", { n: matched.length - KEYS_PAGE })));
};
const close = () => { q = null; tools?.remove(); tools = null; draw(); };
const openTools = () => {
tools = el("div", "acct-proxy-tools");
const f = input("", t("Filter {n} keys — name, key, off, resting…", { n: items.length }));
f.className = "acct-proxy-filter";
f.setAttribute("aria-label", f.placeholder);
// only the lines are drawn again: the filter stays in the page, so an
// IME's text never lands twice (#1055)
f.oninput = () => { q = f.value; draw(); };
f.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") { if (f.value) { f.value = ""; f.oninput(); } else close(); } };
const fewer = el("button", "text", t("Show fewer"));
fewer.type = "button";
fewer.onclick = close;
tools.append(f, fewer);
box.prepend(tools);
};
box.append(tail);
draw();
return box;
}
// proxyLine: one account's or key's line of proxyLines
function proxyLine(it) {
const k = it.k;
const cur = draft.accountProxies[k] || { mode: "", url: "" };
const line = el("div", "acct-proxy");
if (it.user) line.dataset.user = it.user;
if (it.key) line.dataset.key = it.key;
const who = el("span", "who", it.name);
who.title = it.name;
const addr = input(cur.url || "", "http://127.0.0.1:7890");
addr.className = "proxy-url";
addr.classList.toggle("off", cur.mode !== "custom");
addr.oninput = () => { draft.accountProxies[k] = { ...(draft.accountProxies[k] || { mode: "custom" }), url: addr.value }; };
const seg = segs([["", t("Provider's proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], cur.mode || "", (v) => {
draft.accountProxies[k] = { ...(draft.accountProxies[k] || {}), mode: v };
addr.classList.toggle("off", v !== "custom");
});
seg.classList.add("proxy-mode");
const row = el("div", "proxy-row");
row.append(seg, addr);
line.append(who, row);
return line;
}
// accountProxiesOfDraft is each account's own proxy as it is saved — the
// accounts that follow the provider's left out — or { missing: user } when
// one's Custom has no address yet.
@@ -0,0 +1,116 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A provider with hundreds of keys (@NetRozee on X: a thousand keys on a
// custom endpoint froze magpie): its editor's per-key proxy lines fold as
// its Accounts list does. Folded, the first five and the keys with a proxy
// of their own, and All 300 keys; opened, a filter and a page of 50 lines
// and how many more. A key picked in the filter keeps its pick folded
// again, and Save posts every key's own proxy, drawn or not. In English
// and Chinese.
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 N = 300;
const idOf = (i) => i.toString(16).padStart(10, "0");
const relay = () => ({
id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "big", name: "", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…0000" }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: Array.from({ length: N }, (_, i) => ({ id: idOf(i), name: "", masked: "sk-…" + String(i).padStart(4, "0"), on: true, active: i === 0 })),
accountProxies: { [idOf(120)]: "socks5://10.0.0.5:1080", [idOf(200)]: "direct" },
});
function serve(lang, posts) {
const providers = { providers: [relay()], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() });
return json(providers);
}
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 words = {
en: { all: "All 300 keys", fewer: "Show fewer", more: "250 more — type to narrow them down", none: "No key matches", direct: "Direct", save: "Save", filter: "Filter 300 keys — name, key, off, resting…" },
zh: { all: "全部 300 个密钥", fewer: "收起", more: "还有 250 个,输入关键词缩小范围", none: "没有匹配的密钥", direct: "直连", save: "保存", filter: "筛选 300 个密钥:名称、密钥、已停用、休息中…" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
test(`${engine} ${lang}: 300 keys' proxy lines fold, open on a filter, and keep their picks`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
let page;
t.after(async () => {
if (process.env.ARTIFACT_DIR && page) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-many-keys-proxy.png`) });
}
await browser.close();
});
page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "Relay" }).first().click();
// Proxy is under Advanced, open already when one is set
{ const adv = page.locator(".editor details.advanced"); await adv.waitFor({ state: "attached" }); if (!(await adv.evaluate((d) => d.open))) await adv.locator(":scope > summary").click(); }
const more = page.locator(".editor .acct-proxies > .acct-proxy-more");
await more.waitFor();
const lines = () => page.locator(".editor .acct-proxy").evaluateAll((ls) => ls.map((l) => l.dataset.key));
// folded: the first five and the two with a proxy of their own
assert.deepEqual(await lines(), [0, 1, 2, 3, 4, 120, 200].map(idOf));
assert.equal((await more.textContent()).trim(), w.all);
assert(await page.locator(".editor .segs").count() < 20, "a line was drawn for every key");
// opened: a filter, focused, over 50 lines and how many more
await more.click();
const filter = page.locator(".editor .acct-proxy-tools .acct-proxy-filter");
await filter.waitFor();
assert.equal(await filter.getAttribute("placeholder"), w.filter);
assert(await filter.evaluate((e) => e === document.activeElement), "the filter is focused");
assert.equal((await lines()).length, 50);
assert.equal(await page.locator(".editor .acct-proxy-rest").textContent(), w.more);
assert.equal(await more.count(), 0);
await filter.fill("0123");
assert.deepEqual(await lines(), [idOf(123)]);
assert.equal(await page.locator(".editor .acct-proxy-rest").count(), 0);
await page.locator(`.editor .acct-proxy[data-key="${idOf(123)}"] .proxy-mode .opt`, { hasText: w.direct }).click();
await filter.fill("nothing-like-it");
assert.equal(await page.locator(".editor .acct-proxy-none").textContent(), w.none);
assert.equal((await lines()).length, 0);
// folded again, the key just picked shows among the others
await page.locator(".editor .acct-proxy-tools").getByRole("button", { name: w.fewer, exact: true }).click();
await more.waitFor();
assert.equal(await page.locator(".editor .acct-proxy-tools").count(), 0);
assert.deepEqual(await lines(), [0, 1, 2, 3, 4, 120, 123, 200].map(idOf));
const n = posts.length;
await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click();
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
assert.deepEqual(posts.at(-1).body.accountProxies, { [idOf(120)]: "socks5://10.0.0.5:1080", [idOf(123)]: "direct", [idOf(200)]: "direct" });
assert.deepEqual(errors, []);
});
}
}