plugin: a plugin declares its own switches, shown in its provider's editor and read by the plugin (#2038, Vocllum)
Vocllum asked that a plugin can offer the user generic on/off options
without magpie knowing what each one is for. A plugin now declares them
on its auth hook, beside checkin:
auth.options: [{ key, label, description?, default?, confirm? }]
and reads the user's values through input.magpie.option(provider, key)
or input.magpie.options(provider). Each call reads the current values,
so a change reaches the plugin without a restart. magpie only keeps the
value and hands it over: nothing is scheduled or run when an option
changes. The check-in switch (settings.pluginCheckins) and the check-in
plugins are unchanged.
- host.js: optionsOf keeps a key matching [a-z0-9_-]{1,40} with a
non-empty label, drops repeats, caps the label at 60 characters and
the description and confirm at 300, takes default only when it is
true, and keeps at most 16. The values come at init and through
setProviderOptions.
- Go: plugin.Option, Provider.Options, OptionOn and SetProviderOptions
(sent only to a host that is running). settings.PluginOptions is kept
by the plugin's provider id, then the key. POST
/api/settings/plugin-option {provider, key, on} checks the key the same
way and hands the values to the host. The generic settings save keeps
them, as it keeps PluginCheckins. /api/providers' plugins[].options
carry each option's resolved `on`.
- GUI: a "Plugin options" field in a plugin provider's editor. Each
option is a segs Off/On beside the plugin's label and description, put
in with textContent. A confirm text is asked through confirmAction
before turning an option on. Changes wait for Save, which posts each
one before the provider. Strings are added for zh, zh-TW, ja and de.
- Docs: provider-plugins.md (a new section), reference.md, gui-shell.md
and the tests README.
Run:
- TestPluginOptions (a real host with testdata/options). Red with the
old host.js (no options listed) and red with setProviderOptions turned
into a no-op (the plugin still reads the old value).
- TestPluginOptionSetting and TestSettingsSaveKeepsWhatItDoesNotSend.
Both red with the generic save's PluginOptions line removed.
- plugin-options.test.cjs: 22/22 in Chromium and WebKit, at 1100 and 420
wide, in en, zh, zh-TW, ja and de. Red on the old app.js (no field).
The screenshots were looked at: long text wraps and the page has no
sideways scroll at 420.
- provider-concurrency, plugin-signin, plugin-checkin, provider-price-rate
and plugin-move-unserved: 68/68.
- go test ./internal/plugin/... ./internal/settings/... ./internal/gui/...
./internal/provider/..., gofmt -l, and go vet on darwin, linux
(-tags nogui) and windows.
Not tried with a real community plugin, since none declares options yet.
The check-in row doesn't take a plugin-declared label or hint; it is
left as it was.
This commit is contained in:
@@ -464,6 +464,13 @@ with the result on each account's Usage card. A check-in the vendor wants a
|
||||
captcha for is shown as such (check in in the vendor's app); magpie never
|
||||
solves captchas. See [provider-plugins.md](subsystems/provider-plugins.md#a-plugins-daily-check-in).
|
||||
|
||||
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
|
||||
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).
|
||||
|
||||
The gateway issues **gateway keys** for clients, separate from a provider's
|
||||
upstream API keys. Turn on **Settings → Share on local network**, then open
|
||||
**Gateway → Gateway keys → Add gateway key**. This block appears only while
|
||||
|
||||
@@ -265,6 +265,19 @@ switch on through a focus refresh and lets the next click turn it off.
|
||||
[`plugin-checkin.test.cjs`](../../internal/gui/tests/plugin-checkin.test.cjs)
|
||||
covers both response shapes, refreshes and the subsequent toggle.
|
||||
|
||||
### Plugin options
|
||||
|
||||
A plugin provider's editor shows the options its plugin declares
|
||||
(`pluginOptionsField` in [`app.js`](../../internal/gui/assets/app.js); see
|
||||
[provider-plugins.md](provider-plugins.md#a-plugins-own-options)). The
|
||||
plugin's label, description and `confirm` text go in as text, never as HTML.
|
||||
A change is kept in `draft.pluginOptions` until Save, which posts each one
|
||||
to `POST /api/settings/plugin-option` before the provider's own save. An
|
||||
option switched back to where it was is dropped from the draft, so it isn't
|
||||
posted and doesn't make the editor dirty.
|
||||
[`plugin-options.test.cjs`](../../internal/gui/tests/plugin-options.test.cjs)
|
||||
covers it.
|
||||
|
||||
### Shared UI rules
|
||||
|
||||
- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip. Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs`.
|
||||
|
||||
@@ -52,6 +52,14 @@ WorkBuddy's check-in ([`workbuddy_checkin.go`](../../internal/provider/workbuddy
|
||||
|
||||
Qoder plugins without `auth.checkin` still use [`qoder_checkin.go`](../../internal/provider/qoder_checkin.go) through the plugin's fetch. The server's `CLAIMABLE` status decides whether to claim; the local `[startAt, endAt)` check only recognizes an already-claimed campaign and its expiry, including one that crosses Beijing midnight. Successful results keep the active campaign's end in the optional `until` field of `qoder-checkin.json`. Scheduled checks reuse results from the same Beijing day for at most 30 minutes and never past that end, so a long campaign cannot hide new or reset campaigns indefinitely. The existing loop looks every 30 minutes and on a Beijing day change; a midnight refresh saves today's result for the Usage card and TUI. An `inactive` result is now asked again after 30 minutes rather than settled for the day; failures retain their existing retry schedule. A manual check-in always asks immediately. Saved results without `until` remain readable and use the same 30-minute refresh, with no migration needed. Other vendors and plugins with their own check-in retain their daily settlement.
|
||||
|
||||
## 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`).
|
||||
|
||||
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. Nothing runs when an option changes: magpie only keeps and hands over the value. 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.
|
||||
|
||||
## A plugin whose upstream searches
|
||||
|
||||
A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api relay, say) can say its upstream answers a web search tool by itself (#2027). Its `config` hook sets `searches: true` on the provider; the host passes it through (`plugin.Provider.Searches`), and [`pluginProvider`](../../internal/provider/plugins.go) sets the provider's `Searches`, as a custom provider's "Searches the web by itself" does (#359). [`searchesItself`](../../internal/gateway/search.go) honours it for a plugin's provider only, on Anthropic's or Responses' API, and only for one the plugin has a model on: a client's `web_search` then goes to the plugin's `fetch` as sent, not through magpie's search. Another sign-in's `Searches` is never read, and Codex's and Grok's stay as they were. As with a relay, `searchRank` leaves it out, so magpie never picks it to search for other models; Settings can name it by hand (`namedSearcherRank`).
|
||||
@@ -161,6 +169,8 @@ 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. `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, and a change read by the plugin after `SetProviderOptions` without a restart. [`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_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.
|
||||
|
||||
[`stderr_drain_test.go`](../../internal/plugin/stderr_drain_test.go)'s `TestDrainStderrKeepsTheChildGoing` checks that a child writing 8 MiB to stderr with no newline finishes, and that the log says its stderr was dropped. [`stderr_e2e_test.go`](../../internal/plugin/stderr_e2e_test.go)'s `TestHostStartsPastAnOverlongStderrLine` starts a real host whose plugin logs one 5 MiB line while it loads, and checks that the host starts; without the fix it fails on Windows only.
|
||||
|
||||
@@ -41,6 +41,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/mcpauth"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/profile"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/redact"
|
||||
@@ -1169,6 +1170,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
in.FastPicks = cur.FastPicks // switched in the agents' pickers (#954)
|
||||
in.AgentEfforts = cur.AgentEfforts // picked in an agent's row (#1003)
|
||||
in.PluginCheckins = cur.PluginCheckins // set on its own (plugin-checkin below)
|
||||
in.PluginOptions = cur.PluginOptions // set on its own (plugin-option below)
|
||||
in.CheckinOff = cur.CheckinOff // set on its own (checkin-account below)
|
||||
settings.CarryPerModel(&in, &cur)
|
||||
in.LAN, in.LANKey = cur.LAN, cur.LANKey
|
||||
@@ -1721,6 +1723,43 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
}
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// and a switch a plugin declares for its provider (auth.options, #2038),
|
||||
// by the plugin's own provider id, handed to the running host at once
|
||||
mux.HandleFunc("POST /api/settings/plugin-option", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Provider string
|
||||
Key string
|
||||
On bool
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if in.Provider == "" || !pluginOptionKey.MatchString(in.Key) {
|
||||
fail(rw, errors.New("no provider or no such option"))
|
||||
return
|
||||
}
|
||||
s := settings.Load()
|
||||
s.PluginOptions = maps.Clone(s.PluginOptions)
|
||||
if s.PluginOptions == nil {
|
||||
s.PluginOptions = map[string]map[string]bool{}
|
||||
}
|
||||
own := maps.Clone(s.PluginOptions[in.Provider])
|
||||
if own == nil {
|
||||
own = map[string]bool{}
|
||||
}
|
||||
own[in.Key] = in.On
|
||||
s.PluginOptions[in.Provider] = own
|
||||
if err := settings.Save(s); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
// best effort: a host that misses it reads them when it next starts
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
_ = plugin.SetProviderOptions(ctx)
|
||||
cancel()
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// and one account's daily check-in, whichever vendor's (#1902): off
|
||||
// leaves it out while its vendor's is on
|
||||
mux.HandleFunc("POST /api/settings/checkin-account", func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -2668,6 +2668,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
|
||||
over the same row as the provider's, in a quiet card, no stripes */
|
||||
.editor .acct-proxies { display: grid; gap: 8px; margin-top: 4px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); }
|
||||
.editor .acct-proxy { display: grid; gap: 4px; min-width: 0; }
|
||||
/* a plugin's own switches (#2038): its words, then Off/On */
|
||||
.editor .plugin-options { gap: 10px; }
|
||||
.editor .plugin-option { display: flex; align-items: flex-start; gap: 12px; min-width: 0; }
|
||||
.editor .plugin-option-text { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; }
|
||||
.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; }
|
||||
/* what a balance token's URL wants instead, and a balance checked in the form */
|
||||
|
||||
@@ -7471,6 +7471,52 @@ function priceRateField() {
|
||||
box.oninput = () => { draft.priceRate = box.value; };
|
||||
return field(t("Price rate"), box, t("Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set"));
|
||||
}
|
||||
// pluginOptionsField: the switches a plugin declares for its provider
|
||||
// (auth.options, #2038, Vocllum), each an Off/On beside the plugin's own
|
||||
// words for it, put in as text. One the plugin asks to confirm is asked
|
||||
// before it is turned on. A change is kept in the draft as
|
||||
// pluginOptions[key] and saved with the provider; nothing runs when it is,
|
||||
// the plugin reads the value when it next wants it.
|
||||
function pluginOptionsField(sub) {
|
||||
const opts = sub?.plugin?.options || [];
|
||||
if (!opts.length) return [];
|
||||
const now = (o) => (draft.pluginOptions && o.key in draft.pluginOptions ? draft.pluginOptions[o.key] : !!o.on);
|
||||
const set = (o, on) => {
|
||||
const own = { ...draft.pluginOptions };
|
||||
if (on === !!o.on) delete own[o.key]; else own[o.key] = on;
|
||||
if (Object.keys(own).length) draft.pluginOptions = own; else delete draft.pluginOptions;
|
||||
};
|
||||
const box = el("div", "stack plugin-options");
|
||||
for (const o of opts) {
|
||||
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 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")))) {
|
||||
seg.replaceWith(draw());
|
||||
return;
|
||||
}
|
||||
set(o, v === "on");
|
||||
});
|
||||
return seg;
|
||||
};
|
||||
row.append(text, draw());
|
||||
box.append(row);
|
||||
}
|
||||
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 }));
|
||||
}
|
||||
// savePluginOptions saves the plugin options changed in the draft, by the
|
||||
// plugin's own provider id.
|
||||
async function savePluginOptions(sub) {
|
||||
const pid = sub?.plugin?.pid;
|
||||
if (!pid) return;
|
||||
for (const [key, on] of Object.entries(draft.pluginOptions || {})) {
|
||||
prefs = await writingPrefs(api("settings/plugin-option", { provider: pid, key, on }));
|
||||
}
|
||||
}
|
||||
// priceRateOfDraft is the draft's rate as it is saved — null for none,
|
||||
// else the number — or undefined when what is typed isn't one.
|
||||
function priceRateOfDraft() {
|
||||
@@ -8546,6 +8592,7 @@ function drawEditor(p, presetID) {
|
||||
ed.append(...concurrencyField(p));
|
||||
ed.append(...priceRateField());
|
||||
if (p.cline) ed.append(...upstreamField());
|
||||
ed.append(...pluginOptionsField(subOf(a.agent)));
|
||||
// a plugin's provider is reached inside magpie: its plugin:// URLs go
|
||||
// nowhere to show or test
|
||||
const urls = [p.chat, p.responses, p.anthropic].filter(Boolean);
|
||||
@@ -8581,7 +8628,9 @@ function drawEditor(p, presetID) {
|
||||
const priceRate = priceRateOfDraft();
|
||||
if (priceRate === undefined) return priceRateError(ed);
|
||||
if (priceTypedError(ed)) return;
|
||||
saving(saveBtn, t("Saving…")); providerAction("save", { id: p.id, models: chosenIds(), noModels: noneChosen(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...routingOfDraft(p) }, t("{name} saved", { name: p.name })); };
|
||||
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...routingOfDraft(p) };
|
||||
saving(saveBtn, t("Saving…"));
|
||||
savePluginOptions(subOf(a.agent)).then(() => providerAction("save", body, t("{name} saved", { name: p.name })), (e) => { doneSaving(saveBtn); editorError(e.message || String(e)); }); };
|
||||
bar.append(cancel, saveBtn);
|
||||
ed.append(bar);
|
||||
return ed;
|
||||
|
||||
@@ -1909,6 +1909,9 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "自定义数字,最大 1000",
|
||||
"No limit": "不限制",
|
||||
"Price rate": "价格倍率",
|
||||
"Plugin options": "插件选项",
|
||||
"{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,即官方价格",
|
||||
"Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "费用按官方价格乘以此倍率计算,同中转站计费方式,例如 0.8 或 1.5;你为某个模型单独设置的价格保持不变",
|
||||
"Price rate: a number from 0 to 1000, at most three decimals": "价格倍率:0 到 1000 之间的数字,最多三位小数",
|
||||
@@ -6028,6 +6031,9 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "自定義數字,最大 1000",
|
||||
"No limit": "不限制",
|
||||
"Price rate": "價格倍率",
|
||||
"Plugin options": "外掛選項",
|
||||
"{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,即官方價格",
|
||||
"Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "費用按官方價格乘以此倍率計算,同中轉站計費方式,例如 0.8 或 1.5;你為某個模型單獨設定的價格保持不變",
|
||||
"Price rate: a number from 0 to 1000, at most three decimals": "價格倍率:0 到 1000 之間的數字,最多三位小數",
|
||||
@@ -10130,6 +10136,9 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "任意の数(最大 1000)",
|
||||
"No limit": "上限なし",
|
||||
"Price rate": "価格倍率",
|
||||
"Plugin options": "プラグインのオプション",
|
||||
"{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(公式価格)",
|
||||
"Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "費用は公式価格にこの倍率を掛けて計算します(中継サービスの課金方式、例: 0.8 や 1.5)。モデルごとに設定した価格はそのままです",
|
||||
"Price rate: a number from 0 to 1000, at most three decimals": "価格倍率: 0〜1000 の数値、小数点以下 3 桁まで",
|
||||
@@ -14249,6 +14258,9 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "Eine eigene Zahl, bis 1000",
|
||||
"No limit": "Kein Limit",
|
||||
"Price rate": "Preisfaktor",
|
||||
"Plugin options": "Plugin-Optionen",
|
||||
"{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",
|
||||
"Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "Kosten werden zum offiziellen Preis mal diesem Faktor gezählt, wie ein Relay abrechnet, etwa 0.8 oder 1.5; ein für ein Modell gesetzter Preis bleibt",
|
||||
"Price rate: a number from 0 to 1000, at most three decimals": "Preisfaktor: eine Zahl von 0 bis 1000, höchstens drei Nachkommastellen",
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentenv"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// A switch a plugin declares (#2038, Vocllum) is set by itself: its value
|
||||
// is kept under the plugin's provider id and key, the provider's other
|
||||
// options and other providers' are left as they were, a save of the
|
||||
// Settings page, which doesn't send them, keeps them, and a key the host
|
||||
// wouldn't list is refused.
|
||||
func TestPluginOptionSetting(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
|
||||
t.Setenv("APPDATA", filepath.Join(h, "AppData", "Roaming"))
|
||||
t.Setenv("LOCALAPPDATA", filepath.Join(h, "AppData", "Local"))
|
||||
for _, v := range agentenv.Vars {
|
||||
t.Setenv(v, "")
|
||||
}
|
||||
s := settings.Load()
|
||||
s.PluginOptions = map[string]map[string]bool{"other": {"x": true}, "optco": {"beta": true}}
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := Handler(nil, nil)
|
||||
post := func(path, body string) int {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
|
||||
return rec.Code
|
||||
}
|
||||
has := func(want map[string]map[string]bool) {
|
||||
t.Helper()
|
||||
got := settings.Load().PluginOptions
|
||||
if !maps.EqualFunc(got, want, maps.Equal) {
|
||||
t.Fatalf("pluginOptions = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
if c := post("/api/settings/plugin-option", `{"provider":"optco","key":"auto-claim","on":false}`); c != http.StatusOK {
|
||||
t.Fatalf("set: %d", c)
|
||||
}
|
||||
has(map[string]map[string]bool{"other": {"x": true}, "optco": {"beta": true, "auto-claim": false}})
|
||||
if c := post("/api/settings", `{"theme":"dark"}`); c != http.StatusOK {
|
||||
t.Fatalf("settings: %d", c)
|
||||
}
|
||||
has(map[string]map[string]bool{"other": {"x": true}, "optco": {"beta": true, "auto-claim": false}})
|
||||
for _, bad := range []string{`{"key":"beta","on":true}`, `{"provider":"optco","key":"Bad Key","on":true}`, `{"provider":"optco","key":"","on":true}`} {
|
||||
if c := post("/api/settings/plugin-option", bad); c == http.StatusOK {
|
||||
t.Errorf("%s saved", bad)
|
||||
}
|
||||
}
|
||||
has(map[string]map[string]bool{"other": {"x": true}, "optco": {"beta": true, "auto-claim": false}})
|
||||
}
|
||||
+20
-1
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -29,8 +30,21 @@ type pluginSubJSON struct {
|
||||
Methods []plugin.Method `json:"methods"`
|
||||
SignedIn bool `json:"signedIn"`
|
||||
Models int `json:"models"`
|
||||
// Options are the switches the plugin declares (auth.options, #2038),
|
||||
// each with where it stands now
|
||||
Options []pluginOptionJSON `json:"options,omitempty"`
|
||||
}
|
||||
|
||||
// pluginOptionJSON is a plugin's option with the user's value, else its
|
||||
// default.
|
||||
type pluginOptionJSON struct {
|
||||
plugin.Option
|
||||
On bool `json:"on"`
|
||||
}
|
||||
|
||||
// pluginOptionKey is the key an option may have, as the host checks it.
|
||||
var pluginOptionKey = regexp.MustCompile(`^[a-z0-9_-]{1,40}$`)
|
||||
|
||||
// pluginIcon is the vendor's icon: the one the plugin gives its provider,
|
||||
// else the one the plugin market gives the plugin or its provider, else
|
||||
// that of the providers OpenCode names, a plain one for the rest.
|
||||
@@ -57,10 +71,15 @@ func pluginIcon(pp plugin.Provider) string {
|
||||
|
||||
func pluginSubs() []pluginSubJSON {
|
||||
out := []pluginSubJSON{}
|
||||
chosen := settings.Load().PluginOptions
|
||||
for _, pp := range plugin.Cached() {
|
||||
var opts []pluginOptionJSON
|
||||
for _, o := range pp.Options {
|
||||
opts = append(opts, pluginOptionJSON{o, plugin.OptionOn(chosen, pp.ID, o)})
|
||||
}
|
||||
out = append(out, pluginSubJSON{
|
||||
ID: provider.PluginID(pp.ID), PID: pp.ID, Name: pp.Name, Icon: pluginIcon(pp), Spec: pp.Spec,
|
||||
Methods: pp.Methods, SignedIn: pp.SignedIn, Models: len(pp.Models),
|
||||
Methods: pp.Methods, SignedIn: pp.SignedIn, Models: len(pp.Models), Options: opts,
|
||||
})
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -119,6 +119,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
|
||||
FastPicks: map[string][]string{"codex": {"p/n"}},
|
||||
AgentEfforts: map[string]string{"cursor-local": "high"},
|
||||
PluginCheckins: map[string]bool{"fakeco": true},
|
||||
PluginOptions: map[string]map[string]bool{"fakeco": {"auto": true}},
|
||||
CheckinOff: []string{"workbuddy|u1"},
|
||||
ModelNames: map[string]string{"p/m": "Mine"},
|
||||
ModelEfforts: map[string][]string{"p/m": {"low"}},
|
||||
|
||||
@@ -280,6 +280,13 @@ method's questions (a pick, then a text the plugin checks), then takes the
|
||||
code the browser page shows; an API-key way opens the account. English and
|
||||
Chinese, Chromium and WebKit, with the API faked.
|
||||
|
||||
`plugin-options.test.cjs` checks the switches a plugin declares for its
|
||||
provider (#2038), in its editor: the plugin's words shown as text, wrapped
|
||||
inside the editor; a confirm asked before one is turned on, and Cancel
|
||||
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-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,132 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A plugin's own switches (#2038, Vocllum): a plugin declares options for
|
||||
// its provider (auth.options) and its provider's editor shows each as an
|
||||
// Off/On beside the plugin's words, put in as text. One the plugin asks to
|
||||
// confirm asks before it is turned on, and Cancel leaves it off. Changes
|
||||
// wait for Save, which posts each changed one by the plugin's own provider
|
||||
// id before the provider; one switched back is not posted. 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 LONG = "Claims the daily reward whenever usage is read; <b>not</b> on a schedule, and only for accounts that are signed in through this plugin";
|
||||
const plugin = { id: "fakeco", pid: "fakeco", name: "FakeCo", icon: "generic", spec: "opencode-fakeco-auth", signedIn: true, models: 1,
|
||||
methods: [{ type: "api", label: "API key" }],
|
||||
options: [
|
||||
{ key: "auto", label: "Claim <i>rewards</i>", description: LONG, default: true, on: true },
|
||||
{ key: "beta", label: "Beta models", confirm: "Beta models may be withdrawn at any time.", on: false },
|
||||
{ key: "quiet", label: "Quiet", on: false },
|
||||
] };
|
||||
|
||||
function serve(lang, posts) {
|
||||
const payload = { providers: [{ id: "fakeco", name: "FakeCo", icon: "generic", chat: "plugin://fakeco/v1", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "m1", name: "M1", on: true }], agents: [], fallback: [], headers: {}, keyList: [], key: {}, proxy: "", maxConcurrency: null,
|
||||
account: { agent: "fakeco", agentName: "FakeCo", agentIcon: "generic", user: "me@fake", logins: [{ user: "me@fake", active: true, on: true }] } }],
|
||||
presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [plugin] };
|
||||
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 === "/api/settings/plugin-option") {
|
||||
posts.push(["option", route.request().postDataJSON()]);
|
||||
return json({ lang, theme: "light" });
|
||||
}
|
||||
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
|
||||
posts.push([url.pathname.slice("/api/provider/".length), route.request().postDataJSON()]);
|
||||
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 W = {
|
||||
en: { field: "Plugin options", off: "Off", on: "On", turnOn: "Turn on", cancel: "Cancel", save: "Save" },
|
||||
zh: { field: "插件选项", off: "关闭", on: "开启", turnOn: "开启", cancel: "取消", save: "保存" },
|
||||
"zh-TW": { field: "外掛選項", off: "關閉", on: "開啟", turnOn: "開啟", cancel: "取消", save: "儲存" },
|
||||
ja: { field: "プラグインのオプション", off: "オフ", on: "オン", turnOn: "オンにする", cancel: "キャンセル", save: "保存" },
|
||||
de: { field: "Plugin-Optionen", off: "Aus", on: "An", turnOn: "Einschalten", cancel: "Abbrechen", save: "Speichern" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": a plugin's options", 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)) {
|
||||
await t.test(`${width} ${lang}`, async () => {
|
||||
const w = W[lang];
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: "FakeCo" }).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
|
||||
assert.equal(await ed.locator("label", { hasText: w.field }).count(), 1);
|
||||
const row = (k) => box.locator(`.plugin-option[data-key="${k}"]`);
|
||||
const state = async (k) => (await row(k).locator(".opt.on").innerText()).trim();
|
||||
// the plugin's words are text: its markup shows as typed
|
||||
assert.equal(await row("auto").locator(".n").textContent(), "Claim <i>rewards</i>");
|
||||
assert.equal(await row("auto").locator(".hint").textContent(), LONG);
|
||||
assert.equal(await box.locator("i, b").count(), 0);
|
||||
assert.equal(await state("auto"), w.on, "its default");
|
||||
assert.equal(await state("beta"), w.off);
|
||||
// the long words wrap inside the editor; nothing runs past it
|
||||
const spill = await page.evaluate(() => {
|
||||
const e = document.querySelector("#modal .editor"), r = e.getBoundingClientRect();
|
||||
return { page: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
rows: [...e.querySelectorAll(".plugin-option, .plugin-option .segs")].map((x) => x.getBoundingClientRect().right - r.right) };
|
||||
});
|
||||
assert.ok(spill.page <= 0, "the page scrolls sideways by " + spill.page);
|
||||
for (const s of spill.rows) assert.ok(s <= 0, "an option runs past the editor by " + s);
|
||||
if (process.env.ARTIFACT_DIR) await box.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `plugin-options-${engine}-${width}-${lang}.png`) });
|
||||
|
||||
// turning on one the plugin asks to confirm: Cancel leaves it off
|
||||
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(), "Beta models may be withdrawn at any time.");
|
||||
assert.match(await dialog.locator("h2").textContent(), /Beta models/);
|
||||
await dialog.locator("button", { hasText: w.cancel }).click();
|
||||
await dialog.waitFor({ state: "detached" });
|
||||
assert.equal(await state("beta"), w.off);
|
||||
await row("beta").locator(".opt", { hasText: w.on }).click();
|
||||
await dialog.locator("button", { hasText: w.turnOn }).click();
|
||||
await dialog.waitFor({ state: "detached" });
|
||||
assert.equal(await state("beta"), w.on);
|
||||
// no confirm asked of the others; one switched back isn't posted
|
||||
await row("auto").locator(".opt", { hasText: w.off }).click();
|
||||
await row("quiet").locator(".opt", { hasText: w.on }).click();
|
||||
await row("quiet").locator(".opt", { hasText: w.off }).click();
|
||||
assert.equal(await dialog.count(), 0);
|
||||
assert.deepEqual(posts, [], "nothing saved before Save");
|
||||
|
||||
await ed.locator(".bar").getByRole("button", { name: w.save, exact: true }).click();
|
||||
for (let i = 0; i < 50 && !posts.some(([k]) => k === "save"); i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posts.map(([k, b]) => k === "option" ? b : k), [
|
||||
{ provider: "fakeco", key: "beta", on: true },
|
||||
{ provider: "fakeco", key: "auto", on: false },
|
||||
"save",
|
||||
]);
|
||||
assert.deepEqual(errors, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -887,6 +887,7 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) {
|
||||
"directory": settings.Dir(),
|
||||
"config": l.Config,
|
||||
"prefer": l.Prefer,
|
||||
"options": settings.Load().PluginOptions,
|
||||
"plugins": items,
|
||||
}, &res)
|
||||
if err != nil {
|
||||
|
||||
@@ -277,6 +277,9 @@ let userConfig = {}
|
||||
// prefer is the plugin the user picked for a provider id more than one
|
||||
// plugin signs in to: id → its spec (plugins.json's prefer)
|
||||
let prefer = {}
|
||||
// chosen are the user's own values of the plugins' options (auth.options),
|
||||
// provider id → key → true/false (settings.json's pluginOptions, #2038)
|
||||
let chosen = {}
|
||||
const hooks = [] // {spec, hooks}
|
||||
const loaded = [] // {spec, id, error}
|
||||
const loaders = new Map() // account → options the auth loader returned
|
||||
@@ -1135,6 +1138,10 @@ async function loadPlugins(list) {
|
||||
experimental_workspace: { register() {} },
|
||||
serverUrl: new URL("http://127.0.0.1:4096"),
|
||||
$: Bun.$,
|
||||
// magpie's own (OpenCode has none): the plugin's options as the user
|
||||
// set them in magpie, read when wanted, so a change reaches the
|
||||
// plugin without a restart (#2038)
|
||||
magpie: { option: optionValue, options: optionValues },
|
||||
}
|
||||
// pi's packages and extensions are loaded as pi loads them (pi.js)
|
||||
let pi
|
||||
@@ -1377,6 +1384,51 @@ async function info(id, key, strict) {
|
||||
// characters, "" for anything else.
|
||||
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 only kept and handed
|
||||
// over, nothing is run when it changes. 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.
|
||||
const MAX_OPTIONS = 16
|
||||
const OPTION_KEY = /^[a-z0-9_-]{1,40}$/
|
||||
function optionsOf(auth) {
|
||||
const out = []
|
||||
if (!Array.isArray(auth?.options)) return out
|
||||
for (const o of auth.options) {
|
||||
if (out.length >= MAX_OPTIONS) break
|
||||
if (!o || typeof o !== "object" || typeof o.key !== "string" || !OPTION_KEY.test(o.key)) continue
|
||||
if (out.some((x) => x.key === o.key)) continue
|
||||
const label = shown(o.label, 60)
|
||||
if (!label) continue
|
||||
out.push({
|
||||
key: o.key,
|
||||
label,
|
||||
description: shown(o.description, 300),
|
||||
default: o.default === true,
|
||||
confirm: shown(o.confirm, 300),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// optionValues are provider's options as they stand: the user's value,
|
||||
// else the plugin's default, for each key its plugin declares.
|
||||
function optionValues(provider) {
|
||||
const own = chosen?.[provider] ?? {}
|
||||
const out = {}
|
||||
for (const o of optionsOf(auths().get(provider)?.auth)) out[o.key] = typeof own[o.key] === "boolean" ? own[o.key] : o.default
|
||||
return out
|
||||
}
|
||||
|
||||
// optionValue is one of provider's options as it stands; false for a key
|
||||
// its plugin doesn't declare.
|
||||
function optionValue(provider, key) {
|
||||
return optionValues(provider)[key] === true
|
||||
}
|
||||
|
||||
// methods are the auth hook's ways to sign in. An "api" one may say what
|
||||
// its key looks like (placeholder, magpie's own: OpenCode's dialog says
|
||||
// "API key"); its label titles the key's field, as OpenCode's does.
|
||||
@@ -1453,6 +1505,7 @@ async function providers({ proxies } = {}) {
|
||||
icon: iconOf(a),
|
||||
usage: typeof a.auth.usage === "function",
|
||||
checkin: typeof a.auth.checkin === "function",
|
||||
options: optionsOf(a.auth),
|
||||
decide: p.decide === true,
|
||||
searches: p.searches === true,
|
||||
maxConcurrency: concurrencyOf(a),
|
||||
@@ -1983,6 +2036,7 @@ const handlers = {
|
||||
directory = p.directory ?? directory
|
||||
userConfig = p.config ?? {}
|
||||
prefer = p.prefer ?? {}
|
||||
chosen = p.options ?? {}
|
||||
await loadPlugins(p.plugins ?? [])
|
||||
return { plugins: loaded.map(withProviders) }
|
||||
},
|
||||
@@ -1995,6 +2049,12 @@ const handlers = {
|
||||
load,
|
||||
usage,
|
||||
checkin,
|
||||
// setOptions takes the user's option values over, as init did: the
|
||||
// plugin reads them when it next asks (#2038)
|
||||
setProviderOptions(p) {
|
||||
chosen = p?.options ?? {}
|
||||
return null
|
||||
},
|
||||
// check tries one account as a request would: its loader, then its
|
||||
// models as the plugin lists them for it, then its usage, which asks the
|
||||
// vendor of the account itself. refused is the models hook saying the
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// Vocllum (#2038): a plugin declares switches for its provider
|
||||
// (auth.options) and reads the user's values. Only well-formed ones are
|
||||
// listed, at most 16, their text capped; the plugin reads the user's value,
|
||||
// else the default, from the host's start and again after each change,
|
||||
// without a restart.
|
||||
func TestPluginOptions(t *testing.T) {
|
||||
sandbox(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
s := settings.Load()
|
||||
s.PluginOptions = map[string]map[string]bool{"optco": {"auto-claim": false}}
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
abs, _ := filepath.Abs("testdata/options")
|
||||
if _, err := Add(ctx, abs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ps, err := Providers(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
by := map[string]Provider{}
|
||||
for _, p := range ps {
|
||||
by[p.ID] = p
|
||||
}
|
||||
if got := by["plain"].Options; len(got) != 0 {
|
||||
t.Errorf("plain's options = %+v, want none", got)
|
||||
}
|
||||
opts := by["optco"].Options
|
||||
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}) {
|
||||
t.Errorf("first = %+v", opts[0])
|
||||
}
|
||||
if opts[1] != (Option{Key: "beta", Label: "Beta models", Confirm: "Beta models may be withdrawn."}) {
|
||||
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 opts[15].Key != "o12" {
|
||||
t.Errorf("last = %q, want o12", opts[15].Key)
|
||||
}
|
||||
read := func() string {
|
||||
t.Helper()
|
||||
got, err := Validate(ctx, "optco", 0, "probe", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var v []any
|
||||
if json.Unmarshal([]byte(got), &v) != nil || len(v) != 3 {
|
||||
t.Fatalf("the plugin read %q", got)
|
||||
}
|
||||
m, _ := v[0].(map[string]any)
|
||||
return strings.Join([]string{jsonOf(m["auto-claim"]), jsonOf(m["beta"]), jsonOf(m["long"]), jsonOf(v[1]), jsonOf(v[2])}, " ")
|
||||
}
|
||||
// the user's off over the default's on; the rest their defaults
|
||||
if got := read(); got != "false false false false false" {
|
||||
t.Errorf("at start the plugin read %s", got)
|
||||
}
|
||||
s = settings.Load()
|
||||
s.PluginOptions = map[string]map[string]bool{"optco": {"beta": true}}
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetProviderOptions(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(); got != "true true false true false" {
|
||||
t.Errorf("after a change the plugin read %s", got)
|
||||
}
|
||||
if !OptionOn(s.PluginOptions, "optco", opts[0]) || !OptionOn(s.PluginOptions, "optco", opts[1]) || OptionOn(s.PluginOptions, "optco", opts[2]) {
|
||||
t.Error("OptionOn doesn't take the user's value, else the default")
|
||||
}
|
||||
}
|
||||
|
||||
func jsonOf(v any) string {
|
||||
b, _ := json.Marshal(v)
|
||||
return string(b)
|
||||
}
|
||||
@@ -103,6 +103,9 @@ type Provider struct {
|
||||
// Checkin says the plugin presses its vendor's daily check-in for each
|
||||
// account (auth.checkin)
|
||||
Checkin bool `json:"checkin,omitempty"`
|
||||
// Options are the switches the plugin declares for the provider
|
||||
// (auth.options, #2038), as the host checked them
|
||||
Options []Option `json:"options,omitempty"`
|
||||
// Decide says the plugin serves a decision API (TypeSafe's System
|
||||
// One) for this provider: its config hook set decide on it. magpie
|
||||
// posts the questions to the provider's own base, at /systemone,
|
||||
@@ -134,6 +137,38 @@ type Provider struct {
|
||||
MaxConcurrency int `json:"maxConcurrency,omitempty"`
|
||||
}
|
||||
|
||||
// Option is a switch a plugin declares for its provider (auth.options,
|
||||
// #2038): magpie shows it, keeps the user's value in settings'
|
||||
// PluginOptions and hands it to the plugin (input.magpie.option). Nothing
|
||||
// runs when it changes.
|
||||
type Option struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Default bool `json:"default,omitempty"`
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// OptionOn is option o of a provider as it stands with the user's values
|
||||
// in chosen (settings' PluginOptions): theirs, else the plugin's default.
|
||||
func OptionOn(chosen map[string]map[string]bool, provider string, o Option) bool {
|
||||
if v, ok := chosen[provider][o.Key]; ok {
|
||||
return v
|
||||
}
|
||||
return o.Default
|
||||
}
|
||||
|
||||
// SetProviderOptions hands the user's option values (settings' PluginOptions) to
|
||||
// the host running now; a host started later reads them at its start.
|
||||
func SetProviderOptions(ctx context.Context) error {
|
||||
if !Running() {
|
||||
return nil
|
||||
}
|
||||
return Call(ctx, "setProviderOptions", map[string]any{"options": settings.Load().PluginOptions}, nil)
|
||||
}
|
||||
|
||||
// Account is one account a provider is signed in to: Key is where
|
||||
// plugin-auth.json keeps it (the provider's id, else id#slot).
|
||||
type Account struct {
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
// A plugin declaring switches for its provider (auth.options, magpie's own
|
||||
// field, #2038) and reading them as they stand: its key prompt's check
|
||||
// answers with what input.magpie.options says, read when it is asked.
|
||||
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: "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
|
||||
...Array.from({ length: 20 }, (_, i) => ({ key: "o" + i, label: "Option " + i })),
|
||||
],
|
||||
methods: [
|
||||
{
|
||||
type: "api",
|
||||
label: "API key",
|
||||
prompts: [{ type: "text", key: "probe", message: "probe", validate: () => JSON.stringify([input.magpie?.options("optco"), input.magpie?.option("optco", "beta"), input.magpie?.option("optco", "nope")]) }],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
// a provider whose plugin declares none
|
||||
export const Plain = async () => ({ auth: { provider: "plain", options: "not a list", methods: [{ type: "api", label: "API key" }] } })
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "opencode-options-auth",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"main": "index.js"
|
||||
}
|
||||
@@ -184,6 +184,10 @@ type Settings struct {
|
||||
// on or off, by the plugin's provider id; one not set follows its
|
||||
// vendor's switch above, which the plugin took over, else is off.
|
||||
PluginCheckins map[string]bool `json:"pluginCheckins,omitempty"`
|
||||
// PluginOptions are the user's values of the switches plugins declare
|
||||
// for their providers (auth.options, #2038): provider id → the
|
||||
// option's key → on. A key not here takes the plugin's default.
|
||||
PluginOptions map[string]map[string]bool `json:"pluginOptions,omitempty"`
|
||||
// CheckinOff are the accounts left out of their vendor's daily
|
||||
// check-in while it is on (#1902), each by its entry in the vendor's
|
||||
// check-in file: "<site or provider>|<account id>" ("workbuddy|<uid>",
|
||||
|
||||
Reference in New Issue
Block a user