diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 0cedd8c11..674f1bd67 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -48,6 +48,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where `cli_auth_credentials_store` in `$CODEX_HOME/config.toml` says (`codex-rs/login/src/auth/storage.rs`): `file` (default) is `auth.json`; `keyring` the system keychain alone; `auto` the keychain, else `auth.json`, on read and on save; `ephemeral` Codex's memory. Saved to the keychain, Codex removes `auth.json` (#2312, #2367, Dony2050). On macOS magpie reads that item through `security`, as it reads Claude Code's: service `Codex Auth`, account `cli|` + the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (`codexKeychainAccount`), the value auth.json's JSON on one line. `readCodexLogin` is the one reader: `codexAccount`, `codexToken`, `liveLogin`, `CodexAPIKeySignedIn`, `codexLoginAuth`, `codexUntil` (the usage card's and each saved account row's `Until`, from the sign-in Codex holds when it holds that one), session identities and the agent's wiring (`provider.CodexSignIn`: `codexChatGPT`, `Agent.Source`) go through it. `keyring` with no item is signed out; `auto` with no item, or one the keychain wouldn't give, is `auth.json`, as Codex does. An item the keychain wouldn't give under `keyring` is not known (`codexStoreError`), never signed out. With `[features] secret_auth_storage` on (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. There `keyring` and `ephemeral` are not known, `auto` is `auth.json` when Codex left one, and the saved accounts' reason says to set `file` (`codexSignedOutWhy`). Requirements an admin manages (`requirements.cli_auth_credentials_store`) aren't read. Reading the secret can put up to two macOS prompts in front of the user, who may type their password, so one read per item is in flight at a time and waits up to 2 minutes for them (`keychainAsk`, `askCodexKeychain`), outside the cache's lock. A reader waits at most 5s from when that ask started (`keychainHold`) and is otherwise told magpie is waiting for an answer (`errKeychainWaiting`); no request or page waits out the prompt. `security` exit 44 is no item; 51 (errSecAuthFailed) or 128 (errSecUserCanceled) is denied or cancelled (`errKeychainRefused`); the 2 minutes running out is no answer (`errKeychainNoAnswer`); anything else is `errKeychainUnread`. Each says so in the saved accounts' reason, and none of them is signed out. A read the keychain gave is kept while the item is unchanged: after 10s a reader asks only the item's modification date (`Stat`, `find-generic-password` without `-w`, which shows no prompt) and reads the secret again only when Codex or magpie changed it (#2367: with "Allow" once, background polls asked again every ~30s). A refusal or no answer is kept 10 minutes (#2408). magpie's own writes (`codexStore.write`, `keepCodexKeychain`) keep the date of what they wrote; a switch, sign-out or refresh forgets a read (`forgetCodexKeychain`) so the next one checks the date, but keeps a refusal; switching and refreshing read afresh. Beside a refusal, no answer or waiting, the saved accounts' line has Try again (`Exclusion.Retry`, `keychain-retry`, `RetryCodexKeychain`), which reads once past the refusal, and the reason says "Always Allow" lets `/usr/bin/security` read the item, so macOS stops asking each time Codex changes it. A switch or a first sign-in (`saveCodexLogin`) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an `auth.json` beside the item to Codex. Signing the last account out (`deleteCodexLogin`) removes the item, then `auth.json`, as `codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. | [`codex_store.go`](../../internal/provider/codex_store.go), [`codex_store_test.go`](../../internal/provider/codex_store_test.go), [`codex_keychain_ask_unix_test.go`](../../internal/provider/codex_keychain_ask_unix_test.go) | | Codex's other folders | Codex keeps one ChatGPT sign-in a folder (`codex-rs/login/src/auth/storage.rs`: `$CODEX_HOME/auth.json`, or the keychain item named by the folder) and writes its sessions there (`rollout/src/lib.rs`); `--profile` only lays `$CODEX_HOME/.config.toml` over `config.toml`, the sign-in shared (`config/src/loader/mod.rs`). So a second account is Codex run with `CODEX_HOME=~/.codex-work`. `appdir.CodexHomes` finds those folders: `CodexHome` first, then folders in the home folder or beside `CodexHome` named `codex*` or `.codex*`, or one folder down in one (`~/.codex-profiles/work`), that hold `auth.json` or `sessions/`. Sessions and the usage ledger read every one (`sessions.codexFiles`, `Dirs`). `rememberLogins` saves each folder's account with `Home` set to it (`codexHomeLogins`); the one `~/.codex` is signed in to is that one's. Such an account is renewed in its folder, as Codex's own (`codexHeldIn` in `renewSaved`, as `heldByCodex` does for `~/.codex`), so the quota, the gateway and the keep-alive never spend a copy's refresh token under that folder's Codex. It isn't switched into `~/.codex` (`switchSavedLogin`, `NextLogin`'s spares): the error names the folder and the `CODEX_HOME=… codex` command. A refresh OpenAI refuses there marks the account signed out (`codexHeldRefusal`, `codexSignInRead`), so its row has Sign in again, and magpie's sign-in writes the new tokens back to that folder (`codexHeldFolder` in `addLogin`), never to `~/.codex` (`TestCodexHeldInOtherFolderSignedOutThenSignedInAgain`). Remove forgets it and sets that folder's sign-in aside in `codex-homes-removed.json` (the folder to a SHA-256 of its refresh token, `setCodexAside`), the folder's files left as they are; `codexHomeLogins` passes over the folder while it holds that sign-in, and a sign-in made there again is listed again. An unreadable record reads no other folder's account that look (charliepu on Discord: a `.codex-db-backup-…` folder no Codex runs in, refused with "codex logout"; `TestCodexHeldFolderAccountRemoved`). phantom3792 on X: only the default folder's sessions counted, and an account added from another folder read no quota (`TestCodexOtherHome*`, `TestCodexHomesIn`). Not done: Codex's thread names (`session_index.jsonl`) and a `sqlite_home` are read from `CodexHome` only (#3530). | [`codex.go`](../../internal/appdir/codex.go), [`logins.go`](../../internal/provider/logins.go), [`codex_homes_test.go`](../../internal/provider/codex_homes_test.go) | | 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:"` 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. Each failed read says why on the account's row (`codexUsageWords`, `codex_usage_words.go`; hmy on Discord: five ChatGPT accounts each said only "Allowance unavailable", the error being Go's bare status text or decode error, which the GUI read none of): Cloudflare's challenge page in place of an answer (a proxy or VPN address, usually), `HTTP ` with the backend's own `detail` or `error` words, chatgpt.com not reached, or a reply magpie doesn't read; `quotaError` in app.js turns each into a line of the card's language, the raw error in the row's tooltip. The words keep what was matched before: the status text that `passing` (`quota_last.go`) reads to keep the last reading over a 429 or a 5xx, and the answer itself under `Unwrap` for `codexExpired`. An error with no words of its own says "Allowance unavailable — hover for why". A ChatGPT API account (`chatgpt-api`, `chatgpt_api.go`) has no usage read: OpenAI's API tells none, only chatgpt.com/settings/usage does. `loginQuota` says so (`siwcNoUsage`, with that page as `SeeAt`) and asks nothing; it used to read the account as a Codex one, so an active one read Codex's own sign-in ("Codex is signed out; run codex login", or another account's allowance under its name) and the card said only that it couldn't be read (danzi002 on Discord). Guarded by `TestChatGPTAPIUsageSaysWhere`. 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) | +| Sign-in alerts | A system notification tells of an account in use (`On` or `Active`) of a subscription switched on whose row says Sign in again (steven_4422 on Discord: before, only the row and its Signed out pill said so). The test is the Providers page's (`renderAccounts`): any `Lapsed` on a Claude, Copilot or plugin account, and on another built-in one a mark `signInGone` matches (`needsSignIn`); a plugin's usage read that says so marks the account too. A Claude account is told of three days before its sign-in ends as well, as Claude Code's own "Your login expires in N days" is: its credentials' `refreshTokenExpiresAt` (Claude Code sets it from the token reply's `refresh_token_expires_in`, else 30 days from the sign-in, and keeps it over a refresh that sends none; past it, Claude Code takes the sign-in for none), unless the access token outlasts it by more than the three days (`claudeSignInEnds`). Each is told once (`dueSignIns`): a lapse until the account is usable again, an end until it moves; the marks are kept in `signin-alerts.json` beside `providers.json`, so a restart doesn't tell again, and an account not listed keeps them `alertKeep`. An unreadable marks file tells nothing. `WatchSignIns` looks a minute after start and every two minutes after, reading magpie's own files only. It is always on. The GUI sends it under `magpie-signin-|` (`signInKind`, `signInText` in five languages), and a click opens that provider's editor (`clickView` → `providers&edit=`), where the account's Sign in again is; a Linux dismissal opens nothing. Guarded by `TestSignInAlertClaudeSignedOut`, `TestSignInAlertClaudeEnding`, `TestDueSignIns` and `TestSignInAlertOpensItsProvider`. | [`signin_alert.go`](../../internal/provider/signin_alert.go), [`quota_alert_notify.go`](../../internal/gui/quota_alert_notify.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 " 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). ChatGPT also signs in by device code, as `codex login --device-auth` does (`CodexDeviceSite`, `startCodexDeviceSignIn` in `codex_device_signin.go`): magpie asks `auth.openai.com/api/accounts/deviceauth/usercode` for a code, the box shows it with ChatGPT's device page, and magpie polls `deviceauth/token` (403 or 404 is not entered yet, up to 15 minutes), then trades the code at the token endpoint with the verifier it got and the `/deviceauth/callback` redirect. Nothing listens on this machine. The window starts this way when `magpie web` is opened from another computer (`remotePage` in `app.js`: a host other than localhost or loopback; curtinp118 on Discord, magpie on a VPS), and the box offers the other way as a link either way; a device code ChatGPT turns away (404) fails with a link to the browser's way. 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), [`codex_device_signin.go`](../../internal/provider/codex_device_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) | diff --git a/internal/gui/quota_alert_notify.go b/internal/gui/quota_alert_notify.go index 941297d15..fc1295610 100644 --- a/internal/gui/quota_alert_notify.go +++ b/internal/gui/quota_alert_notify.go @@ -140,7 +140,7 @@ func notice(goos, id, title, body string) notifications.NotificationOptions { // clickView is the page a response to a notification opens, "" for none. // A click on an alert opens Usage; on a value masked, the 脱敏 page at the -// request that masked it. On a turn's end, where the user goes is their +// request that masked it; on a sign-in alert, its provider's accounts. On a turn's end, where the user goes is their // agent, not magpie. On Linux only a click (linuxClick) is one: an alert // dismissed there opened the main window, maximised if it was left so, // over the desktop with the focus (#2513). @@ -155,6 +155,9 @@ func clickView(goos string, r notifications.NotificationResponse) string { } return "masking&key=" + key } + if rest, ok := strings.CutPrefix(r.ID, signInNotice); ok { + return signInView(rest) + } return "usage" } @@ -190,6 +193,13 @@ func (h *host) watchAlerts() { title, body := turnDoneText(trayLang(settings.Load().Lang, systemLang), agentName(t.Agent), t) n.sendAs(turnNotice, title, body) } + // an account in use signed out, or a Claude sign-in about to end + // (steven_4422 on Discord): always on, as the account's Sign in + // again is + go provider.WatchSignIns(backendCtx, func(a provider.SignInAlert) { + title, body := signInText(trayLang(settings.Load().Lang, systemLang), a, time.Now()) + n.sendAs(signInKind(a.Provider), title, body) + }) // until this one has handed the gateway to the new version, // which alerts from then on (#4938) provider.WatchQuotas(backendCtx, wake, func(a provider.QuotaAlert) { diff --git a/internal/gui/signin_alert.go b/internal/gui/signin_alert.go new file mode 100644 index 000000000..829cc070a --- /dev/null +++ b/internal/gui/signin_alert.go @@ -0,0 +1,82 @@ +package gui + +import ( + "fmt" + "net/url" + "strings" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// signInNotice is the id a sign-in alert is notified under, followed by +// its provider's id and "|", so a click opens that provider's accounts. +const signInNotice = "magpie-signin-" + +// signInKind is the start of the id a sign-in alert for provider id is +// notified under (sendAs puts the time after it). +func signInKind(id string) string { return signInNotice + url.QueryEscape(id) + "|" } + +// signInView is the page a click on a sign-in alert opens, rest being its +// id after signInNotice: the provider's editor, where the account's Sign +// in again is. +func signInView(rest string) string { + p, _, _ := strings.Cut(rest, "|") + if p, err := url.QueryUnescape(p); err == nil && p != "" { + return "providers&edit=" + url.QueryEscape(p) + } + return "providers" +} + +// signInDays is how many days are left until at, rounded up, as Claude +// Code counts them in its own warning. +func signInDays(at, now time.Time) int { + d := int((at.Sub(now) + 24*time.Hour - 1) / (24 * time.Hour)) + return max(d, 1) +} + +// signInText is the notification of a sign-in alert in the language (en, +// zh, zh-TW, ja or de): the subscription and account, and that it has to +// be signed in again, or in how many days its sign-in ends. +func signInText(lang string, a provider.SignInAlert, now time.Time) (title, body string) { + title = a.Name + if a.User != "" { + title += " · " + a.User + } + n := 0 + if a.Kind == "ending" && a.EndsAt != nil { + n = signInDays(*a.EndsAt, now) + } + switch lang { + case "zh": + if n > 0 { + return title, fmt.Sprintf("登录将在 %d 天后失效,点此重新登录", n) + } + return title, "登录已失效,点此重新登录" + case "zh-TW": + if n > 0 { + return title, fmt.Sprintf("登入將在 %d 天後失效,點此重新登入", n) + } + return title, "登入已失效,點此重新登入" + case "ja": + if n > 0 { + return title, fmt.Sprintf("サインインはあと %d 日で切れます。クリックしてサインインし直してください", n) + } + return title, "サインインが切れました。クリックしてサインインし直してください" + case "de": + if n == 1 { + return title, "Die Anmeldung endet in 1 Tag – zum erneuten Anmelden klicken" + } + if n > 0 { + return title, fmt.Sprintf("Die Anmeldung endet in %d Tagen – zum erneuten Anmelden klicken", n) + } + return title, "Abgemeldet – zum erneuten Anmelden klicken" + } + if n == 1 { + return title, "Sign-in ends in 1 day — click to sign in again" + } + if n > 0 { + return title, fmt.Sprintf("Sign-in ends in %d days — click to sign in again", n) + } + return title, "Signed out — click to sign in again" +} diff --git a/internal/gui/signin_alert_notify_test.go b/internal/gui/signin_alert_notify_test.go new file mode 100644 index 000000000..cac1fdce5 --- /dev/null +++ b/internal/gui/signin_alert_notify_test.go @@ -0,0 +1,68 @@ +//go:build !nogui + +package gui + +import ( + "fmt" + "strings" + "testing" + "time" + + "github.com/wailsapp/wails/v3/pkg/services/notifications" + "github.com/yetone/magpie/internal/provider" +) + +// A click on a sign-in alert opens its provider's editor, where the +// account's Sign in again is (steven_4422 on Discord); a Linux dismissal +// still opens nothing. +func TestSignInAlertOpensItsProvider(t *testing.T) { + for _, c := range []struct { + goos, provider, action, want string + }{ + {"darwin", "claude", notifications.DefaultActionIdentifier, "providers&edit=claude"}, + {"windows", "codex", notifications.DefaultActionIdentifier, "providers&edit=codex"}, + {"linux", "copilot", linuxClick, "providers&edit=copilot"}, + {"linux", "copilot", notifications.DefaultActionIdentifier, ""}, + {"darwin", "a|b&c", notifications.DefaultActionIdentifier, "providers&edit=a%7Cb%26c"}, + } { + id := fmt.Sprintf("%s%d", signInKind(c.provider), time.Now().UnixNano()) + r := notifications.NotificationResponse{ID: id, ActionIdentifier: c.action} + if got := clickView(c.goos, r); got != c.want { + t.Errorf("clickView(%s, %s %s) = %q, want %q", c.goos, id, c.action, got, c.want) + } + } +} + +// The notification names the subscription and account, and says to sign +// in again, or in how many days the sign-in ends, in every language. +func TestSignInText(t *testing.T) { + now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC) + gone := provider.SignInAlert{Provider: "claude", Name: "Claude", User: "a@example.com", Kind: "lapsed"} + in := func(d time.Duration) provider.SignInAlert { + at := now.Add(d) + return provider.SignInAlert{Provider: "claude", Name: "Claude", User: "a@example.com", Kind: "ending", EndsAt: &at} + } + for _, c := range []struct { + lang string + a provider.SignInAlert + want string + }{ + {"en", gone, "Signed out — click to sign in again"}, + {"en", in(2*24*time.Hour + time.Hour), "Sign-in ends in 3 days — click to sign in again"}, + {"en", in(5 * time.Hour), "Sign-in ends in 1 day — click to sign in again"}, + {"zh", gone, "登录已失效,点此重新登录"}, + {"zh", in(48 * time.Hour), "登录将在 2 天后失效,点此重新登录"}, + {"zh-TW", gone, "登入已失效,點此重新登入"}, + {"ja", in(24 * time.Hour), "サインインはあと 1 日で切れます。クリックしてサインインし直してください"}, + {"de", in(5 * time.Hour), "Die Anmeldung endet in 1 Tag – zum erneuten Anmelden klicken"}, + {"de", gone, "Abgemeldet – zum erneuten Anmelden klicken"}, + } { + title, body := signInText(c.lang, c.a, now) + if title != "Claude · a@example.com" || body != c.want { + t.Errorf("%s %s: %q / %q, want %q", c.lang, c.a.Kind, title, body, c.want) + } + } + if title, _ := signInText("en", provider.SignInAlert{Name: "Cursor", Kind: "lapsed"}, now); strings.Contains(title, "·") { + t.Errorf("an account with no name titled %q", title) + } +} diff --git a/internal/provider/signin_alert.go b/internal/provider/signin_alert.go new file mode 100644 index 000000000..c92602d91 --- /dev/null +++ b/internal/provider/signin_alert.go @@ -0,0 +1,209 @@ +package provider + +// Sign-in alerts (steven_4422 on Discord): a notification when an account +// in use has to be signed in again, and, for Claude, before its sign-in +// ends. Until now a sign-in its vendor refused or revoked showed only on +// the account's row (Sign-in required, Sign in again) and the row's +// Signed out pill, seen only by opening magpie. The test of an account that +// has to be signed in again is the one the Providers page uses +// (renderAccounts in app.js), so a notification names exactly the rows +// that say so. Each is said once, until the account is usable again; what +// was said is kept in a file, so a restart doesn't say it again. +// +// Claude Code keeps when a sign-in's refresh token ends +// (claudeAiOauth.refreshTokenExpiresAt, from the token reply's +// refresh_token_expires_in, else 30 days from the sign-in) and says "Your +// login expires in N days · run /login to renew" from three days before; +// past it, it takes the sign-in for none. A refresh doesn't move it unless +// Anthropic sends a new one. magpie tells the same, from the same field. + +import ( + "context" + "encoding/json" + "log" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +// SignInAlert is a sign-in to tell the user of. Kind is "lapsed" for an +// account that has to be signed in again, "ending" for one whose sign-in +// ends at EndsAt. +type SignInAlert struct { + Provider string // the provider's id: the row a click opens + Name string + User string + Kind string + EndsAt *time.Time +} + +// needsSignIn says an account of agent marked lapsed has to be signed in +// again, as the Providers page decides it (renderAccounts' unusable and +// signedOut): any mark on a Claude, Copilot or plugin account, and on +// another built-in one a mark that says so (signInGone, app.js's +// SIGN_IN_GONE). A plugin's usage read that says so marks the account +// too (pluginLoginQuota), so its mark covers the page's other case. +func needsSignIn(agent string, isPlugin bool, lapsed string) bool { + if lapsed == "" { + return false + } + return agent == "claude" || agent == "copilot" || isPlugin || signInGone.MatchString(lapsed) +} + +// claudeEndsWithin is how long before a Claude sign-in ends it is told of: +// Claude Code's own warning's three days. +const claudeEndsWithin = 3 * 24 * time.Hour + +// claudeSignInEnds is when the Claude sign-in auth ends, as Claude Code +// reads it: its refresh token's end, unless its access token outlasts that +// by more than the warning (a sign-in whose end is not the refresh +// token's). ok is false when it says none. +func claudeSignInEnds(auth []byte) (at time.Time, ok bool) { + c, parsed := parseClaudeCredentials(auth) + if !parsed || c.OAuth.RefreshToken == "" || c.OAuth.RefreshExpiresAt <= 0 { + return time.Time{}, false + } + if c.OAuth.ExpiresAt > c.OAuth.RefreshExpiresAt+claudeEndsWithin.Milliseconds() { + return time.Time{}, false + } + return time.UnixMilli(c.OAuth.RefreshExpiresAt), true +} + +// signInState is one account as the alerts see it. +type signInState struct { + Provider, Name, User string + Gone bool + EndsAt *time.Time +} + +// signInStates is every account in use of every subscription switched on: +// whether it has to be signed in again, and when a Claude one's sign-in +// ends. +func signInStates() []signInState { + ends := map[string]time.Time{} + var out []signInState + for _, p := range Accounts() { + a := p.Account + if a == nil || p.Off { + continue + } + agent, isPlugin := a.Agent, false + if _, ok := PluginOf(p.ID); ok && p.IsPlugin() { + agent, isPlugin = p.ID, true // its accounts go by the provider's id + } + ls := Logins(agent) + if agent == "claude" && len(ls) > 0 { + for _, l := range sharedLogins() { + if l.Agent == "claude" { + if at, ok := claudeSignInEnds(l.Auth); ok { + ends[strings.ToLower(l.User)] = at + } + } + } + } + for _, l := range ls { + if !l.On && !l.Active { + continue // not in use: nothing is lost while it is signed out + } + s := signInState{Provider: p.ID, Name: p.Name, User: l.User, Gone: needsSignIn(a.Agent, isPlugin, l.Lapsed)} + if at, ok := ends[strings.ToLower(l.User)]; ok && agent == "claude" && !s.Gone { + s.EndsAt = &at + } + out = append(out, s) + } + } + return out +} + +// dueSignIns is what the accounts ss call for, the marks in marks brought +// up to date: an account that has to be signed in again, once until it is +// usable again; a sign-in ending within claudeEndsWithin, once for that +// end. An account not listed now (its plugin not started yet) keeps its +// marks a while, so it isn't told of again when it is. +func dueSignIns(ss []signInState, marks map[string]alertMark, now time.Time) []SignInAlert { + var out []SignInAlert + seen := map[string]bool{} + for _, s := range ss { + pre := s.Provider + "|" + strings.ToLower(s.User) + "|" + gone, ends := pre+"gone", pre+"ends" + seen[gone], seen[ends] = true, true + if !s.Gone { + delete(marks, gone) + } else if _, ok := marks[gone]; !ok { + marks[gone] = alertMark{At: now} + out = append(out, SignInAlert{Provider: s.Provider, Name: s.Name, User: s.User, Kind: "lapsed"}) + } + if s.EndsAt == nil || !s.EndsAt.After(now) || s.EndsAt.Sub(now) > claudeEndsWithin { + if s.EndsAt == nil || s.EndsAt.Sub(now) > claudeEndsWithin { + delete(marks, ends) // signed in anew, or not ending yet + } + continue + } + if m, ok := marks[ends]; ok && sameRun(m.Until, s.EndsAt) { + continue + } + at := *s.EndsAt + marks[ends] = alertMark{At: now, Until: &at} + out = append(out, SignInAlert{Provider: s.Provider, Name: s.Name, User: s.User, Kind: "ending", EndsAt: &at}) + } + for k, m := range marks { + if !seen[k] && now.Sub(m.At) > alertKeep { + delete(marks, k) + } + } + return out +} + +func signInAlertPath() string { return filepath.Join(filepath.Dir(Path()), "signin-alerts.json") } + +// signInAlertMu keeps the file to one writer in this magpie. +var signInAlertMu sync.Mutex + +// checkSignIns says what the accounts ss call for, keeping the marks in +// path. +func checkSignIns(path string, ss []signInState, now time.Time) []SignInAlert { + signInAlertMu.Lock() + defer signInAlertMu.Unlock() + marks := map[string]alertMark{} + if b, err := os.ReadFile(path); err == nil { + if json.Unmarshal(b, &marks) != nil { + // unknown, not empty: a mark lost would say every lapse again + return nil + } + } else if !os.IsNotExist(err) { + return nil + } + before, _ := json.Marshal(marks) + out := dueSignIns(ss, marks, now) + if after, _ := json.Marshal(marks); string(after) != string(before) { + os.MkdirAll(filepath.Dir(path), 0o755) + writePrivate(path, append(after, '\n')) + } + return out +} + +// signInAlertEvery is how often the accounts are looked at: a mark is set +// as a request is refused, so this reads magpie's own files, asking no +// vendor. +const signInAlertEvery = 2 * time.Minute + +// WatchSignIns hands send each sign-in alert due, a minute after it starts +// and every signInAlertEvery after, until ctx ends. +func WatchSignIns(ctx context.Context, send func(SignInAlert)) { + t := time.NewTimer(time.Minute) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + for _, a := range checkSignIns(signInAlertPath(), signInStates(), time.Now()) { + log.Printf("sign-in alert: %s %s %s", a.Kind, a.Name, a.User) + send(a) + } + t.Reset(signInAlertEvery) + } +} diff --git a/internal/provider/signin_alert_test.go b/internal/provider/signin_alert_test.go new file mode 100644 index 000000000..b91625d35 --- /dev/null +++ b/internal/provider/signin_alert_test.go @@ -0,0 +1,163 @@ +package provider + +import ( + "path/filepath" + "testing" + "time" +) + +// signInAlertsOf is what a look at the accounts calls for now, the marks +// kept in path. +func signInAlertsOf(t *testing.T, path string, now time.Time) []SignInAlert { + t.Helper() + forgetAccountCaches() + return checkSignIns(path, signInStates(), now) +} + +// setSideClaude writes the saved Claude account side back as it is now. +func setSideClaude(t *testing.T, side savedLogin) { + t.Helper() + writeFile(t, loginsPath(), []savedLogin{side}) + forgetAccountCaches() +} + +// A Claude account in use whose sign-in Claude Code couldn't use is told +// of once, with the provider a click opens, and again only after it was +// usable in between (steven_4422 on Discord: nothing said so outside the +// account's row). +func TestSignInAlertClaudeSignedOut(t *testing.T) { + _, side := claudeAuthFixture(t, claudeAuthLapse) + path := filepath.Join(t.TempDir(), "signin-alerts.json") + now := time.Now() + got := signInAlertsOf(t, path, now) + if len(got) != 1 || got[0].Kind != "lapsed" || got[0].Provider != "claude" || got[0].User != side.User || got[0].Name == "" { + t.Fatalf("alerts for a signed-out Claude account: %+v", got) + } + if got := signInAlertsOf(t, path, now.Add(5*time.Minute)); len(got) != 0 { + t.Fatalf("told again: %+v", got) + } + side.Lapsed = "" + setSideClaude(t, side) + if got := signInAlertsOf(t, path, now.Add(10*time.Minute)); len(got) != 0 { + t.Fatalf("a usable account told of: %+v", got) + } + side.Lapsed = claudeAuthLapse + setSideClaude(t, side) + if got := signInAlertsOf(t, path, now.Add(15*time.Minute)); len(got) != 1 || got[0].Kind != "lapsed" { + t.Fatalf("signed out again, not told: %+v", got) + } +} + +// An account not in use is told of nothing: no request goes to it. +func TestSignInAlertSkipsAccountsNotInUse(t *testing.T) { + _, side := claudeAuthFixture(t, claudeAuthLapse) + side.On = false + setSideClaude(t, side) + if got := signInAlertsOf(t, filepath.Join(t.TempDir(), "a.json"), time.Now()); len(got) != 0 { + t.Fatalf("an account not in use told of: %+v", got) + } +} + +// A Claude sign-in whose refresh token ends within three days is told of +// once for that end, as Claude Code's own "Your login expires in N days" +// is; one further off, or signed in anew, is not. +func TestSignInAlertClaudeEnding(t *testing.T) { + _, side := claudeAuthFixture(t, "") + now := time.Now() + creds := func(ends time.Time) { + side.Auth = mustJSONRaw(t, map[string]any{"claudeAiOauth": map[string]any{ + "accessToken": "old-access", "refreshToken": "old-refresh", + "expiresAt": now.Add(time.Hour).UnixMilli(), "refreshTokenExpiresAt": ends.UnixMilli(), "subscriptionType": "max", + }}) + setSideClaude(t, side) + } + path := filepath.Join(t.TempDir(), "signin-alerts.json") + creds(now.Add(20 * 24 * time.Hour)) + if got := signInAlertsOf(t, path, now); len(got) != 0 { + t.Fatalf("told of a sign-in 20 days from its end: %+v", got) + } + ends := now.Add(2*24*time.Hour + time.Hour) + creds(ends) + got := signInAlertsOf(t, path, now) + if len(got) != 1 || got[0].Kind != "ending" || got[0].User != side.User || got[0].EndsAt == nil || !got[0].EndsAt.Equal(time.UnixMilli(ends.UnixMilli())) { + t.Fatalf("alerts for a sign-in ending in 2 days: %+v", got) + } + if got := signInAlertsOf(t, path, now.Add(time.Hour)); len(got) != 0 { + t.Fatalf("told again of the same end: %+v", got) + } + creds(now.Add(30 * 24 * time.Hour)) // signed in anew + if got := signInAlertsOf(t, path, now.Add(2*time.Hour)); len(got) != 0 { + t.Fatalf("told of a new sign-in: %+v", got) + } + creds(now.Add(24 * time.Hour)) + if got := signInAlertsOf(t, path, now.Add(3*time.Hour)); len(got) != 1 || got[0].Kind != "ending" { + t.Fatalf("the new sign-in's end not told: %+v", got) + } +} + +// Claude Code's own rule: no end said, or an access token that outlasts +// the refresh token's end by more than the warning, is no end to tell. +func TestClaudeSignInEnds(t *testing.T) { + now := time.Now() + blob := func(o map[string]any) []byte { + o["accessToken"], o["refreshToken"] = "a", "r" + return mustJSONRaw(t, map[string]any{"claudeAiOauth": o}) + } + if at, ok := claudeSignInEnds(blob(map[string]any{"expiresAt": now.Add(time.Hour).UnixMilli(), "refreshTokenExpiresAt": now.Add(48 * time.Hour).UnixMilli()})); !ok || at.UnixMilli() != now.Add(48*time.Hour).UnixMilli() { + t.Fatalf("end not read: %v %v", at, ok) + } + if _, ok := claudeSignInEnds(blob(map[string]any{"expiresAt": now.Add(time.Hour).UnixMilli()})); ok { + t.Fatal("an end read where none is said") + } + if _, ok := claudeSignInEnds(blob(map[string]any{"expiresAt": now.Add(10 * 24 * time.Hour).UnixMilli(), "refreshTokenExpiresAt": now.Add(time.Hour).UnixMilli()})); ok { + t.Fatal("an end read under an access token that outlasts it") + } +} + +// Every subscription whose row says Sign in again is told of, as the +// Providers page decides it: a Claude, Copilot or plugin account's mark, +// and a built-in's that says its sign-in is gone. A failure of the moment +// is not. +func TestSignInGoneAsThePageSaysIt(t *testing.T) { + for _, c := range []struct { + agent string + plugin bool + lapsed string + want bool + }{ + {"claude", false, claudeAuthLapse, true}, + {"copilot", false, copilotLapsedText, true}, + {"cursor", true, "Cursor refused this sign-in", true}, + {"codex", false, revokedText("a@example.com"), true}, + {"codex", false, "a@example.com's sign-in has expired — add the account again to use it", true}, + {"chatgpt-api", false, "a@example.com's ChatGPT sign-in has expired — sign in again", true}, + {"codex", false, "usage read failed: HTTP 502", false}, + {"codex", false, "", false}, + {"claude", false, "", false}, + } { + if got := needsSignIn(c.agent, c.plugin, c.lapsed); got != c.want { + t.Errorf("needsSignIn(%q, %v, %q) = %v", c.agent, c.plugin, c.lapsed, got) + } + } +} + +// The marks: one alert per account and kind, cleared when the account is +// usable again; an account not listed keeps its marks a while, so a plugin +// not started yet isn't told of again when it is. +func TestDueSignIns(t *testing.T) { + now := time.Now() + marks := map[string]alertMark{} + gone := []signInState{{Provider: "cursor", Name: "Cursor", User: "U@x", Gone: true}, {Provider: "codex", Name: "Codex", User: "b"}} + if got := dueSignIns(gone, marks, now); len(got) != 1 || got[0].Provider != "cursor" { + t.Fatalf("first look: %+v", got) + } + if got := dueSignIns(nil, marks, now.Add(time.Hour)); len(got) != 0 || len(marks) != 1 { + t.Fatalf("not listed: %+v, marks %v", got, marks) + } + if got := dueSignIns(gone, marks, now.Add(2*time.Hour)); len(got) != 0 { + t.Fatalf("told again after a look it wasn't listed in: %+v", got) + } + if dueSignIns(nil, marks, now.Add(alertKeep+3*time.Hour)); len(marks) != 0 { + t.Fatalf("a mark kept past alertKeep: %v", marks) + } +}