mirror of
https://github.com/tiennm99/ccs.git
synced 2026-10-15 18:15:40 +00:00
fix(bar): stop false re-auth on non-default native subscription profiles
Fixes the two collector-side root causes of #1601: 1. Claude per-profile credential reads were file-only, but on macOS Claude Code stores the OAuth token for an isolated CLAUDE_CONFIG_DIR in a per-directory Keychain item ("Claude Code-credentials-<sha256(dir)[0..8]>"). The .credentials.json file never exists, so every isolated profile was parked with needsReauth:true forever. The reader now falls back to that Keychain item (file-first, same security-CLI read the shipped global fallback already performs; TTL-gated so it is not on every /summary). 2. Non-default profiles were cache-only forever, so they could never leave the parked state even with valid credentials. getNativeAccountRows now gives each surface ONE rotating live slot: the stalest eligible non-default profile is refreshed per pass, skipping profiles inside breaker/reauth cooldowns. Every account converges to real quota within a few polls while the per-pass upstream budget stays constant (<= 2 calls per surface regardless of profile count). Codex named profiles with valid auth but sparse payloads now yield an active quota-less row instead of a false needsReauth row. Non-default rows keep paused:true (dimmed) even when freshly refreshed so only the default renders active and rows do not flicker between polls. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7fb56d62e1
commit
a5a5b742e4
6 files changed
+401
-67
No files matched your search
@@ -8,6 +8,8 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
readClaudeCredentials,
|
||||
readClaudeCredentialsForConfigDir,
|
||||
claudeKeychainServiceForConfigDir,
|
||||
getAccessToken,
|
||||
getSubscriptionTier,
|
||||
hasSupportedSubscription,
|
||||
@@ -124,3 +126,92 @@ describe('token + tier extraction', () => {
|
||||
expect(getSubscriptionTier(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-config-dir credential reading (isolated `ccs auth` profiles on macOS)
|
||||
//
|
||||
// Claude Code stores OAuth credentials for a non-default CLAUDE_CONFIG_DIR in
|
||||
// a per-directory Keychain item: service "Claude Code-credentials-<hash>",
|
||||
// where <hash> is the first 8 hex chars of sha256(configDir). These tests pin
|
||||
// that derivation and the file-first / Keychain-fallback read order.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('claudeKeychainServiceForConfigDir', () => {
|
||||
it('derives the service name from sha256 of the config dir path (first 8 hex chars)', () => {
|
||||
// sha256("/home/test/.ccs/instances/work") = ffeb4b45...
|
||||
expect(claudeKeychainServiceForConfigDir('/home/test/.ccs/instances/work')).toBe(
|
||||
'Claude Code-credentials-ffeb4b45'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readClaudeCredentialsForConfigDir', () => {
|
||||
const configDir = '/home/test/.ccs/instances/work';
|
||||
const credFile = `${configDir}/.credentials.json`;
|
||||
|
||||
it('reads <configDir>/.credentials.json when present (file-first, no Keychain)', () => {
|
||||
let keychainCalled = false;
|
||||
const creds = readClaudeCredentialsForConfigDir(configDir, {
|
||||
platform: 'darwin',
|
||||
existsSyncImpl: (p: string) => p === credFile,
|
||||
readFileSyncImpl: (p: string) => {
|
||||
expect(p).toBe(credFile);
|
||||
return JSON.stringify(makeCreds());
|
||||
},
|
||||
execSyncImpl: () => {
|
||||
keychainCalled = true;
|
||||
return '';
|
||||
},
|
||||
});
|
||||
expect(creds?.claudeAiOauth?.accessToken).toBe('tok-abc');
|
||||
expect(keychainCalled).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to the per-config-dir Keychain service when the file is absent', () => {
|
||||
let keychainCmd = '';
|
||||
const creds = readClaudeCredentialsForConfigDir(configDir, {
|
||||
platform: 'darwin',
|
||||
existsSyncImpl: () => false,
|
||||
readFileSyncImpl: () => {
|
||||
throw new Error('should not read file');
|
||||
},
|
||||
execSyncImpl: (cmd: string) => {
|
||||
keychainCmd = cmd;
|
||||
return JSON.stringify(makeCreds({ subscriptionType: 'team' }));
|
||||
},
|
||||
});
|
||||
expect(creds?.claudeAiOauth?.subscriptionType).toBe('team');
|
||||
expect(keychainCmd).toContain('Claude Code-credentials-ffeb4b45');
|
||||
});
|
||||
|
||||
it('returns null when both file and Keychain are absent', () => {
|
||||
const creds = readClaudeCredentialsForConfigDir(configDir, {
|
||||
platform: 'darwin',
|
||||
existsSyncImpl: () => false,
|
||||
readFileSyncImpl: () => {
|
||||
throw new Error('no file');
|
||||
},
|
||||
execSyncImpl: () => {
|
||||
throw new Error('no keychain entry');
|
||||
},
|
||||
});
|
||||
expect(creds).toBeNull();
|
||||
});
|
||||
|
||||
it('does not consult the Keychain on non-darwin platforms', () => {
|
||||
let keychainCalled = false;
|
||||
const creds = readClaudeCredentialsForConfigDir(configDir, {
|
||||
platform: 'linux',
|
||||
existsSyncImpl: () => false,
|
||||
readFileSyncImpl: () => {
|
||||
throw new Error('no file');
|
||||
},
|
||||
execSyncImpl: () => {
|
||||
keychainCalled = true;
|
||||
return '';
|
||||
},
|
||||
});
|
||||
expect(creds).toBeNull();
|
||||
expect(keychainCalled).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1170,8 +1170,10 @@ describe('multi-profile: account_id and wire fields', () => {
|
||||
|
||||
const rows = await getNativeAccountRows(deps);
|
||||
expect(rows.length).toBe(claudeProfiles.length + codexProfiles.length);
|
||||
expect(deps.claudeFetchCount()).toBe(1);
|
||||
expect(deps.codexNetworkCount()).toBe(1);
|
||||
// Budget per pass: the default + one rotating non-default live slot per
|
||||
// surface — constant regardless of profile count.
|
||||
expect(deps.claudeFetchCount()).toBe(2);
|
||||
expect(deps.codexNetworkCount()).toBe(2);
|
||||
});
|
||||
|
||||
it('rows are sorted by (surface, profile)', async () => {
|
||||
@@ -1396,8 +1398,9 @@ describe('multi-profile: per-profile circuit breaker isolation', () => {
|
||||
const ckRow = rows.find((r) => r.profile === 'ck');
|
||||
const workRow = rows.find((r) => r.profile === 'work');
|
||||
|
||||
// 'ck' stays cache-only, independent of work's breaker.
|
||||
expect(ckRow?.quotaStatus).toBe('unsupported');
|
||||
// 'ck' gets its own live row via the rotating slot, independent of work's
|
||||
// breaker history.
|
||||
expect(ckRow?.quotaStatus).toBe('ok');
|
||||
// 'work' is also fine after reset (no breaker state).
|
||||
expect(workRow?.quotaStatus).toBe('ok');
|
||||
});
|
||||
@@ -1431,10 +1434,11 @@ describe('multi-profile: per-profile circuit breaker isolation', () => {
|
||||
},
|
||||
});
|
||||
|
||||
// First call: 'work' gets a 429, 'ck' remains cache-only.
|
||||
// First call: 'work' gets a 429; 'ck' is refreshed by the rotating slot and
|
||||
// succeeds — work's failures do not leak into ck's state.
|
||||
const rows1 = await getNativeAccountRows(deps);
|
||||
const ck1 = rows1.find((r) => r.profile === 'ck');
|
||||
expect(ck1?.quotaStatus).toBe('unsupported');
|
||||
expect(ck1?.quotaStatus).toBe('ok');
|
||||
expect(workCall429Count).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Skip past cooldown for 'work' only; 'ck' is within TTL.
|
||||
@@ -1443,8 +1447,8 @@ describe('multi-profile: per-profile circuit breaker isolation', () => {
|
||||
// Second call past 'work' cooldown: work tries again (429 again); ck cached.
|
||||
const rows2 = await getNativeAccountRows(deps);
|
||||
const ck2 = rows2.find((r) => r.profile === 'ck');
|
||||
// 'ck' remains cache-only and is not affected by work's breaker.
|
||||
expect(ck2?.quotaStatus).toBe('unsupported');
|
||||
// 'ck' keeps its healthy cached row and is not affected by work's breaker.
|
||||
expect(ck2?.quotaStatus).toBe('ok');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1537,15 +1541,18 @@ describe('review focus areas: reauth caching + codex local fallback', () => {
|
||||
codexNetworkFetch: async () => ({ success: false, needsReauth: true }) as CodexQuotaResult,
|
||||
});
|
||||
|
||||
// The rotating slot polls 'ck' once; the 401 parks it into the reauth
|
||||
// cooldown.
|
||||
const first = await getNativeAccountRows(deps);
|
||||
const r1 = first.find((r) => r.profile === 'ck');
|
||||
expect(r1?.needsReauth).toBe(true);
|
||||
expect(r1?.paused).toBe(true);
|
||||
expect(deps.codexNetworkCount()).toBe(0);
|
||||
expect(deps.codexNetworkCount()).toBe(1);
|
||||
|
||||
// Within the cooldown it is NOT re-polled (no repeated 401s), even forced.
|
||||
const second = await getNativeAccountRows(deps, { force: true });
|
||||
expect(second.find((r) => r.profile === 'ck')?.cached).toBe(true);
|
||||
expect(deps.codexNetworkCount()).toBe(0);
|
||||
expect(deps.codexNetworkCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('Codex named profile without on-disk auth is parked, never filled from global local data', async () => {
|
||||
@@ -1655,7 +1662,7 @@ describe('review focus areas: reauth caching + codex local fallback', () => {
|
||||
expect(deps.claudeFetchCount()).toBe(1); // re-checked -> fetched
|
||||
});
|
||||
|
||||
it('Codex named profile with valid auth but sparse payload stays parked when not default', async () => {
|
||||
it('Codex named profile with valid auth but sparse payload yields an active quota-less row', async () => {
|
||||
resetNativeQuotaState();
|
||||
const clock = { now: 7_000_000 };
|
||||
const deps = makeMultiProfileDeps({
|
||||
@@ -1668,13 +1675,15 @@ describe('review focus areas: reauth caching + codex local fallback', () => {
|
||||
codexNetworkFetch: async () => ({ success: true }) as CodexQuotaResult,
|
||||
});
|
||||
|
||||
// The rotating slot polls 'ck'; the token authenticated, so it is a valid
|
||||
// active subscription with a sparse payload — an active quota-less row,
|
||||
// still dimmed because it is not the default profile.
|
||||
const rows = await getNativeAccountRows(deps);
|
||||
const ck = rows.find((r) => r.profile === 'ck');
|
||||
expect(ck).toBeDefined();
|
||||
expect(ck?.paused).toBe(true); // cache-only, parked until selected as default
|
||||
expect(ck?.needsReauth).toBe(true);
|
||||
expect(ck?.quotaStatus).toBe('unsupported');
|
||||
expect(ck?.quota_percentage).toBeNull(); // no windows while parked
|
||||
expect(ck?.paused).toBe(true); // non-default rows always render dimmed
|
||||
expect(ck?.needsReauth).toBe(false);
|
||||
expect(ck?.quota_percentage).toBeNull(); // no windows in the payload
|
||||
});
|
||||
|
||||
it('non-default cache-only rows do not overwrite the canonical live cache', async () => {
|
||||
@@ -1691,9 +1700,11 @@ describe('review focus areas: reauth caching + codex local fallback', () => {
|
||||
});
|
||||
deps.defaultCodexProfile = () => codexDefault;
|
||||
|
||||
// First pass: 'ck' (default) is live-polled and the rotating slot also
|
||||
// refreshes 'default' — two upstream calls.
|
||||
const first = await getNativeAccountRows(deps);
|
||||
expect(first.find((r) => r.profile === 'ck')?.paused).toBe(false);
|
||||
expect(deps.codexNetworkCount()).toBe(1);
|
||||
expect(deps.codexNetworkCount()).toBe(2);
|
||||
|
||||
codexDefault = 'default';
|
||||
const second = await getNativeAccountRows(deps);
|
||||
@@ -1710,3 +1721,109 @@ describe('review focus areas: reauth caching + codex local fallback', () => {
|
||||
expect(deps.codexNetworkCount()).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Multi-profile: rotating live slot for non-default profiles
|
||||
//
|
||||
// Non-default profiles used to be cache-only forever, so accounts other than
|
||||
// the default never showed real quota — they sat parked ("needs re-auth") for
|
||||
// the lifetime of the server. One rotating live slot per surface refreshes the
|
||||
// stalest eligible non-default profile per pass, so every account converges to
|
||||
// real data within a few polls while the per-pass upstream budget stays
|
||||
// constant (<= 2 calls per surface) regardless of profile count.
|
||||
// ============================================================================
|
||||
|
||||
describe('multi-profile: rotating live slot for non-default profiles', () => {
|
||||
it('live-polls the default plus one stale non-default Claude profile per pass', async () => {
|
||||
const clock = { now: 1_000_000 };
|
||||
const deps = makeMultiProfileDeps({
|
||||
clock,
|
||||
claudeProfiles: ['work', 'personal', 'fc'],
|
||||
codexProfiles: [],
|
||||
claudeDefault: 'work',
|
||||
credsForProfile: () => maxCreds(),
|
||||
claudeFetch: async () => successQuota(),
|
||||
});
|
||||
|
||||
// Pass 1: default (work) + one stale non-default get live data.
|
||||
let rows = await getNativeAccountRows(deps);
|
||||
expect(deps.claudeFetchCount()).toBe(2);
|
||||
expect(rows.filter((r) => r.quotaStatus === 'ok').length).toBe(2);
|
||||
|
||||
// Pass 2 after the parked TTL: the remaining profile gets its live row.
|
||||
clock.now += 31_000;
|
||||
rows = await getNativeAccountRows(deps);
|
||||
expect(deps.claudeFetchCount()).toBe(3);
|
||||
expect(rows.filter((r) => r.quotaStatus === 'ok').length).toBe(3);
|
||||
|
||||
// Pass 3 while everything is within TTL: fully cached, zero upstream calls.
|
||||
clock.now += 1_000;
|
||||
rows = await getNativeAccountRows(deps);
|
||||
expect(deps.claudeFetchCount()).toBe(3);
|
||||
expect(rows.filter((r) => r.quotaStatus === 'ok').length).toBe(3);
|
||||
});
|
||||
|
||||
it('rotated non-default rows keep paused:true (only the default renders active)', async () => {
|
||||
const clock = { now: 1_000_000 };
|
||||
const deps = makeMultiProfileDeps({
|
||||
clock,
|
||||
claudeProfiles: ['work', 'personal'],
|
||||
codexProfiles: [],
|
||||
claudeDefault: 'work',
|
||||
credsForProfile: () => maxCreds(),
|
||||
claudeFetch: async () => successQuota(),
|
||||
});
|
||||
|
||||
const rows = await getNativeAccountRows(deps);
|
||||
const personal = rows.find((r) => r.profile === 'personal');
|
||||
expect(personal?.quotaStatus).toBe('ok');
|
||||
expect(personal?.needsReauth).toBe(false);
|
||||
expect(personal?.paused).toBe(true);
|
||||
expect(personal?.is_default).toBe(false);
|
||||
});
|
||||
|
||||
it('codex non-default profiles also get one rotating live slot per pass', async () => {
|
||||
const clock = { now: 1_000_000 };
|
||||
const deps = makeMultiProfileDeps({
|
||||
clock,
|
||||
claudeProfiles: [],
|
||||
codexProfiles: ['personal', 'ck'],
|
||||
codexDefault: 'personal',
|
||||
codexNativeAuth: (p) => ({ accessToken: `tok-${p}`, accountId: `id-${p}` }),
|
||||
codexNetworkFetch: async () => codexSuccessQuota(),
|
||||
});
|
||||
|
||||
const rows = await getNativeAccountRows(deps);
|
||||
expect(deps.codexNetworkCount()).toBe(2);
|
||||
const ck = rows.find((r) => r.profile === 'ck');
|
||||
expect(ck?.paused).toBe(true);
|
||||
expect(ck?.needsReauth).toBe(false);
|
||||
});
|
||||
|
||||
it('profiles in reauth cooldown are skipped by the rotating slot', async () => {
|
||||
const clock = { now: 1_000_000 };
|
||||
let failProfile: string | null = 'personal';
|
||||
const deps = makeMultiProfileDeps({
|
||||
clock,
|
||||
claudeProfiles: ['work', 'personal'],
|
||||
codexProfiles: [],
|
||||
claudeDefault: 'work',
|
||||
credsForProfile: () => maxCreds(),
|
||||
claudeFetch: async (_token: string, accountId?: string) =>
|
||||
accountId === `ccs:${failProfile}`
|
||||
? ({ success: false, needsReauth: true, retryable: false } as ClaudeQuotaResult)
|
||||
: successQuota(),
|
||||
});
|
||||
|
||||
// Pass 1: personal is rotated in, 401s, and enters the reauth cooldown.
|
||||
let rows = await getNativeAccountRows(deps);
|
||||
expect(rows.find((r) => r.profile === 'personal')?.needsReauth).toBe(true);
|
||||
expect(deps.claudeFetchCount()).toBe(2);
|
||||
|
||||
// Pass 2 inside the cooldown: the slot must NOT re-poll (and re-401) it.
|
||||
clock.now += 31_000;
|
||||
rows = await getNativeAccountRows(deps);
|
||||
expect(deps.claudeFetchCount()).toBe(2);
|
||||
expect(rows.find((r) => r.profile === 'personal')?.needsReauth).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user