plugins: an option's words in the window's language, and a filtered model list says so (plugins#590)

anewuser6937 (Discord, plugins#590) saw one model in WorkBuddy's editor
and took the plugin for broken. They had turned on "Free models only"
themselves, but its label and description read in English in the Chinese
window, and nothing by the models said the list was filtered.

A plugin option (auth.options, magpie's own field; OpenCode's AuthHook is
provider/loader/methods and never reads it) may now give `labels`,
`descriptions` and `confirms`, each keyed by the window's language
("zh", "zh-TW", "ja", "de"), beside the plain strings, as a page's
`titles` do. The host keeps only non-empty strings under language names
of 16 or less, 16 languages at most, each capped as the plain one is
(60/300/300). The editor shows the exact language, then its first part
(zh-TW reads zh), else the plain words, in the row, the hint, and the
confirm dialog and its title. `filtersModels: true` says the plugin's
model list leaves models out while the switch is on; while one is on, as
saved, the Models field says under the chips "Only some models are
listed: the plugin option “…” is on." (zh 只列出部分模型:插件选项「…」已开启。,
zh-TW, ja, de too). An older plugin shows what it showed before, and an
older magpie shows a new plugin's plain words with no note.

WorkBuddy 0.2.10 gives "Free models only" in all four languages with
filtersModels (magpie-community/plugins aec58ae, on npm: `npm view
@magpie-community/opencode-workbuddy-auth@0.2.10 --prefer-online` on mote
says 0.2.10, latest), and the mover's min is raised to it so every moved
user gets it. The CLI's `magpie plugin options` stays English, as the CLI is.

The core scripts would have gone 608 bytes over their budget; three of the
provider editor's comments in app.js are cut down instead, no raise
(1,532,865 of 1,533,105).

Run, on mote (mote-run), at this tree:
- node --test plugin-option-words.test.cjs (new): Chromium and WebKit,
  1100 and 420 wide, en/zh/zh-TW/ja/de, switch on and off: each
  language's label and description, zh-TW falling back to zh and ja/de to
  the plain words for a zh-only option, the note exactly once under the
  chips in a .hint inside the editor with no sideways scroll, none while
  off, the confirm in the language. With app.js put back: 19 of 21 red
  in Chromium (only "en off" passes, both widths).
- With plugin-options.test.cjs and i18n-keys.test.cjs, both engines:
  68 pass, 0 fail.
- go test ./internal/plugin ./internal/provider ./internal/cli: ok.
  TestPluginOptions with host.js put back: red (empty maps, FiltersModels
  false). The real WorkBuddy 0.2.10 index.mjs loaded into this host
  (a temporary test, not kept): plugin.Providers lists free_only for
  workbuddy and workbuddy-ai with all four languages and filtersModels true.
- go test ./internal/gui: TestCoreScriptBudget ok after the cut. Red,
  and red the same at origin/main ed5872d18 (run there too):
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
  /macOS_26_SDK on macOS 27 (#3949); TestColdTurnsTaken red once in the
  package run and passed at origin/main (#4510, the same 0.00s red).
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- plugins: HOME=$(mktemp -d) bun test packages/workbuddy 303 pass 0
  fail; the new freeonly test red 2 of 2 with index.mjs put back.

Not run: the whole GUI suite. mote and the WSL box were each running
another session's full GUI suite (hours left on both), and one runs per
machine; it runs on mote once that one ends. Not tried: a real WorkBuddy
account in the real app window. go test ./... was not run.
This commit is contained in:
yetone
2026-11-01 13:24:50 +08:00
parent ed5872d186
commit e84870f173
12 changed files with 215 additions and 40 deletions
+4 -1
View File
@@ -593,7 +593,10 @@ solves captchas. See [provider-plugins.md](subsystems/provider-plugins.md#a-plug
A plugin can also declare its own switches for its provider (`auth.options`).
They are listed under **Plugin options** in the provider's editor, an Off/On
each with the plugin's own words, and saved with the provider. The values are
each with the plugin's own words (in the window's language when the
plugin gives them, `labels` and `descriptions`), and saved with the
provider. While a switch that leaves models out (`filtersModels`) is on,
the Models field says the list is filtered. The values are
kept in `pluginOptions` in `settings.json`, and the plugin reads them as it
works. Changing one starts nothing by itself. See
[provider-plugins.md](subsystems/provider-plugins.md#a-plugins-own-options).
+3 -3
View File
@@ -70,11 +70,11 @@ Qoder plugins without `auth.checkin` still use [`qoder_checkin.go`](../../intern
## A plugin's own options
A plugin can declare switches for its provider (#2038): its `auth` hook gains `options: [{key, label, description?, default?, confirm?}]`. The host ([`host.js`](../../internal/plugin/host.js) `optionsOf`) keeps an option whose `key` matches `[a-z0-9_-]{1,40}` and whose `label` isn't empty, drops a key seen before, caps the label at 60 characters and the description and `confirm` at 300, takes `default` only when it is `true`, and keeps the first 16. The provider is listed with them (`plugin.Provider.Options`).
A plugin can declare switches for its provider (#2038): its `auth` hook gains `options: [{key, label, description?, default?, confirm?}]`. The host ([`host.js`](../../internal/plugin/host.js) `optionsOf`) keeps an option whose `key` matches `[a-z0-9_-]{1,40}` and whose `label` isn't empty, drops a key seen before, caps the label at 60 characters and the description and `confirm` at 300, takes `default` only when it is `true`, and keeps the first 16. The provider is listed with them (`plugin.Provider.Options`). An option may give its words in the window's other languages, as a page's `titles` do (plugins#590): `labels`, `descriptions` and `confirms`, each `{"zh": "…", "zh-TW": "…", "ja": "…", "de": "…"}`, kept without what isn't a string or is empty, a language name over 16, or past 16 languages, each capped as the plain one is. `label` stays a string beside them, so an older magpie, which copies only the plain fields, shows the plain words, and OpenCode, whose `AuthHook` is `provider`, `loader` and `methods`, never reads `options` at all. `filtersModels: true` (anything else is false) says the plugin's model list leaves models out while the switch is on, as WorkBuddy's "Free models only" does.
The user's values are kept in `settings.PluginOptions` by the plugin's own provider id and the option's key, and set with `POST /api/settings/plugin-option {provider, key, on}`, which checks the key the same way. The host is handed them at `init` (`options`) and again after each change (`setProviderOptions`, `plugin.SetProviderOptions`, sent only to a host already running). A plugin reads them through `input.magpie.option(provider, key)` (the user's value, else the default; false for a key it didn't declare) or `input.magpie.options(provider)` (every declared key). Both read the current values each time, so a change reaches the plugin without a restart. A plugin written for older hosts checks `input.magpie?.option` first. When an option changes magpie keeps and hands over the value, and forgets the providers it keeps, so they are listed again: a models hook may list by an option (WorkBuddy's "Free models only", plugins#430). Nothing else runs. The check-in switch is separate and unchanged.
The provider's editor lists them under *Plugin options* (`pluginOptionsField` in [`app.js`](../../internal/gui/assets/app.js), the values from `/api/providers`' `plugins[].options[].on`), an Off/On each beside the plugin's label and description, put in as text. One with `confirm` asks it before it is turned on. Changes wait for Save, which posts each changed one before the provider.
The provider's editor lists them under *Plugin options* (`pluginOptionsField` in [`app.js`](../../internal/gui/assets/app.js), the values from `/api/providers`' `plugins[].options[].on`), an Off/On each beside the plugin's label and description, put in as text, in the window's language (`optionWords`: its `labels`/`descriptions`/`confirms` by the language, then by its first part, so zh-TW reads zh, else the plain one). One with `confirm` asks it before it is turned on. Changes wait for Save, which posts each changed one before the provider. While an option that says `filtersModels` is on, as saved (the list was read with it), the Models field says so under the chips (`pluginFilterNote`): "Only some models are listed: the plugin option “…” is on.", with the option's label in the window's language. Off, or with no such option, nothing is said.
## A plugin whose upstream searches
@@ -268,7 +268,7 @@ Gateway parity tests in [`plugin_parity_test.go`](../../internal/gateway/plugin_
[`plugin_checkin_test.go`](../../internal/provider/plugin_checkin_test.go) runs the fake plugin's `auth.checkin` (`FAKE_CHECKIN`) through the schedule: off, each outcome, no second press the same day, failures only after the retry window, the next day, cards and Settings, and the vendor check-in stepping aside; `TestPluginCheckinTellsSignInsOfOneNameApart` signs in four accounts under two names, two of each (plugins#254), and checks each is checked in, kept, carded and switched off on its own, and `TestPluginCheckinCarriesOverDisplayNameEntries` upgrades a file and an `Off` kept by display name. `TestPluginCheckinQoderRechecksCampaigns` holds the Qoder plugins' recheck, by the loop and a press, after `inactive` and `done`, `TestPluginCheckinOthersSettledForTheDay` every other plugin's day from noon Beijing, and `TestPluginCheckinEarlyDoneAskedAgain` the reporter's 00:00:28 done asked again by the loop and a press (#3326); `TestPluginCheckinAsksAgainAtUntil` holds the clock from 09:27 Beijing through the next day's 10:30, with the machine in UTC, UTC-8 and Beijing, and checks the asks land at 09:27, 10:01, the Beijing day's turn and 10:01 again, and a failure in the 09:59 gap at 10:01; `checkin-early-done.test.cjs` covers that card; `qoder-checkin-recheck.test.cjs` covers the card's press. `plugin-checkin.test.cjs` covers the card row and the Settings tab.
[`plugin_options_test.go`](../../internal/plugin/plugin_options_test.go) loads `testdata/options` in a real host: which declared options are kept and how they are capped, the user's value over the default at start, a change read by the plugin after `SetProviderOptions` without a restart, and a models hook's list that goes by an option following it after the change. [`plugin_option_api_test.go`](../../internal/gui/plugin_option_api_test.go) covers the endpoint, a bad key, and a Settings save keeping the values. `plugin-options.test.cjs` covers the editor in Chromium and WebKit, 1100 and 420 wide, in every language.
[`plugin_options_test.go`](../../internal/plugin/plugin_options_test.go) loads `testdata/options` in a real host: which declared options are kept and how they are capped, the user's value over the default at start, a change read by the plugin after `SetProviderOptions` without a restart, and a models hook's list that goes by an option following it after the change. [`plugin_option_api_test.go`](../../internal/gui/plugin_option_api_test.go) covers the endpoint, a bad key, and a Settings save keeping the values. `plugin-options.test.cjs` covers the editor in Chromium and WebKit, 1100 and 420 wide, in every language. `plugin-option-words.test.cjs` covers the words in each language (zh-TW falling back to zh, ja and de to the plain ones when a plugin gives only zh) and the note under the models, on and off, in both engines, 1100 and 420 wide.
[`plugin_cliproxy_test.go`](../../internal/plugin/plugin_cliproxy_test.go)'s `TestPluginHostTakesANewProxy` starts a real host without a proxy, sets one, and checks that a program the plugin starts gets it. [`plugin_lan_test.go`](../../internal/plugin/plugin_lan_test.go)'s `TestPluginLeavesTheUserNetworkDirect` checks with a real host that fetches (http:// and https://) and an HTTP/2 session to this computer's private address reach it directly with a proxy set, and that a public address and an unresolvable name still go through the proxy. `plugin-signed-out-account.test.cjs` covers a moved Grok account signed out while in use and as the agent's own, in Chromium and WebKit, en and zh, 420 and 1100 wide.
+21 -21
View File
@@ -7717,11 +7717,12 @@ function pluginOptionsField(sub) {
const row = el("div", "plugin-option");
row.dataset.key = o.key;
const text = el("div", "plugin-option-text");
text.append(el("div", "n", o.label));
if (o.description) text.append(el("div", "hint", o.description));
const label = optionWords(o, "label"), about = optionWords(o, "description"), ask = optionWords(o, "confirm");
text.append(el("div", "n", label));
if (about) text.append(el("div", "hint", about));
const draw = () => {
const seg = segs([["off", t("Off")], ["on", t("On")]], now(o) ? "on" : "off", async (v) => {
if (v === "on" && !now(o) && o.confirm && !(await confirmAction(t("Turn on {name}?", { name: o.label }), o.confirm, t("Turn on")))) {
if (v === "on" && !now(o) && ask && !(await confirmAction(t("Turn on {name}?", { name: label }), ask, t("Turn on")))) {
seg.replaceWith(draw());
return;
}
@@ -7734,6 +7735,16 @@ function pluginOptionsField(sub) {
}
return field(t("Plugin options"), box, t("{plugin} declares these and reads them as it works; nothing runs on its own when one changes.", { plugin: sub.plugin.name || sub.plugin.pid }));
}
// a plugin option's words in the window's language (plugins#590)
function optionWords(o, which) {
const m = o[which + "s"] || {};
return m[locale] || m[locale.split("-")[0]] || o[which] || "";
}
// said under the models while a filtersModels switch is on, as saved
function pluginFilterNote(sub) {
return (sub?.plugin?.options || []).filter((o) => o.filtersModels && o.on)
.map((o) => t("Only some models are listed: the plugin option “{option}” is on.", { option: optionWords(o, "label") })).join(" ");
}
// savePluginOptions saves the draft's changed plugin options, by its own id.
async function savePluginOptions(sub) {
const pid = sub?.plugin?.pid;
@@ -8979,11 +8990,7 @@ const decideOnly = (p) => !!p?.decide && !(p.chat || p.responses || p.anthropic
// they are: its Jev Router (typesafe/jev-router) is a chat model
const decidesModel = (p, id) => !!p.decide && (decideOnly(p) || (p.deciders ? p.deciders.includes(id) : id.split("/").some((s) => /^jev(?:-|$)/i.test(s))));
// modelAPIs: the APIs one of p's models can be asked on alone, those it has
// a URL for when it has more than one — a custom provider's, a preset's or
// a subscription's alike (01huadalang on Discord: 一个 api 里有很多模型但是不同协议;
// OpenCode Go's DeepSeek answers on Responses too), its Gemini URL's
// among them (Kayphoon on Discord: 自定义供应商兼容 gemini 格式了,模型的
// 配置里还是只能选 chat 和 anthropic)
// a URL for when it has more than one, Gemini's too (01huadalang, Kayphoon)
const modelAPIs = (p) => {
const urls = ["chat", "responses", "anthropic", "gemini"].filter((k) => ((draft?.id === p.id ? draft[k] : undefined) ?? p[k] ?? "").trim());
return urls.length < 2 ? [] : PROTOS.filter(([k]) => urls.includes(k));
@@ -9201,13 +9208,9 @@ function drawEditor(p, presetID) {
b.title = t(hint);
b.onclick = () => {
if (draft.api === v) return;
// each protocol keeps its own URL (#105). One typed here and not
// saved moves to a protocol without one, spelled as that protocol
// wants it: the kind was picked after the URL (#73). A saved URL
// stays where it is, and one not given yet stays empty.
// A URL then typed for the protocol it was carried to is that
// protocol's own, and the carried one goes back where it was typed,
// so a URL can be typed for each protocol in turn (#1231).
// each protocol keeps its own URL (#105); an unsaved one moves to a
// protocol without one, in its spelling (#73), and goes back once
// that protocol is given its own (#1231)
const from = apiField[draft.api], to = apiField[v];
carried = null;
if (!draft[to] && draft[from] && draft[from] !== (p?.[from] || "")) {
@@ -9321,7 +9324,7 @@ function drawEditor(p, presetID) {
acct.append(icon(a.agentIcon), el("span", "n", a.user), hideAccounts.eye(a.user, p.id), el("span", "plan", accountPlan(a)));
ed.append(...field(t("Account"), acct, t("{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.", { agent: a.agentName })));
}
ed.append(...field(t("Models"), renderModels(p), ""));
ed.append(...field(t("Models"), renderModels(p), pluginFilterNote(subOf(a.agent))));
if (p.drawIds?.length) ed.append(...renderDrawers(p));
// a subscription's window too: Codex's backend says 272K for models
// that take 872K (#120)
@@ -9403,11 +9406,8 @@ function drawEditor(p, presetID) {
ed.append(...field(t("Endpoint"), endpoint, pr.endpointHint ? t(pr.endpointHint) : ""));
}
// a server on this machine (Ollama, LM Studio, oMLX, MLX-Serve) can
// listen on another port, or be another computer's: its address moves each URL, each API
// keeping its path, as provider.AtAddress does. Shown first and never
// folded: folded under the key, an LM Studio on another computer read
// as one whose base URL can't be changed (mengxiangziyou on X)
// a local server's address moves each URL, keeping its path
// (provider.AtAddress); shown first, never folded (mengxiangziyou on X)
let address = null, addressField = null;
if (pr?.kind === "local") {
// a saved provider's URLs (or a duplicate's) start it; a new one's are
+4
View File
@@ -2347,6 +2347,7 @@ const I18N = {
"Count its models as free": "把它的模型算作免费",
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "适用于免费额度,比如每日免费额度:「免费优先」会先用它的模型,再用付费的;「最便宜优先」把它们算作不花钱。价格和用量统计的费用保持原样。",
"Plugin options": "插件选项",
"Only some models are listed: the plugin option “{option}” is on.": "只列出部分模型:插件选项「{option}」已开启。",
"{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} 声明了这些选项,并在工作时读取;更改选项不会自行运行任何操作。",
"Turn on {name}?": "开启「{name}」?",
"1, the official price": "1,即官方价格",
@@ -6667,6 +6668,7 @@ const I18N = {
"Count its models as free": "把它的模型算作免費",
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "適用於免費額度,例如每日免費額度:「免費優先」會先用它的模型,再用付費的;「最便宜優先」把它們算作不花錢。價格和用量統計的費用維持原樣。",
"Plugin options": "外掛選項",
"Only some models are listed: the plugin option “{option}” is on.": "只列出部分模型:外掛選項「{option}」已開啟。",
"{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} 宣告了這些選項,並在工作時讀取;變更選項不會自行執行任何動作。",
"Turn on {name}?": "開啟「{name}」?",
"1, the official price": "1,即官方價格",
@@ -10965,6 +10967,7 @@ const I18N = {
"Count its models as free": "このモデルを無料として扱う",
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "毎日の無料枠のような無料分に。「無料優先」は有料のものより先にこのモデルを使い、「最安優先」はコストなしとして扱います。価格と使用量で数える費用はそのままです。",
"Plugin options": "プラグインのオプション",
"Only some models are listed: the plugin option “{option}” is on.": "一部のモデルのみ表示しています。プラグインのオプション「{option}」がオンです。",
"{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} が宣言し、動作中に読み取ります。変更しても、それだけで何かが実行されることはありません。",
"Turn on {name}?": "「{name}」をオンにしますか?",
"1, the official price": "1(公式価格)",
@@ -15294,6 +15297,7 @@ const I18N = {
"Count its models as free": "Seine Modelle als kostenlos zählen",
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "Für ein Gratiskontingent, etwa ein tägliches: „Kostenlos zuerst“ nutzt seine Modelle vor bezahlten, und „Günstigste zuerst“ rechnet sie als kostenlos. Preise und die Kosten in der Nutzung bleiben wie gelistet.",
"Plugin options": "Plugin-Optionen",
"Only some models are listed: the plugin option “{option}” is on.": "Nur einige Modelle werden angezeigt: Die Plugin-Option „{option}“ ist an.",
"{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} legt diese fest und liest sie bei der Arbeit; eine Änderung löst selbst nichts aus.",
"Turn on {name}?": "{name} einschalten?",
"1, the official price": "1, der offizielle Preis",
File diff suppressed because one or more lines are too long
+8
View File
@@ -337,6 +337,14 @@ leaving it off; Save posting each changed one by the plugin's provider id
before the provider, and none switched back. Chromium and WebKit, 1100 and
420 wide, every language.
`plugin-option-words.test.cjs` checks a plugin option in the reader's
language (plugins#590): its `labels`, `descriptions` and `confirms` by the
window's language, zh-TW falling back to zh and the rest to the plain
words; and, while a `filtersModels` switch is on as saved, the note under
the Models field's chips that the list is filtered, inside the editor; off,
none. A WorkBuddy moved onto its plugin, Chromium and WebKit, 1100 and 420
wide, every language.
`plugin-move-overflow.test.cjs` checks a Plugins card that offers a
built-in's accounts: the button is one word beside the name, as Install is
("Move", its title saying whose accounts and how many), on one line, and it
@@ -0,0 +1,119 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A plugin option in the reader's language, and a short model list said to
// be filtered (plugins#590, anewuser6937 on Discord): WorkBuddy's "Free
// models only" showed in English inside the Chinese window, and with it on
// the editor listed one model with nothing saying why, so the plugin read as
// broken. The option's labels, descriptions and confirms give its words by
// the window's language (zh-TW falls back to zh, any other to the plain
// one), and while a switch that says filtersModels is on, as saved, the
// Models field says so under the chips. Off, nothing is said. Both engines,
// 1100 and 420 wide, every language.
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 free = (on) => ({
key: "free_only", label: "Free models only", description: "Lists only the models WorkBuddy serves at no cost.",
labels: { zh: "仅免费模型", "zh-TW": "僅免費模型", ja: "無料モデルのみ", de: "Nur kostenlose Modelle" },
descriptions: { zh: "只列出 WorkBuddy 免费提供的模型。", "zh-TW": "只列出 WorkBuddy 免費提供的模型。", ja: "WorkBuddy が無料で提供するモデルだけを表示します。", de: "Listet nur die Modelle, die WorkBuddy kostenlos anbietet." },
filtersModels: true, on,
});
// only Simplified Chinese words: zh-TW reads them, the rest the plain ones
const beta = { key: "beta", label: "Beta models", confirm: "Beta models may be withdrawn.", labels: { zh: "测试版模型" }, confirms: { zh: "测试版模型可能会下线。" }, on: false };
function serve(lang, on) {
const plugin = { id: "workbuddy", pid: "workbuddy", name: "WorkBuddy", icon: "generic", spec: "@magpie-community/opencode-workbuddy-auth", signedIn: true, models: 1,
methods: [{ type: "api", label: "API key" }], options: [free(on), beta] };
const payload = { providers: [{ id: "workbuddy", name: "WorkBuddy", icon: "generic", chat: "plugin://workbuddy/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "hy3", name: "Hy3", on: true }], agents: [], fallback: [], headers: {}, keyList: [], key: {}, proxy: "", maxConcurrency: null,
account: { agent: "workbuddy", agentName: "WorkBuddy", agentIcon: "generic", user: "me@fake", logins: [{ user: "me@fake", active: true, on: true }] } }],
// moved onto its plugin, as every WorkBuddy user is since 10-17
presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [plugin], onPlugins: ["workbuddy"] };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json(payload);
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const W = {
en: { models: "Models", on: "On", label: "Free models only", about: "Lists only the models WorkBuddy serves at no cost.", beta: "Beta models", ask: "Beta models may be withdrawn.",
note: "Only some models are listed: the plugin option “Free models only” is on." },
zh: { models: "模型", on: "开启", label: "仅免费模型", about: "只列出 WorkBuddy 免费提供的模型。", beta: "测试版模型", ask: "测试版模型可能会下线。",
note: "只列出部分模型:插件选项「仅免费模型」已开启。" },
"zh-TW": { models: "模型", on: "開啟", label: "僅免費模型", about: "只列出 WorkBuddy 免費提供的模型。", beta: "测试版模型", ask: "测试版模型可能会下线。",
note: "只列出部分模型:外掛選項「僅免費模型」已開啟。" },
ja: { models: "モデル", on: "オン", label: "無料モデルのみ", about: "WorkBuddy が無料で提供するモデルだけを表示します。", beta: "Beta models", ask: "Beta models may be withdrawn.",
note: "一部のモデルのみ表示しています。プラグインのオプション「無料モデルのみ」がオンです。" },
de: { models: "Modelle", on: "An", label: "Nur kostenlose Modelle", about: "Listet nur die Modelle, die WorkBuddy kostenlos anbietet.", beta: "Beta models", ask: "Beta models may be withdrawn.",
note: "Nur einige Modelle werden angezeigt: Die Plugin-Option „Nur kostenlose Modelle“ ist an." },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a plugin option's own words and its filtered list", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const width of [1100, 420]) for (const lang of Object.keys(W)) for (const on of [true, false]) {
await t.test(`${width} ${lang} ${on ? "on" : "off"}`, async () => {
const w = W[lang];
const ctx = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, on));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "WorkBuddy" }).click();
const ed = page.locator("#modal .editor");
const box = ed.locator(".plugin-options");
await box.waitFor();
await page.waitForTimeout(300); // the editor drawn again as what it asked for comes in
const row = (k) => box.locator(`.plugin-option[data-key="${k}"]`);
assert.equal(await row("free_only").locator(".n").textContent(), w.label);
assert.equal(await row("free_only").locator(".hint").textContent(), w.about);
assert.equal(await row("beta").locator(".n").textContent(), w.beta);
// the Models field: its label, then the chips, the note under them
const models = ed.locator("label", { hasText: new RegExp("^" + w.models + "$") }).first();
await models.waitFor();
const field = models.locator("xpath=following-sibling::div[1]");
const notes = await field.locator(":scope > .hint").allTextContents();
if (on) {
assert.deepEqual(notes, [w.note]);
const where = await field.evaluate((f) => {
const hint = f.querySelector(":scope > .hint"), chips = f.firstElementChild, r = f.closest(".editor").getBoundingClientRect(), h = hint.getBoundingClientRect();
return { below: h.top >= chips.getBoundingClientRect().bottom - 1, spill: h.right - r.right, page: document.documentElement.scrollWidth - document.documentElement.clientWidth };
});
assert.ok(where.below, "the note is under the chips");
assert.ok(where.spill <= 0, "the note runs past the editor by " + where.spill);
assert.ok(where.page <= 0, "the page scrolls sideways by " + where.page);
if (process.env.ARTIFACT_DIR) await field.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `plugin-option-words-${engine}-${width}-${lang}.png`) });
} else {
assert.deepEqual(notes, [], "nothing said while the switch is off");
}
// its confirm in the reader's language too
await row("beta").locator(".opt", { hasText: w.on }).click();
const dialog = page.locator("dialog.action-confirm");
await dialog.waitFor();
assert.equal(await dialog.locator("p").textContent(), w.ask);
assert.ok((await dialog.locator("h2").textContent()).includes(w.beta));
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
+30 -6
View File
@@ -1894,14 +1894,34 @@ const shown = (v, n) => (typeof v === "string" ? v.trim().slice(0, n) : "")
// optionsOf are the switches a plugin declares for its provider, magpie's
// own field (#2038, Vocllum): auth.options, each {key, label, description?,
// default?, confirm?}. magpie shows each as an Off/On switch in the
// provider's editor and keeps what the user sets; the plugin reads it with
// input.magpie.option(provider, key). A switch is kept and handed over,
// and the models listed again (one may go by it); nothing else is run. Keys are [a-z0-9_-], 1–40 long,
// the first of a key kept; at most MAX_OPTIONS; one without a key or a
// label is left out.
// default?, confirm?, labels?, descriptions?, confirms?, filtersModels?}.
// magpie shows each as an Off/On switch in the provider's editor and keeps
// what the user sets; the plugin reads it with input.magpie.option(provider,
// key). A switch is kept and handed over, and the models listed again (one
// may go by it); nothing else is run. Keys are [a-z0-9_-], 1–40 long, the
// first of a key kept; at most MAX_OPTIONS; one without a key or a label is
// left out. labels, descriptions and confirms are the same words in the
// window's other languages ({"zh": "…", "zh-TW": "…", "ja": "…", "de":
// "…"}), as a page's titles are (plugins#590): label stays a string beside
// them, so an older magpie still reads the option. filtersModels says the
// plugin's model list leaves models out while the switch is on, which the
// editor says by the models.
const MAX_OPTIONS = 16
const OPTION_KEY = /^[a-z0-9_-]{1,40}$/
// inLanguages are words by language, each capped at n, at most 16, without
// the empty ones; undefined for none or for what isn't an object
function inLanguages(m, n) {
if (!m || typeof m !== "object" || Array.isArray(m)) return undefined
let out
for (const [k, v] of Object.entries(m)) {
const lang = k.trim(), said = shown(v, n)
if (!lang || lang.length > 16 || !said) continue
out ??= {}
if (Object.keys(out).length >= 16) break
out[lang] = said
}
return out
}
function optionsOf(auth) {
const out = []
if (!Array.isArray(auth?.options)) return out
@@ -1917,6 +1937,10 @@ function optionsOf(auth) {
description: shown(o.description, 300),
default: o.default === true,
confirm: shown(o.confirm, 300),
labels: inLanguages(o.labels, 60),
descriptions: inLanguages(o.descriptions, 300),
confirms: inLanguages(o.confirms, 300),
filtersModels: o.filtersModels === true,
})
}
return out
+9 -4
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
@@ -44,14 +45,18 @@ func TestPluginOptions(t *testing.T) {
if len(opts) != 16 {
t.Fatalf("optco has %d options, want 16: %+v", len(opts), opts)
}
if opts[0] != (Option{Key: "auto-claim", Label: "Claim rewards", Description: "Claims the daily reward when usage is read.", Default: true}) {
if want := (Option{Key: "auto-claim", Label: "Claim rewards", Description: "Claims the daily reward when usage is read.", Default: true,
Descriptions: map[string]string{"zh": "读取用量时领取每日奖励。"}, FiltersModels: true}); !reflect.DeepEqual(opts[0], want) {
t.Errorf("first = %+v", opts[0])
}
if opts[1] != (Option{Key: "beta", Label: "Beta models", Confirm: "Beta models may be withdrawn."}) {
// plugins#590: the words in other languages, without what isn't one
if want := (Option{Key: "beta", Label: "Beta models", Confirm: "Beta models may be withdrawn.",
Labels: map[string]string{"zh": "测试版模型", "de": "Beta-Modelle"}, Confirms: map[string]string{"zh": "测试版模型可能会下线。"}}); !reflect.DeepEqual(opts[1], want) {
t.Errorf("second = %+v", opts[1])
}
if o := opts[2]; o.Key != "long" || len([]rune(o.Label)) > 60 || len([]rune(o.Description)) > 300 || o.Default {
t.Errorf("long = %q (%d), %d, default %v", o.Key, len([]rune(o.Label)), len([]rune(o.Description)), o.Default)
if o := opts[2]; o.Key != "long" || len([]rune(o.Label)) > 60 || len([]rune(o.Description)) > 300 || o.Default || o.FiltersModels || o.Labels != nil ||
len([]rune(o.Descriptions["zh"])) != 300 || len(o.Confirms) != 16 {
t.Errorf("long = %q (%d), %d, default %v, filters %v, labels %v, %d, %d confirms", o.Key, len([]rune(o.Label)), len([]rune(o.Description)), o.Default, o.FiltersModels, o.Labels, len([]rune(o.Descriptions["zh"])), len(o.Confirms))
}
if opts[15].Key != "o12" {
t.Errorf("last = %q, want o12", opts[15].Key)
+10
View File
@@ -190,6 +190,16 @@ type Option struct {
// Confirm is asked before the switch is turned on, when the plugin
// says turning it on does something the user should agree to
Confirm string `json:"confirm,omitempty"`
// Labels, Descriptions and Confirms are the same words in the window's
// other languages, by its language ("zh", "zh-TW", "ja", "de"), as a
// page's Titles are (plugins#590); the plain ones are the fallback
Labels map[string]string `json:"labels,omitempty"`
Descriptions map[string]string `json:"descriptions,omitempty"`
Confirms map[string]string `json:"confirms,omitempty"`
// FiltersModels says the plugin's model list leaves models out while
// the switch is on (WorkBuddy's "Free models only"): the editor says
// so by the models
FiltersModels bool `json:"filtersModels,omitempty"`
}
// OptionOn is option o of a provider as it stands with the user's values
+5 -3
View File
@@ -19,12 +19,14 @@ export const Optco = async (input) => ({
auth: {
provider: "optco",
options: [
{ key: "auto-claim", label: " Claim rewards ", description: "Claims the daily reward when usage is read.", default: true },
{ key: "beta", label: "Beta models", confirm: "Beta models may be withdrawn." },
{ key: "auto-claim", label: " Claim rewards ", description: "Claims the daily reward when usage is read.", default: true, descriptions: { zh: " 读取用量时领取每日奖励。 " }, filtersModels: true },
// the words in other languages (plugins#590): what isn't a string,
// an empty one and a language name over 16 are left out
{ key: "beta", label: "Beta models", confirm: "Beta models may be withdrawn.", labels: { zh: " 测试版模型 ", "zh-TW": "", ja: 5, "a-language-name-too-long": "x", de: "Beta-Modelle" }, confirms: { zh: "测试版模型可能会下线。" } },
{ key: "beta", label: "the same key again" }, // dropped
{ key: "Bad Key", label: "not a key" }, // dropped
{ key: "nolabel" }, // dropped
{ key: "long", label: "L".repeat(200), description: "D".repeat(1000), default: "yes" }, // default is no boolean: off
{ key: "long", label: "L".repeat(200), description: "D".repeat(1000), default: "yes", filtersModels: "yes", labels: "not an object", descriptions: { zh: "D".repeat(1000) }, confirms: Object.fromEntries(Array.from({ length: 20 }, (_, i) => ["l" + i, "c"])) }, // default and filtersModels are no boolean: off; the words capped, at most 16 languages
...Array.from({ length: 20 }, (_, i) => ({ key: "o" + i, label: "Option " + i })),
],
methods: [
File diff suppressed because one or more lines are too long