diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index f18f675f2..b6cfbf4ae 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -178,6 +178,8 @@ What a plugin writes with `console.log`, `console.warn` and the rest goes to the A plugin's account whose sign-in its vendor refused (`lapsed`, or an allowance read saying so) keeps Sign in again and Remove on its row, whether it is in use or the agent's own (`signedOut` in `renderAccounts`, `app.js`). +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`). + 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 diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go index 64e40dfdb..af0cc8e1e 100644 --- a/internal/cli/plugins_cli.go +++ b/internal/cli/plugins_cli.go @@ -480,7 +480,9 @@ func pluginLogin(ctx context.Context, name, method string) error { if a.URL != "" { fmt.Println("Sign in in your browser. If it didn't open, go to:") fmt.Println(faint.Render(a.URL)) - openInBrowser(a.URL) + if !a.Opened { + openInBrowser(a.URL) + } } if a.Instructions != "" { fmt.Println(a.Instructions) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 2c1386a12..68c997e1b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11842,7 +11842,7 @@ async function followSignIn(id) { if (signing?.id !== id) continue; if (st.state === "waiting" || st.state === "installing") { // the CLI it needed is in: now the vendor's page can open - if (signing.state === "installing" && st.state === "waiting" && st.url) { + if (signing.state === "installing" && st.state === "waiting" && st.url && !st.opened) { api("open", { url: st.url }).catch((e) => { if (signing?.id === id) { signing = { ...signing, openError: e.message }; renderProviders(); } }); @@ -11927,7 +11927,8 @@ async function startPluginSignIn(sub, method, inputs = {}, o = {}) { if (o.user) body.user = o.user; if (o.proxy != null) body.proxy = o.proxy; signing = { ...(await api("plugin-signin", body)), ...keep }; - if (web && signing.url) api("open", { url: signing.url }); + // opened: the plugin's own CLI opened the page already (Grok Build's) + if (web && signing.url && !signing.opened) api("open", { url: signing.url }); renderProviders(); followSignIn(signing.id); } catch (e) { diff --git a/internal/gui/plugin_signin_open_test.go b/internal/gui/plugin_signin_open_test.go new file mode 100644 index 000000000..5ae685e45 --- /dev/null +++ b/internal/gui/plugin_signin_open_test.go @@ -0,0 +1,75 @@ +package gui + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "sync" + "testing" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// openCounter is a desktop that counts the pages it was asked to open. +type openCounter struct { + webHost + mu sync.Mutex + opened []string +} + +func (w *openCounter) OpenURL(u string) error { + w.mu.Lock() + defer w.mu.Unlock() + w.opened = append(w.opened, u) + return nil +} + +// A plugin's sign-in page opens once. Grok Build's `grok login` opens its +// page in the browser itself on macOS and Windows, and magpie opened it +// again: two pages every time (andyfmyth on X). A plugin that says the page +// is open already gets none opened by magpie; one that doesn't gets one. +func TestPluginSignInPageOpensOnce(t *testing.T) { + bun := testenv.Bun(t) + dir := t.TempDir() + testenv.SetHome(t, dir) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache")) + t.Setenv("MAGPIE_BUN", bun) + t.Setenv("MAGPIE_PLUGIN_MARKET", "off") + t.Cleanup(plugin.Settle) + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(t.Context(), abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(t.Context()); err != nil { + t.Fatal(err) + } + start := func(team string) (int, provider.SignInState) { + t.Helper() + w := &openCounter{} + body, _ := json.Marshal(map[string]any{"provider": "fakeco", "method": 1, "inputs": map[string]string{"where": "work", "team": team}}) + rec := httptest.NewRecorder() + Handler(w, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/plugin-signin", bytes.NewReader(body))) + if rec.Code != http.StatusOK { + t.Fatalf("sign-in: %d %s", rec.Code, rec.Body) + } + var st provider.SignInState + if err := json.Unmarshal(rec.Body.Bytes(), &st); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { provider.CancelSignIn(st.ID) }) + w.mu.Lock() + defer w.mu.Unlock() + return len(w.opened), st + } + if n, st := start("cli-opened"); n != 0 || !st.Opened || st.URL == "" { + t.Fatalf("a page the plugin's CLI opened was opened %d more times: %+v", n, st) + } + if n, st := start("blue"); n != 1 || st.Opened { + t.Fatalf("a page nothing opened was opened %d times: %+v", n, st) + } +} diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index e4f0baaea..e10c18db6 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -717,7 +717,7 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { return } var failed string - if w != nil { + if w != nil && !st.Opened { failed = openError(w, st.URL) } writeJSON(rw, signInOpened{st, failed}) diff --git a/internal/gui/tests/plugin-signin-opened.test.cjs b/internal/gui/tests/plugin-signin-opened.test.cjs new file mode 100644 index 000000000..f11227c12 --- /dev/null +++ b/internal/gui/tests/plugin-signin-opened.test.cjs @@ -0,0 +1,89 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A plugin's sign-in page opens once. Grok Build's `grok login` opens its +// page in the browser itself on macOS and Windows, and the window opened it +// again: two pages every time (andyfmyth on X). A sign-in that says its page +// is open already (opened) has the window ask for no /api/open, right away +// or once the CLI it needed is installed; one that doesn't still gets one. +// In every language, Chromium and WebKit; the API is faked here. +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"); + +// a plugin of its own name: the built-in Grok tile sits beside one named Grok +const plugin = { id: "fakeco", pid: "fakeco", name: "FakeCo", icon: "generic", spec: "opencode-fakeco-auth", signedIn: false, models: 3, + methods: [{ type: "oauth", label: "Sign in with Grok Build" }, { type: "api", label: "API key" }] }; + +const URL_ = "https://accounts.x.ai/oauth2/device?user_code=AB12-CD34"; + +// first is what /api/plugin-signin answers, then is what /api/signin/p1 does +function server(lang, first, then, opens) { + const payload = () => ({ providers: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], 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:true};` }); + 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/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/plugin-signin/prompt") return json({ prompt: null, inputs: {} }); + if (url.pathname === "/api/plugin-signin") return json(first); + if (url.pathname === "/api/signin/p1") { then.asked = (then.asked || 0) + 1; return json(then); } + if (url.pathname === "/api/open") { opens.push(JSON.parse(route.request().postData() || "{}").url); return route.fulfill({ status: 204, body: "" }); } + 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 waiting = (opened) => ({ id: "p1", agent: "fakeco", state: "waiting", url: URL_, instructions: "Approve the sign-in on the page; Grok Build finishes it.", ...(opened ? { opened: true } : {}) }); +const installing = { id: "p1", agent: "fakeco", state: "installing", installing: "Grok Build" }; +const cases = [ + { name: "opened by its CLI", first: waiting(true), then: waiting(true), want: 0 }, + { name: "not opened", first: waiting(false), then: waiting(false), want: 1 }, + { name: "opened by its CLI after the install", first: installing, then: waiting(true), want: 0 }, + { name: "not opened, after the install", first: installing, then: waiting(false), want: 1 }, +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a plugin sign-in's page opens once", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const c of cases) { + await t.test(`${lang} ${c.name}`, async () => { + const page = await (await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(15000); // a busy machine takes seconds over a click + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const opens = []; + const then = { ...c.then }; + await page.route("**/*", server(lang, c.first, then, opens)); + // in a browser tab the window opens a page itself + await page.exposeFunction("__opened", (u) => opens.push(u)); + await page.addInitScript(() => { window.open = (u) => { window.__opened(String(u)); return null; }; }); + await page.goto("http://magpie.test/?view=providers"); + await page.locator("#addProvider").click(); + const sheet = page.locator("#addSheet"); + await sheet.locator('.tile[data-pick="FakeCo"]').click(); + const box = sheet.locator(".signing"); + await box.locator("button", { hasText: "Sign in with Grok Build" }).press("Enter"); + // the window shows the page's words, then follows the sign-in two + // more times: past where it would have opened the page + await box.locator(".s", { hasText: "Grok Build finishes it" }).waitFor(); + const asked = then.asked || 0; + await new Promise((r) => { const tick = () => (then.asked || 0) >= asked + 2 ? r() : setTimeout(tick, 50); tick(); }); + assert.deepEqual(opens, c.want ? [URL_] : [], "pages opened"); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + } + }); +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 6badab79a..36376492b 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -2061,7 +2061,10 @@ async function authorize({ provider, method, inputs, account, proxy }) { const a = await via.run(proxy ?? "", () => inScope(provider, key, () => m.authorize(m.prompts?.length ? inputs ?? {} : undefined))) const session = String(nextSession++) sessions.set(session, { provider, key, a, inputs, proxy: proxy ?? "" }) - return { session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method } + // 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 } } // failed is a sign-in's failure, with why, where the plugin tells it diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 56b603a91..72bfe1f83 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -810,6 +810,9 @@ type Authorization struct { URL string `json:"url"` Instructions string `json:"instructions"` Method string `json:"method"` + // Opened is a page the plugin (its vendor's CLI) opened already, not + // to be opened again + Opened bool `json:"opened"` } // NewAccount is the account a sign-in goes to when it is a new one: the diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index 7a40501e8..60ee44f81 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -132,6 +132,9 @@ export const FakePlugin = async ({ client }) => ({ url: "https://fake.invalid/auth?where=" + inputs.where, instructions: "Paste the code", method: "code", + // team "cli-opened": the page is open already, as Grok Build's + // `grok login` opens its own on macOS and Windows + opened: inputs.team === "cli-opened", callback: async (code) => (process.env.FAKE_SIGNIN && (await fetch(process.env.FAKE_SIGNIN + "/token").catch(() => {})), code === "good") ? { type: "success", refresh: "r-" + (inputs.team ?? "none"), access: "stale", expires: 0, ...fakeWho(inputs.team) } diff --git a/internal/provider/migrate_side.go b/internal/provider/migrate_side.go index e0f3d61d1..b79353b07 100644 --- a/internal/provider/migrate_side.go +++ b/internal/provider/migrate_side.go @@ -97,7 +97,7 @@ func init() { // names, as the built-in does: the homes stay where they are. movers["grok"] = &mover{ pkg: "@magpie-community/opencode-grok-auth", - min: "0.1.16", // a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223); a sign-in with no email (an X account) is kept by its xAI user id, GROK_AUTH_PATH no longer takes it elsewhere, and a login that leaves none says where it looked + min: "0.1.17", // the sign-in page opens once, where Grok Build opened it and magpie again (andyfmyth on X); a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223); a sign-in with no email (an X account) is kept by its xAI user id, GROK_AUTH_PATH no longer takes it elsewhere, and a login that leaves none says where it looked agents: []string{"grok"}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/pluginsignin.go b/internal/provider/pluginsignin.go index 4025af0ba..cdfa75300 100644 --- a/internal/provider/pluginsignin.go +++ b/internal/provider/pluginsignin.go @@ -132,7 +132,7 @@ func (s *signInFlow) pluginBegin(id string, method int, inputs map[string]string return nil } s.st.State, s.st.Installing = "waiting", "" - s.st.URL, s.st.Instructions, s.st.Code = a.URL, a.Instructions, codeIn(a.Instructions) + s.st.URL, s.st.Instructions, s.st.Code, s.st.Opened = a.URL, a.Instructions, codeIn(a.Instructions), a.Opened s.stop = stop if a.Method == "code" { s.st.PasteCode, s.plugin = true, a.Session diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 4e73232c0..ac5a3292b 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -75,6 +75,9 @@ type SignInState struct { PasteKey bool `json:"pasteKey,omitempty"` KeysURL string `json:"keysURL,omitempty"` Instructions string `json:"instructions,omitempty"` // a plugin's words for its page + // Opened is a page the plugin's own CLI opened already (Grok Build's + // `grok login`), shown but not opened a second time + Opened bool `json:"opened,omitempty"` // Installing is the CLI being installed before the sign-in can start Installing string `json:"installing,omitempty"` User string `json:"user,omitempty"` // the account, once done