From ed842abce2af43e722310b11e72e1520b8c255e0 Mon Sep 17 00:00:00 2001 From: konayre Date: Tue, 22 Sep 2026 13:52:34 +0400 Subject: [PATCH 1/4] fix(claude-accounts): keep the managed Claude token alive while Claude panes stay open The Claude usage meter died ~8h after authentication and never came back while any Claude pane was open (#20251, #21935). Two independent defects: - The live-PTY gate skipped the active account's refresh whenever any Claude PTY was live, and only reopened on the 1 -> 0 edge. When the live CLIs run on another CLAUDE_CONFIG_DIR, read-back never sees their rotation, so the deferral was permanent. Stop deferring once the managed token has been expired for longer than a 10-minute grace window: a CLI sharing Orca's store refreshes before expiry and read-back adopts that, so a token still dead that long has no live CLI rotating it. If that refresh fails while PTYs are live and the runtime already holds the same blob, skip the rewrite so a rotation a live Claude saved during the request is not clobbered. - The refresh POST went out with net.fetch's default Chromium User-Agent, and platform.claude.com answers 429 to that (and to curl's) regardless of body, so Orca's own refresh never succeeded. Send 'orca-desktop'. Now that refresh actually succeeds, persist an inactive account's rotated token before honouring an abort: the server has already consumed the old single-use refresh token by then. --- .../claude-accounts/oauth-refresh.test.ts | 41 +++++++ src/main/claude-accounts/oauth-refresh.ts | 27 ++++- ...untime-auth-service-launch-refresh.test.ts | 111 +++++++++++++++++- .../runtime-auth-service-test-harness.ts | 1 + .../runtime-auth-managed-credentials.ts | 4 +- .../runtime-auth/runtime-auth-sync.ts | 13 +- ...aude-fetcher-managed-account-usage.test.ts | 44 +++++++ .../claude-managed-account-usage.ts | 7 +- 8 files changed, 235 insertions(+), 13 deletions(-) diff --git a/src/main/claude-accounts/oauth-refresh.test.ts b/src/main/claude-accounts/oauth-refresh.test.ts index dd5e01c245a5..05c43d0f54fb 100644 --- a/src/main/claude-accounts/oauth-refresh.test.ts +++ b/src/main/claude-accounts/oauth-refresh.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { applyRefreshedToken, + isOauthTokenExpiredPastGrace, isOauthTokenExpiring, parseClaudeOauthBlob, readRefreshToken, @@ -80,6 +81,33 @@ describe('isOauthTokenExpiring', () => { }) }) +describe('isOauthTokenExpiredPastGrace', () => { + it('is false while the token is valid or only inside the refresh buffer', () => { + expect(isOauthTokenExpiredPastGrace(credentials(), NOW)).toBe(false) + expect(isOauthTokenExpiredPastGrace(credentials({ expiresAt: NOW + 60 * 1000 }), NOW)).toBe( + false + ) + }) + + it('is false just after expiry, while a live Claude could still be rotating it', () => { + expect(isOauthTokenExpiredPastGrace(credentials({ expiresAt: NOW - 60 * 1000 }), NOW)).toBe( + false + ) + }) + + it('is true once the token has been expired for longer than the grace window', () => { + expect( + isOauthTokenExpiredPastGrace(credentials({ expiresAt: NOW - 60 * 60 * 1000 }), NOW) + ).toBe(true) + }) + + it('is false without numeric expiry metadata, since nothing proves the token is dead', () => { + expect(isOauthTokenExpiredPastGrace(credentials({ expiresAt: undefined }), NOW)).toBe(false) + expect(isOauthTokenExpiredPastGrace(credentials({ expiresAt: 'soon' }), NOW)).toBe(false) + expect(isOauthTokenExpiredPastGrace('{}', NOW)).toBe(false) + }) +}) + describe('applyRefreshedToken', () => { it('rotates access + refresh token and recomputes expiry', () => { const updated = applyRefreshedToken( @@ -171,6 +199,19 @@ describe('refreshClaudeOauthCredentials', () => { expect(oauth.refreshToken).toBe('fresh-refresh') }) + it('identifies itself with a non-browser User-Agent', async () => { + // Why: the token endpoint answers 429 to the Chromium User-Agent net.fetch sends by default. + netFetchMock.mockResolvedValue({ + ok: true, + json: async () => ({ access_token: 'fresh-access', expires_in: 3600 }) + }) + + await refreshClaudeOauthCredentials(credentials(), NOW) + + const [, init] = netFetchMock.mock.calls[0] + expect(init.headers['User-Agent']).toBe('orca-desktop') + }) + it('returns null on a non-ok response and logs the status for diagnosability', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) netFetchMock.mockResolvedValue({ ok: false, status: 429, json: async () => ({}) }) diff --git a/src/main/claude-accounts/oauth-refresh.ts b/src/main/claude-accounts/oauth-refresh.ts index cc717ef51ee8..bbebc0cbda9e 100644 --- a/src/main/claude-accounts/oauth-refresh.ts +++ b/src/main/claude-accounts/oauth-refresh.ts @@ -8,10 +8,16 @@ import { ensureElectronProxyFromEnvironment } from '../network/proxy-settings' // after the CLI rotates it (the lossy path that strands stale tokens). const OAUTH_TOKEN_URL = 'https://platform.claude.com/v1/oauth/token' const OAUTH_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e' +// Why: the token endpoint answers 429 to net.fetch's default Chromium User-Agent +// (and to curl's) whatever the body, so a refresh without one never succeeds. +const OAUTH_REFRESH_USER_AGENT = 'orca-desktop' // Refresh slightly ahead of expiry so a token doesn't expire mid-launch. The // CLI uses the same 5-minute skew for its own refresh decision. const OAUTH_EXPIRY_BUFFER_MS = 5 * 60 * 1000 +// A CLI using the token refreshes it ahead of expiry, so a token still expired +// this long after expiresAt has no live CLI rotating it. +const OAUTH_LIVE_ROTATION_GRACE_MS = 10 * 60 * 1000 const REFRESH_TIMEOUT_MS = 10_000 type ClaudeOauthBlob = { @@ -74,6 +80,22 @@ export function isOauthTokenExpiring(credentialsJson: string, now: number = Date return now + OAUTH_EXPIRY_BUFFER_MS >= expiresAt } +/** + * Whether the stored access token expired longer ago than a live Claude CLI + * would have left it unrotated. Unlike isOauthTokenExpiring, missing expiry + * metadata is false: only a known-dead token may override the live-PTY gate. + */ +export function isOauthTokenExpiredPastGrace( + credentialsJson: string, + now: number = Date.now() +): boolean { + const expiresAt = parseClaudeOauthBlob(credentialsJson)?.expiresAt + if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) { + return false + } + return now >= expiresAt + OAUTH_LIVE_ROTATION_GRACE_MS +} + /** * Merge a token-endpoint response into the stored credentials, returning the * updated credentials JSON. Preserves every field the caller already had @@ -141,7 +163,10 @@ export async function refreshClaudeOauthCredentials( // routes through Chromium's stack so the env proxy bridge above applies. const res = await net.fetch(OAUTH_TOKEN_URL, { method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': OAUTH_REFRESH_USER_AGENT + }, body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, diff --git a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts index 85d68d30e8b8..9e45a99d291f 100644 --- a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts +++ b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts @@ -15,7 +15,11 @@ import { import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { isOauthTokenExpiring, refreshClaudeOauthCredentials } from './oauth-refresh' +import { + isOauthTokenExpiredPastGrace, + isOauthTokenExpiring, + refreshClaudeOauthCredentials +} from './oauth-refresh' vi.mock('electron', () => createElectronMock()) @@ -173,9 +177,9 @@ describe('ClaudeRuntimeAuthService', () => { vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null) }) - it('does not refresh the active account while a Claude PTY is live', async () => { - const expired = createClaudeCredentialsJson('one@example.com', 'one-expired', null, 1_000) - const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired) + it('does not refresh the active account while a Claude PTY is live and the token is only expiring', async () => { + const expiring = createClaudeCredentialsJson('one@example.com', 'one-expiring') + const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expiring) const settings = createSettings({ claudeManagedAccounts: [ createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' }) @@ -207,6 +211,105 @@ describe('ClaudeRuntimeAuthService', () => { } }) + it('refreshes the active account despite a live Claude PTY once the token is expired past the grace window', async () => { + const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json') + const expired = createClaudeCredentialsJson( + 'one@example.com', + 'one-expired', + null, + Date.now() - 60 * 60 * 1000 + ) + const refreshedCreds = createClaudeCredentialsJson( + 'one@example.com', + 'one-refreshed', + null, + Date.now() + 8 * 60 * 60 * 1000 + ) + const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired) + const settings = createSettings({ + claudeManagedAccounts: [ + createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' }) + ], + activeClaudeManagedAccountId: 'account-1' + }) + const store = createStore(settings) + + vi.mocked(isOauthTokenExpiring).mockReturnValue(true) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true) + vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(refreshedCreds) + + const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate') + const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service') + const service = new ClaudeRuntimeAuthService(store as never) + + // The live Claude runs on another config dir (nothing lands in ~/.claude), so read-back + // never sees a rotation — the setup where the deferral used to last forever (#20251). + markClaudePtySpawned('pty-live-1') + try { + const preparation = await service.prepareForRateLimitFetch() + expect(refreshClaudeOauthCredentials).toHaveBeenCalled() + expect(preparation.managedRefreshDeferredByLivePty).toBe(false) + expect(readManagedCredentialsForTest('account-1', managedAuthPath1)).toBe(refreshedCreds) + expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(refreshedCreds) + } finally { + markClaudePtyExited('pty-live-1') + vi.mocked(isOauthTokenExpiring).mockReturnValue(false) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false) + vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null) + } + }) + + it('keeps a live Claude rotation that lands while a past-grace refresh fails', async () => { + const expired = createClaudeCredentialsJson( + 'one@example.com', + 'one-expired', + null, + Date.now() - 60 * 60 * 1000 + ) + const cliRotated = createClaudeCredentialsJson( + 'one@example.com', + 'cli-rotated', + null, + Date.now() + 8 * 60 * 60 * 1000 + ) + const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired) + const settings = createSettings({ + claudeManagedAccounts: [ + createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' }) + ], + activeClaudeManagedAccountId: 'account-1' + }) + const store = createStore(settings) + + vi.mocked(isOauthTokenExpiring).mockReturnValue(true) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true) + + const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate') + const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service') + + markClaudePtySpawned('pty-live-1') + try { + const service = new ClaudeRuntimeAuthService(store as never) + await service.syncForCurrentSelection() + expect(testState.legacyKeychainCredentials).toBe(expired) + + // A Claude on Orca's store wins the single-use refresh while Orca's request is in + // flight, so Orca's request fails; rewriting the stale blob would strand both copies. + vi.mocked(refreshClaudeOauthCredentials).mockImplementationOnce(async () => { + testState.legacyKeychainCredentials = cliRotated + return null + }) + await service.syncForCurrentSelection() + + expect(testState.legacyKeychainCredentials).toBe(cliRotated) + } finally { + markClaudePtyExited('pty-live-1') + vi.mocked(isOauthTokenExpiring).mockReturnValue(false) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false) + vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null) + } + }) + it('adopts a rotated-refresh-token runtime credential on cold-start read-back', async () => { const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json') // Same expiry on both sides (cold start), but the runtime refresh token has diff --git a/src/main/claude-accounts/runtime-auth-service-test-harness.ts b/src/main/claude-accounts/runtime-auth-service-test-harness.ts index 874e7534ff1a..fa22c721b8df 100644 --- a/src/main/claude-accounts/runtime-auth-service-test-harness.ts +++ b/src/main/claude-accounts/runtime-auth-service-test-harness.ts @@ -42,6 +42,7 @@ export function createElectronMock() { export function createOauthRefreshMock() { return { isOauthTokenExpiring: vi.fn(() => false), + isOauthTokenExpiredPastGrace: vi.fn(() => false), refreshClaudeOauthCredentials: vi.fn(async () => null) } } diff --git a/src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts b/src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts index ad68d59eadb7..a95d491182e1 100644 --- a/src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts +++ b/src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts @@ -53,8 +53,8 @@ export class ClaudeRuntimeAuthManagedCredentials extends ClaudeRuntimeAuthCreden * managed storage. Returns the refreshed credentials JSON, or null when no * refresh happened (token valid, no refresh token, or network failure). * - * Caller guarantees this account isn't the live/active one and runs inside the - * serialized mutation queue, so the single-use refresh token can't rotate concurrently. + * Caller runs inside the serialized mutation queue, so Orca can't rotate the + * single-use refresh token concurrently; runtime-auth-sync.ts owns the live-PTY gate. */ protected async refreshManagedAccountTokenIfNeeded( account: ClaudeManagedAccount, diff --git a/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts b/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts index f191689a4466..4846b49911ab 100644 --- a/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts +++ b/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts @@ -7,7 +7,7 @@ import { type ClaudeAccountSelectionTarget } from '../runtime-selection' import { hasLiveClaudePtys } from '../live-pty-gate' -import { isOauthTokenExpiring } from '../oauth-refresh' +import { isOauthTokenExpiredPastGrace, isOauthTokenExpiring } from '../oauth-refresh' import { writeActiveClaudeKeychainCredentialsForRuntime } from '../keychain' import { ClaudeRuntimeAuthPreparationService } from './runtime-auth-preparation' @@ -242,17 +242,24 @@ export class ClaudeRuntimeAuthSync extends ClaudeRuntimeAuthPreparationService { } // Why: rotate+persist the single-use token to managed storage before materializing (else runtime gets a stale token that fails invalid_grant); skip while a live PTY owns the creds since refreshing would double-rotate it (invalidating one copy) — read-back preserves its refresh instead. + // Why: stop deferring once the token is dead past the grace window — a live Claude using this store would have rotated it by now (read-back adopts that), so it runs on another config dir and the wait never ends. const liveClaudePtys = hasLiveClaudePtys() - if (liveClaudePtys && isOauthTokenExpiring(credentialsJson)) { + const deferToLiveClaude = liveClaudePtys && !isOauthTokenExpiredPastGrace(credentialsJson) + if (deferToLiveClaude && isOauthTokenExpiring(credentialsJson)) { this.managedRefreshDeferredByLivePtyAccountId = activeAccount.id } - if (!liveClaudePtys) { + if (!deferToLiveClaude) { const refreshed = await this.refreshManagedAccountTokenIfNeeded( activeAccount, credentialsJson ) if (refreshed) { credentialsJson = refreshed + } else if (liveClaudePtys && credentialsJson === this.lastWrittenCredentialsJson) { + // Why: runtime already holds this blob; rewriting it would clobber a rotation a live Claude saved while our refresh was in flight. + this.lastSyncedAccountId = activeAccount.id + this.hasMaterializedRuntimeAuth = true + return } } diff --git a/src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts b/src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts index c01bcb00f6eb..3042811317f5 100644 --- a/src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts +++ b/src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts @@ -422,4 +422,48 @@ describe('fetchClaudeRateLimits', () => { ) expect(usageCall?.[1]?.headers?.Authorization).toBe('Bearer fresh-access') }) + + it('persists a rotated inactive account token even when the fetch is aborted mid-refresh', async () => { + setPlatform('linux') + tempDir = mkdtempSync(join(tmpdir(), 'orca-claude-fetcher-')) + appGetPathMock.mockReturnValue(tempDir) + const ownedAuthPath = join(tempDir, 'claude-accounts', 'account-1', 'auth') + mkdirSync(ownedAuthPath, { recursive: true }) + writeFileSync(join(ownedAuthPath, '.orca-managed-claude-auth'), 'account-1\n', 'utf-8') + const credentialsPath = join(ownedAuthPath, '.credentials.json') + writeFileSync( + credentialsPath, + JSON.stringify({ + claudeAiOauth: { + accessToken: 'stale-access', + refreshToken: 'stale-refresh', + expiresAt: Date.now() - 60_000 + } + }), + 'utf-8' + ) + const controller = new AbortController() + // The server has already consumed the single-use refresh token by the time the + // abort (e.g. app quit) lands, so dropping the rotation would strand the account. + netFetchMock.mockImplementationOnce(async () => { + controller.abort() + return { + ok: true, + json: async () => ({ + access_token: 'fresh-access', + expires_in: 3600, + refresh_token: 'fresh-refresh' + }) + } + }) + + const result = await fetchManagedAccountUsage( + { id: 'account-1', managedAuthPath: ownedAuthPath }, + { signal: controller.signal } + ) + + expect(result.status).not.toBe('ok') + const persisted = JSON.parse(readFileSync(credentialsPath, 'utf-8')) + expect(persisted.claudeAiOauth.refreshToken).toBe('fresh-refresh') + }) }) diff --git a/src/main/rate-limits/claude-managed-account-usage.ts b/src/main/rate-limits/claude-managed-account-usage.ts index ddf7b3df7508..80b9992e0073 100644 --- a/src/main/rate-limits/claude-managed-account-usage.ts +++ b/src/main/rate-limits/claude-managed-account-usage.ts @@ -50,10 +50,8 @@ export async function fetchInactiveClaudeAccountUsage( let token = parseClaudeOAuthCredentialsJson(credentialsJson, 'credentials-file').token if (isOauthTokenExpiring(credentialsJson)) { const refreshed = await refreshClaudeOauthCredentials(credentialsJson) - if (options.signal?.aborted) { - return abortedClaudeRateLimitResult() - } if (refreshed) { + // Why: the server consumed the single-use refresh token already, so persist before honoring an abort. try { await writeClaudeManagedCredentialsJson(location, refreshed) } catch { @@ -62,6 +60,9 @@ export async function fetchInactiveClaudeAccountUsage( credentialsJson = refreshed token = parseClaudeOAuthCredentialsJson(refreshed, 'credentials-file').token } + if (options.signal?.aborted) { + return abortedClaudeRateLimitResult() + } } if (!token) { From 3052f9b720dfe508d77ec8aa95a69c74061a7e7c Mon Sep 17 00:00:00 2001 From: konayre Date: Wed, 23 Sep 2026 23:41:56 +0400 Subject: [PATCH 2/4] fix(claude-accounts): don't overwrite a live Claude rotation after a failed past-grace refresh The guard against rewriting the stale blob keyed off lastWrittenCredentialsJson, which is still null on the first sync after launch, so a rotation a daemon-surviving Claude saved while Orca's refresh was in flight could be overwritten there (CodeRabbit on #22510). After a failed past-grace refresh with live PTYs, re-run read-back instead: adopt a verified rotation, leave a valid unverifiable change alone, and in steady state skip the rewrite even when read-back can't see the rotation yet. Only a wiped runtime, or a first sync with nothing to compare against, falls through to materialize. --- ...untime-auth-service-launch-refresh.test.ts | 105 ++++++++++++++++++ .../runtime-auth/runtime-auth-sync.ts | 20 +++- 2 files changed, 120 insertions(+), 5 deletions(-) diff --git a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts index 9e45a99d291f..729be6c2b35c 100644 --- a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts +++ b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts @@ -302,6 +302,111 @@ describe('ClaudeRuntimeAuthService', () => { await service.syncForCurrentSelection() expect(testState.legacyKeychainCredentials).toBe(cliRotated) + expect(readManagedCredentialsForTest('account-1', managedAuthPath1)).toBe(cliRotated) + } finally { + markClaudePtyExited('pty-live-1') + vi.mocked(isOauthTokenExpiring).mockReturnValue(false) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false) + vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null) + } + }) + + it('does not rewrite the runtime after a failed past-grace refresh when read-back cannot see a rotation yet', async () => { + const expired = createClaudeCredentialsJson( + 'one@example.com', + 'one-expired', + null, + Date.now() - 60 * 60 * 1000 + ) + const cliRotated = createClaudeCredentialsJson( + 'one@example.com', + 'cli-rotated', + null, + Date.now() + 8 * 60 * 60 * 1000 + ) + const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired) + const settings = createSettings({ + claudeManagedAccounts: [ + createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' }) + ], + activeClaudeManagedAccountId: 'account-1' + }) + const store = createStore(settings) + + vi.mocked(isOauthTokenExpiring).mockReturnValue(true) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true) + + const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate') + const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service') + + markClaudePtySpawned('pty-live-1') + try { + const service = new ClaudeRuntimeAuthService(store as never) + await service.syncForCurrentSelection() + + // The Claude's keychain write is still in flight (reads fail) when Orca re-reads + // after its own refresh fails, so read-back reports 'unchanged'. + vi.mocked(refreshClaudeOauthCredentials).mockImplementationOnce(async () => { + testState.legacyKeychainCredentials = cliRotated + testState.throwLegacyKeychainRead = true + testState.throwScopedKeychainRead = true + return null + }) + await service.syncForCurrentSelection() + + expect(testState.legacyKeychainCredentials).toBe(cliRotated) + } finally { + markClaudePtyExited('pty-live-1') + vi.mocked(isOauthTokenExpiring).mockReturnValue(false) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false) + vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null) + } + }) + + it('keeps a live Claude rotation that lands during the first sync after launch', async () => { + const expired = createClaudeCredentialsJson( + 'one@example.com', + 'one-expired', + null, + Date.now() - 60 * 60 * 1000 + ) + const cliRotated = createClaudeCredentialsJson( + 'one@example.com', + 'cli-rotated', + null, + Date.now() + 8 * 60 * 60 * 1000 + ) + const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired) + const settings = createSettings({ + claudeManagedAccounts: [ + createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' }) + ], + activeClaudeManagedAccountId: 'account-1' + }) + const store = createStore(settings) + // The previous run materialized this account, and its Claude pane outlived the restart + // in the daemon. Nothing has been written this run, so lastWrittenCredentialsJson is null. + writeFileSync(join(testState.fakeHomeDir, '.claude', '.credentials.json'), expired, 'utf-8') + testState.scopedKeychainCredentials = expired + testState.legacyKeychainCredentials = expired + + vi.mocked(isOauthTokenExpiring).mockReturnValue(true) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true) + vi.mocked(refreshClaudeOauthCredentials).mockImplementationOnce(async () => { + testState.legacyKeychainCredentials = cliRotated + return null + }) + + const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate') + const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service') + + markClaudePtySpawned('pty-live-1') + try { + const service = new ClaudeRuntimeAuthService(store as never) + await service.syncForCurrentSelection() + + expect(testState.legacyKeychainCredentials).toBe(cliRotated) + expect(readManagedCredentialsForTest('account-1', managedAuthPath1)).toBe(cliRotated) } finally { markClaudePtyExited('pty-live-1') vi.mocked(isOauthTokenExpiring).mockReturnValue(false) diff --git a/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts b/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts index 4846b49911ab..456a4c0648bf 100644 --- a/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts +++ b/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts @@ -255,11 +255,21 @@ export class ClaudeRuntimeAuthSync extends ClaudeRuntimeAuthPreparationService { ) if (refreshed) { credentialsJson = refreshed - } else if (liveClaudePtys && credentialsJson === this.lastWrittenCredentialsJson) { - // Why: runtime already holds this blob; rewriting it would clobber a rotation a live Claude saved while our refresh was in flight. - this.lastSyncedAccountId = activeAccount.id - this.hasMaterializedRuntimeAuth = true - return + } else if (liveClaudePtys && this.lastSyncedAccountId === activeAccount.id) { + // Why: a live Claude may have rotated the runtime token while our refresh was in flight (even on the first sync, before lastWrittenCredentialsJson exists); adopt it or leave it rather than rewrite the stale blob over it. Only a wiped runtime, or a first sync that has nothing to compare against, falls through to materialize. + const readBackResult = await this.readBackRefreshedTokens(credentialsJson, { + updateLastWrittenCredentialsJson: true + }) + if ( + readBackResult.status === 'persisted' || + (readBackResult.status === 'rejected' && + readBackResult.hasValidChangedRuntimeCredentials) || + (readBackResult.status === 'unchanged' && + credentialsJson === this.lastWrittenCredentialsJson) + ) { + this.hasMaterializedRuntimeAuth = true + return + } } } From 72c8944382f13fc1853bb632e8eae1a3222a4958 Mon Sep 17 00:00:00 2001 From: konayre Date: Thu, 24 Sep 2026 03:01:20 +0400 Subject: [PATCH 3/4] fix(claude-accounts): re-materialize the active account when post-failure read-back adopts another Read-back matches a runtime rotation against every managed account, so a Claude signed in as another account could have its rotation filed under that account while the active account's refresh was in flight. Returning early on 'persisted' then left the shared runtime on the other account while preparation still reported the active one (CodeRabbit on #22510). Only skip materialization when the adopted rotation landed in the active account's managed credentials; otherwise fall through and restore it, as the read-back at the top of the sync already does. --- ...untime-auth-service-launch-refresh.test.ts | 57 +++++++++++++++++++ .../runtime-auth/runtime-auth-sync.ts | 5 +- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts index 729be6c2b35c..e7039bb1785b 100644 --- a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts +++ b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts @@ -363,6 +363,63 @@ describe('ClaudeRuntimeAuthService', () => { } }) + it('re-materializes the active account when the post-failure read-back adopts another account', async () => { + const expired = createClaudeCredentialsJson( + 'one@example.com', + 'one-expired', + null, + Date.now() - 60 * 60 * 1000 + ) + const twoRotated = createClaudeCredentialsJson( + 'two@example.com', + 'two-rotated', + null, + Date.now() + 8 * 60 * 60 * 1000 + ) + const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired) + const managedAuthPath2 = createManagedClaudeAuth( + testState.userDataDir, + 'account-2', + createClaudeCredentialsJson('two@example.com', 'two-old', null, Date.now() - 60_000) + ) + const settings = createSettings({ + claudeManagedAccounts: [ + createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' }), + createClaudeAccount('account-2', managedAuthPath2, { email: 'two@example.com' }) + ], + activeClaudeManagedAccountId: 'account-1' + }) + const store = createStore(settings) + + vi.mocked(isOauthTokenExpiring).mockReturnValue(true) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true) + + const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate') + const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service') + + markClaudePtySpawned('pty-live-1') + try { + const service = new ClaudeRuntimeAuthService(store as never) + await service.syncForCurrentSelection() + + // A Claude signed in as account-2 rotates its token into the shared runtime while + // account-1's refresh is in flight; read-back rightly saves it to account-2. + vi.mocked(refreshClaudeOauthCredentials).mockImplementationOnce(async () => { + testState.legacyKeychainCredentials = twoRotated + return null + }) + await service.syncForCurrentSelection() + + expect(readManagedCredentialsForTest('account-2', managedAuthPath2)).toBe(twoRotated) + expect(testState.legacyKeychainCredentials).toBe(expired) + } finally { + markClaudePtyExited('pty-live-1') + vi.mocked(isOauthTokenExpiring).mockReturnValue(false) + vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false) + vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null) + } + }) + it('keeps a live Claude rotation that lands during the first sync after launch', async () => { const expired = createClaudeCredentialsJson( 'one@example.com', diff --git a/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts b/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts index 456a4c0648bf..1472cbf7d157 100644 --- a/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts +++ b/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts @@ -256,12 +256,13 @@ export class ClaudeRuntimeAuthSync extends ClaudeRuntimeAuthPreparationService { if (refreshed) { credentialsJson = refreshed } else if (liveClaudePtys && this.lastSyncedAccountId === activeAccount.id) { - // Why: a live Claude may have rotated the runtime token while our refresh was in flight (even on the first sync, before lastWrittenCredentialsJson exists); adopt it or leave it rather than rewrite the stale blob over it. Only a wiped runtime, or a first sync that has nothing to compare against, falls through to materialize. + // Why: a live Claude may have rotated the runtime token while our refresh was in flight (even on the first sync, before lastWrittenCredentialsJson exists); adopt it or leave it rather than rewrite the stale blob over it. Only a wiped runtime, a rotation read-back filed under another account, or a first sync with nothing to compare against falls through to materialize. const readBackResult = await this.readBackRefreshedTokens(credentialsJson, { updateLastWrittenCredentialsJson: true }) if ( - readBackResult.status === 'persisted' || + (readBackResult.status === 'persisted' && + (await this.readManagedCredentials(activeAccount)) !== credentialsJson) || (readBackResult.status === 'rejected' && readBackResult.hasValidChangedRuntimeCredentials) || (readBackResult.status === 'unchanged' && From c8ecb12f764b8c6baaaa40b005e9aaf95176f6ee Mon Sep 17 00:00:00 2001 From: konayre Date: Thu, 24 Sep 2026 10:17:10 +0400 Subject: [PATCH 4/4] test(claude-accounts): assert the runtime credentials file is restored to the active account --- .../runtime-auth-service-launch-refresh.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts index e7039bb1785b..f1978b151dbd 100644 --- a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts +++ b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts @@ -412,6 +412,9 @@ describe('ClaudeRuntimeAuthService', () => { expect(readManagedCredentialsForTest('account-2', managedAuthPath2)).toBe(twoRotated) expect(testState.legacyKeychainCredentials).toBe(expired) + expect( + readFileSync(join(testState.fakeHomeDir, '.claude', '.credentials.json'), 'utf-8') + ).toBe(expired) } finally { markClaudePtyExited('pty-live-1') vi.mocked(isOauthTokenExpiring).mockReturnValue(false)