plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X)

"magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里".
Grok's plugin signs in through `grok login --device-auth`, and Grok Build
(1.0.50, the webbrowser crate) opens the device page itself, through
NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER;
the macOS binary has no "BROWSER" string. magpie then opened the same URL
from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a
browser tab) or `magpie plugin login`. Reproduced in a sandbox
HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not
involved, with and without SSH_CONNECTION. Built-in grok is retired
(2927a161e), so the plugin's path is the only one.

- The plugin's authorize result can say `opened: true` (not OpenCode's).
  host.js passes it on as Authorization.Opened, then SignInState.Opened,
  and the desktop handler, the CLI and app.js (both open points) open
  nothing then; the link is still shown.
- opencode-grok-auth 0.1.17 (magpie-community/plugins 47fbf63, on npm per
  `npm view --prefer-online`) says opened on darwin/win32, and elsewhere
  gives grok BROWSER=true, a no-op, so magpie stays the one opener there.
  The grok mover min is raised to 0.1.17.
- No other plugin's CLI opens a page: devin, cursor, kiro and qoder run
  status/refresh commands only.
- docs/subsystems/provider-plugins.md says so.

Tests:
- TestPluginSignInPageOpensOnce: the fake plugin signs in through
  /api/plugin-signin. "cli-opened" opens 0 pages; otherwise 1. Red with
  the old gui/plugins.go ("opened 1 more times").
- plugin-signin-opened.test.cjs: in a browser tab, right away and after
  an install, 5 languages, Chromium and WebKit. Every "opened" case is
  red on HEAD's app.js (23 fail); 42/42 with the change.

Run at the change (base origin/main 2ceff7370):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean.
- go test -p 4 -count=1 ./... -timeout 45m (load 150-380): every package
  ok except two.
  - gateway: TestVisionWaitIsntTheDescribersTime. It passes alone; filed
    as #2901.
  - gui: TestDockReopenKeepsTheWindowsSpace, TestMainWindowCorners,
    TestMainWindowRightToLeft, TestTrayCellClickReleasedPanel and
    TestCoveredWindowStaysUp, killed at their deadlines. All pass alone
    with TestPluginSignInPageOpensOnce; filed as #2645/#1936.
- GUI, both engines, at most 2 workers: plugin-signin-opened,
  plugin-signin, plugin-signin-no-url, plugin-moved-signin,
  signin-paste-plugin, signin-browser-down, signin-link,
  plugin-password-prompt and plugin-replaced. The run went 126 pass,
  10 fail, all launch or 5s timeouts at load ~380. Alone,
  plugin-signin-opened passes in both engines and password-prompt
  passes. signin-browser-down was red in one case per run, a different
  one each time. plugin-moved-signin (Chromium) is red alone at HEAD's
  app.js too. Both are filed as #2900.
- plugins: bun test packages/grok 49 pass; scripts/check.mjs ok. Its
  publish run is red only for middleware-think-tags's npm trust
  (plugins#180); grok 0.1.17 was published.
This commit is contained in:
yetone
2026-10-19 12:42:48 +08:00
parent e7114d3882
commit f76201a84a
12 changed files with 188 additions and 7 deletions
+2
View File
@@ -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
+3 -1
View File
@@ -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)
+3 -2
View File
@@ -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) {
+75
View File
@@ -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)
}
}
+1 -1
View File
@@ -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})
@@ -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();
});
}
}
});
}
+4 -1
View File
@@ -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
+3
View File
@@ -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
+3
View File
@@ -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) }
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+3
View File
@@ -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