Skip to content

fix: Token refresh on re-login and account switch#5

Open
hiscc wants to merge 1 commit intoXueshiQiao:mainfrom
hiscc:fix/token-refresh-and-auto-switch
Open

fix: Token refresh on re-login and account switch#5
hiscc wants to merge 1 commit intoXueshiQiao:mainfrom
hiscc:fix/token-refresh-and-auto-switch

Conversation

@hiscc
Copy link
Copy Markdown

@hiscc hiscc commented Apr 7, 2026

Summary

  • Fix login() breaking when CLI exits non-zero after opening browser ("Opening browser to sign in...")
  • Fix loginNewAccount not refreshing usage when re-logging existing account (was returning early without calling refresh())
  • Fix reauthenticateAccount not clearing expired error state after success
  • Add post-switch credential re-capture in switchAccount to keep backups fresh
  • Add auto token refresh attempt for active accounts before showing expired error
  • Add "Re-auth" button in Usage Dashboard for expired token cards
  • Add defer guard for isAutoSwitching flag
  • Add auto-switch functionality based on usage thresholds
  • Add CHANGELOG.md documenting full iteration history

Test plan

  • Re-login with an existing account that shows "Token expired" → should clear error and refresh usage
  • Switch to an account with stale backup → should attempt token refresh automatically
  • Click "Re-auth" button on expired card → should open browser login and refresh
  • Verify auto-switch triggers when active account exceeds usage threshold
  • Verify anti-oscillation cooldown prevents rapid A→B→A switching

🤖 Generated with Claude Code

- Added auto-switch feature to switch accounts when usage exceeds a specified threshold.
- Introduced AppStorage properties for enabling auto-switch and setting the usage threshold.
- Enhanced AppState to manage cached usage data and handle auto-switch logic.
- Updated UI to display usage in the menu bar and added settings for auto-switch.
- Improved error handling for account usage fetching and token refresh processes.
- Added changelog to document changes and improvements.
@XueshiQiao
Copy link
Copy Markdown
Owner

Hi @hiscc, thanks so much for taking the time to work on this PR! It's clear you've put real thought into the auto-switch feature and the token refresh improvements. Several ideas here are genuinely valuable for the project.

I've done a thorough review and wanted to share some feedback before we can move forward with merging.

Blockers

  1. project.yml signing changes — The PR switches to ad-hoc signing (CODE_SIGN_IDENTITY: "-", DEVELOPMENT_TEAM: ""). I understand this is likely for local build convenience, but this would break our CI/CD pipeline (notarization, DMG packaging). Please revert these to the original values. Also note that main is currently at v1.3.1 (build 38), so the version numbers will need rebasing.

  2. Email obfuscation removedAccount.swift now returns raw email/displayName from obfuscatedEmail and obfuscatedDisplayName. We recently added a showFullEmail toggle (commit c6aae48) that lets users choose. The PR bypasses this setting entirely, which is a privacy regression. Please keep the obfuscation logic intact and respect the existing user preference.

  3. Hardcoded Asia/Shanghai timezoneresetDateString in UsageData.swift uses TimeZone(identifier: "Asia/Shanghai"). This would show incorrect reset times for users outside China. Please use TimeZone.current instead, or keep the existing relative format ("2 hr 30 min"), which is locale-agnostic and arguably more user-friendly.

  4. Auto-switch without user notification — Silently swapping keychain credentials is risky. If Claude Code CLI has an active session, a background credential swap could cause auth failures mid-conversation. I'd like to see at minimum a system notification when auto-switch fires, so the user knows what happened and can react if needed.

Suggestions

  1. Split into smaller PRs — This PR mixes bug fixes, a new feature, UI changes, and config changes in a single commit. It would be much easier to review and cherry-pick if split into separate PRs, e.g.:

    • Bug fixes (defer guards, login error handling, token refresh improvements)
    • Auto-switch feature
    • UI/UX improvements (re-auth button, usage caching, card redesign)
  2. @AppStorage on ObservableObject@AppStorage("autoSwitchEnabled") and @AppStorage("autoSwitchThreshold") on AppState may not reliably trigger objectWillChange. Consider using UserDefaults directly with manual publishing, or keeping @AppStorage in the view layer.

  3. 429 retry timing — Retrying a rate-limited API after only 3 seconds could trigger further rate limiting from Anthropic. A longer backoff (or skipping the retry entirely and relying on cache) would be safer for users' accounts.

  4. cachedUsage encapsulation — Views currently access appState.cachedUsage directly. Since resolveSessionUtilization(for:) already exists as a private method, exposing a public version would keep the cache as an internal implementation detail.

What I really like

  • The defer guards for isLoggingIn / isAutoSwitching — these fix real bugs in the current code
  • CachedUsageEntry with reset-aware stale detection is well-designed
  • Anti-oscillation logic (cooldown + lastAbandonedAccountId) is thoughtful
  • Post-switch credential re-capture is a great catch
  • nvm path discovery and claudeBinDir on PATH are practical fixes
  • The re-auth button UX is a nice touch

I'd love to get the good parts of this merged. Happy to discuss any of the above — let me know your thoughts!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants