signin: Settings can keep sign-in pages out of the default browser (max2020)
max2020 on Discord signs in from a separate, fingerprint browser so the vendor never sees their default one. Every waiting sign-in already shows its link with Copy link (since52c8e838d), but magpie still opened the page in the default browser first. Settings › Privacy › Sign-in pages › "Open sign-in pages in the browser", On by default, so nothing changes unless it is turned off. Off (settings.SignInLinkOnly) opens nothing: /api/signin and /api/plugin-signin go through openSignIn, which skips the open and answers linkOnly; a web tab skips window.open on linkOnly, after an install step too; the box says the page wasn't opened and its button reads Open, not Open again. `magpie accounts add` and a plugin's command-line login print the link without opening it. A plugin whose own CLI opens the page (Grok Build on macOS and Windows, opened) still does. Callbacks, by flow: Claude Code's login, Codex (localhost:1455), ChatGPT API, Gemini/Antigravity and localhost plugins come back to this machine, so another browser on it finishes them, and the pasted final address covers one whose proxy keeps it off loopback. Copilot, Grok and other device-code flows work from any browser. Run: - TestSignInLinkOnlyOpensNothing (new; built-in and plugin sign-in, the setting on and off) with TestPluginSignIn*, TestSettingsSave*, TestCoreScriptBudget and TestI18n* on mote: ok. Budget holds with no raise (app.js 1,313,244 of 1,315,316). - signin-link-only.test.cjs (new; every language, Chromium and WebKit, 900 and 360px), signin-link and account-discovery on WSL: 42/42 and the neighbours green. - Full Go suite on WSL (go test -timeout 45m ./...): every package ok except internal/agent's TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir and TestZedAppPath, red the same on origin/main387e8572athere (#4033, #3548); root, internal/cli and internal/gui need gtk4 there and were run with -tags nogui: ok. - gofmt; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean. - The whole GUI suite (both engines) is still running on mote at push time; reds it shows that aren't on file get issues. Broken by hand: openSignIn ignoring the setting made the Go test red ("built-in: kept to its link, its page was opened 1 times"); dropping startSignIn's linkOnly check made the GUI test red ("no page opened", 12 of 42). Not tried: a real vendor sign-in from a fingerprint browser; Grok on macOS/Windows still opens its own page; MCP server sign-ins unchanged.
This commit is contained in:
@@ -46,7 +46,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:<mark>"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. A ChatGPT account's usage read marks it too (`codexSignInRead` in `loginQuota`, charliepu on Discord: an account OpenAI signed out showed only a blank allowance): `/wham/usage` answering 401 with those words is refreshed once (`codexWindowsRenewing`), and the account is marked for the token turned away when the refreshed read is turned away the same (`codexSignInGone`), or, for the one Codex is signed in to, when its refresh is refused (its row used to say nothing, its allowance line "run codex login"; a saved one's refused refresh is `savedRefreshFailed`'s). Any other 401, a 403, a 5xx or a network error is unknown and marks nothing. Sign in again runs magpie's own sign-in for the account (`addLogin`), which replaces its tokens, in Codex's `auth.json` too when Codex is signed in to it. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, served a request (`ServedSignIn`), or its usage read going through, it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) |
|
||||
| A token called expired | A ChatGPT 401 whose words say the access token has expired and ask for a refresh (`SignInExpired`: `token_expired`, "Provided authentication token is expired. Please try refreshing it."; never `refresh_token_expired`, which is revoked) while the token's own `exp` is still ahead (willz on Discord, #2973: two saved Team accounts) is mended by one refresh. `codexToken` refreshes only as `exp` nears, so before this the token went out as it was until the user signed in again, and the card said only Unauthorized. The usage read (`codexWindowsRenewing`: `loginQuota`, `codexSubscriptionUsage`, and the reset spenders through `codexUserWindows`) refreshes once and reads once more, never again: a refresh refused says to sign in again (a saved account is marked lapsed, `savedRefreshFailed`; Codex's own is marked revoked, see A revoked sign-in, through `loginQuota`, while `codexSubscriptionUsage`'s card still says `codex login`), and a token refreshed for it and still called expired says so too (`errCodexStillExpired`) and is marked revoked the same. The gateway renews the account a request went with (`NoteExpiredSignIn` from `noteSignIn`, 20s at most); the request itself fails over as before, and the next goes with the new token. Each refresh is keyed on the token turned away (`codexTokenRenewing`, `renewSavedLoginFrom`), under the lock signing waits on: a sign-in holding another token by then, renewed by Codex or another reply, is used as it is, so two replies for one token spend one rotation. Codex's own sign-in is read from its store afresh for it and written back through `codexStore.write` (temp and rename), a saved one's through `writeLogins`. Not tried against the real backend. | [`codex_expired.go`](../../internal/provider/codex_expired.go), [`account.go`](../../internal/provider/account.go), [`logins_on.go`](../../internal/provider/logins_on.go) |
|
||||
| Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say "<user> is signed out", as the app's row does. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go), [`claude_dirs.go`](../../internal/provider/claude_dirs.go) |
|
||||
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
|
||||
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. The window or `magpie web` opens the sign-in page in the default browser (`openSignIn` in `internal/gui/api.go`; `openSignInPage` in `app.js` for a web tab), and the waiting box always shows the link with Copy link. With Settings › Privacy › Sign-in pages off (`SignInLinkOnly`, max2020 on Discord, who signs in from a separate fingerprint browser), magpie opens nothing: the reply carries `linkOnly`, the box says the page wasn't opened and offers Open, and `magpie accounts add` and a plugin's browser login from the command line (`pluginLogin`) print the link without opening it. A callback on this machine still comes back from another browser on it, and the pasted address covers one that can't reach it. A plugin whose own CLI opens the page (`opened`, Grok Build's device sign-in on macOS and Windows) still opens it. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
|
||||
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) |
|
||||
| Claude setup-token | A Claude account can be added from the long-lived token `claude setup-token` prints (sfss5362 on X), which Claude Code takes in `CLAUDE_CODE_OAUTH_TOKEN` (the window's *Use a setup-token instead…* and *Add an account by setup-token…*, `POST /api/signin/claude-token`). `AddClaudeSetupToken` keeps it in `logins.json` as `{"setupToken":…}`, named `Claude setup-token <6 hex of its hash>` (it tells no email), on beside the others; the same token again is the same account. Such a token has the inference scope only: Claude Code's `auth status` says `oauth_token` with no email or plan, and its `/usage` prints the API cost view, so `/usage` is never run for it and its allowance is unknown (`errClaudeSetupToken`, kept by `passing` as saying nothing about the account) until a reply's rate-limit event tells it. Its config directory (`claudeTokenDir`) holds no `.credentials.json`, which Claude Code could fall back to on a refused token. Claude Code itself is never signed in to it: `addLogin`, `switchLogin`, `putClaudeLogin`, `SetKeepLoginAs`, `NextLogin` and `signInToFirst` pass it over, and the window shows Remove and *magpie only* in place of Use and Make first. Not tried with a real token. | [`claude_setup_token.go`](../../internal/provider/claude_setup_token.go), [`claude_subscription.go`](../../internal/gateway/claude_subscription.go) (`inClaudeDir`), [`providers.go`](../../internal/gui/providers.go) |
|
||||
| Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex failing over (#1385) has it in place of the old *ChatGPT accounts* button. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). Not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) |
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// accountsCmd: `magpie accounts [agent] [--json]`, `magpie accounts add <agent>`,
|
||||
@@ -476,12 +477,20 @@ func addAccount(agentID string) error {
|
||||
return fmt.Errorf("sign-in didn't finish: %s", st.Error)
|
||||
}
|
||||
}
|
||||
fmt.Println("Finish signing in in your browser. If it didn't open, go to:")
|
||||
linkOnly := settings.Load().SignInLinkOnly
|
||||
if linkOnly {
|
||||
// the user keeps sign-in pages to a browser of their own
|
||||
fmt.Println("Open this link in the browser you sign in with:")
|
||||
} else {
|
||||
fmt.Println("Finish signing in in your browser. If it didn't open, go to:")
|
||||
}
|
||||
fmt.Println(faint.Render(st.URL))
|
||||
if st.Code != "" {
|
||||
fmt.Println("and confirm the code", st.Code)
|
||||
}
|
||||
openInBrowser(st.URL)
|
||||
if !linkOnly {
|
||||
openInBrowser(st.URL)
|
||||
}
|
||||
ctx, stop := interruptContext()
|
||||
defer stop()
|
||||
if st.PasteCallback || st.PasteCode {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/pluginrt"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
@@ -494,9 +495,16 @@ func pluginLogin(ctx context.Context, name, method string) error {
|
||||
return err
|
||||
}
|
||||
if a.URL != "" {
|
||||
fmt.Println("Sign in in your browser. If it didn't open, go to:")
|
||||
// the user may keep sign-in pages to a browser of their own; a
|
||||
// page the plugin's CLI opened itself is open either way
|
||||
linkOnly := settings.Load().SignInLinkOnly && !a.Opened
|
||||
if linkOnly {
|
||||
fmt.Println("Open this link in the browser you sign in with:")
|
||||
} else {
|
||||
fmt.Println("Sign in in your browser. If it didn't open, go to:")
|
||||
}
|
||||
fmt.Println(faint.Render(a.URL))
|
||||
if !a.Opened {
|
||||
if !a.Opened && !linkOnly {
|
||||
openInBrowser(a.URL)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2728,6 +2728,23 @@ func state() stateJSON {
|
||||
type signInOpened struct {
|
||||
provider.SignInState
|
||||
OpenError string `json:"openError,omitempty"`
|
||||
// LinkOnly is a sign-in whose page magpie didn't open, as the user
|
||||
// asked (settings.SignInLinkOnly): the window says to copy its link
|
||||
LinkOnly bool `json:"linkOnly,omitempty"`
|
||||
}
|
||||
|
||||
// openSignIn opens an account sign-in's page, unless the user keeps those
|
||||
// pages to a browser of their own (settings.SignInLinkOnly), and says how
|
||||
// it went for signInOpened.
|
||||
func openSignIn(w Windows, st provider.SignInState) signInOpened {
|
||||
if settings.Load().SignInLinkOnly {
|
||||
return signInOpened{SignInState: st, LinkOnly: true}
|
||||
}
|
||||
var failed string
|
||||
if w != nil && !st.Opened {
|
||||
failed = openError(w, st.URL)
|
||||
}
|
||||
return signInOpened{SignInState: st, OpenError: failed}
|
||||
}
|
||||
|
||||
// mcpSignInOpened is signInOpened for a sign-in to an MCP server.
|
||||
|
||||
@@ -12424,7 +12424,7 @@ 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) {
|
||||
if (web && signing.url && !signing.linkOnly) {
|
||||
const id = signing.id;
|
||||
openSignInPage(signing.url).catch((e) => {
|
||||
if (signing?.id === id) { signing = { ...signing, openError: e.message }; renderProviders(); }
|
||||
@@ -12462,7 +12462,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 && !st.opened) {
|
||||
if (signing.state === "installing" && st.state === "waiting" && st.url && !st.opened && !signing.linkOnly) {
|
||||
openSignInPage(st.url).catch((e) => {
|
||||
if (signing?.id === id) { signing = { ...signing, openError: e.message }; renderProviders(); }
|
||||
});
|
||||
@@ -12481,7 +12481,7 @@ async function followSignIn(id) {
|
||||
// again and a proxy picked for it — its site and way, the account signed
|
||||
// in to again, the proxy picked
|
||||
function signingKept() {
|
||||
return { site: signing.site, method: signing.method, inputs: signing.inputs, forUser: signing.forUser, picked: signing.picked, askProxy: signing.askProxy, customProxy: signing.customProxy, openError: signing.openError };
|
||||
return { site: signing.site, method: signing.method, inputs: signing.inputs, forUser: signing.forUser, picked: signing.picked, askProxy: signing.askProxy, customProxy: signing.customProxy, openError: signing.openError, linkOnly: signing.linkOnly };
|
||||
}
|
||||
|
||||
// signInProxyOf: the proxy an account's sign-in goes through when none is
|
||||
@@ -12550,7 +12550,7 @@ 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) {
|
||||
if (web && signing.url && !signing.opened && !signing.linkOnly) {
|
||||
const id = signing.id;
|
||||
openSignInPage(signing.url).catch((e) => {
|
||||
if (signing?.id === id) { signing = { ...signing, openError: e.message }; renderProviders(); }
|
||||
@@ -12961,6 +12961,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.linkOnly && !signing.opened ? t("magpie didn't open the sign-in page, as set in Settings. Copy the link below into the browser you sign in with.")
|
||||
: 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.")))
|
||||
@@ -12984,7 +12985,7 @@ function renderSigning(sub) {
|
||||
link.append(u, cp);
|
||||
tt.append(link);
|
||||
const acts = el("span", "acts");
|
||||
const open = el("button", "link", t("Open again"));
|
||||
const open = el("button", "link", signing.linkOnly && !signing.opened ? t("Open") : t("Open again"));
|
||||
// one that fails says why, where "magpie opened the sign-in page" was (#2043)
|
||||
// a poll may have put a fresh copy of the same sign-in in its place
|
||||
const flow = signing;
|
||||
@@ -19957,7 +19958,7 @@ function renderSettings() {
|
||||
renderReplies(s, keep);
|
||||
renderDisabledModels(s);
|
||||
renderRedact(s, keep);
|
||||
renderDiscovery(s);
|
||||
renderDiscovery(s, keep);
|
||||
renderSessionReads(s);
|
||||
renderOTel(s, keep);
|
||||
renderPort(s);
|
||||
@@ -21835,7 +21836,7 @@ const REDACT_KINDS = [
|
||||
// the rest — and serves them as subscriptions (#1535). Set on its own:
|
||||
// saved, magpie forgets the accounts it read, and API-key providers go on.
|
||||
// MAGPIE_NO_ACCOUNTS keeps it off for that run whatever is saved.
|
||||
function renderDiscovery(s) {
|
||||
function renderDiscovery(s, keep) {
|
||||
const box = $("#discoveryList");
|
||||
const r = el("div", "row pref");
|
||||
const who = el("div", "who");
|
||||
@@ -21859,7 +21860,17 @@ function renderDiscovery(s) {
|
||||
.catch(settingsErr);
|
||||
}));
|
||||
r.append(who, val);
|
||||
// sign-in pages left to a browser the user picks (max2020 on Discord)
|
||||
const o = el("div", "row pref");
|
||||
o.id = "signInOpenRow";
|
||||
const ow = el("div", "who");
|
||||
ow.append(el("div", "name", t("Open sign-in pages in the browser")),
|
||||
el("div", "sub", t("Adding an account opens its sign-in page in your default browser. Off, magpie only shows the link, to copy into the browser you sign in with")));
|
||||
const ov = el("div", "val");
|
||||
ov.append(segs([["off", t("Off")], ["on", t("On")]], s.signInLinkOnly ? "off" : "on", (v) => savePrefs({ ...keep, signInLinkOnly: v === "off" })));
|
||||
o.append(ow, ov);
|
||||
box.replaceChildren(r);
|
||||
$("#signInOpenList").replaceChildren(o);
|
||||
}
|
||||
// what turning discovery off stops: the subscriptions signed in now, by
|
||||
// name, the Providers list read for it when no page has yet
|
||||
@@ -22754,7 +22765,7 @@ function prefsKeep(s) {
|
||||
trayUsages: s.trayUsages || [],
|
||||
redact: !!s.redact, redactPersonal: !!s.redactPersonal, redactKinds: s.redactKinds || {}, redactWords: s.redactWords || [], redactWordsAnyCase: !!s.redactWordsAnyCase, redactWordsWhole: !!s.redactWordsWhole, redactShape: !!s.redactShape, codexWarmup: s.codexWarmup || "",
|
||||
claudeWarmup: s.claudeWarmup || "", codexWarmAt: s.codexWarmAt || "", claudeWarmAt: s.claudeWarmAt || "",
|
||||
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, noStats: !!s.noStats, noUsageStats: !!s.noUsageStats,
|
||||
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, noStats: !!s.noStats, noUsageStats: !!s.noUsageStats, signInLinkOnly: !!s.signInLinkOnly,
|
||||
memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, refusalRetries: s.refusalRetries ?? null,
|
||||
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload, updateChannel: s.updateChannel || "",
|
||||
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
|
||||
|
||||
@@ -1837,6 +1837,10 @@ const I18N = {
|
||||
"{name} is used through its own CLI, which isn't on this computer yet. magpie is installing it with the official installer; the sign-in page opens as soon as it's done.": "{name} 需通过自身 CLI 使用,本机尚未安装。正在用官方安装脚本安装,完成后立即打开登录页。",
|
||||
"magpie opened the sign-in page. The account shows up here as soon as you're done.": "已打开登录页,完成后账号会出现在这里。",
|
||||
"Open again": "重新打开",
|
||||
"Sign-in pages": "登录页",
|
||||
"Open sign-in pages in the browser": "在浏览器中打开登录页",
|
||||
"Adding an account opens its sign-in page in your default browser. Off, magpie only shows the link, to copy into the browser you sign in with": "添加账号时会在默认浏览器中打开登录页。关闭后,magpie 只显示链接,复制到你用来登录的浏览器里打开",
|
||||
"magpie didn't open the sign-in page, as set in Settings. Copy the link below into the browser you sign in with.": "magpie 按设置没有打开登录页。把下面的链接复制到你用来登录的浏览器里。",
|
||||
"Other ways to sign in…": "其他登录方式…",
|
||||
"ZCode app's sign-in": "使用 ZCode 应用已登录的账号",
|
||||
"GLM Coding Plan API key": "GLM Coding Plan API Key",
|
||||
@@ -6042,6 +6046,10 @@ const I18N = {
|
||||
"{name} is used through its own CLI, which isn't on this computer yet. magpie is installing it with the official installer; the sign-in page opens as soon as it's done.": "{name} 需透過自身 CLI 使用,本機尚未安裝。正在用官方安裝指令碼安裝,完成後立即開啟登入頁。",
|
||||
"magpie opened the sign-in page. The account shows up here as soon as you're done.": "已開啟登入頁,完成後帳號會出現在這裡。",
|
||||
"Open again": "重新開啟",
|
||||
"Sign-in pages": "登入頁",
|
||||
"Open sign-in pages in the browser": "在瀏覽器中開啟登入頁",
|
||||
"Adding an account opens its sign-in page in your default browser. Off, magpie only shows the link, to copy into the browser you sign in with": "新增帳號時會在預設瀏覽器中開啟登入頁。關閉後,magpie 只顯示連結,複製到你用來登入的瀏覽器裡開啟",
|
||||
"magpie didn't open the sign-in page, as set in Settings. Copy the link below into the browser you sign in with.": "magpie 依設定沒有開啟登入頁。把下面的連結複製到你用來登入的瀏覽器裡。",
|
||||
"Other ways to sign in…": "其他登入方式…",
|
||||
"ZCode app's sign-in": "使用 ZCode 應用已登入的帳號",
|
||||
"GLM Coding Plan API key": "GLM Coding Plan API Key",
|
||||
@@ -10224,6 +10232,10 @@ const I18N = {
|
||||
"{name} is used through its own CLI, which isn't on this computer yet. magpie is installing it with the official installer; the sign-in page opens as soon as it's done.": "{name} は専用の CLI を通じて使いますが、このコンピュータにはまだありません。magpie が公式インストーラでインストールしています。完了するとすぐにサインインページが開きます。",
|
||||
"magpie opened the sign-in page. The account shows up here as soon as you're done.": "magpie がサインインページを開きました。完了するとすぐにアカウントがここに表示されます。",
|
||||
"Open again": "もう一度開く",
|
||||
"Sign-in pages": "サインインページ",
|
||||
"Open sign-in pages in the browser": "サインインページをブラウザで開く",
|
||||
"Adding an account opens its sign-in page in your default browser. Off, magpie only shows the link, to copy into the browser you sign in with": "アカウントを追加すると、サインインページを既定のブラウザで開きます。オフにすると、magpie はリンクだけを表示します。サインインに使うブラウザにコピーしてください",
|
||||
"magpie didn't open the sign-in page, as set in Settings. Copy the link below into the browser you sign in with.": "設定に従い、magpie はサインインページを開いていません。下のリンクをサインインに使うブラウザにコピーしてください。",
|
||||
"Other ways to sign in…": "ほかの方法でサインイン…",
|
||||
"ZCode app's sign-in": "ZCode アプリでサインイン中のアカウント",
|
||||
"GLM Coding Plan API key": "GLM Coding Plan の API キー",
|
||||
@@ -14436,6 +14448,10 @@ const I18N = {
|
||||
"{name} is used through its own CLI, which isn't on this computer yet. magpie is installing it with the official installer; the sign-in page opens as soon as it's done.": "{name} wird über seine eigene CLI verwendet, die auf diesem Computer noch fehlt. magpie installiert sie mit dem offiziellen Installer; die Anmeldeseite öffnet sich, sobald das erledigt ist.",
|
||||
"magpie opened the sign-in page. The account shows up here as soon as you're done.": "magpie hat die Anmeldeseite geöffnet. Das Konto erscheint hier, sobald Sie fertig sind.",
|
||||
"Open again": "Erneut öffnen",
|
||||
"Sign-in pages": "Anmeldeseiten",
|
||||
"Open sign-in pages in the browser": "Anmeldeseiten im Browser öffnen",
|
||||
"Adding an account opens its sign-in page in your default browser. Off, magpie only shows the link, to copy into the browser you sign in with": "Beim Hinzufügen eines Kontos öffnet sich seine Anmeldeseite im Standardbrowser. Aus zeigt magpie nur den Link, zum Kopieren in den Browser, mit dem du dich anmeldest",
|
||||
"magpie didn't open the sign-in page, as set in Settings. Copy the link below into the browser you sign in with.": "magpie hat die Anmeldeseite wie in den Einstellungen festgelegt nicht geöffnet. Kopiere den Link unten in den Browser, mit dem du dich anmeldest.",
|
||||
"Other ways to sign in…": "Auf andere Weise anmelden…",
|
||||
"ZCode app's sign-in": "Anmeldung der ZCode-App",
|
||||
"GLM Coding Plan API key": "GLM-Coding-Plan-API-Schlüssel",
|
||||
|
||||
@@ -441,6 +441,8 @@
|
||||
<div class="list prefs" id="shareList"></div>
|
||||
<div class="row-head"><span class="label" data-t>Agents' sign-ins</span></div>
|
||||
<div class="list prefs" id="discoveryList"></div>
|
||||
<div class="row-head"><span class="label" data-t>Sign-in pages</span></div>
|
||||
<div class="list prefs" id="signInOpenList"></div>
|
||||
<div class="row-head"><span class="label" data-t>Agents' session history</span></div>
|
||||
<div class="list prefs" id="sessionReadsList"></div>
|
||||
</section>
|
||||
|
||||
@@ -818,11 +818,7 @@ func pluginRoutes(mux *http.ServeMux, w Windows) {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
var failed string
|
||||
if w != nil && !st.Opened {
|
||||
failed = openError(w, st.URL)
|
||||
}
|
||||
writeJSON(rw, signInOpened{st, failed})
|
||||
writeJSON(rw, openSignIn(w, st))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -2379,7 +2379,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
// one that installs a CLI first has no URL yet: the window opens it
|
||||
// once there is one
|
||||
writeJSON(rw, signInOpened{st, openError(w, st.URL)})
|
||||
writeJSON(rw, openSignIn(w, st))
|
||||
})
|
||||
mux.HandleFunc("GET /api/signin/{id}", func(rw http.ResponseWriter, r *http.Request) {
|
||||
st, ok := provider.SignInStatus(r.PathValue("id"))
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// An account's sign-in page is left out of the default browser when the
|
||||
// user keeps sign-in pages to a browser of their own (max2020 on Discord:
|
||||
// signing in from a separate, fingerprint browser, the default one never
|
||||
// reaching the vendor). The sign-in still starts and gives its link, said
|
||||
// to be unopened; with the setting off, as by default, the page opens as
|
||||
// before. Both the built-in sign-ins and a plugin's.
|
||||
func TestSignInLinkOnlyOpensNothing(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)
|
||||
}
|
||||
type opened struct {
|
||||
provider.SignInState
|
||||
LinkOnly bool `json:"linkOnly"`
|
||||
}
|
||||
start := func(path string, body any) (int, opened) {
|
||||
t.Helper()
|
||||
w := &openCounter{}
|
||||
b, _ := json.Marshal(body)
|
||||
rec := httptest.NewRecorder()
|
||||
Handler(w, nil).ServeHTTP(rec, httptest.NewRequest("POST", path, bytes.NewReader(b)))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: %d %s", path, rec.Code, rec.Body)
|
||||
}
|
||||
var st opened
|
||||
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
|
||||
}
|
||||
ways := []struct {
|
||||
name, path string
|
||||
body any
|
||||
}{
|
||||
{"built-in", "/api/signin", map[string]any{"agent": "gemini"}},
|
||||
{"plugin", "/api/plugin-signin", map[string]any{"provider": "fakeco", "method": 1, "inputs": map[string]string{"where": "work", "team": "blue"}}},
|
||||
}
|
||||
for _, linkOnly := range []bool{true, false} {
|
||||
s := settings.Load()
|
||||
s.SignInLinkOnly = linkOnly
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, way := range ways {
|
||||
n, st := start(way.path, way.body)
|
||||
if !strings.HasPrefix(st.URL, "http") || st.State != "waiting" {
|
||||
t.Fatalf("%s, link only %v: no link to copy: %+v", way.name, linkOnly, st)
|
||||
}
|
||||
if linkOnly && (n != 0 || !st.LinkOnly) {
|
||||
t.Fatalf("%s: kept to its link, its page was opened %d times (linkOnly %v)", way.name, n, st.LinkOnly)
|
||||
}
|
||||
if !linkOnly && (n != 1 || st.LinkOnly) {
|
||||
t.Fatalf("%s: by default its page was opened %d times (linkOnly %v)", way.name, n, st.LinkOnly)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1672,6 +1672,15 @@ with a click, with no left-border accent. The copy button beside it
|
||||
says it was copied. Open again is still there, and nothing scrolls. The
|
||||
checks run in English and Chinese, in Chromium and WebKit.
|
||||
|
||||
`signin-link-only.test.cjs` checks Settings › Privacy › Sign-in pages (max2020
|
||||
on Discord, who signs in from a separate fingerprint browser). "Open sign-in
|
||||
pages in the browser" is On by default, and Off saves signInLinkOnly without
|
||||
moving the page or scrolling sideways, at 900px and 360px. A sign-in the
|
||||
server kept to its link (linkOnly) opens no tab. It says so, shows the link
|
||||
with Copy link, and offers Open where it would say Open again. A sign-in
|
||||
without linkOnly opens its page once, as before. Every language, in Chromium
|
||||
and WebKit; the API is faked.
|
||||
|
||||
`copy-command.test.cjs` copies from a tab with no clipboard API, as
|
||||
`magpie web` on a NAS is when opened from another computer over http:
|
||||
/api/copy refuses and navigator.clipboard is missing, so the copy command
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Sign-in pages kept out of the default browser (max2020 on Discord: they
|
||||
// sign in from a separate, fingerprint browser, and magpie opening the page
|
||||
// in the default one shows the vendor that browser). Settings → Privacy →
|
||||
// Sign-in pages has "Open sign-in pages in the browser", On by default; Off
|
||||
// saves signInLinkOnly. A sign-in the server says it kept to its link
|
||||
// (linkOnly) opens no page in a browser tab either, says so, and offers its
|
||||
// link to copy and Open (not "Open again"); one without it opens its page as
|
||||
// before. Every language, Chromium and WebKit, a narrow window; no click
|
||||
// moves the page. No backend, 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 { openPart, reach } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const LINK = "https://accounts.example/o/oauth2/auth?client_id=x&redirect_uri=http%3A%2F%2F127.0.0.1%3A51234%2Fcallback&state=" + "s".repeat(80);
|
||||
|
||||
const W = {
|
||||
en: { head: "Sign-in pages", name: "Open sign-in pages in the browser", anyway: "Sign in anyway", said: "magpie didn't open the sign-in page", open: "Open", again: "Open again", copy: "Copy link" },
|
||||
zh: { head: "登录页", name: "在浏览器中打开登录页", anyway: "仍然登录", said: "magpie 按设置没有打开登录页", open: "打开", again: "重新打开", copy: "复制链接" },
|
||||
"zh-TW": { head: "登入頁", name: "在瀏覽器中開啟登入頁", anyway: "仍然登入", said: "magpie 依設定沒有開啟登入頁", open: "開啟", again: "重新開啟", copy: "複製連結" },
|
||||
ja: { head: "サインインページ", name: "サインインページをブラウザで開く", anyway: "それでもサインイン", said: "設定に従い、magpie はサインインページを開いていません", open: "開く", again: "もう一度開く", copy: "リンクをコピー" },
|
||||
de: { head: "Anmeldeseiten", name: "Anmeldeseiten im Browser öffnen", anyway: "Trotzdem anmelden", said: "magpie hat die Anmeldeseite wie in den Einstellungen festgelegt nicht geöffnet", open: "Öffnen", again: "Erneut öffnen", copy: "Link kopieren" },
|
||||
};
|
||||
|
||||
function settingsPayload(lang, over) {
|
||||
return {
|
||||
theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd",
|
||||
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
|
||||
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
|
||||
trayUsage: "", trayUsages: [], trayUsageEvery: 3, vision: "", imageGen: "",
|
||||
version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
|
||||
proxyNow: "none", proxySource: "none", login: false,
|
||||
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
|
||||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function server(lang, web, sign, posts) {
|
||||
let cur = settingsPayload(lang);
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.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:${web}};` });
|
||||
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" }, fx: cur.fx });
|
||||
if (url.pathname === "/api/settings") {
|
||||
if (req.method() === "POST") { posts.push(req.postDataJSON()); cur = { ...cur, ...req.postDataJSON() }; }
|
||||
return json(cur);
|
||||
}
|
||||
if (url.pathname === "/api/providers") return json({ providers: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
|
||||
if (url.pathname === "/api/signin" || url.pathname.startsWith("/api/signin/")) return json(sign);
|
||||
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: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
async function newPage(browser, width, route) {
|
||||
const context = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
// a tab the page opens is counted, not opened
|
||||
await page.addInitScript(() => {
|
||||
window.__opened = [];
|
||||
window.open = (u) => { window.__opened.push(String(u)); return {}; };
|
||||
});
|
||||
await page.route("**/*", route);
|
||||
return { context, page, errors };
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": sign-in pages kept to their link", async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const lang of Object.keys(W)) {
|
||||
const w = W[lang];
|
||||
for (const width of [900, 360]) {
|
||||
await t.test(`${lang} ${width}: the setting`, async () => {
|
||||
const posts = [];
|
||||
const { context, page, errors } = await newPage(browser, width, server(lang, false, {}, posts));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
await page.locator("#prefs").click();
|
||||
await openPart(page, "privacy");
|
||||
const box = page.locator("#signInOpenList");
|
||||
await box.locator(".opt").first().waitFor();
|
||||
assert.equal((await box.evaluate((b) => b.previousElementSibling.querySelector(".label").textContent)).trim(), w.head);
|
||||
assert.equal((await box.locator(".name").textContent()).trim(), w.name);
|
||||
const opts = box.locator(".opt");
|
||||
assert.equal(await opts.nth(1).evaluate((b) => b.classList.contains("on")), true, "On by default");
|
||||
const fit = await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1);
|
||||
assert(fit, "no sideways scroll");
|
||||
await reach(page, opts.nth(0)); // by the wheel, as a reader does: magpie puts back a scroll no one asked for
|
||||
await page.waitForTimeout(200);
|
||||
const top = await page.locator("#view-settings").evaluate((v) => v.scrollTop);
|
||||
await opts.nth(0).click();
|
||||
for (let i = 0; i < 40 && !posts.length; i++) await page.waitForTimeout(50);
|
||||
assert.equal(posts.at(-1)?.signInLinkOnly, true, "Off saves signInLinkOnly");
|
||||
await page.waitForFunction(() => document.querySelectorAll("#signInOpenList .opt")[0]?.classList.contains("on"));
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await page.locator("#view-settings").evaluate((v) => v.scrollTop), top, "the click didn't move the page");
|
||||
assert.deepEqual(errors, []);
|
||||
await context.close();
|
||||
});
|
||||
}
|
||||
for (const linkOnly of [true, false]) {
|
||||
await t.test(`${lang}: a sign-in ${linkOnly ? "kept to its link" : "opened"} in a browser tab`, async () => {
|
||||
const sign = { id: "s1", agent: "factory", state: "waiting", url: LINK, ...(linkOnly ? { linkOnly: true } : {}) };
|
||||
const { context, page, errors } = await newPage(browser, 900, server(lang, true, sign, []));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator("#addProvider").click();
|
||||
const sheet = page.locator("#addSheet");
|
||||
await sheet.locator('.tile[data-pick="Factory"]').click();
|
||||
const box = sheet.locator(".signing");
|
||||
await box.locator("button", { hasText: w.anyway }).click();
|
||||
await box.locator(".signlink").waitFor();
|
||||
assert.equal(await box.locator(".signlink code").textContent(), LINK);
|
||||
assert.equal(await box.locator(".signlink button.copy").getAttribute("title"), w.copy);
|
||||
const said = await box.locator(".tt > .s").first().textContent();
|
||||
const opened = await page.evaluate(() => window.__opened);
|
||||
if (linkOnly) {
|
||||
assert.deepEqual(opened, [], "no page opened");
|
||||
assert(said.startsWith(w.said), said);
|
||||
assert.equal(await box.locator(".acts button", { hasText: new RegExp("^" + w.open + "$") }).count(), 1, "Open");
|
||||
assert.equal(await box.locator(".acts button", { hasText: w.again }).count(), 0, "not Open again");
|
||||
} else {
|
||||
assert.deepEqual(opened, [LINK], "the page opened once");
|
||||
assert(!said.startsWith(w.said), said);
|
||||
assert.equal(await box.locator(".acts button", { hasText: w.again }).count(), 1, "Open again");
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
await context.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -372,6 +372,13 @@ type Settings struct {
|
||||
// as by default, subscriptions are found as ever. This computer's own
|
||||
// (KeepOwn), set only by its own switch or `magpie accounts discovery`.
|
||||
NoAccountDiscovery bool `json:"noAccountDiscovery,omitempty"`
|
||||
// SignInLinkOnly keeps an account's sign-in page out of the default
|
||||
// browser: the window (and the command line) shows its link to copy
|
||||
// into a browser the user picks, a separate or fingerprint browser
|
||||
// (max2020 on Discord). Off, as by default, the page opens as ever. A
|
||||
// plugin whose own CLI opens its page (Grok Build on macOS and
|
||||
// Windows) still does: magpie can't stop that.
|
||||
SignInLinkOnly bool `json:"signInLinkOnly,omitempty"`
|
||||
// NoStats stops the one event a day that counts magpie's users (see
|
||||
// internal/stats).
|
||||
NoStats bool `json:"noStats,omitempty"`
|
||||
|
||||
Reference in New Issue
Block a user