-
Notifications
You must be signed in to change notification settings - Fork 372
fix: Comprehensive authentication error handling #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: Comprehensive authentication error handling #12
Conversation
📝 WalkthroughWalkthroughReplaces interactive credential-file/login logic in shell scripts with readiness checks for Claude CLI and config directory; adds runtime Claude CLI authentication detection and user guidance in Python ( Changes
Sequence Diagram(s)sequenceDiagram
participant StartScript as start.sh / start_ui.sh
participant PythonRunner as start.py
participant ClaudeCLI as Claude CLI (external)
participant FS as Filesystem (~/.claude & spec)
participant Agent as Agent process
StartScript->>PythonRunner: invoke runner
PythonRunner->>ClaudeCLI: run spec creation command
ClaudeCLI-->>PythonRunner: stdout / stderr + exit code
alt exit non-zero & matches AUTH_ERROR_PATTERNS
PythonRunner->>PythonRunner: is_auth_error(stderr) -> true
PythonRunner->>StartScript: print_auth_error_help()
else exit non-zero other error
PythonRunner->>StartScript: print stderr / hints
end
PythonRunner->>FS: check for produced spec file
alt spec exists
PythonRunner->>Agent: run agent with spec
Agent-->>PythonRunner: stdout / stderr + exit code
alt agent exit non-zero & matches AUTH_ERROR_PATTERNS
PythonRunner->>StartScript: print_auth_error_help()
else
PythonRunner->>StartScript: print stderr / hints
end
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
start.sh
🔇 Additional comments (1)
start.sh (1)
23-27: Pragmatic authentication check - well-documented approach.The comment correctly notes that modern Claude CLI on macOS stores credentials in the encrypted macOS Keychain rather than in a .credentials.json file, and the credentials file gets deleted when logging in on macOS. The dual check (
claude --version+ directory existence) is a reasonable heuristic that:
- Verifies the CLI is functional (not just present in PATH)
- Confirms the config directory has been initialized
- Works across platforms (macOS uses Keychain, Linux still uses .credentials.json in this directory)
The approach balances reliability with user experience by avoiding forced interactive flows.
The previous credential check looked for ~/.claude/.credentials.json, which no longer exists in recent versions of Claude CLI. This caused the script to incorrectly prompt users to login even when they were already authenticated. Changes: - Remove check for non-existent .credentials.json file - Check for ~/.claude directory existence instead - Always remind users about 'claude login' since we can't verify auth status without making an API call - If ~/.claude doesn't exist, pause and warn (but allow continuing) - Add explanatory comments about the limitation The new approach is honest about what we can and can't verify: - We CAN check if the CLI is installed (command -v claude) - We CAN check if ~/.claude directory exists (CLI has been run) - We CANNOT verify actual auth status without an API call 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
71eb07e to
81dbc4b
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @start.sh:
- Around line 23-28: Replace the existing directory-only check in the if
statement that currently reads like the block checking "$HOME/.claude" with a
combined operational check that runs the claude CLI version command and verifies
the directory exists (i.e., use a command-execution check for "claude --version"
and the directory test together). Update the if condition used around the echo
lines so it only enters the block when the CLI executable returns success and
the config directory exists, and keep the existing echo messages unchanged.
- Around line 29-35: The else branch currently still blocks with a read prompt;
remove the blocking read or guard it so the script truly emits a non-blocking
warning. Specifically, in the else block that prints "[!] Claude CLI not
configured" (the section containing the read -p "Press Enter to continue anyway,
or Ctrl+C to exit..."), either delete that read line entirely to make the
warning non-blocking, or wrap it in an interactive-only guard (e.g., if [ -t 0
]; then read -p ...; fi) so automated/non-interactive runs are not blocked.
🧹 Nitpick comments (1)
start.sh (1)
26-28: Consider refining the authenticated-user message.Line 28 displays
"(If you're not logged in, run: claude login)"even when the.claudedirectory exists, which typically indicates the user IS logged in. This might cause unnecessary confusion for authenticated users.Consider a more confident message when the directory exists, or move the login reminder to the else block where it's more contextually appropriate.
💬 Suggested messaging refinement
if claude --version &> /dev/null && [ -d "$HOME/.claude" ]; then - echo "[OK] Claude CLI directory found" - echo " (If you're not logged in, run: claude login)" + echo "[OK] Claude CLI configured"
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
start.sh
🔇 Additional comments (1)
start.sh (1)
23-35: Note: Authentication error handling in start.py becomes more critical.Since this script now performs relaxed authentication checks and allows execution to continue without confirming the user is authenticated, robust error handling in
start.pybecomes increasingly important.The previous review comment on this PR identified that
start.pydoesn't explicitly handle Claude authentication failures—whenrun_spec_creation()orrun_agent()call the Claude CLI, subprocess errors aren't parsed or contextualized for the user.With start.sh being more permissive, consider prioritizing the authentication error handling improvements in start.py to provide users with clear feedback when authentication actually fails during operation.
Based on past review comments on this PR.
| # Note: Claude CLI no longer stores credentials in ~/.claude/.credentials.json | ||
| # We can't reliably check auth status without making an API call, so we just | ||
| # verify the CLI is installed and remind the user to login if needed | ||
| if [ -d "$HOME/.claude" ]; then | ||
| echo "[OK] Claude CLI directory found" | ||
| echo " (If you're not logged in, run: claude login)" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Implementation doesn't match PR description: missing CLI operational check.
The PR description explicitly states the fix should use:
if claude --version &> /dev/null && [ -d "$HOME/.claude" ]; thenHowever, line 26 only checks for the directory:
if [ -d "$HOME/.claude" ]; thenThe claude --version check is essential because it verifies the CLI is operational, not just that a config directory exists. Without it, the script could proceed with a broken or misconfigured CLI installation.
🔧 Add the operational check as described in the PR
-if [ -d "$HOME/.claude" ]; then
+if claude --version &> /dev/null && [ -d "$HOME/.claude" ]; then
echo "[OK] Claude CLI directory found"
echo " (If you're not logged in, run: claude login)"🤖 Prompt for AI Agents
In @start.sh around lines 23 - 28, Replace the existing directory-only check in
the if statement that currently reads like the block checking "$HOME/.claude"
with a combined operational check that runs the claude CLI version command and
verifies the directory exists (i.e., use a command-execution check for "claude
--version" and the directory test together). Update the if condition used around
the echo lines so it only enters the block when the CLI executable returns
success and the config directory exists, and keep the existing echo messages
unchanged.
| else | ||
| echo "[!] Not authenticated with Claude" | ||
| echo "[!] Claude CLI not configured" | ||
| echo "" | ||
| echo "You need to run 'claude login' to authenticate." | ||
| echo "This will open a browser window to sign in." | ||
| echo "Please run 'claude login' to authenticate before continuing." | ||
| echo "" | ||
| read -p "Would you like to run 'claude login' now? (y/n): " LOGIN_CHOICE | ||
|
|
||
| if [[ "$LOGIN_CHOICE" =~ ^[Yy]$ ]]; then | ||
| echo "" | ||
| echo "Running 'claude login'..." | ||
| echo "Complete the login in your browser, then return here." | ||
| echo "" | ||
| claude login | ||
|
|
||
| # Check if login succeeded | ||
| if [ -f "$CLAUDE_CREDS" ]; then | ||
| echo "" | ||
| echo "[OK] Login successful!" | ||
| else | ||
| echo "" | ||
| echo "[ERROR] Login failed or was cancelled." | ||
| echo "Please try again." | ||
| exit 1 | ||
| fi | ||
| else | ||
| echo "" | ||
| echo "Please run 'claude login' manually, then try again." | ||
| exit 1 | ||
| fi | ||
| read -p "Press Enter to continue anyway, or Ctrl+C to exit..." | ||
| fi |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script still blocks execution, contradicting PR's non-blocking claim.
The PR description states the change "emits a non-blocking warning with instructions when not configured (instead of forcing login)" and "removes the forced interactive flow." However, line 34 still blocks execution:
read -p "Press Enter to continue anyway, or Ctrl+C to exit..."This forces user interaction before the script can proceed, which contradicts the non-blocking design goal.
♻️ Make the warning truly non-blocking
else
echo "[!] Claude CLI not configured"
echo ""
echo "Please run 'claude login' to authenticate before continuing."
- echo ""
- read -p "Press Enter to continue anyway, or Ctrl+C to exit..."
fi🤖 Prompt for AI Agents
In @start.sh around lines 29 - 35, The else branch currently still blocks with a
read prompt; remove the blocking read or guard it so the script truly emits a
non-blocking warning. Specifically, in the else block that prints "[!] Claude
CLI not configured" (the section containing the read -p "Press Enter to continue
anyway, or Ctrl+C to exit..."), either delete that read line entirely to make
the warning non-blocking, or wrap it in an interactive-only guard (e.g., if [ -t
0 ]; then read -p ...; fi) so automated/non-interactive runs are not blocked.
Add detection and helpful messaging for Claude CLI authentication errors in the Python launcher, complementing the shell script improvements. Changes: - Add is_auth_error() helper with regex patterns for common auth errors - Add print_auth_error_help() for consistent, actionable error messages - Update run_spec_creation() to capture stderr and detect auth failures - Update run_agent() to capture stderr and detect auth failures - Both functions now provide helpful "run claude login" guidance Error patterns detected: - "not logged in" / "not authenticated" - "authentication failed/required/error" - "login required" - "please run claude login" - "unauthorized" - "invalid token/credential/api key" - "expired token/session/credential" This aligns the Python UX with the shell script's non-blocking warning approach while adding proactive error detection. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (4)
start.py (4)
28-40: Consider refining overly broad patterns.Some regex patterns might produce false positives:
- Line 35:
r"unauthorized"is very broad and could match non-authentication errors (e.g., "unauthorized access to resource X" might be a permissions issue rather than a login issue)- Line 36:
r"invalid\s+(token|credential|api.?key)"won't matchapi_key(underscore separator) - considerapi[._\s]?keyinsteadThese are unlikely to cause significant issues but could lead to misleading error messages in edge cases.
♻️ Suggested refinements
- r"unauthorized", + r"(not\s+authorized|unauthorized\s+(access|request|user))", - r"invalid\s+(token|credential|api.?key)", + r"invalid\s+(token|credential|api[._\s]?key)",
43-60: Update docstring to match actual usage.The docstring states the function accepts "Combined stdout/stderr from subprocess," but in practice, only
stderris passed to this function (lines 280, 450). The implementation is correct, but the documentation is misleading.📝 Proposed docstring fix
""" Check if output contains Claude CLI authentication error messages. Args: - output: Combined stdout/stderr from subprocess + output: stderr output from subprocess Returns: True if authentication error detected, False otherwise """
297-299: Remove or clarify redundant authentication hint.Lines 297-299 suggest running
claude loginafter any non-zero exit where no spec was created. However:
- If the failure was actually an auth error,
print_auth_error_help()was already called at line 281, and the function returned False at line 282.- This code path only executes for non-authentication errors where spec creation failed.
- Suggesting
claude loginfor non-auth failures could mislead users away from the actual problem (e.g., filesystem issues, invalid project path, etc.).Consider either removing this hint or making it more conditional.
♻️ Suggested fix
print("\n" + "-" * 50) print("Spec creation incomplete.") print(f"Please ensure app_spec.txt exists in: {get_project_prompts_dir(project_dir)}") - # If failed with non-zero exit and no spec, might be auth issue - if result.returncode != 0: - print("\nIf you're having authentication issues, try running: claude login") return FalseOr make it more specific:
- # If failed with non-zero exit and no spec, might be auth issue - if result.returncode != 0: - print("\nIf you're having authentication issues, try running: claude login") + # Only hint about auth if we haven't already shown the auth error help + if result.returncode != 0 and not is_auth_error(stderr_output): + print("\nIf the issue persists, verify Claude CLI is working: claude --version")
456-457: Remove generic authentication hint for non-auth errors.Lines 456-457 suggest running
claude loginwhenever stderr contains "error" or "exception", even after the specific auth error detection (line 450) determined it's not an authentication error.This is misleading because:
- The function already has comprehensive auth error pattern matching via
is_auth_error()- If the patterns didn't match, the error is likely not auth-related
- Generic terms like "error" and "exception" appear in most stderr output (filesystem errors, Python exceptions, validation errors, etc.)
- This could misdirect users away from the actual problem
Trust the specific auth detection and remove this generic fallback.
♻️ Proposed fix
elif stderr_output.strip(): # Show any other errors print(f"\nAgent error:\n{stderr_output.strip()}") - # Still hint about auth if exit was unexpected - if "error" in stderr_output.lower() or "exception" in stderr_output.lower(): - print("\nIf this is an authentication issue, try running: claude login")
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
start.py
🔇 Additional comments (2)
start.py (2)
12-12: LGTM!The
reimport is necessary for the new authentication error pattern matching functionality.
63-73: LGTM!The authentication error help message is clear, well-formatted, and provides actionable guidance to users.
Extend auth error detection to the web UI flow: server/main.py: - Fix setup_status() endpoint to check ~/.claude directory instead of non-existent .credentials.json file - Add explanatory comments about Claude CLI credential storage changes server/services/process_manager.py: - Add AUTH_ERROR_PATTERNS for detecting auth errors in agent output - Add is_auth_error() helper function - Add AUTH_ERROR_HELP message template - Update _stream_output() to detect auth errors in real-time - Buffer last 20 lines to catch auth errors on process exit - Broadcast clear help message to WebSocket clients when auth fails start_ui.sh: - Add Claude CLI installation check with helpful guidance - Add ~/.claude directory check with login reminder - Non-blocking warnings that don't prevent UI from starting This ensures users get clear, actionable feedback when authentication fails, whether using the CLI or the web UI. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @server/main.py:
- Around line 123-127: The current directory-based check using claude_dir and
credentials is unreliable; change the logic so credentials is true when the
appropriate environment variables are present instead of checking ~/.claude:
check ANTHROPIC_API_KEY for standard auth and also consider provider flags like
CLAUDE_CODE_USE_BEDROCK or CLAUDE_CODE_USE_VERTEX combined with their respective
provider credential env vars; update the assignment of the credentials variable
(replace the claude_dir.exists() check) to test os.environ for these keys so
authentication detection is based on environment variables rather than directory
presence.
In @server/services/process_manager.py:
- Around line 39-51: Update the AUTH_ERROR_PATTERNS list to include two
additional regexes to catch missing API key/session and setup-token messages:
add a pattern matching "missing api key" or "missing session" (e.g.,
r"missing\s+(api.?key|session)") and a pattern matching setup-token mentions
(e.g., r"setup.?token"); ensure these new patterns are appended to the
AUTH_ERROR_PATTERNS array so functions that scan error strings (using
AUTH_ERROR_PATTERNS) will detect "Missing API key · Run /login" and "Please run
setup-token" cases.
🧹 Nitpick comments (1)
start_ui.sh (1)
23-30: Consider clarifying the "not configured" message.Line 28's message says "run 'claude login' first" but the script continues execution regardless. This creates a minor inconsistency between the imperative tone and the non-blocking behavior.
💬 Suggested messaging refinement
- echo "[!] Claude CLI not configured - run 'claude login' first" + echo "[!] Claude CLI may not be configured - run 'claude login' if you see auth errors"This aligns the message with the non-blocking design and sets appropriate expectations.
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
server/main.pyserver/services/process_manager.pystart_ui.sh
🧰 Additional context used
🧬 Code graph analysis (1)
server/services/process_manager.py (1)
start.py (1)
is_auth_error(43-60)
🔇 Additional comments (5)
start_ui.sh (1)
12-22: LGTM! Clear messaging for missing Claude CLI.The check provides helpful guidance with installation instructions. The non-blocking approach (continuing despite missing CLI) aligns with the PR's design decision to show warnings rather than hard failures.
server/services/process_manager.py (4)
54-62: LGTM! Clean authentication error detection logic.The implementation is straightforward and correct:
- Defensive early return for empty input
- Case-insensitive matching via lowercase conversion
- Short-circuit on first pattern match for efficiency
65-78: LGTM! Clear and actionable authentication help message.The help banner is well-formatted and provides users with:
- Clear problem identification
- Specific command to run (
claude login)- Expected behavior (browser window)
- Next steps
229-256: Effective real-time authentication error detection with buffering.The implementation correctly:
- Maintains a 20-line sliding window for auth error detection on exit
- Detects auth errors in real-time during streaming
- Broadcasts help only once during streaming (via
auth_error_detectedflag)- Preserves formatting by broadcasting help line-by-line
The 20-line buffer is a reasonable trade-off between memory usage and coverage. Authentication errors typically appear early in Claude CLI output, so this should catch most cases.
268-273: LGTM! Defensive auth error detection on process exit.This fallback check ensures authentication errors are caught even if:
- They weren't detected during real-time streaming
- They appear within the last 20 lines of output
- The process exits with a non-zero code
The
not auth_error_detectedguard prevents duplicate help messages.
| # Check for Claude CLI configuration directory | ||
| # Note: Claude CLI no longer stores credentials in ~/.claude/.credentials.json | ||
| # The existence of ~/.claude indicates the CLI has been configured | ||
| claude_dir = Path.home() / ".claude" | ||
| credentials = claude_dir.exists() and claude_dir.is_dir() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🌐 Web query:
Claude CLI ~/.claude directory authentication configuration
💡 Result:
Summary — what ~/.claude is and how authentication/config works
-
~/.claude contains Claude Code user settings (settings.json) and per-project .claude/settings*.json files. User settings apply globally; project settings live in .claude/ in the project. [1][2]
-
Authentication is normally done with an Anthropic API key via the ANTHROPIC_API_KEY environment variable. Claude Code also supports enterprise providers (Amazon Bedrock, Google Vertex) by setting provider-specific env vars and credentials (e.g., CLAUDE_CODE_USE_BEDROCK=1 + AWS creds). Some third‑party wrappers/proxies (e.g., ZenMux) use different env vars (ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN). [3][2][5]
Quick examples
- Preferred: export ANTHROPIC_API_KEY="sk-..." (works systemwide / in your shell/profile). [3]
- Alternative (user settings file): put an apiKey field in ~/.claude/settings.json (less recommended for secrets). [1][4]
- For Bedrock/Vertex: set CLAUDE_CODE_USE_BEDROCK=1 and configure AWS credentials, or CLAUDE_CODE_USE_VERTEX=1 and configure GCP credentials. [3]
Notes / gotchas
- Environment-variable auth is the standard / recommended method. Some third‑party tools or versions may change how ~/.claude/env or settings are read — check your Claude Code version/docs if env settings in settings.json appear ignored. [5][1]
Sources
[1] Claude Code settings (settings.json, user & project settings).
[2] Claude Code CLI reference (commands/flags & config file locations).
[3] Claude Code SDK — Authentication (ANTHROPIC_API_KEY, Bedrock/Vertex).
[4] Community config reference (example ~/.claude config).
[5] Third‑party integration note (env loading / ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN).
The directory-based authentication check is unreliable and should verify the ANTHROPIC_API_KEY environment variable instead.
Web search confirms that Claude CLI authentication is primarily handled via the ANTHROPIC_API_KEY environment variable (or provider-specific env vars for enterprise), not by checking directory existence. While ~/.claude stores settings.json, the directory's presence does not reliably indicate authentication is configured—a user could have the directory without credentials set, or vice versa.
Instead, the check should verify the relevant environment variable(s):
- For standard auth: check if
ANTHROPIC_API_KEYis set - For enterprise: check
CLAUDE_CODE_USE_BEDROCK,CLAUDE_CODE_USE_VERTEX, or similar provider flags alongside their respective credentials
🤖 Prompt for AI Agents
In @server/main.py around lines 123 - 127, The current directory-based check
using claude_dir and credentials is unreliable; change the logic so credentials
is true when the appropriate environment variables are present instead of
checking ~/.claude: check ANTHROPIC_API_KEY for standard auth and also consider
provider flags like CLAUDE_CODE_USE_BEDROCK or CLAUDE_CODE_USE_VERTEX combined
with their respective provider credential env vars; update the assignment of the
credentials variable (replace the claude_dir.exists() check) to test os.environ
for these keys so authentication detection is based on environment variables
rather than directory presence.
| # Patterns that indicate Claude CLI authentication errors | ||
| AUTH_ERROR_PATTERNS = [ | ||
| r"not\s+logged\s+in", | ||
| r"not\s+authenticated", | ||
| r"authentication\s+(failed|required|error)", | ||
| r"login\s+required", | ||
| r"please\s+(run\s+)?['\"]?claude\s+login", | ||
| r"unauthorized", | ||
| r"invalid\s+(token|credential|api.?key)", | ||
| r"expired\s+(token|session|credential)", | ||
| r"could\s+not\s+authenticate", | ||
| r"sign\s+in\s+(to|required)", | ||
| ] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🌐 Web query:
Claude CLI authentication error messages and login requirements
💡 Result:
Summary — common Claude (Claude Code / claude CLI) authentication errors and what they mean
-
"Missing API key · Run /login" — CLI/IDE couldn’t find a stored session or ANTHROPIC_API_KEY; run the interactive /login inside claude or set ANTHROPIC_API_KEY in your environment (export ANTHROPIC_API_KEY=sk-...). [1][2]
-
"Invalid API key · Please run /login" — the provided API key is rejected or not accepted by the current auth flow (CLI sometimes expects a session from /login rather than a raw API key); re-check key value, ensure it’s an Anthropic API key, or run /login to authenticate. [2][3]
-
Errors about Cloudflare/verification or web-based auth failures — when the browser-based auth flow is blocked (e.g., Cloudflare checks or SSO/browser restrictions) the CLI cannot complete interactive /login; resolve by allowing the browser flow or using an API key if the CLI build supports it. (Users have reported this preventing login.) [3]
-
"Please run setup-token" (or instructions referencing setup-token) — some CLI workflows expect a subscription/session-based token; use claude setup-token if your account/subscription supports it, or use ANTHROPIC_API_KEY for direct API access if the CLI version supports it. [1][2]
Quick checklist to fix auth problems
- If automation/non-interactive: export ANTHROPIC_API_KEY with a valid Anthropic API key and retry. [1]
- If interactive CLI/IDE: run /login from within claude to open the browser auth flow and complete sign-in. [1][3]
- If browser flow is blocked: allow the browser auth, disable blocking proxies/Cloudflare checks, or use an API-key-compatible CLI version. [3]
- If errors persist: check ~/.config/claude/config.json for conflicting config and update CLI to the latest release. [1][3]
Sources
- Anthropic Claude Code quickstart / CLI auth docs. [Anthropic documentation]. [1]
- Claude CLI docs / integration notes (environment variable ANTHROPIC_API_KEY; setup-token mention). [2]
- GitHub issue reports describing "Missing API key · Run /login" and Cloudflare/browser auth failures. [3]
Would you like exact command examples for exporting keys, running /login, or checking your config file?
🏁 Script executed:
# Find the is_auth_error function and understand pattern usage
rg -A 10 "is_auth_error|AUTH_ERROR_PATTERNS" server/services/process_manager.pyRepository: leonvanzyl/autocoder
Length of output: 1944
🏁 Script executed:
# Search for any test files that might show expected error messages
fd -e test.py -e spec.py -o -e "*test*.py" | xargs rg -l "AUTH_ERROR|auth.*error" 2>/dev/null | head -5Repository: leonvanzyl/autocoder
Length of output: 241
🏁 Script executed:
# Look for any claude CLI or authentication-related documentation in the repo
fd -type f \( -name "*.md" -o -name "*.txt" -o -name "*.rst" \) | xargs rg -l "claude.*login|authentication.*error|not.*logged" 2>/dev/null | head -10Repository: leonvanzyl/autocoder
Length of output: 361
Add missing patterns for API key and setup-token errors.
The patterns cover most common authentication errors well, but the web documentation reveals gaps:
-
"Missing API key · Run /login" — The current
invalid\s+(token|credential|api.?key)pattern covers "Invalid API key" but misses the "missing" variant. Add pattern:r"missing\s+(api.?key|session)" -
"Please run setup-token" — Not covered by any current pattern. Add pattern:
r"setup.?token"
These additions would ensure more comprehensive coverage of Claude CLI authentication error messages as documented.
🤖 Prompt for AI Agents
In @server/services/process_manager.py around lines 39 - 51, Update the
AUTH_ERROR_PATTERNS list to include two additional regexes to catch missing API
key/session and setup-token messages: add a pattern matching "missing api key"
or "missing session" (e.g., r"missing\s+(api.?key|session)") and a pattern
matching setup-token mentions (e.g., r"setup.?token"); ensure these new patterns
are appended to the AUTH_ERROR_PATTERNS array so functions that scan error
strings (using AUTH_ERROR_PATTERNS) will detect "Missing API key · Run /login"
and "Please run setup-token" cases.
|
@mantarayDigital Thank you! |
This commit addresses issues found during review of PRs #12 and #28: ## PR #12 (Auth Error Handling) Fixes - Create shared auth.py module with centralized AUTH_ERROR_PATTERNS, is_auth_error(), and print_auth_error_help() functions - Fix start.bat to use directory check instead of outdated .credentials.json file check (matching start.sh behavior) - Update process_manager.py to import from shared auth module - Update start.py to import from shared auth module - Update documentation comments in autonomous_agent_demo.py and client.py to remove references to deprecated .credentials.json ## PR #28 (Feature Management) Improvements - Add _priority_lock threading lock to feature_mcp.py to prevent race conditions when multiple features are created simultaneously - Apply lock to feature_create, feature_create_bulk, and feature_skip - Add checkAndSendTimeoutRef cleanup in useAssistantChat.ts to prevent memory leaks on component unmount - Clear currentAssistantMessageRef on response_done ## Code Quality - All Python files pass ruff linting - All security tests pass (91/91) - UI passes ESLint and TypeScript compilation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Verified GET /api/projects endpoint returns correct data: - HTTP 200 status code - JSON array of all registered projects - Each project has name, path, createdAt fields - Tested with curl and browser automation - Screenshot captured for verification Feature AutoForgeAI#12 marked as passing (12/230 features now complete) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…geAI#12 - ProjectsPage now fetches projects from GET /api/projects endpoint - Displays each project with name, path, and createdAt fields - Added loading spinner while fetching data - Added error handling for API failures - Added empty state when no projects exist - Each project card has a View link to navigate to project details - Supports dark mode theming Fixes regression where ProjectsPage was a placeholder showing only heading Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Created 2 test projects via POST /api/projects - Verified GET /api/projects returns 200 with array of projects - Each project contains name, path, createdAt fields - Browser verification confirms Projects page displays all projects - Screenshots captured for API response and UI Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* feat(database): Add Bug SQLAlchemy model for bug tracking - Add Bug class with all required fields (severity, source, status, etc.) - Add to_dict() method for JSON serialization - Create _migrate_create_bugs_table() migration function - Register migration in create_database() - Add BUG_SEVERITIES, BUG_STATUSES, BUG_SOURCES, BUG_CATEGORIES constants Feature #1: Bug database model - verified complete Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: update progress notes for Bug database model Feature #1 complete - Bug SQLAlchemy model implemented Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(triage): Add bug triage engine for auto-triage and priority scoring - Create api/bug_triage.py with pattern matching for severity and category - SEVERITY_PATTERNS: critical, high, medium, low with regex patterns - CATEGORY_PATTERNS: auth, api, database, ui, testing with regex patterns - auto_triage_bug(): Analyze title/error/stack_trace to determine severity/category - compute_priority_score(): Calculate priority from severity, age, and source factors Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: update progress notes for Bug triage engine Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(schemas): Add Bug Pydantic schemas for bug tracking API Added complete set of Pydantic schemas for bug management: - BugSeverity/BugStatus type aliases with Literal types - BugCreate: request schema with auto-detect severity option - BugUpdate: partial update schema with all optional fields - BugResponse: response schema with all Bug model fields - BugListResponse: paginated bug list with total count - BugStatsResponse: statistics with counts by severity/status Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: update progress notes for Bug Pydantic schemas Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(api): Add Bug REST API router for bug tracking - Create server/routers/bugs.py with full CRUD endpoints - GET /: List bugs with filters (severity, status, limit, offset) - POST /: Create bug with auto-triage support - GET /stats: Return bug statistics - GET/PATCH/DELETE /{bug_id}: Single bug operations - POST /{bug_id}/retry: Reset bug to 'new' status - POST /{bug_id}/escalate: Set severity to 'critical' - Follow existing router patterns (lazy imports, get_db_session) - Use HTTPException for proper error handling Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix regression: Register bugs_router in server - Added bugs_router import in server/routers/__init__.py - Added bugs_router to __all__ exports - Added bugs_router import in server/main.py - Added app.include_router(bugs_router) to register endpoints The Bug REST API router was implemented but never wired up to the FastAPI application, making all /api/projects/{name}/bugs endpoints inaccessible. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(ui): Add Bug React hooks for bug tracking API - Add bug types to ui/src/lib/types.ts (Bug, BugCreate, BugUpdate, BugStats, BugFilters, BugListResponse) - Add API functions to ui/src/lib/api.ts (getBugs, getBugStats, getBug, createBug, updateBug, deleteBug, retryBug, escalateBug) - Create ui/src/hooks/useBugs.ts with React Query hooks: - useBugs: List bugs with optional filters (10s refetch) - useBugStats: Get bug statistics (10s refetch) - useBug: Get single bug by ID - useCreateBug: Create new bug report - useUpdateBug: Update existing bug - useDeleteBug: Delete a bug - useRetryBug: Reset bug to 'new' status - useEscalateBug: Set severity to 'critical' - All hooks follow established patterns from useRefinement.ts - Verified with TypeScript compiler (npm run build) Implements Feature AutoForgeAI#8 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: update progress notes for Bug React hooks (Feature AutoForgeAI#8) * feat(ui): Add BugSeverityBadge component for bug tracking - Create BugSeverityBadge.tsx with severity-based color coding - Support 'critical', 'high', 'medium', 'low' severity levels - Show AlertTriangle icon for critical and high severity - Use neo-badge classes with 'sm' and 'md' size variants - Color mapping: critical=red, high=orange, medium=yellow, low=gray Feature AutoForgeAI#9: BugSeverityBadge component - PASSING Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: update progress notes for BugSeverityBadge (Feature AutoForgeAI#9) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(service): Add BugWatcherService for background bug triage - Create server/services/bug_watcher_service.py following pr_watcher.py pattern - Implement BugWatcherService class with poll_interval=30s - Add _poll_bugs() to auto-triage new bugs (severity/category detection) - Add _check_stale_bugs() to detect bugs stuck >24h in investigating/fixing - Implement start()/stop() async methods for lifespan integration - Add module-level singleton: get_bug_watcher(), cleanup_bug_watcher() Feature AutoForgeAI#5 complete Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: update progress notes for Bug watcher service (Feature AutoForgeAI#5) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(ui): Add BugCard component for bug list display - Create BugCard.tsx following FeatureCard.tsx pattern - Display bug severity badge (top-right), title with line-clamp-2 - Show status badge with color coding for all bug statuses - Display category badge when present - Show relative created time (e.g., "2h ago") using inline helper - Show source indicator (API, Webhook, Regression, Test) if not manual - Use neo-card styling with hover effect - Feature AutoForgeAI#10 marked as passing Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(mcp): Add Bug MCP tools for bug management Implemented 5 new MCP tools for bug tracking and agent assignment: - bug_get_assigned: Get bug assigned to a specific agent - bug_update_status: Update bug status with optional notes - bug_mark_fixed: Mark bug as fixed and ready for testing - bug_get_next: Get highest priority triaged bugs - bug_claim: Claim a bug for investigation by an agent All tools follow existing patterns with: - @mcp.tool() decorator - Annotated type hints with Field validation - JSON return format - Proper session handling and error rollback Feature AutoForgeAI#7 - Bug MCP tools - PASSING Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: Update progress notes for Bug MCP tools (Feature AutoForgeAI#7) Progress: 9/12 features passing (75%) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(server): Register bug watcher service in FastAPI lifespan - Import get_bug_watcher and cleanup_bug_watcher from bug_watcher_service - Start bug watcher during lifespan startup (after PR watcher) - Cleanup bug watcher during lifespan shutdown (after PR watcher cleanup) - Bugs router was already registered in a previous commit Feature AutoForgeAI#6: Server registration for bugs - PASSING Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: Update progress notes for Feature AutoForgeAI#6 - Server registration for bugs now PASSING - Bug watcher service registered in FastAPI lifespan - Progress: 10/12 features (83.3%) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(ui): Add BugReportModal component for bug reporting - Create modal form using Radix Dialog for accessibility - Add form fields: title (required), error message, stack trace (monospace), reproduction steps - Add optional severity and category selects with auto-detect option - Use useCreateBug mutation with loading state and error handling - Follow neobrutalism design with neo-input, neo-btn styling - Reset form on close, prevent close during submission Implements Feature AutoForgeAI#12: BugReportModal component Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(ui): Add BugList component for bug list view - Implements filterable bug list with severity and status filters - Uses useBugs hook for data fetching with 10s auto-refresh - Displays bugs in responsive grid (1/2/3 cols) using BugCard - Shows loading skeleton while fetching (KanbanBoard pattern) - Shows empty state when no bugs match filters - Integrates BugReportModal for creating new bug reports - TypeScript verified, build passing Implements Feature AutoForgeAI#11 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: Update progress notes for Feature AutoForgeAI#11 (BugList component) All 12 features now passing (100% complete) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address code review issues for bug watcher feature Critical fixes: - Add input validation for bug category field against BUG_CATEGORIES - Add input validation for bug source field against BUG_SOURCES High priority fixes: - Add atomic locking to bug_claim MCP tool to prevent race conditions - Add CHECK constraints to Bug model for data integrity (severity, status, source, category, priority_score) - Add retry decorator for database lock errors in bugs router Medium priority fixes: - Optimize get_bug_stats to use SQL aggregates instead of loading all bugs - Add text length limit in bug triage to prevent excessive processing - Fix Path import conflict in refinement.py (pathlib.Path vs fastapi.Path) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Admin <admin@localhost> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
…ture AutoForgeAI#12 - Added list_agent_specs endpoint with filtering and pagination - Query parameters: task_type, source_feature_id, tags, limit, offset - Filter by task_type with validation (coding, testing, refactoring, etc.) - Filter by source_feature_id for linked features - Filter by tags using SQLite JSON functions - Returns AgentSpecListResponse with pagination metadata - X-Total-Count header for pagination UI - Added test script for router verification - Fixed schema exports in server/schemas/__init__.py Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Added detailed verification summary for GET /api/agent-specs endpoint - Documented all test commands and their results Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…redentials-check fix: Comprehensive authentication error handling
This commit addresses issues found during review of PRs AutoForgeAI#12 and AutoForgeAI#28: ## PR AutoForgeAI#12 (Auth Error Handling) Fixes - Create shared auth.py module with centralized AUTH_ERROR_PATTERNS, is_auth_error(), and print_auth_error_help() functions - Fix start.bat to use directory check instead of outdated .credentials.json file check (matching start.sh behavior) - Update process_manager.py to import from shared auth module - Update start.py to import from shared auth module - Update documentation comments in autonomous_agent_demo.py and client.py to remove references to deprecated .credentials.json ## PR AutoForgeAI#28 (Feature Management) Improvements - Add _priority_lock threading lock to feature_mcp.py to prevent race conditions when multiple features are created simultaneously - Apply lock to feature_create, feature_create_bulk, and feature_skip - Add checkAndSendTimeoutRef cleanup in useAssistantChat.ts to prevent memory leaks on component unmount - Clear currentAssistantMessageRef on response_done ## Code Quality - All Python files pass ruff linting - All security tests pass (91/91) - UI passes ESLint and TypeScript compilation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Summary
This PR provides comprehensive authentication error handling across all entry points:
start.sh,start_ui.sh)start.py)server/main.py,server/services/process_manager.py)Root Cause
Claude CLI no longer stores credentials at
~/.claude/.credentials.json. Multiple files in the codebase checked for this non-existent file, causing:Changes
1. start.sh - Shell Launcher
2. start.py - Python CLI Launcher
AUTH_ERROR_PATTERNS- 10 regex patterns to detect auth errorsis_auth_error()helper functionprint_auth_error_help()for consistent error messagingrun_spec_creation()to capture stderr and detect auth failuresrun_agent()to capture stderr and detect auth failures3. start_ui.sh - UI Shell Launcher
~/.claudedirectory check with login reminder4. server/main.py - Setup Status API
5. server/services/process_manager.py - Agent Process Streaming
AUTH_ERROR_PATTERNSandis_auth_error()helperAUTH_ERROR_HELPmessage template_stream_output()to detect auth errors in real-timeAuth Error Patterns Detected
Example Output
CLI (start.py)
Web UI (WebSocket stream)
Files Changed
start.shstart.pystart_ui.shserver/main.pyserver/services/process_manager.pyDesign Principles
Test Plan
./start.shwith Claude CLI installed → Shows directory found + reminder./start_ui.shwith Claude CLI installed → Shows status + reminder/api/setup/statusreturnscredentials: truewhen~/.claudeexists🤖 Generated with Claude Code
Summary by CodeRabbit
Refactor
Improvements
✏️ Tip: You can customize this high-level summary in your review settings.