plugin: a cancelled sign-in saves nothing, and a failed authorize says why (#5016)

Found reviewing magpie-community/plugins#658 (AStudio's and Agnes Code's
sign-ins wait up to 5 minutes for the vendor's desktop app).

Cancel didn't end a plugin sign-in. The window's Cancel (and the sign-in's
timeout) ended plugin.Finish's context, but "callback" was not a
cancellable call, so the host never heard: the plugin's wait went on, and
a session file written after Cancel still saved the account. Now
authorize, callback and apiKey are cancellable as gatewayRequest is
(host.go `cancellable`): magpie writes `abort`, host.js (`signInSteps`)
drops whatever the plugin answers after it, so nothing is saved, and
counts the call done at once. The plugin's wait is told too: every fetch
it makes for the sign-in carries the sign-in's signal
(`whileSigningIn`), and magpie's hook passes the signal as
callback(code, { signal }) / authorize(inputs, { signal }), which OpenCode
doesn't, so a plugin can stop polling a file. A plugin that ignores the
signal keeps running until its own deadline, but its answer is dropped.

An oauth method's authorize that returned { type: "failed", error } (no
callback) was stored and its missing callback called, so the user saw
"s.a.callback is not a function". host.js now answers that, or any result
with no callback, as the sign-in's failure, and plugin.Authorize returns
ErrFailed with the plugin's reason, for auto and code methods; an api
method's authorize already did. The GUI's start shows it as its failure,
`magpie plugin login` prints it.

Docs: provider-plugins.md, and the plugin guide (en, zh, ja) on failing
from authorize and the signal.

Not changed: #3083's timeout field, #4678's model/usage task lifetime.

Tests (testdata/signinend, no network; the vendor is testenv.FakeVendor):
TestCancelledSignInSavesNothing, TestCancelledSignInEndsThePluginsWait,
TestCancelledSignInEndsItsFetch, TestSignInFailsWithThePluginsReason
(internal/plugin), TestCancelledPluginSignInSavesNothing
(internal/provider, through StartPluginSignIn/CancelSignIn).

Run on mote (macOS 27), at this change on d73f2254d (the new tests and vet of both packages again after the rebase on 897e88d7e, which touches neither):
- go test -count=1 -timeout 45m ./internal/plugin/ ./internal/provider/:
  ok (134s, 145s); the new tests -v: all PASS.
- ./internal/cli ok; ./internal/gui FAIL only in
  TestMainWindowCorners/macOS_26_SDK, #3949 (macOS 27 on mote; this
  change touches no GUI code).
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok;
  gofmt -l: nothing.
- GUI (Chromium + WebKit): plugin-signin, plugin-signin-no-url,
  plugin-signin-opened (en, zh, zh-TW, ja, de), plugin-signin-scrolls,
  plugin-keyless-signin, plugin-moved-signin, signin-paste-plugin,
  signin-close, i18n-keys: 108/108.

Red on the old code (origin/main's host.js, host.go, providers.go): all
four plugin tests (an account saved after Cancel; the plugin's wait and
its fetch not ended, timed out; methods 2/3/4 said "s.a.callback is not
a function"), and TestCancelledPluginSignInSavesNothing.
Broken by hand: host.go's `cancellable` back to gatewayRequest only, all
three cancel tests red; the whileSigningIn line out of the fetch wrapper,
TestCancelledSignInEndsItsFetch red.

Not tried: the real AStudio and Agnes Code plugins (plugins#658) against
this host; the site's plugin guide isn't deployed by this commit.
This commit is contained in:
yetone
2026-11-03 13:40:20 +08:00
parent 897e88d7e6
commit 441a2b6b16
10 changed files with 425 additions and 12 deletions
+2
View File
@@ -287,6 +287,8 @@ A plugin's account whose sign-in its vendor refused (`lapsed`, or an allowance r
A plugin sign-in's page is opened once. An `authorize` result may say `opened: true` (not OpenCode's field): the plugin's own CLI opened the page already. Grok's `grok login --device-auth` does this on macOS and Windows, where nothing turns it off, and magpie's opening it too showed two pages (andyfmyth on X; plugin 0.1.17, which on other systems gives grok a `BROWSER` that opens nothing instead). `host.js` passes it on as `Authorization.Opened`, then `SignInState.Opened`, and the desktop's `/api/plugin-signin`, `magpie plugin login` and the window in a browser tab (`startPluginSignIn`, and `followSignIn` after an install) then open nothing; the page's link is still shown (`TestPluginSignInPageOpensOnce`, `plugin-signin-opened.test.cjs`).
A plugin sign-in magpie gives up on ends in the host too (#5016). The user's Cancel, or the sign-in's timeout (`signInTimeout`), ends `plugin.Finish`'s context, and `authorize`, `callback` and `apiKey` are cancellable calls (`cancellable` in [`host.go`](../../internal/plugin/host.go)), as a gateway request is: magpie writes `abort` for the call, and `host.js` (`signInSteps`) drops whatever the plugin answers after it, so nothing is saved, and counts the call as done at once. The plugin's own wait is told where the host can tell it: every fetch the plugin makes for the sign-in carries the sign-in's signal (`whileSigningIn`), and magpie's hook hands the signal to the plugin as a second argument, `callback(code, { signal })` and `authorize(inputs, { signal })` (OpenCode passes none), so a plugin that polls a file or its vendor for minutes (AStudio's waits on its desktop app's session file, plugins#658) can stop. Before, a session file written after Cancel still signed the account in. An `oauth` method's `authorize` that can't start says why as an `api` method's does, `{ type: "failed", error }`; `host.js` answers it, or a result with no `callback`, as the sign-in's failure (`plugin.Authorize` gives `ErrFailed` with the reason) instead of calling the callback it lacks, which reached the user as "s.a.callback is not a function". `TestCancelledSignInSavesNothing`, `TestCancelledSignInEndsThePluginsWait`, `TestCancelledSignInEndsItsFetch` and `TestSignInFailsWithThePluginsReason` in [`plugin_signinend_test.go`](../../internal/plugin/plugin_signinend_test.go).
The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSignIn`. A change to sign-in or provider presentation must follow these paths as well as the built-in paths it affects.
## Verification
+7 -2
View File
@@ -118,7 +118,7 @@ type call struct {
// the body's reader takes them: the host's reader queues them without
// ever waiting on one request's consumer (see push).
stream bool
cancellable bool // a gateway request owns asynchronous I/O, without a stream slot
cancellable bool // a gateway request or sign-in step owns asynchronous I/O, without a stream slot
mu sync.Mutex
queue []message
queued int // the queued chunks' decoded bytes
@@ -1594,6 +1594,11 @@ func (h *host) releaseSlot(c *call) {
}
}
// cancellable are the methods whose work the host ends when their caller
// gives up: a gateway request's I/O, and a sign-in's steps, so a sign-in
// cancelled or timed out saves nothing the plugin answers after (#5016).
var cancellable = map[string]bool{"gatewayRequest": true, "authorize": true, "callback": true, "apiKey": true}
// call asks the host method with params and reads its answer into out.
func (h *host) call(ctx context.Context, method string, params, out any) error {
id, c, err := h.begin(false)
@@ -1601,7 +1606,7 @@ func (h *host) call(ctx context.Context, method string, params, out any) error {
return err
}
c.mu.Lock()
c.cancellable = method == "gatewayRequest"
c.cancellable = cancellable[method]
c.mu.Unlock()
if err := h.enqueueCall(ctx, map[string]any{"id": id, "method": method, "params": params}, nil, c); err != nil {
c.settle(err)
+77 -7
View File
@@ -604,8 +604,23 @@ function unsaid(input, init) {
return [input, init]
}
// signInSignal is the signal of the sign-in a plugin's step runs for: a
// fetch made for it fails once magpie has given the sign-in up.
const signInSignal = new AsyncLocalStorage()
// whileSigningIn gives a fetch made for a sign-in that sign-in's signal
// beside its own, so a sign-in magpie gave up on stops polling its vendor
// (#5016).
function whileSigningIn(input, init) {
const signal = signInSignal.getStore()
if (!signal) return [input, init]
const own = init?.signal ?? (input instanceof Request ? input.signal : undefined)
return [input, { ...init, signal: own ? AbortSignal.any([own, signal]) : signal }]
}
globalThis.fetch = Object.assign(function fetch(input, init) {
;[input, init] = unsaid(input, init)
;[input, init] = whileSigningIn(input, init)
const r = reach.getStore()
if (!r) return asked(input, init)
return asked(input, init).then(
@@ -2300,7 +2315,14 @@ let nextSession = 1
// as fetch's: "", "direct" or its URL), so the vendor sees the account
// come from one place from its first request on (#1663): authorize and the
// callback that trades the code are both run under it.
async function authorize({ provider, method, inputs, account, proxy }) {
//
// A sign-in magpie gives up on (the user cancelled it, or it timed out)
// ends here as well (#5016): signal is aborted, the fetches the plugin
// makes for it fail, the plugin's own wait is handed it (magpie's hook:
// callback(code, { signal }), authorize(inputs, { signal }); OpenCode
// passes none), and whatever the plugin answers after it is dropped,
// nothing saved.
async function authorize({ provider, method, inputs, account, proxy }, signal) {
const m = authOf(provider).methods[method]
if (!m) throw new Error(`no sign-in method ${method} for ${provider}`)
if (m.type !== "oauth") throw new Error("not an oauth method")
@@ -2310,13 +2332,21 @@ async function authorize({ provider, method, inputs, account, proxy }) {
// auth login) calls, and a plugin told so asks its questions on the
// terminal, magpie's stdin here (opencode-antigravity-auth waited on its
// "Project ID" prompt, the sign-in never starting)
const a = await via.run(proxy ?? "", () => inScope(provider, key, () => m.authorize(m.prompts?.length ? inputs ?? {} : undefined)))
const a = await signingIn(signal, proxy ?? "", provider, key, () => m.authorize(m.prompts?.length ? inputs ?? {} : undefined, { signal }))
if (signal?.aborted) throw abortedSignIn()
// a plugin that can't start the sign-in may say why as an api method's
// authorize does ({ type: "failed", error }) rather than throw; with no
// callback there is nothing to wait on, and calling the one it lacks
// said "s.a.callback is not a function" instead of its reason
// (plugins#658)
if (a?.type === "failed") return failed(a)
if (typeof a?.callback !== "function") return { ok: false, error: `${provider}'s sign-in gave nothing to finish it with` }
const session = String(nextSession++)
sessions.set(session, { provider, key, a, inputs, proxy: proxy ?? "" })
// opened (not OpenCode's) is a page the plugin's own CLI opened already:
// Grok Build's `grok login` opens it on macOS and Windows, and magpie's
// opening it too showed it twice (andyfmyth on X)
return { session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method, opened: a.opened === true }
return { ok: true, session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method, opened: a.opened === true }
}
// failed is a sign-in's failure, with why, where the plugin tells it
@@ -2326,16 +2356,28 @@ function failed(r) {
return why ? { ok: false, error: why.slice(0, 500) } : { ok: false }
}
async function callback({ session, code }) {
function abortedSignIn() {
return new DOMException("the sign-in was cancelled", "AbortError")
}
// signingIn runs a plugin's sign-in step fn for key under proxy and
// signal; it ends when signal aborts, whether fn does or not.
function signingIn(signal, proxy, provider, key, fn) {
const step = via.run(proxy, () => inScope(provider, key, () => signInSignal.run(signal, fn)))
return signal ? bounded(Promise.resolve(step), signal) : step
}
async function callback({ session, code }, signal) {
const s = sessions.get(session)
if (!s) throw new Error("no such sign-in")
sessions.delete(session)
const r = await via.run(s.proxy, () => inScope(s.provider, s.key, () => (s.a.method === "code" ? s.a.callback(code ?? "") : s.a.callback())))
const r = await signingIn(signal, s.proxy, s.provider, s.key, () => (s.a.method === "code" ? s.a.callback(code ?? "", { signal }) : s.a.callback(undefined, { signal })))
if (signal?.aborted) throw abortedSignIn()
if (!r || r.type !== "success") return failed(r)
return { ok: true, ...save(s.provider, s.key, r, undefined) }
}
async function apiKey({ provider, method, inputs, key, account, proxy }) {
async function apiKey({ provider, method, inputs, key, account, proxy }, signal) {
const m = authOf(provider).methods[method]
if (!m || m.type !== "api") throw new Error("not an API key method")
const at = signInKey(provider, account)
@@ -2344,7 +2386,8 @@ async function apiKey({ provider, method, inputs, key, account, proxy }) {
setAuth(at, { type: "api", key, ...md })
return { ok: true, provider, account: settle(provider, at) }
}
const r = await via.run(proxy ?? "", () => inScope(provider, at, () => m.authorize(inputs ?? {})))
const r = await signingIn(signal, proxy ?? "", provider, at, () => m.authorize(inputs ?? {}, { signal }))
if (signal?.aborted) throw abortedSignIn()
if (!r || r.type !== "success") return failed(r)
return { ok: true, ...save(provider, at, r, inputs, key) }
}
@@ -3009,6 +3052,12 @@ const done = () => {
}
const gatewayInflight = new Map() // RPC id -> AbortController
// A sign-in's steps are given up on by magpie as a gateway request is
// (host.go's cancellable): the user cancelled it, or it timed out. Its
// answer is then nobody's, and it counts as done at once, whether the
// plugin's wait ends or not (#5016).
const signInSteps = new Set(["authorize", "callback", "apiKey"])
const signInInflight = new Map() // RPC id -> AbortController
const rl = readline.createInterface({ input: process.stdin, terminal: false })
rl.on("line", (line) => {
if (!line.trim()) return
@@ -3023,6 +3072,7 @@ rl.on("line", (line) => {
const record = inflight.get(id)
if (record) transitionFetch(record, "cancelled")
gatewayInflight.get(id)?.abort()
signInInflight.get(id)?.abort()
return
}
if (msg.method === "credit") {
@@ -3086,6 +3136,26 @@ rl.on("line", (line) => {
})
return
}
if (signInSteps.has(msg.method)) {
const ctl = new AbortController()
signInInflight.set(msg.id, ctl)
let over = false
const end = () => {
if (over) return
over = true
signInInflight.delete(msg.id)
done()
}
ctl.signal.addEventListener("abort", end, { once: true })
bounded(ready ?? Promise.reject(new Error("the host has not been initialised")), ctl.signal)
.then(() => handlers[msg.method](msg.params ?? {}, ctl.signal))
.then(
(result) => { if (!ctl.signal.aborted) send({ id: msg.id, result: result ?? null }) },
(e) => { if (!ctl.signal.aborted) send({ id: msg.id, error: { message: String(e?.message ?? e) } }) },
)
.finally(end)
return
}
const wait = ready ?? Promise.reject(new Error("the host has not been initialised"))
const fn = handlers[msg.method]
if (!fn) {
+172
View File
@@ -0,0 +1,172 @@
package plugin
import (
"context"
"errors"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/testenv"
)
// signInEnd adds testdata/signinend, whose sign-ins wait on $HOME/go as
// AStudio's waits on its desktop app's session file (plugins#658).
func signInEnd(t *testing.T) (context.Context, string) {
t.Helper()
sandbox(t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
abs, _ := filepath.Abs("testdata/signinend/index.js")
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
return ctx, os.Getenv("HOME")
}
// markedWithin is whether the plugin wrote $HOME/name within d.
func markedWithin(home, name string, d time.Duration) bool {
for end := time.Now().Add(d); ; {
if _, err := os.Stat(filepath.Join(home, name)); err == nil {
return true
}
if time.Now().After(end) {
return false
}
time.Sleep(20 * time.Millisecond)
}
}
// cancelledFinish starts the method's sign-in and gives its wait up once
// the plugin is waiting (it marks $HOME/waiting, or its vendor is asked),
// as the GUI's Cancel does (signInFlow.stop).
func cancelledFinish(t *testing.T, ctx context.Context, method int, waiting <-chan struct{}) {
t.Helper()
a, err := Authorize(ctx, "signinend", method, nil, NewAccount)
if err != nil {
t.Fatal(err)
}
wait, cancel := context.WithCancel(ctx)
go func() {
if waiting != nil {
<-waiting
} else {
markedWithin(os.Getenv("HOME"), "waiting", 30*time.Second)
}
cancel()
}()
if _, err := Finish(wait, a.Session, ""); !errors.Is(err, context.Canceled) {
t.Fatalf("Finish after cancel = %v, want context.Canceled", err)
}
}
// #5016: a sign-in cancelled in magpie saved the account all the same
// when the plugin's wait came true after it. What the plugin answers once
// the sign-in is given up is dropped.
func TestCancelledSignInSavesNothing(t *testing.T) {
ctx, home := signInEnd(t)
cancelledFinish(t, ctx, 0, nil)
if err := os.WriteFile(filepath.Join(home, "go"), nil, 0o600); err != nil {
t.Fatal(err)
}
if !markedWithin(home, "returned", 30*time.Second) {
t.Fatal("the plugin's wait never came true")
}
// one more answer from the host, after the callback's result was dealt with
if _, err := Providers(ctx); err != nil {
t.Fatal(err)
}
if SignedIn("signinend") {
b, _ := os.ReadFile(AuthPath())
t.Fatalf("a cancelled sign-in was saved: %s", b)
}
// and the next sign-in is the user's
a, err := Authorize(ctx, "signinend", 0, nil, NewAccount)
if err != nil {
t.Fatal(err)
}
if got, err := Finish(ctx, a.Session, ""); err != nil || got != (Saved{"signinend", "signinend"}) {
t.Fatalf("Finish = %+v, %v", got, err)
}
if b, _ := os.ReadFile(AuthPath()); !strings.Contains(string(b), `"tok-late"`) {
t.Fatalf("auth file: %s", b)
}
}
// #5016: the plugin's wait is told the sign-in is over (magpie's hook:
// callback(code, { signal })), so it stops instead of waiting out its own
// minutes.
func TestCancelledSignInEndsThePluginsWait(t *testing.T) {
ctx, home := signInEnd(t)
cancelledFinish(t, ctx, 1, nil)
if !markedWithin(home, "aborted", 20*time.Second) {
t.Fatal("the plugin's wait was never told the sign-in was cancelled")
}
}
// #5016: a sign-in that polls its vendor stops polling once cancelled:
// the fetch it made for the sign-in fails.
func TestCancelledSignInEndsItsFetch(t *testing.T) {
asked := make(chan struct{})
gone := make(chan struct{})
testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(asked)
select {
case <-r.Context().Done():
close(gone)
case <-time.After(time.Minute):
}
}))
ctx, home := signInEnd(t)
cancelledFinish(t, ctx, 7, asked)
if !markedWithin(home, "fetch-aborted", 20*time.Second) {
t.Fatal("the sign-in's fetch went on after it was cancelled")
}
select {
case <-gone:
case <-time.After(20 * time.Second):
t.Fatal("the vendor's request was never closed")
}
if b, _ := os.ReadFile(filepath.Join(home, "fetch-aborted")); string(b) != "AbortError" {
t.Errorf("the fetch failed with %q, want AbortError", b)
}
}
// plugins#658: an oauth method's authorize that fails ({ type: "failed",
// error }) reached the user as "s.a.callback is not a function"; the
// plugin's reason is the error, for every method type.
func TestSignInFailsWithThePluginsReason(t *testing.T) {
ctx, _ := signInEnd(t)
for _, c := range []struct {
method int
want string
}{
{2, "this AStudio account is banned"},
{3, "Agnes Code signs in on Windows only"},
{4, "signinend's sign-in gave nothing to finish it with"},
} {
a, err := Authorize(ctx, "signinend", c.method, nil, NewAccount)
if err == nil {
_, err = Finish(ctx, a.Session, "x")
}
if !errors.Is(err, ErrFailed) || !strings.HasSuffix(err.Error(), ": "+c.want) {
t.Errorf("method %d: %v, want the sign-in failed: %s", c.method, err, c.want)
}
}
if _, err := APIKey(ctx, "signinend", 5, nil, "k", NewAccount); !errors.Is(err, ErrFailed) || !strings.HasSuffix(err.Error(), ": that key is revoked") {
t.Errorf("api method: %v", err)
}
a, err := Authorize(ctx, "signinend", 6, nil, NewAccount)
if err != nil || a.Method != "code" {
t.Fatalf("Authorize = %+v, %v", a, err)
}
if _, err := Finish(ctx, a.Session, "x"); !errors.Is(err, ErrFailed) || !strings.HasSuffix(err.Error(), ": that code expired") {
t.Errorf("code callback: %v", err)
}
if SignedIn("signinend") {
t.Error("a failed sign-in was saved")
}
}
+14 -3
View File
@@ -887,10 +887,21 @@ const NewAccount = "new"
// Authorize begins an OAuth sign-in to account (a key, or NewAccount),
// through the proxy ctx names (netproxy.With): the plugin's requests for
// it, there and in Finish, go through that one (#1663).
// A plugin that can't start one says why ({ type: "failed", error }), and
// that is the error (plugins#658).
func Authorize(ctx context.Context, provider string, method int, inputs map[string]string, account string) (Authorization, error) {
var a Authorization
err := Call(ctx, "authorize", map[string]any{"provider": provider, "method": method, "inputs": inputs, "account": account, "proxy": proxyOf(ctx)}, &a)
return a, err
var r struct {
OK bool `json:"ok"`
Error string `json:"error"`
Authorization
}
if err := Call(ctx, "authorize", map[string]any{"provider": provider, "method": method, "inputs": inputs, "account": account, "proxy": proxyOf(ctx)}, &r); err != nil {
return Authorization{}, err
}
if !r.OK {
return Authorization{}, failure(r.Error)
}
return r.Authorization, nil
}
// Saved is where a sign-in was kept: the provider (a plugin may sign in
+73
View File
@@ -0,0 +1,73 @@
// A plugin whose sign-ins end in ways magpie must follow (#5016,
// plugins#658): a wait on a file a desktop app writes, one that ignores
// magpie giving up and one that heeds it, and authorize results that fail
// with no callback to call.
import { existsSync, writeFileSync } from "node:fs"
import { join } from "node:path"
const home = () => process.env.HOME
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const mark = (name, text = "") => writeFileSync(join(home(), name), text)
// waits for $HOME/go as AStudio's plugin waits for its app's session
// file, every 50ms, for a minute at most
async function wait(signal) {
mark("waiting")
for (let i = 0; i < 1200; i++) {
if (signal?.aborted) {
mark("aborted")
return { type: "failed", error: "aborted" }
}
if (existsSync(join(home(), "go"))) {
mark("returned")
return { type: "success", key: "tok-late", metadata: { uid: "late" } }
}
await sleep(50)
}
return { type: "failed", error: "no session" }
}
export const SignInEndPlugin = async () => ({
auth: {
provider: "signinend",
methods: [
// 0: waits on its own, deaf to magpie giving up
{ type: "oauth", label: "deaf", authorize: async () => ({ url: "https://signinend.invalid/", instructions: "", method: "auto", callback: async () => wait() }) },
// 1: waits on its own, and stops when given magpie's signal
{
type: "oauth",
label: "heeds",
authorize: async () => ({ url: "https://signinend.invalid/", instructions: "", method: "auto", callback: async (_code, o) => wait(o?.signal) }),
},
// 2: an auto sign-in that fails before it starts, as AStudio's
// banned account does
{ type: "oauth", label: "banned", authorize: async () => ({ type: "failed", error: "this AStudio account is banned" }) },
// 3: a code sign-in that fails before it starts
{ type: "oauth", label: "code failed", authorize: async () => ({ type: "failed", error: "Agnes Code signs in on Windows only", method: "code" }) },
// 4: a result with nothing to finish it with
{ type: "oauth", label: "no callback", authorize: async () => ({ url: "https://signinend.invalid/", method: "auto" }) },
// 5: a key sign-in that fails with why
{ type: "api", label: "key failed", authorize: async () => ({ type: "failed", error: "that key is revoked" }) },
// 6: a code sign-in whose callback fails with why
{ type: "oauth", label: "code", authorize: async () => ({ url: "https://signinend.invalid/", method: "code", callback: async () => ({ type: "failed", error: "that code expired" }) }) },
// 7: polls its vendor, whose answer never comes
{
type: "oauth",
label: "polls",
authorize: async () => ({
url: "https://signinend.invalid/",
method: "auto",
callback: async () => {
try {
await fetch(process.env.FAKE_BASE + "/poll", { headers: { "X-Fake-Run": process.env.FAKE_RUN ?? "" } })
return { type: "success", key: "tok-polled" }
} catch (e) {
mark("fetch-aborted", e?.name ?? String(e))
return { type: "failed", error: String(e) }
}
},
}),
},
],
},
})
@@ -0,0 +1,74 @@
package provider
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/testenv"
)
// #5016, through the window's Cancel: a plugin sign-in cancelled while the
// plugin waits for its vendor's desktop app (AStudio's session file,
// plugins#658) saves nothing when the file comes after; and one whose
// authorize fails says the plugin's reason, not "s.a.callback is not a
// function".
func TestCancelledPluginSignInSavesNothing(t *testing.T) {
bun := testenv.Bun(t)
home := claudeHome(t)
t.Setenv("MAGPIE_BUN", bun)
t.Cleanup(plugin.Settle)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("../plugin/testdata/signinend/index.js")
if _, err := plugin.Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
if _, err := StartPluginSignIn("signinend", 2, nil); err == nil || !strings.Contains(err.Error(), "this AStudio account is banned") {
t.Fatalf("a failed authorize: %v", err)
}
st, err := StartPluginSignIn("signinend", 0, nil)
if err != nil {
t.Fatal(err)
}
marked := func(name string) bool {
for end := time.Now().Add(30 * time.Second); time.Now().Before(end); time.Sleep(20 * time.Millisecond) {
if _, err := os.Stat(filepath.Join(home, name)); err == nil {
return true
}
}
return false
}
if !marked("waiting") {
t.Fatal("the plugin never began waiting")
}
CancelSignIn(st.ID)
if got, _ := SignInStatus(st.ID); got.State != "canceled" {
t.Fatalf("after Cancel: %+v", got)
}
if err := os.WriteFile(filepath.Join(home, "go"), nil, 0o600); err != nil {
t.Fatal(err)
}
if !marked("returned") {
t.Fatal("the plugin's wait never came true")
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
if plugin.SignedIn("signinend") {
b, _ := os.ReadFile(plugin.AuthPath())
t.Fatalf("a cancelled sign-in was saved: %s", b)
}
if got, _ := SignInStatus(st.ID); got.State != "canceled" {
t.Fatalf("after the plugin answered: %+v", got)
}
}
+2
View File
@@ -411,6 +411,8 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<li><code>key</code> を含む成功は API キーとして保存されます。</li>
<li>結果に <code>provider: "other-id"</code> を付けると、そのプラグインがサインインする別のプロバイダにサインイン情報を保存します。</li>
<li>失敗時の <code>error</code> は magpie 独自のフィールドで、ユーザーに理由(最大 500 文字)が表示されます。なければ、サインインに失敗したことだけが表示されます。</li>
<li><code>authorize</code> がサインインを始められないときは、エラーを投げるか、<code>callback</code> なしの <code>{type: "failed", error}</code> を返します。ユーザーにはその理由が表示されます。</li>
<li>ユーザーがキャンセルした、または時間切れになったサインインはそこで終わります。その後に <code>callback</code> が返したものは捨てられ、そのサインインのための fetch も失敗します。magpie はサインインの <code>AbortSignal</code> を <code>callback(code, { signal })</code>(と <code>authorize(inputs, { signal })</code>)で渡すので、長く待つ callback は中止されたときに止められます。</li>
<li><code>inputs</code> は <code>prompts</code> を持つメソッドにだけ渡されます。prompts のないメソッドには、OpenCode の TUI が呼ぶときと同じく <code>undefined</code> が渡ります。空のオブジェクトは OpenCode の CLI の呼び方で、その場合ターミナルで質問するプラグインもあります。</li>
</ul>
<h3>サインイン前の質問</h3>
+2
View File
@@ -411,6 +411,8 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<li>A success with <code>key</code> is saved as an API key.</li>
<li><code>provider: "other-id"</code> on the result saves the sign-in to another provider the plugin signs in to.</li>
<li><code>error</code> on a failure is magpie’s own field: the user sees why (up to 500 characters). Without it, they see only that the sign-in failed.</li>
<li>When <code>authorize</code> can’t start the sign-in, throw, or return <code>{type: "failed", error}</code> with no <code>callback</code>: the user sees that reason.</li>
<li>A sign-in the user cancels, or that times out, is over: whatever <code>callback</code> returns after it is dropped, and the fetches it makes for it fail. magpie also passes the sign-in’s <code>AbortSignal</code> as <code>callback(code, { signal })</code> (and <code>authorize(inputs, { signal })</code>), so a callback that waits a long time can stop when it aborts.</li>
<li><code>inputs</code> is passed only to a method with <code>prompts</code>. A method without prompts gets <code>undefined</code>, as OpenCode’s TUI calls it. An empty object is how OpenCode’s CLI calls, and some plugins then ask on the terminal.</li>
</ul>
<h3>Questions before signing in</h3>
+2
View File
@@ -411,6 +411,8 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<li>带 <code>key</code> 的成功结果保存为 API key。</li>
<li>结果里写 <code>provider: "other-id"</code>,登录就保存到插件负责的另一个供应商下。</li>
<li>失败结果里的 <code>error</code> 是 magpie 自己的字段:用户会看到原因(最多 500 字符)。不写的话,用户只能看到登录失败。</li>
<li><code>authorize</code> 无法开始登录时,可以抛出错误,或者返回不带 <code>callback</code> 的 <code>{type: "failed", error}</code>:用户会看到这条原因。</li>
<li>用户取消或超时的登录就此结束:之后 <code>callback</code> 返回什么都会被丢弃,它为这次登录发出的请求也会失败。magpie 还会把这次登录的 <code>AbortSignal</code> 传进去:<code>callback(code, { signal })</code>(以及 <code>authorize(inputs, { signal })</code>),等得久的 callback 可以在它中止时停下。</li>
<li>只有带 <code>prompts</code> 的方式才会收到 <code>inputs</code>。没有 prompts 的方式收到 <code>undefined</code>,和 OpenCode 的 TUI 一样。OpenCode 的 CLI 传的是空对象,有些插件因此会在终端里自己提问。</li>
</ul>
<h3>登录前的提问</h3>