From 3b643f3978b209dfba3022fb74ef656962fea5d6 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 16 Nov 2026 10:09:43 +0800 Subject: [PATCH] provider: a Claude sign-in read mid-write on Windows is no sign-out xbpb6 on X (0.1.4281, Windows 11, TUI mode): the account Claude Code is signed in to said "Sign-in required" with "can't read the allowance"; signing in again fixed it for a while, then it came back. Claude Code on Windows writes .credentials.json and .claude.json through a temp file and a rename. Go's os.ReadFile opens without FILE_SHARE_DELETE, so while magpie reads the file the rename gets EPERM. Claude Code then truncates the file and writes it in place (xO in its writer). A read in between finds the file empty or cut short. - rememberLogins took that read as a sign-out. claudeLoggedOut marked the Held account lapsed with claudeLogoutLapse, which breaks the rule that a failed read means unknown. - The account then read as not in use. Then claudeSavedDir, which has no Held check, could copy Claude Code's own sign-in into claude-accounts/ for a warm-up, a usage read or a request. Two Claude Codes then held one rotating refresh token, so whichever refreshed second signed the other out for good. That is why the account comes back as signed out again and again. Now: - claudeSignInUnsure reads the files again. The account counts as signed out only if the file is gone, Claude Code emptied it, `claude auth status` says logged out, or no account is named. A file that can't be read or isn't whole JSON is unknown for up to claudeUnsureGrace (2 minutes). - Meanwhile, rememberLogins doesn't lapse the Held account, and Logins and renewLogins keep it active. - claudeSavedDir refuses a Held account with errClaudeHeld, whose text is not one ClaudeSignInRequired matches. - The Mac keychain path is unchanged. Run: - TestClaudeHalfWrittenSignInIsNoLogout was red on the old code on mote, in two ways (logs kept). An empty credentials file gave Active:false with claudeLogoutLapse, the screenshot's state. claudeSavedDir put the Held account in .config/magpie/claude-accounts/7f327d2462d8fb58 with no error. Green after. - mote: go test ./internal/provider ./internal/gateway -count=1 -timeout 45m: ok, 142s and 913s. - win-run (xiaomi-gpu, Windows 11): TestClaudeHalfWrittenSignInIsNoLogout, TestClaudeAccountsOutliveLogout and TestClaudeSwitchIsNoLogout pass. - gofmt -l is clean. GOOS=windows and GOOS=linux go vet ./internal/provider pass. Not tried: - No real Claude account on Windows. The EPERM rewrite was read from Claude Code 2.1.316's source, not watched. - No full ./... suite. - A Claude Code killed mid-refresh on Windows is not covered. --- docs/subsystems/providers-accounts.md | 2 +- internal/provider/claude_dirs.go | 94 ++++++++++++++++++ internal/provider/claude_half_written_test.go | 99 +++++++++++++++++++ internal/provider/keepalive.go | 4 + internal/provider/logins.go | 10 +- 5 files changed, 207 insertions(+), 2 deletions(-) create mode 100644 internal/provider/claude_half_written_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 2480b7ae2..7ec8c0a50 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -55,7 +55,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:"` 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. The magpie serving the gateway tells the same alerts to request hooks' `onSignIn`, with marks of their own in `signin-hooks.json` ([gateway-request-hooks](gateway-request-hooks.md#sign-in-notification)). Guarded by `TestSignInAlertClaudeSignedOut`, `TestSignInAlertClaudeEnding`, `TestDueSignIns`, `TestSignInAlertOpensItsProvider` and `TestRevokedAccountToldToHooksOnce`. | [`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) | +| 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. A `Held` account never gets a config directory of magpie's either (`claudeSavedDir` refuses it, `errClaudeHeld`): a second Claude Code there would spend the refresh token Claude Code holds and sign it out. A sign-in that can't be read whole is no sign-out: Claude Code on Windows rewrites `.credentials.json` and `.claude.json` in place while magpie has the file open (its rename gets EPERM), so a read can find either empty or cut short. Until such a read has lasted `claudeUnsureGrace` (2 minutes), the `Held` account stays active and is not marked lapsed (`claudeSignInUnsure` in `rememberLogins`, `Logins` and `renewLogins`); it is marked lapsed only when the file is gone, Claude Code emptied it, `claude auth status` says it is logged out, or no account is named (xbpb6 on X: the account said Sign-in required over and over on Windows; `TestClaudeHalfWrittenSignInIsNoLogout`). The Mac's keychain item is read whole or not at all, and there nothing changes. 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, with a Settings › link to the row, 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) | | 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. Claude also reads claude-swap's `cswap export` (format 1, claude-swap 0.29; `cswapEntry`, #4532): each account's `credentials.claudeAiOauth` and `config.oauthAccount`, with its organization name, and its alias becomes the account's name when that account has none and no other account is called or signed in as it (`importNames`). An encrypted export, another format, a Codex entry and an API-key entry are refused with what to do; `testdata/cswap_0.29.0_export.json` is claude-swap's own output. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). A Claude sign-in for an account magpie has, Claude Code's own or a saved one that can be used, with another refresh token is taken only when the file's `expiresAt` is later than the one magpie has (the account's own config directory counted, `claudeNewerKept`); otherwise it is `exists` with why, and nothing is written: an export made before Claude Code's last refresh holds a spent refresh token, and written over Claude Code's own it signed the account out (#4532, `TestImportCswapKeepsNewerSignIn`). A file that gives no `expiresAt` never replaces one. A sign-in itself imported and never run since is kept with `expiresAt` 1, so any dated file is taken over it. 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) | | Antigravity to agy | The withdrawn Antigravity plugin (`antigravity`) signed in with Antigravity's own Google OAuth client, the one `agy` signs in with, so its accounts move to Antigravity (local agy CLI) as they are (@tongzhenbao on X). `AgyMoveUsers` names the plugin's sign-ins (then the built-in's never moved) whose email agy-cli doesn't have, as `agyMove` in `/api/providers`; the line over the list (`agymove.js`, imported only when there are any) has Move and Not now. `MoveToAgy` (`provider/toagy`) installs agy-cli at `agyCLIMin` (0.1.68, whose `auth.import` takes them; from the plugins repo's dist branch while npm has none), agy when it is missing, and hands every sign-in to its import, which writes each into an agy home of its own and keeps it only once `agy models` runs with it; one agy refuses is said by name (`agyMoved`). The token goes only where it went (Google, through agy), and the old sign-ins are left where they are. `TestAgyMoveUsersAreTheOldPluginsNotInAgyCLI`, `TestMoveToAgyImportsTheOldSignIns`, `TestToAgyMovesAndSaysEachAccount`, `agy-move.test.cjs`. | [`agy_move.go`](../../internal/provider/agy_move.go), [`providers.go`](../../internal/gui/providers.go), [`agymove.js`](../../internal/gui/assets/agymove.js) | diff --git a/internal/provider/claude_dirs.go b/internal/provider/claude_dirs.go index 07da57b75..01ed54cfa 100644 --- a/internal/provider/claude_dirs.go +++ b/internal/provider/claude_dirs.go @@ -261,6 +261,12 @@ func claudeSavedDir(user string) (string, error) { if i < 0 { return "", fmt.Errorf("no saved claude account %q", user) } + if ls[i].Held { + // Claude Code's own, though a read just now found it signed in to + // none (claudeSignInUnsure): put here too, a second Claude Code + // would refresh the refresh token it holds and sign it out + return "", fmt.Errorf(errClaudeHeld, user) + } if claudeSetupToken(ls[i].Auth) != "" { // no sign-in to put there: the token goes in Claude Code's // environment (ClaudeDirToken) @@ -543,6 +549,94 @@ const legacyClaudeLogoutLapse = "Claude Code's /logout signed it out (it revokes // be used. const claudeGoneLapse = "its sign-in is gone; sign in again" +// errClaudeHeld is why the account Claude Code itself is signed in to gets +// no config directory of magpie's. +const errClaudeHeld = "Claude Code itself is signed in to %s; magpie runs it there, not in a folder of its own" + +// claudeUnsureGrace is how long a sign-in of Claude Code's that can't be +// read is taken for one being written. Claude Code on Windows rewrites +// .credentials.json and .claude.json in place while magpie has the file +// open (its rename over it gets EPERM), and a read between the truncate +// and the write finds it empty or cut short. A write takes milliseconds; +// one unreadable for longer is gone. +var claudeUnsureGrace = 2 * time.Minute + +var claudeUnsure struct { + sync.Mutex + since time.Time +} + +// claudeSignInUnsure says, once liveLogin found Claude Code signed in to +// no account, that this isn't known: what it keeps its sign-in in can't be +// read whole now (claudeSignInUnread), and has been so for less than +// claudeUnsureGrace. The account it held stays its own meanwhile, neither +// lapsed (claudeLoggedOut) nor run elsewhere (claudeSavedDir). A sign-in in +// the Mac's keychain is read whole or not at all, and is left as it was. +func claudeSignInUnsure() bool { + if settings.AccountDiscoveryOff() || claudeKeychain { + return false + } + unread := claudeSignInUnread() + claudeUnsure.Lock() + defer claudeUnsure.Unlock() + if !unread { + claudeUnsure.since = time.Time{} + return false + } + now := time.Now() + if claudeUnsure.since.IsZero() { + claudeUnsure.since = now + } + return now.Sub(claudeUnsure.since) < claudeUnsureGrace +} + +// claudeSignInUnread says Claude Code's sign-in isn't known to be gone: +// gone is no credentials file, one Claude Code emptied, `claude auth +// status` saying it is logged out, or no account named for it. A file +// that can't be read or isn't whole JSON is one being written, and so is +// a sign-in read whole now, which a read a moment ago (claudeCredential's) +// didn't find. +func claudeSignInUnread() bool { + b, err := readAccountFile(claudeCredentialsPath()) + if err != nil { + return !os.IsNotExist(err) + } + c, ok := parseClaudeCredentials(b) + if c.raw == nil { + return true + } + if !ok { + return false + } + user, _, signedOut := claudeIdentity() + if signedOut { + return false + } + b, err = os.ReadFile(claudeProfilePath()) + if err != nil { + return !os.IsNotExist(err) || user != "" + } + var m struct { + OAuthAccount map[string]any `json:"oauthAccount"` + } + if json.Unmarshal(b, &m) != nil { + return true + } + email, _ := m.OAuthAccount["emailAddress"].(string) + return strings.TrimSpace(email) != "" || user != "" +} + +// claudeHeldUser is the account Claude Code was signed in to when last +// looked at, "" for none. +func claudeHeldUser(ls []savedLogin) string { + for _, l := range ls { + if l.Agent == "claude" && l.Held { + return l.User + } + } + return "" +} + // claudeLoggedOut marks the account Claude Code held, now that it holds no // sign-in, as lapsed: magpie's copy of that account is the same sign-in, // gone too — revoked by a /logout (POST /revoke, Claude Code diff --git a/internal/provider/claude_half_written_test.go b/internal/provider/claude_half_written_test.go new file mode 100644 index 000000000..c6f290653 --- /dev/null +++ b/internal/provider/claude_half_written_test.go @@ -0,0 +1,99 @@ +package provider + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// Claude Code on Windows rewrites ~/.claude/.credentials.json and +// ~/.claude.json in place when magpie has the file open (its rename gets +// EPERM, and it truncates and writes the file instead), so a read can find +// it empty or cut short. That is no sign-out: the account Claude Code holds +// stays its own and in use, never marked "Sign-in required", and its +// sign-in is never put in a config directory of magpie's, where a second +// Claude Code would refresh the same refresh token and sign the first out +// (xbpb6 on X: signed out again and again on Windows). One unreadable for +// longer than a write takes is gone after all. +func TestClaudeHalfWrittenSignInIsNoLogout(t *testing.T) { + home := claudeHome(t) + t.Setenv("CLAUDE_CONFIG_DIR", "") + noAnthropic(t) + cred := claudeSignIn(t, home, time.Now().Add(time.Hour)) + profile := filepath.Join(home, ".claude.json") + writeFile(t, profile, map[string]any{"oauthAccount": map[string]any{"emailAddress": "own@example.com"}}) + good, err := os.ReadFile(cred) + if err != nil { + t.Fatal(err) + } + goodProfile, err := os.ReadFile(profile) + if err != nil { + t.Fatal(err) + } + ForgetAccounts() + own := func(when string) Login { + t.Helper() + ForgetAccounts() + forgetClaudeCredential() + for _, l := range Logins("claude") { + if l.User == "own@example.com" { + return l + } + } + t.Fatalf("%s: no own account in %+v", when, Logins("claude")) + return Login{} + } + if l := own("signed in"); !l.Active || l.Lapsed != "" { + t.Fatalf("signed in: %+v", l) + } + // whatever reads the account as not in use for a moment (warm-up, a + // card's reading, a request served beside it) is given no folder of + // its own for it while Claude Code holds it + if dir, err := claudeSavedDir("own@example.com"); err == nil || ClaudeSignInRequired(err.Error()) { + t.Fatalf("Claude Code's own sign-in put in %q: %v", dir, err) + } + if _, err := os.Stat(claudeAccountDir("own@example.com")); !os.IsNotExist(err) { + t.Fatalf("a second holder of Claude Code's refresh token: %v", err) + } + + for _, c := range []struct { + name string + path string + half, restore []byte + }{ + {"credentials empty", cred, nil, good}, + {"credentials cut short", cred, good[:len(good)/2], good}, + {"profile cut short", profile, goodProfile[:len(goodProfile)/2], goodProfile}, + } { + if err := os.WriteFile(c.path, c.half, 0o600); err != nil { + t.Fatal(err) + } + if l := own(c.name); !l.Active || l.Lapsed != "" { + t.Fatalf("%s: taken for a sign-out: %+v", c.name, l) + } + if dir, err := claudeSavedDir("own@example.com"); err == nil { + t.Fatalf("%s: Claude Code's own sign-in put in %s", c.name, dir) + } + if _, err := os.Stat(claudeAccountDir("own@example.com")); !os.IsNotExist(err) { + t.Fatalf("%s: a second holder of Claude Code's refresh token: %v", c.name, err) + } + if err := os.WriteFile(c.path, c.restore, 0o600); err != nil { + t.Fatal(err) + } + if l := own(c.name + ", written"); !l.Active || l.Lapsed != "" { + t.Fatalf("%s, written: %+v", c.name, l) + } + } + + // unreadable past what a write takes: gone after all + old := claudeUnsureGrace + claudeUnsureGrace = 0 + t.Cleanup(func() { claudeUnsureGrace = old }) + if err := os.WriteFile(cred, nil, 0o600); err != nil { + t.Fatal(err) + } + if l := own("left empty"); l.Active || l.Lapsed != claudeLogoutLapse { + t.Fatalf("left empty: %+v", l) + } +} diff --git a/internal/provider/keepalive.go b/internal/provider/keepalive.go index 6ac2f522d..9ec25ae98 100644 --- a/internal/provider/keepalive.go +++ b/internal/provider/keepalive.go @@ -124,6 +124,10 @@ func renewLogins(ctx context.Context, every time.Duration, atOnce int) []Renewal } ls := readLogins() loginsMu.Unlock() + if _, ok := active["claude"]; !ok && claudeSignInUnsure() { + // Claude Code's own still, its sign-in read mid-write + active["claude"] = claudeHeldUser(ls) + } out := []Renewal{} tried := 0 for _, l := range ls { diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 233e199ae..ff5a0d2f8 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -1051,7 +1051,9 @@ func rememberLogins(force bool) { } } if !ok { - if agent == "claude" && claudeLoggedOut(ls) { + // half-written as Claude Code rewrites it on Windows: unknown, + // not a sign-out (claudeSignInUnsure) + if agent == "claude" && !claudeSignInUnsure() && claudeLoggedOut(ls) { changed = true } continue @@ -1231,6 +1233,12 @@ func loginsNow(agent string) []Login { } var out []Login ls := readLogins() + if _, ok := active["claude"]; !ok && claudeSignInUnsure() { + // read as Claude Code writes it: the account it held is still its own + if u := claudeHeldUser(ls); u != "" { + active["claude"] = u + } + } standIn := "" if _, ok := active["claude"]; !ok { // the one the provider is listed on (claudeStandInAccount), a