diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index a6510476a..407c2b29b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -12284,7 +12284,12 @@ async function startSignIn(agent, risky, site, o = {}) { if (o.user) body.user = o.user; if (o.proxy != null) body.proxy = o.proxy; signing = { ...(await api("signin", body)), ...keep }; - if (web && signing.url) api("open", { url: signing.url }); + if (web && signing.url) { + const id = signing.id; + openSignInPage(signing.url).catch((e) => { + if (signing?.id === id) { signing = { ...signing, openError: e.message }; renderProviders(); } + }); + } renderProviders(); followSignIn(signing.id); } catch (e) { @@ -12293,6 +12298,22 @@ async function startSignIn(agent, risky, site, o = {}) { } } +// openSignInPage opens a sign-in's page for the window. In a browser tab +// (magpie web: a server, Docker) that's a new tab the viewer's browser may +// block, as it was asked for after the sign-in started, not on the click: +// then it says so, and the page opens from Open again, a click +// (treeMan on Discord). A tab opened without noopener is the one way to +// learn it was blocked, so the page it opens is cut from this one at once. +const openBlocked = "\u0000blocked"; +function openSignInPage(url) { + if (!web) return api("open", { url }); + let w = null; + try { w = window.open(url, "_blank"); } catch {} + if (!w) return Promise.reject(new Error(openBlocked)); + try { w.opener = null; } catch {} + return Promise.resolve(null); +} + async function followSignIn(id) { while (signing?.id === id && signingOpen()) { await new Promise((r) => setTimeout(r, 800)); @@ -12302,7 +12323,7 @@ async function followSignIn(id) { 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 && !st.opened) { - api("open", { url: st.url }).catch((e) => { + openSignInPage(st.url).catch((e) => { if (signing?.id === id) { signing = { ...signing, openError: e.message }; renderProviders(); } }); } @@ -12388,7 +12409,12 @@ async function startPluginSignIn(sub, method, inputs = {}, o = {}) { if (o.proxy != null) body.proxy = o.proxy; signing = { ...(await api("plugin-signin", body)), ...keep }; // opened: the plugin's own CLI opened the page already (Grok Build's) - if (web && signing.url && !signing.opened) api("open", { url: signing.url }); + if (web && signing.url && !signing.opened) { + const id = signing.id; + openSignInPage(signing.url).catch((e) => { + if (signing?.id === id) { signing = { ...signing, openError: e.message }; renderProviders(); } + }); + } renderProviders(); followSignIn(signing.id); } catch (e) { @@ -12823,6 +12849,7 @@ function renderSigning(sub) { } tt.append(el("span", "n", t("Finish signing in to {name} in your browser", { name: sub.name })), el("span", "s", signing.state === "starting" ? t("Starting the sign-in…") + : signing.openError === openBlocked ? t("Your browser blocked the sign-in page from opening. Open it with Open again below, or copy the link into a browser.") : signing.openError ? t("magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.", { error: signing.openError }) : sub.plugin ? (signing.instructions || (signing.pasteCode ? t("magpie opened the sign-in page. Paste the code it shows below.") : t("magpie opened the sign-in page. The account shows up here as soon as you're done."))) : signing.pasteCode ? t("magpie opened the sign-in page. Paste the code it shows below.") diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 1b4b960f5..de0de193e 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1790,6 +1790,7 @@ const I18N = { "Copy link": "复制链接", "Sign-in link": "登录链接", "magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.": "magpie 没能打开浏览器:{error}。请自己在浏览器中打开下面的登录链接。", + "Your browser blocked the sign-in page from opening. Open it with Open again below, or copy the link into a browser.": "浏览器拦下了登录页面,没让它打开。请点下面的「重新打开」,或把链接复制到浏览器里打开。", "Proxy: {proxy}": "代理:{proxy}", "The sign-in goes through this proxy, as the account's requests will. One picked here is kept as the account's.": "登录经由这个代理,与这个账号之后的请求相同。在这里选的代理会保存为这个账号的代理。", "Sign in through": "登录经由", @@ -5889,6 +5890,7 @@ const I18N = { "Copy link": "複製連結", "Sign-in link": "登入連結", "magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.": "magpie 無法開啟瀏覽器:{error}。請自行在瀏覽器中開啟下方的登入連結。", + "Your browser blocked the sign-in page from opening. Open it with Open again below, or copy the link into a browser.": "瀏覽器擋下了登入頁面,沒讓它開啟。請點下方的「重新開啟」,或把連結複製到瀏覽器中開啟。", "Proxy: {proxy}": "代理:{proxy}", "The sign-in goes through this proxy, as the account's requests will. One picked here is kept as the account's.": "登入經由這個代理,與這個帳號之後的請求相同。在這裡選的代理會儲存為這個帳號的代理。", "Sign in through": "登入經由", @@ -9965,6 +9967,7 @@ const I18N = { "Copy link": "リンクをコピー", "Sign-in link": "サインインリンク", "magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.": "magpie はブラウザを開けませんでした:{error}。下のサインインリンクをご自身でブラウザで開いてください。", + "Your browser blocked the sign-in page from opening. Open it with Open again below, or copy the link into a browser.": "ブラウザがサインインページを開くのをブロックしました。下の「もう一度開く」で開くか、リンクをブラウザにコピーしてください。", "Proxy: {proxy}": "プロキシ:{proxy}", "The sign-in goes through this proxy, as the account's requests will. One picked here is kept as the account's.": "サインインはこのプロキシを経由します。このアカウントのリクエストも同じです。ここで選んだプロキシはこのアカウントのものとして保存されます。", "Sign in through": "サインインの経路", @@ -14071,6 +14074,7 @@ const I18N = { "Copy link": "Link kopieren", "Sign-in link": "Anmeldelink", "magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.": "magpie konnte den Browser nicht öffnen: {error}. Öffne den Anmeldelink unten selbst in einem Browser.", + "Your browser blocked the sign-in page from opening. Open it with Open again below, or copy the link into a browser.": "Dein Browser hat das Öffnen der Anmeldeseite blockiert. Öffne sie unten mit „Erneut öffnen“ oder kopiere den Link in einen Browser.", "Proxy: {proxy}": "Proxy: {proxy}", "The sign-in goes through this proxy, as the account's requests will. One picked here is kept as the account's.": "Die Anmeldung läuft über diesen Proxy, wie später die Anfragen des Kontos. Ein hier gewählter wird als Proxy des Kontos gespeichert.", "Sign in through": "Anmelden über", diff --git a/internal/gui/tests/plugin-signin-opened.test.cjs b/internal/gui/tests/plugin-signin-opened.test.cjs index f11227c12..78490c28f 100644 --- a/internal/gui/tests/plugin-signin-opened.test.cjs +++ b/internal/gui/tests/plugin-signin-opened.test.cjs @@ -67,7 +67,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", 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.addInitScript(() => { window.open = (u) => { window.__opened(String(u)); return {}; }; }); await page.goto("http://magpie.test/?view=providers"); await page.locator("#addProvider").click(); const sheet = page.locator("#addSheet"); diff --git a/internal/gui/tests/signin-paste-key.test.cjs b/internal/gui/tests/signin-paste-key.test.cjs index d87032060..63c0292f7 100644 --- a/internal/gui/tests/signin-paste-key.test.cjs +++ b/internal/gui/tests/signin-paste-key.test.cjs @@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], asked = []; page.on("pageerror", (e) => errors.push(e.message)); // web: a page opens in the browser, not through magpie - await page.addInitScript(() => { window.opened = []; window.open = (u) => { window.opened.push(u); return null; }; }); + await page.addInitScript(() => { window.opened = []; window.open = (u) => { window.opened.push(u); return {}; }; }); await page.route("**/*", server(lang, asked)); await page.goto("http://magpie.test/?view=providers"); await page.locator("#addProvider").click(); diff --git a/internal/gui/tests/signin-web-blocked.test.cjs b/internal/gui/tests/signin-web-blocked.test.cjs new file mode 100644 index 000000000..e16c43837 --- /dev/null +++ b/internal/gui/tests/signin-web-blocked.test.cjs @@ -0,0 +1,107 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// magpie web on a server or in Docker (treeMan on Discord): a sign-in's page +// is opened in the viewer's browser as a new tab once the sign-in has +// started, after the click, and a browser may block it. The window said +// the page was open while nothing opened. Now a blocked tab is said to be +// blocked, beside the link, and Open again (a click) opens it. Right +// away and once the CLI a plugin needed is installed; 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 = { id: "p1", agent: "fakeco", state: "waiting", url: URL_, instructions: "Approve the sign-in on the page; Grok Build finishes it." }; +const installing = { id: "p1", agent: "fakeco", state: "installing", installing: "Grok Build" }; +const cases = [ + { name: "at the start", first: waiting }, + { name: "after the install", first: installing }, +]; +const blocked = { + en: "Your browser blocked the sign-in page", + zh: "浏览器拦下了登录页面", + "zh-TW": "瀏覽器擋下了登入頁面", + ja: "ブラウザがサインインページを開くのをブロックしました", + de: "Dein Browser hat das Öffnen der Anmeldeseite blockiert", +}; +const again = { en: "Open again", zh: "重新打开", "zh-TW": "重新開啟", ja: "もう一度開く", de: "Erneut öffnen" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a sign-in page the browser blocked says so, and Open again opens it", 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 = []; + await page.route("**/*", server(lang, c.first, { ...waiting }, opens)); + // the browser blocks the tab asked for after the sign-in started, + // and lets the one a click asks for open + await page.exposeFunction("__opened", (u) => opens.push(u)); + await page.addInitScript(() => { + window.__tabs = []; + window.open = (u) => { + window.__opened(String(u)); + if (!window.__clicked) return null; + const w = { opener: window }; + window.__tabs.push(w); + return w; + }; + }); + 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"); + await box.locator(".s", { hasText: blocked[lang] }).waitFor(); + assert.deepEqual(opens, [URL_], "the page was asked for once"); + assert.equal(await box.locator(".signlink code").textContent(), URL_, "the link is shown"); + await page.evaluate(() => { window.__clicked = true; }); + await box.locator("button", { hasText: again[lang] }).click(); + await box.locator(".s", { hasText: "Grok Build finishes it" }).waitFor(); + assert.equal(await box.locator(".s", { hasText: blocked[lang] }).count(), 0, "the blocked line is gone"); + assert.deepEqual(opens, [URL_, URL_]); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + } + }); +}