Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

plugins, provider, gui: a keyless plugin sign-in needs no key, and a single-identity plugin has one account (#2695, LoKi)

LoKi5871f02dd653
diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md
index 9a844e7fd..36ea7e70c 100644
--- a/docs/subsystems/provider-plugins.md
+++ b/docs/subsystems/provider-plugins.md
@@ -228,3 +228,14 @@ Run the relevant package tests with an isolated home directory. Resolve GOPATH a
```
Some migration and gateway plugin tests require Bun on PATH and use local plugin fixtures; they skip when Bun is unavailable. Report any skipped tests and verify the community package separately when its implementation changes.
+
+### Fixed-credential sign-in
+
+An `auth.methods` API method may declare magpie-only `keyless: true` when
+its `authorize` function supplies the credential. The host carries this
+boolean only for API methods with an authorize function. GUI and CLI skip
+personal-key entry for it; ordinary API methods still require a key.
+`auth.single: true` declares one provider identity: signing in again reuses
+its account slot and the account action says Sign in again. Existing records
+are not deleted. Other plugins keep multiple accounts. OpenCode ignores
+these optional fields; no provider id is special-cased in magpie.
diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go
index af0cc8e1e..83ce70dac 100644
--- a/internal/cli/plugins_cli.go
+++ b/internal/cli/plugins_cli.go
@@ -465,9 +465,13 @@ func pluginLogin(ctx context.Context, name, method string) error {
ctx = provider.Via(ctx, provider.PluginID(pp.ID))
var saved plugin.Saved
if pp.Methods[m].Type == "api" {
- key, err := secret("key", keyPrompt(pp.Name, pp.Methods[m]), false)
- if err != nil {
- return err
+ key := ""
+ if !pp.Methods[m].Keyless {
+ var err error
+ key, err = secret("key", keyPrompt(pp.Name, pp.Methods[m]), false)
+ if err != nil {
+ return err
+ }
}
if saved, err = plugin.APIKey(ctx, pp.ID, m, inputs, key, plugin.NewAccount); err != nil {
return err
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index 309464e02..9e7dd94c3 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -11998,7 +11998,7 @@ function pluginMethod(sub, site) {
// magpie, signs in and carries the requests.
function pluginSubs() {
return (providers.plugins || []).map((x) => ({
- agent: x.id, pid: x.pid, name: x.name, icon: x.icon, plugin: x, own: true,
+ agent: x.id, pid: x.pid, name: x.name, icon: x.icon, plugin: x, own: true, single: !!x.single,
get plans() { return t("from the plugin {spec}", { spec: x.spec }); },
}));
}
@@ -12175,7 +12175,8 @@ async function startPluginSignIn(sub, method, inputs = {}, o = {}) {
return renderProviders();
}
if (ms[method].type === "api") {
- signing = { agent: sub.agent, ...keep, state: "key" };
+ signing = { agent: sub.agent, ...keep, state: ms[method].keyless === true ? "starting" : "key" };
+ if (ms[method].keyless === true) return pluginKey(sub, "");
return renderProviders();
}
const body = { provider: sub.pid, method, inputs };
@@ -12219,7 +12220,7 @@ async function pluginKey(sub, key) {
const st = await api("plugin-signin", { provider: sub.pid, method: flow.method, inputs: flow.inputs, key });
if (signing?.agent === sub.agent) signedIn(st);
} catch (e) {
- if (signing?.agent === sub.agent) { signing = { ...flow, error: e.message }; renderProviders(); }
+ if (signing?.agent === sub.agent) { signing = { ...flow, state: flow.state === "starting" ? "failed" : flow.state, error: e.message }; renderProviders(); }
}
}
@@ -13089,7 +13090,7 @@ function renderAccounts(a, p) {
const add = el("button", "acc add");
const ic = el("span", "dot");
ic.append(svg(PLUS, 10, 1.8));
- add.append(ic, el("span", "n", t(sub.single ? "Sign in to another {name} account" : "Add another {name} account", { name: sub.name })));
+ add.append(ic, el("span", "n", t(sub.single && sub.plugin ? "Sign in again" : sub.single ? "Sign in to another {name} account" : "Add another {name} account", { name: sub.name })));
add.onclick = () => startSignIn(a.agent);
list.append(add);
if (sub.importable) {
diff --git a/internal/gui/plugin_keyless_test.go b/internal/gui/plugin_keyless_test.go
new file mode 100644
index 000000000..29c53d377
--- /dev/null
+++ b/internal/gui/plugin_keyless_test.go
@@ -0,0 +1,25 @@
+package gui
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/yetone/magpie/internal/plugin"
+)
+
+func TestPluginSubscriptionCarriesSingleIdentity(t *testing.T) {
+ cfg := pluginsSandbox(t)
+ if err := os.MkdirAll(cfg, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(cfg, "plugins.json"), []byte(`{"plugins":[{"spec":"public-fixture-plugin"}]}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ plugin.UseCached([]plugin.Provider{{ID: "public-fixture", Spec: "public-fixture-plugin", Name: "Public fixture", Single: true, Methods: []plugin.Method{{Type: "api", Keyless: true}}}})
+ t.Cleanup(func() { plugin.UseCached(nil) })
+ subs := pluginSubs()
+ if len(subs) != 1 || !subs[0].Single || len(subs[0].Methods) != 1 || !subs[0].Methods[0].Keyless {
+ t.Fatalf("subscription lost metadata: %+v", subs)
+ }
+}
diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go
index d36829d47..0eb87a369 100644
--- a/internal/gui/plugins.go
+++ b/internal/gui/plugins.go
@@ -31,6 +31,7 @@ type pluginSubJSON struct {
Spec string `json:"spec"` // the plugin
Methods []plugin.Method `json:"methods"`
SignedIn bool `json:"signedIn"`
+ Single bool `json:"single,omitempty"`
Models int `json:"models"`
// Options are the switches the plugin declares (auth.options, #2038),
// each with where it stands now
@@ -81,7 +82,7 @@ func pluginSubs() []pluginSubJSON {
}
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), Options: opts,
+ Methods: pp.Methods, SignedIn: pp.SignedIn, Single: pp.Single, Models: len(pp.Models), Options: opts,
})
}
return out
diff --git a/internal/gui/tests/plugin-keyless-signin.test.cjs b/internal/gui/tests/plugin-keyless-signin.test.cjs
new file mode 100644
index 000000000..cd61ac4d7
--- /dev/null
+++ b/internal/gui/tests/plugin-keyless-signin.test.cjs
@@ -0,0 +1,59 @@
+const {test}=require('node:test');
+const assert=require('node:assert/strict');
+const fs=require('node:fs/promises');
+const path=require('node:path');
+const {chromium,webkit}=require('playwright');
+const assets=path.resolve(__dirname,'../assets');
+for(const [engine,browserType] of Object.entries({chromium,webkit}))for(const lang of ['en','zh','zh-TW','ja','de']){
+ test(`${engine} ${lang}: plugin-declared keyless access skips keys and retains one identity`,async(t)=>{
+ const browser=await browserType.launch({headless:true});t.after(()=>browser.close());
+ const page=await browser.newPage({viewport:{width:900,height:900},reducedMotion:'reduce'});
+ page.setDefaultTimeout(5000);
+ const asked=[],errors=[];let signed=false;page.on('pageerror',e=>errors.push(e.message));
+ const methods=[{type:'api',label:'Enable fixed access',keyless:true}];
+ const plugins=[{id:'fixed-access-plugin',pid:'fixed-access',name:'PublicFixture',icon:'generic',spec:'public-fixture',methods,single:true},{id:'ordinary-fixture',pid:'ordinary-fixture',name:'OrdinaryFixture',icon:'generic',spec:'ordinary-fixture',methods:[{type:'api',label:'Personal credential'}]}];
+ const payload=()=>({providers:[{id:'openai',name:'OpenAI',icon:'openai',models:[],agents:[],key:{}},...(signed?[{id:'fixed-access-plugin',name:'PublicFixture',icon:'generic',models:[],agents:[],key:{},account:{agent:'fixed-access-plugin',agentName:'PublicFixture',agentIcon:'generic',user:'public-fixture',logins:[{user:'public-fixture',active:true,on:true}]}}]:[])],presets:[],excluded:[],gateway:{running:true,window:true},plugins:plugins.map((p,i)=>({...p,signedIn:i===0&&signed,models:1}))});
+ await page.route('**/*',async route=>{
+ const u=new URL(route.request().url()),json=data=>route.fulfill({json:data});
+ if(u.pathname==='/boot.js')return route.fulfill({contentType:'text/javascript',body:`window.bootPrefs=${JSON.stringify({lang,theme:'light',web:true})}`});
+ if(u.pathname==='/wails/runtime.js')return route.fulfill({contentType:'text/javascript',body:'export const Window = {};'});
+ if(u.pathname==='/api/state')return json({agents:[],profiles:[],settings:{lang,theme:'light'}});
+ if(u.pathname==='/api/providers')return json(payload());
+ if(u.pathname==='/api/plugin-signin/prompt')return json({prompt:null,inputs:{}});
+ if(u.pathname==='/api/plugin-signin'){
+ const b=route.request().postDataJSON();asked.push(b);if(lang==='en' && asked.length===1)return route.fulfill({status:400,json:{error:'fixture denied'}});signed=true;
+ return json({agent:'fixed-access-plugin',state:'done',user:'public-fixture',using:true,again:asked.length>1});
+ }
+ if(u.pathname==='/api/groups')return json({groups:[],models:[]});
+ if(u.pathname==='/api/plugins')return json({plugins:[]});
+ if(u.pathname.startsWith('/api/'))return json({});
+ const file=path.join(assets,u.pathname==='/'?'index.html':u.pathname);
+ try{return route.fulfill({body:await fs.readFile(file),contentType:{'.html':'text/html','.js':'text/javascript','.css':'text/css','.svg':'image/svg+xml'}[path.extname(file)]});}catch{return route.fulfill({status:404,body:''});}
+ });
+ await page.goto('http://magpie.test/?view=providers');
+ await page.locator('#addProvider').click();
+ await page.locator('#addSheet .tile[data-pick="PublicFixture"]').click();
+ const choice=page.getByRole('button',{name:'Enable fixed access',exact:true});
+ if(await choice.count())await choice.click();
+ if(lang==='en'){await page.locator('.signing.failed').waitFor();assert.equal(await page.locator('.callback-form input').count(),0);await page.locator('.signing.failed button.primary').click();}
+ await page.locator('button.acc.add .n').waitFor();
+ assert.deepEqual(asked,Array.from({length:lang==='en'?2:1},()=>({provider:'fixed-access',method:0,inputs:{},key:''})));
+ assert.equal(await page.locator('.callback-form input').count(),0,'no personal-key field');
+ assert.ok(!(await page.locator('button.acc.add .n').innerText()).includes('PublicFixture'),'single identity offers sign-in again, not another account');
+ const renewed=page.waitForRequest(r=>new URL(r.url()).pathname==='/api/plugin-signin');
+ await page.locator('button.acc.add').click();
+ if(await choice.count())await choice.click();
+ await renewed;
+ await page.locator('button.acc.add .n').waitFor();
+ assert.equal(asked.length,lang==='en'?3:2,'explicit sign-in again makes one request');
+ await page.keyboard.press('Escape');await page.locator('#modal').waitFor({state:'hidden'});
+ await page.locator('#addProvider').click();
+ await page.locator('#addSheet .tile[data-pick="OrdinaryFixture"]').click();
+ const ordinary=page.getByRole('button',{name:'Personal credential',exact:true});
+ if(await ordinary.count())await ordinary.click();
+ await page.getByLabel('Personal credential',{exact:true}).waitFor();
+ assert.equal(asked.length,lang==='en'?3:2,'ordinary plugin waits for a personal key');
+ for(const width of [440,900]){await page.setViewportSize({width,height:900});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));}
+ assert.deepEqual(errors,[]);
+ });
+}
diff --git a/internal/plugin/host.js b/internal/plugin/host.js
index 61642a7bc..0f5702594 100644
--- a/internal/plugin/host.js
+++ b/internal/plugin/host.js
@@ -1841,6 +1841,7 @@ function methods(auth) {
return (auth.methods ?? []).map((m) => ({
type: m.type,
label: m.label,
+ ...(m.type === "api" && m.keyless === true && typeof m.authorize === "function" ? { keyless: true } : {}),
...(m.type === "api" && shown(m.placeholder, 200) ? { placeholder: shown(m.placeholder, 200) } : {}),
}))
}
@@ -1922,6 +1923,7 @@ async function providers({ proxies } = {}) {
npm: p.npm ?? "",
api: p.api ?? "",
methods: methods(a.auth),
+ single: a.auth.single === true,
icon: iconOf(a),
usage: typeof a.auth.usage === "function",
checkin: typeof a.auth.checkin === "function",
@@ -2044,6 +2046,7 @@ function save(provider, key, result, inputs, apiKey) {
// signInKey is where a sign-in goes: the account named, else a new one.
function signInKey(provider, account) {
+ if (authOf(provider).single === true) return accountsOf(readAuth(), provider)[0] ?? provider
return account && account !== "new" && providerOf(account) === provider ? account : freshKey(provider)
}
diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go
index 5a6be67e2..4aef959e7 100644
--- a/internal/plugin/providers.go
+++ b/internal/plugin/providers.go
@@ -29,6 +29,8 @@ type Method struct {
// Placeholder is the hint an "api" method gives in its key's field
// (magpie's own field: OpenCode's says "API key")
Placeholder string `json:"placeholder,omitempty"`
+ // Keyless skips personal-key entry; authorize supplies the credential.
+ Keyless bool `json:"keyless,omitempty"`
}
// KeyTitle is what an "api" method's key is asked as: its label, as
@@ -151,6 +153,8 @@ type Provider struct {
// Accounts are the accounts signed in to it, the one kept under its
// own id first; SignedIn, AuthType and AccountID are that one's.
Accounts []Account `json:"accounts"`
+ // Single is the auth hook declaring that sign-in replaces one identity.
+ Single bool `json:"single,omitempty"`
// MaxConcurrency is how many requests the plugin says each of its
// accounts takes at once (magpie's own field, which OpenCode ignores:
// the auth hook's maxConcurrency, else package.json's
diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js
index f4b0ecb16..9e2092e09 100644
--- a/internal/plugin/testdata/fake/index.js
+++ b/internal/plugin/testdata/fake/index.js
@@ -131,8 +131,9 @@ export const FakePlugin = async ({ client }) => ({
},
auth: {
provider: ID,
+ single: process.env.FAKE_KEYLESS === "1",
methods: [
- { type: "api", label: "API key" },
+ { type: "api", label: "API key", ...(process.env.FAKE_KEYLESS === "1" ? { keyless: true, authorize: async (inputs) => ({ type: "success", key: inputs.credential || "public-fixture" }) } : {}) },
{
type: "oauth",
label: "Browser",
diff --git a/internal/provider/pluginsignin.go b/internal/provider/pluginsignin.go
index cdfa75300..8565099a2 100644
--- a/internal/provider/pluginsignin.go
+++ b/internal/provider/pluginsignin.go
@@ -215,7 +215,10 @@ func (s *signInFlow) pluginDone(saved plugin.Saved, err error) {
// provider's magpie id.
func PluginAPIKey(ctx context.Context, id string, method int, inputs map[string]string, key string) (string, error) {
if strings.TrimSpace(key) == "" {
- return "", errors.New("enter the key")
+ pp, ok := PluginOf(PluginID(id))
+ if !ok || method < 0 || method >= len(pp.Methods) || pp.Methods[method].Type != "api" || !pp.Methods[method].Keyless {
+ return "", errors.New("enter the key")
+ }
}
// through the proxy the provider's requests go through (#1663)
saved, err := plugin.APIKey(Via(ctx, PluginID(id)), id, method, inputs, strings.TrimSpace(key), plugin.NewAccount)
diff --git a/internal/provider/pluginsignin_test.go b/internal/provider/pluginsignin_test.go
index 11fecc3c5..aa0d16db6 100644
--- a/internal/provider/pluginsignin_test.go
+++ b/internal/provider/pluginsignin_test.go
@@ -2,6 +2,7 @@ package provider
import (
"context"
+ "os"
"path/filepath"
"slices"
"strings"
@@ -9,6 +10,7 @@ import (
"time"
"github.com/yetone/magpie/internal/plugin"
+ "github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/testenv"
)
@@ -228,3 +230,61 @@ func TestPluginAccounts(t *testing.T) {
t.Fatalf("shown again with %v, was %v", got, us)
}
}
+
+// Keyless is generic metadata: neither the provider id nor credential is
+// known to the host. Ordinary API methods still reject empty input.
+func TestPluginKeylessSingleIdentity(t *testing.T) {
+ bun := testenv.Bun(t)
+ claudeHome(t)
+ t.Setenv("MAGPIE_BUN", bun)
+ t.Setenv("FAKE_KEYLESS", "1")
+ t.Cleanup(plugin.Settle)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
+ if _, err := plugin.Add(ctx, abs); err != nil {
+ t.Fatal(err)
+ }
+ ps, err := plugin.Providers(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(ps) != 1 || !ps[0].Single || !ps[0].Methods[0].Keyless || ps[0].Methods[1].Keyless {
+ t.Fatalf("keyless metadata lost or leaked to OAuth: %+v", ps)
+ }
+ for _, credential := range []string{"public-fixture", "renewed-fixture"} {
+ if id, err := PluginAPIKey(ctx, "fakeco", 0, map[string]string{"credential": credential}, ""); err != nil || id != "fakeco" {
+ t.Fatalf("keyless sign-in: %q %v", id, err)
+ }
+ }
+ ps, err = plugin.Providers(ctx)
+ if err != nil || len(ps[0].Accounts) != 1 {
+ t.Fatalf("single identity duplicated: %+v %v", ps, err)
+ }
+ if _, err := PluginAPIKey(ctx, "fakeco", 1, nil, ""); err == nil {
+ t.Fatal("OAuth must not accept an empty API key")
+ }
+}
+
+// An empty key is taken only by an API method the plugin says is keyless:
+// a plain API method, or one of another plugin, still asks for the key.
+func TestPluginEmptyKeyOnlyKeyless(t *testing.T) {
+ claudeHome(t)
+ t.Setenv("MAGPIE_BUN", "")
+ spec := "@example/opencode-acme-auth"
+ os.MkdirAll(settings.Dir(), 0o700)
+ if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), []byte(`{"plugins":[{"spec":"`+spec+`"}]}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ plugin.UseCached([]plugin.Provider{{ID: "acme", Spec: spec, Name: "Acme",
+ Methods: []plugin.Method{{Type: "api", Label: "API key"}, {Type: "oauth", Label: "Browser", Keyless: true}}}})
+ t.Cleanup(func() { plugin.UseCached(nil) })
+ for _, m := range []int{0, 1, 2, -1} {
+ if _, err := PluginAPIKey(context.Background(), "acme", m, nil, " "); err == nil || err.Error() != "enter the key" {
+ t.Errorf("method %d with no key: %v, want enter the key", m, err)
+ }
+ }
+ if _, err := PluginAPIKey(context.Background(), "nobody", 0, nil, ""); err == nil || err.Error() != "enter the key" {
+ t.Errorf("an unknown plugin with no key: %v", err)
+ }
+}