Compare commits

..

7 Commits

Author SHA1 Message Date
AndyMik90 9fc7320158 feat(web): extract i18n namespaces, consolidate settings locale, and harden stores
Extract all hardcoded UI strings into i18n namespace JSON files (kanban,
views, integrations, layout). Consolidate duplicated settings keys from
layout namespace into dedicated settings namespace. Distinguish network
errors from API errors in task-store so connectivity issues show empty
state while server errors surface to the UI. Add test coverage for
Settings button accessibility.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 19:39:29 +01:00
AndyMik90 d64e999db5 feat(web): wire onboarding wizard, add config files and pre-existing hooks
Connect OnboardingWizard to AppShell via UI store. Add the remaining
web app config files (next.config.js, tsconfig.json, postcss.config.js),
auth layer, Convex hooks, API routes, and Dockerignore files that were
part of the skeleton but not yet tracked.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 16:09:21 +01:00
AndyMik90 85d6b18529 feat(web): add GitLab views, task creation wizard, onboarding, and keyboard shortcuts
- GitLabIssuesView with list/detail split pane matching GitHub pattern
- GitLabMRsView with approval tracking and AI review button
- TaskCreationWizard with 3-step flow (details, metadata, review)
- OnboardingWizard with step-by-step setup flow
- Keyboard shortcuts for all navigation views (K, N, D, I, L, C, G, P, B, R)
- Theme-aware rendering from settings store
- Sidebar now includes GitLab navigation items

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 16:05:36 +01:00
AndyMik90 737060902f feat(web): add full app shell with sidebar, navigation, and all major page views
Build the web app as a 1:1 replica of the Electron app's UI structure:
- Sidebar with navigation matching Electron app (kanban, insights, roadmap, ideation, changelog, context, GitHub)
- Project tab bar with multi-project support
- KanbanBoard with task cards, status columns, and task detail modal
- RoadmapView with board/timeline/list tabs and feature detail panel
- IdeationView with category filters and idea cards
- InsightsView with AI chat interface and session sidebar
- ChangelogView with expandable version entries
- ContextView with project overview, services, and memories tabs
- GitHubIssuesView and GitHubPRsView with list/detail split pane
- SettingsView with section-based navigation
- Dual-mode data layer (HTTP API + Convex) with Zustand stores
- Dark mode theme system matching Electron app's design tokens

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 16:02:20 +01:00
AndyMik90 062758bc1d refactor: rename libs/ to packages/ for consistency
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 15:51:13 +01:00
AndyMik90 435cc0733a chore: bump to v2.7.7 stable and fix libs build chain for npm publishing
- Update all package versions to 2.7.7 (removing beta flags)
- Fix libs/ui build chain: add TypeScript paths mapping for dev typecheck,
  override with empty paths in build config to use workspace resolution
- Sync roadmap types: add TaskOutcome type and taskOutcome/previousStatus
  fields to RoadmapFeature in libs/types (drifted during rebase)
- Add root build:libs script for ordered types → ui compilation
- Update @auto-claude/types peer dependency in libs/ui to 2.7.7

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 12:36:41 +01:00
Andy 5aac714b59 Cloud Phase 1 — OSS Repo Preparation: Extract shared types and UI into workspace packages (#1783)
* auto-claude: subtask-1-1 - Create libs/types/ and libs/ui/ package scaffolding

* auto-claude: subtask-1-2 - Add @auto-claude/types and @auto-claude/ui as workspace deps

Add workspace package dependencies to apps/frontend/package.json and verify
npm workspace resolution creates correct symlinks in node_modules/@auto-claude/.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-2-1 - Copy all 11 portable type files from apps/frontend

Copies common.ts, task.ts, project.ts, settings.ts, agent.ts, kanban.ts,
changelog.ts, insights.ts, roadmap.ts, integrations.ts, pr-status.ts to
libs/types/src/. Creates constants.ts with inline type definitions for
ExecutionPhase, CompletablePhase, and SupportedLanguage. Updates import
paths in task.ts and settings.ts to use local constants.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-2-2 - Create cloud-specific types and future phase stubs

Add cloud.ts (Tier, CloudUser, SubscriptionStatus, FeatureFlag, TierLimits, Usage),
team.ts (Team, TeamMember, TeamRole), and Phase 3-6 stub types: billing.ts,
pr-lifecycle.ts, feedback.ts, sessions.ts with @stub JSDoc annotations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-2-3 - Create barrel exports and re-export layer

- libs/types/src/index.ts: barrel export for all shared type files
- apps/frontend/src/shared/types/index.ts: re-exports from @auto-claude/types
  plus Electron-specific types (terminal, ipc, screenshot, etc.)
- Fix duplicate ExecutionPhase export conflict in task.ts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-3-1 - Extract cn() utility and theme CSS to libs/ui

- Create libs/ui/src/utils.ts with cn() (clsx + tailwind-merge)
- Create libs/ui/src/styles/theme.css with @theme block, all 7 color
  themes (default, dusk, lime, ocean, retro, neo, forest) with
  light/dark variants
- Update frontend utils.ts to re-export cn() from @auto-claude/ui
- Export cn and ClassValue from libs/ui/src/index.ts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-3-2 - Extract all 26 shadcn/ui primitive components to libs/ui

Copies all 26 UI primitives from apps/frontend/src/renderer/components/ui/
to libs/ui/src/primitives/ with updated imports:
- cn() import changed from '../../lib/utils' to '../utils'
- error-boundary: removed Sentry dependency, added optional onError prop
- toaster/use-toast: updated internal imports to local primitives
- input/textarea: kept react-i18next import (peer dependency)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-3-3 - Create primitives barrel export and wire up UI re-exports

- Create libs/ui/src/primitives/index.ts barrel export for all 26 primitives + useToast
- Create libs/ui/components.json for shadcn CLI compatibility
- Update libs/ui/src/index.ts to re-export primitives
- Replace all frontend UI component files with one-line re-exports from @auto-claude/ui
- Update frontend components/ui/index.ts to re-export from @auto-claude/ui/primitives
- Update globals.css: import shared theme.css, add @source directive, remove extracted @theme and color selectors
- Update use-toast hook to re-export from @auto-claude/ui
- Add @auto-claude/ui path mappings to frontend tsconfig.json

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-4-1 - Build three core feature gating components

Add FeatureGate, UsageLimitGate, and UpgradePrompt components to
libs/ui/src/core/ with tier hierarchy comparison, usage quota
enforcement, and upgrade CTA display.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-4-2 - Build auth-related components in libs/ui/src/core/

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-5-1 - Build spec management components in libs/ui/src/specs/

Add SpecCard, SpecList, and SpecEditor components as pure prop-driven
UI components for spec/task management. SpecCard displays a single task
with status badge, metadata, and action buttons. SpecList renders a
filterable/sortable list with loading and empty states. SpecEditor
provides a form for creating/editing specs with classification fields
and model selection.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-5-2 - Build persona management components in libs/ui/src

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-6-1 - Update build config for workspace packages

- Add @auto-claude/types and @auto-claude/ui to externalizeDepsPlugin exclude
  list so they are bundled (not externalized) in main process builds
- Add resolve.alias entries for workspace packages pointing to source dirs
  for proper Vite resolution and HMR support
- Add @auto-claude/types paths to tsconfig.json for TypeScript resolution
- Include libs/types/src in tsconfig include array
- Fix CSS import paths in globals.css (4 levels -> 5 levels to reach repo root)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-6-2 - Fix UI package exports and verify full build suite

Add explicit export mapping for use-toast.ts in @auto-claude/ui package
to fix resolution of .ts files alongside .tsx glob pattern.

Verification results:
- libs/types: tsc --noEmit ✓
- libs/ui: tsc --noEmit ✓
- apps/frontend: typecheck ✓, lint ✓ (warnings only), 3048 tests passed, build ✓

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* auto-claude: subtask-6-3 - Create GitHub Actions workflow for npm package publishing

Add publish-packages.yml workflow that:
- Triggers on v* tag pushes to build and publish @auto-claude/types and @auto-claude/ui
- Validates with typecheck on libs/types, libs/ui, and frontend + frontend tests
- Runs dry-run publish on PRs touching libs/ to catch issues early
- Publishes both packages with --access public using NPM_TOKEN secret

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: Address PR review findings for OSS repo preparation

- Restore Sentry error reporting in ErrorBoundary by creating a
  wrapper in the frontend app that injects captureException as onError
- Add react-i18next and i18next as peerDependencies in libs/ui
- Add explicit directory exports (primitives, core, specs, personas)
  to libs/ui package.json for proper Node.js module resolution
- Fix .replace('_', ' ') to .replace(/_/g, ' ') in SpecCard and
  SpecEditor to handle categories with multiple underscores
- Add currentTier/upgradeTier props to UsageLimitGate instead of
  hardcoding 'pro'/'free'
- Add configurable label props with English defaults to ErrorBoundary,
  LoginForm, UpgradePrompt, AuthGate, UsageLimitGate, PersonaManager,
  and SpecEditor for i18n support at the consumer level
- Replace raw HTML input/select/button elements with shared Input,
  Label, Button primitives in PersonaManager and SpecEditor
- Clean up duplicate IPCResult type: update ipc.ts and mcp-api.ts to
  import from @auto-claude/types, convert common.ts to re-export
- Export new Labels types from barrel files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: Add --provenance flag to npm publish commands

The workflow already requests id-token: write for OIDC attestation
but the publish commands were missing the --provenance flag, making
the permission unused. Adding provenance enables npm supply chain
attestation for published packages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: Add build step for npm packages, fix duplicate CSS, add publish recovery

- Add tsconfig.build.json for both @auto-claude/types and @auto-claude/ui
  that compiles TypeScript to JavaScript + declaration files in dist/
- Add build/clean/prepublishOnly scripts to both package.json files
- Update exports to use conditional exports with types + default conditions
  pointing to compiled dist/ output (source still shipped for reference)
- Add build steps to all CI workflow jobs (validate, dry-run, publish)
- Add version-exists check before each npm publish to handle re-runs
  gracefully when one package published but the other failed
- Remove redundant NPM_TOKEN env blocks from publish steps (already
  configured via .npmrc)
- Remove duplicate .progress-working CSS definition in globals.css that
  silently overrode the themed glow-sweep animation with a plain white
  shimmer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: Add tag-version validation, improve publish error handling, fix ErrorBoundary shadowing

- Add tag-to-package version validation step in publish workflow to
  catch mismatches before attempting to publish
- Improve version-exists check to distinguish network errors from
  "not published" state instead of swallowing all errors
- Re-export Sentry-integrated ErrorBoundary from ui barrel to prevent
  base component from shadowing the app-level wrapper
- Remove unnecessary @auto-claude/ui from main process exclude list
  since it is not imported in src/main/

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: Use ::warning:: for optimistic publish, simplify ErrorBoundary to function component

- Change ::error:: to ::warning:: in publish workflow fallback branches
  since the step intentionally proceeds with publishing anyway
- Convert ErrorBoundary wrapper from class to function component since
  all error boundary logic is delegated to BaseErrorBoundary

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 10:55:18 +01:00
328 changed files with 22820 additions and 22151 deletions
+10
View File
@@ -0,0 +1,10 @@
node_modules
.next
.git
.env*
*.md
tests
scripts
guides
apps/frontend
apps/backend
+165
View File
@@ -0,0 +1,165 @@
# Publish OSS Packages to npm
#
# Builds and publishes @auto-claude/types and @auto-claude/ui to npm
# when a version tag is pushed. Includes a dry-run job on PRs to catch
# issues before release.
name: Publish Packages
on:
push:
tags:
- 'v*'
pull_request:
branches: [main, develop]
paths:
- 'packages/**'
- 'package.json'
- 'package-lock.json'
- '.github/workflows/publish-packages.yml'
concurrency:
group: publish-packages-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
# --------------------------------------------------------------------------
# Validate - Typecheck and test before publishing
# --------------------------------------------------------------------------
validate:
name: Validate packages
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js and install dependencies
uses: ./.github/actions/setup-node-frontend
with:
ignore-scripts: 'true'
- name: Typecheck @auto-claude/types
run: npx tsc --project packages/types/tsconfig.json --noEmit
- name: Typecheck @auto-claude/ui
run: npx tsc --project packages/ui/tsconfig.json --noEmit
- name: Build @auto-claude/types
run: npx tsc --project packages/types/tsconfig.build.json
- name: Build @auto-claude/ui
run: npx tsc --project packages/ui/tsconfig.build.json
- name: Typecheck frontend
working-directory: apps/frontend
run: npm run typecheck
- name: Run frontend tests
working-directory: apps/frontend
run: npm run test
# --------------------------------------------------------------------------
# Dry Run - Verify publish would succeed (PRs only)
# --------------------------------------------------------------------------
dry-run:
name: Publish dry run
runs-on: ubuntu-latest
needs: validate
if: github.event_name == 'pull_request'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js and install dependencies
uses: ./.github/actions/setup-node-frontend
with:
ignore-scripts: 'true'
- name: Build @auto-claude/types
run: npx tsc --project packages/types/tsconfig.build.json
- name: Build @auto-claude/ui
run: npx tsc --project packages/ui/tsconfig.build.json
- name: Dry run publish @auto-claude/types
run: npm publish --workspace packages/types --dry-run
- name: Dry run publish @auto-claude/ui
run: npm publish --workspace packages/ui --dry-run
# --------------------------------------------------------------------------
# Publish - Push packages to npm (tagged releases only)
# --------------------------------------------------------------------------
publish:
name: Publish to npm
runs-on: ubuntu-latest
needs: validate
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
permissions:
contents: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js and install dependencies
uses: ./.github/actions/setup-node-frontend
with:
ignore-scripts: 'true'
- name: Configure npm authentication
run: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Validate tag matches package versions
run: |
TAG_VERSION="${GITHUB_REF#refs/tags/v}"
TYPES_VERSION=$(node -p "require('./packages/types/package.json').version")
UI_VERSION=$(node -p "require('./packages/ui/package.json').version")
echo "Tag version: ${TAG_VERSION}"
echo "types version: ${TYPES_VERSION}"
echo "ui version: ${UI_VERSION}"
if [ "$TAG_VERSION" != "$TYPES_VERSION" ]; then
echo "::error::Tag v${TAG_VERSION} does not match @auto-claude/types version ${TYPES_VERSION}"
exit 1
fi
if [ "$TAG_VERSION" != "$UI_VERSION" ]; then
echo "::error::Tag v${TAG_VERSION} does not match @auto-claude/ui version ${UI_VERSION}"
exit 1
fi
- name: Build @auto-claude/types
run: npx tsc --project packages/types/tsconfig.build.json
- name: Build @auto-claude/ui
run: npx tsc --project packages/ui/tsconfig.build.json
- name: Publish @auto-claude/types
run: |
PACKAGE_VERSION=$(node -p "require('./packages/types/package.json').version")
HTTP_CODE=$(npm view "@auto-claude/types@${PACKAGE_VERSION}" version --json 2>&1) && RC=$? || RC=$?
if [ $RC -eq 0 ] && echo "$HTTP_CODE" | grep -q "$PACKAGE_VERSION"; then
echo "::notice::@auto-claude/types@${PACKAGE_VERSION} already published, skipping"
elif echo "$HTTP_CODE" | grep -qi "E404\|not found\|is not in this registry"; then
npm publish --workspace packages/types --access public --provenance
else
echo "::warning::Unexpected error checking @auto-claude/types@${PACKAGE_VERSION}: ${HTTP_CODE}"
npm publish --workspace packages/types --access public --provenance
fi
- name: Publish @auto-claude/ui
run: |
PACKAGE_VERSION=$(node -p "require('./packages/ui/package.json').version")
HTTP_CODE=$(npm view "@auto-claude/ui@${PACKAGE_VERSION}" version --json 2>&1) && RC=$? || RC=$?
if [ $RC -eq 0 ] && echo "$HTTP_CODE" | grep -q "$PACKAGE_VERSION"; then
echo "::notice::@auto-claude/ui@${PACKAGE_VERSION} already published, skipping"
elif echo "$HTTP_CODE" | grep -qi "E404\|not found\|is not in this registry"; then
npm publish --workspace packages/ui --access public --provenance
else
echo "::warning::Unexpected error checking @auto-claude/ui@${PACKAGE_VERSION}: ${HTTP_CODE}"
npm publish --workspace packages/ui --access public --provenance
fi
+1
View File
@@ -119,6 +119,7 @@ apps/frontend/node_modules
# Build output
dist/
out/
.next
*.tsbuildinfo
apps/frontend/python-runtime/
+4 -31
View File
@@ -127,13 +127,6 @@ fi
if git diff --cached --name-only | grep -q "^apps/backend/.*\.py$"; then
echo "Python changes detected, running backend checks..."
# Detect if we're in a worktree
IS_WORKTREE=false
if [ -f ".git" ]; then
# .git is a file (not directory) in worktrees
IS_WORKTREE=true
fi
# Determine ruff command (venv or global)
RUFF=""
if [ -f "apps/backend/.venv/bin/ruff" ]; then
@@ -165,16 +158,7 @@ if git diff --cached --name-only | grep -q "^apps/backend/.*\.py$"; then
echo "$STAGED_PY_FILES" | xargs git add
fi
else
if [ "$IS_WORKTREE" = true ]; then
echo ""
echo "⚠️ WARNING: ruff not available in this worktree."
echo " Python linting checks will be skipped."
echo " This is expected for auto-claude worktrees."
echo " Full validation will occur when PR is created/merged."
echo ""
else
echo "Warning: ruff not found, skipping Python linting. Install with: uv pip install ruff"
fi
echo "Warning: ruff not found, skipping Python linting. Install with: uv pip install ruff"
fi
# Run pytest (skip slow/integration tests and Windows-incompatible tests for pre-commit speed)
@@ -208,28 +192,17 @@ if git diff --cached --name-only | grep -q "^apps/backend/.*\.py$"; then
elif [ -d "apps/backend/.venv" ]; then
echo "Warning: venv exists but Python not found in it, using system Python"
PYTHONPATH=apps/backend python -m pytest tests/ -v --tb=short -x -m "not slow and not integration" -k "not windows_path" $IGNORE_TESTS
elif [ "$IS_WORKTREE" = true ]; then
echo ""
echo "⚠️ WARNING: Python venv not available in this worktree."
echo " Python tests will be skipped."
echo " This is expected for auto-claude worktrees."
echo " Full validation will occur when PR is created/merged."
echo ""
exit 77 # GNU convention for 'test skipped' (avoids pytest exit-code collision)
else
echo "Warning: No .venv found in apps/backend, using system Python"
PYTHONPATH=apps/backend python -m pytest tests/ -v --tb=short -x -m "not slow and not integration" -k "not windows_path" $IGNORE_TESTS
fi
)
PYTHON_EXIT=$?
if [ $PYTHON_EXIT -eq 77 ]; then
echo "Backend checks passed! (Python tests skipped — worktree)"
elif [ $PYTHON_EXIT -ne 0 ]; then
if [ $? -ne 0 ]; then
echo "Python tests failed. Please fix failing tests before committing."
exit 1
else
echo "Backend checks passed!"
fi
echo "Backend checks passed!"
fi
# =============================================================================
+20 -12
View File
@@ -97,8 +97,9 @@ repos:
- id: ruff-format
files: ^apps/backend/
# Python tests (apps/backend/) - run full test suite from project root
# Python tests (apps/backend/) - skip slow/integration tests for pre-commit speed
# Tests to skip: graphiti (external deps), merge_file_tracker/service_orchestrator/worktree/workspace (Windows path/git issues)
# NOTE: Skip this hook in worktrees (where .git is a file, not a directory)
- repo: local
hooks:
- id: pytest
@@ -107,24 +108,31 @@ repos:
args:
- -c
- |
# Run pytest directly from project root
if [ -f "apps/backend/.venv/bin/pytest" ]; then
PYTEST_CMD="apps/backend/.venv/bin/pytest"
elif [ -f "apps/backend/.venv/Scripts/pytest.exe" ]; then
PYTEST_CMD="apps/backend/.venv/Scripts/pytest.exe"
# Skip in worktrees - .git is a file pointing to main repo, not a directory
# This prevents path resolution issues with ../../tests/ in worktree context
if [ -f ".git" ]; then
echo "Skipping pytest in worktree (path resolution would fail)"
exit 0
fi
cd apps/backend
if [ -f ".venv/bin/pytest" ]; then
PYTEST_CMD=".venv/bin/pytest"
elif [ -f ".venv/Scripts/pytest.exe" ]; then
PYTEST_CMD=".venv/Scripts/pytest.exe"
else
PYTEST_CMD="python -m pytest"
fi
$PYTEST_CMD tests/ \
PYTHONPATH=. $PYTEST_CMD \
../../tests/ \
-v \
--tb=short \
-x \
-m "not slow and not integration" \
--ignore=tests/test_graphiti.py \
--ignore=tests/test_merge_file_tracker.py \
--ignore=tests/test_service_orchestrator.py \
--ignore=tests/test_worktree.py \
--ignore=tests/test_workspace.py
--ignore=../../tests/test_graphiti.py \
--ignore=../../tests/test_merge_file_tracker.py \
--ignore=../../tests/test_service_orchestrator.py \
--ignore=../../tests/test_worktree.py \
--ignore=../../tests/test_workspace.py
language: system
files: ^(apps/backend/.*\.py$|tests/.*\.py$)
pass_filenames: false
-9
View File
@@ -52,15 +52,6 @@ Auto Claude is a desktop application (+ CLI) where users describe a goal and AI
**Electron path resolution** — For bug fixes in the Electron app, always check path resolution differences between dev and production builds (`app.isPackaged`, `process.resourcesPath`). Paths that work in dev often break when Electron is bundled for production — verify both contexts.
### Resetting PR Review State
To fully clear all PR review data so reviews run fresh, delete/reset these three things in `.auto-claude/github/`:
1. `rm .auto-claude/github/pr/logs_*.json` — review log files
2. `rm .auto-claude/github/pr/review_*.json` — review result files
3. Reset `pr/index.json` to `{"reviews": [], "last_updated": null}`
4. Reset `bot_detection_state.json` to `{"reviewed_commits": {}}` — this is the gatekeeper; without clearing it, the bot detector skips already-seen commits
## Project Structure
```
+13 -14
View File
@@ -8,7 +8,6 @@
[![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/KCXaPBr4Dj)
[![YouTube](https://img.shields.io/badge/YouTube-Subscribe-FF0000?style=flat-square&logo=youtube&logoColor=white)](https://www.youtube.com/@AndreMikalsen)
[![CI](https://img.shields.io/github/actions/workflow/status/AndyMik90/Auto-Claude/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/AndyMik90/Auto-Claude/actions)
[![Mentioned in Awesome Claude Code](https://awesome.re/mentioned-badge-flat.svg)](https://github.com/hesreallyhim/awesome-claude-code)
---
@@ -17,17 +16,17 @@
### Stable Release
<!-- STABLE_VERSION_BADGE -->
[![Stable](https://img.shields.io/badge/stable-2.7.5-blue?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.5)
[![Stable](https://img.shields.io/badge/stable-2.7.7-blue?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.7)
<!-- STABLE_VERSION_BADGE_END -->
<!-- STABLE_DOWNLOADS -->
| Platform | Download |
|----------|----------|
| **Windows** | [Auto-Claude-2.7.5-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.5-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.5-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.5-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-amd64.deb) |
| **Windows** | [Auto-Claude-2.7.7-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.7-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.7-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.7-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.7-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-linux-amd64.deb) |
| **Linux (Flatpak)** | [Auto-Claude-2.7.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-x86_64.flatpak) |
<!-- STABLE_DOWNLOADS_END -->
@@ -36,18 +35,18 @@
> ⚠️ Beta releases may contain bugs and breaking changes. [View all releases](https://github.com/AndyMik90/Auto-Claude/releases)
<!-- BETA_VERSION_BADGE -->
[![Beta](https://img.shields.io/badge/beta-2.7.6--beta.5-orange?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6-beta.5)
[![Beta](https://img.shields.io/badge/beta-2.7.6--beta.4-orange?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6-beta.4)
<!-- BETA_VERSION_BADGE_END -->
<!-- BETA_DOWNLOADS -->
| Platform | Download |
|----------|----------|
| **Windows** | [Auto-Claude-2.7.6-beta.5-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-beta.5-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.6-beta.5-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.6-beta.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.6-beta.5-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-amd64.deb) |
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-beta.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-x86_64.flatpak) |
| **Windows** | [Auto-Claude-2.7.6-beta.4-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-beta.4-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.6-beta.4-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.6-beta.4-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.6-beta.4-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-linux-amd64.deb) |
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-beta.4-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-linux-x86_64.flatpak) |
<!-- BETA_DOWNLOADS_END -->
> All releases include SHA256 checksums and VirusTotal scan results for security verification.
+1 -6
View File
@@ -67,9 +67,4 @@ tests/
# Auto Claude data directory
.auto-claude/
# Auto Claude generated files
.auto-claude-security.json
.auto-claude-status
.security-key
logs/security/
coverage.json
+1 -1
View File
@@ -19,5 +19,5 @@ Quick Start:
See README.md for full documentation.
"""
__version__ = "2.7.6-beta.5"
__version__ = "2.7.7"
__author__ = "Auto Claude Team"
@@ -31,7 +31,6 @@ class ProjectAnalyzer:
"""Run full project analysis."""
self._detect_project_type()
self._find_and_analyze_services()
self._aggregate_dependency_locations()
self._analyze_infrastructure()
self._detect_conventions()
self._map_dependencies()
@@ -125,63 +124,6 @@ class ProjectAnalyzer:
self.index["services"] = services
def _aggregate_dependency_locations(self) -> None:
"""Aggregate dependency location metadata from all services.
Collects dependency_locations from each service and stores them as
paths relative to the project root (e.g., 'apps/backend/.venv'
instead of just '.venv').
"""
aggregated: list[dict[str, Any]] = []
for service_name, service_info in self.index.get("services", {}).items():
service_deps = service_info.get("dependency_locations", [])
service_path = service_info.get("path", "")
# Compute service-relative prefix once per service
service_rel: Path | None = None
if service_path:
try:
service_rel = Path(service_path).relative_to(self.project_dir)
except ValueError:
# Service path is outside the project root — skip its deps
# to avoid producing absolute paths that bypass containment
continue
for dep in service_deps:
dep_path = dep.get("path")
if not dep_path:
continue
# Build project-relative path from service path + dep path
if service_rel is not None:
project_relative = str(service_rel / dep_path)
else:
project_relative = dep_path
entry: dict[str, Any] = {
"type": dep.get("type", "unknown"),
"path": project_relative,
"exists": dep.get("exists", False),
"service": service_name,
}
if dep.get("requirements_file"):
# Convert to project-relative path like we do for "path"
if service_rel is not None:
entry["requirements_file"] = str(
service_rel / dep["requirements_file"]
)
else:
entry["requirements_file"] = dep["requirements_file"]
pkg_mgr = dep.get("package_manager") or service_info.get(
"package_manager"
)
if pkg_mgr:
entry["package_manager"] = pkg_mgr
aggregated.append(entry)
self.index["dependency_locations"] = aggregated
def _analyze_infrastructure(self) -> None:
"""Analyze infrastructure configuration."""
infra = {}
@@ -40,8 +40,6 @@ class ServiceAnalyzer(BaseAnalyzer):
self._find_key_directories()
self._find_entry_points()
self._detect_dependencies()
self._detect_dependency_locations()
self._detect_package_manager()
self._detect_testing()
self._find_dockerfile()
@@ -211,121 +209,6 @@ class ServiceAnalyzer(BaseAnalyzer):
deps.append(match.group(1))
self.analysis["dependencies"] = deps[:20]
def _detect_dependency_locations(self) -> None:
"""Detect where dependencies live on disk for this service."""
locations: list[dict[str, Any]] = []
# Node.js: node_modules (only if package.json exists)
if self._exists("package.json"):
node_modules = self.path / "node_modules"
locations.append(
{
"type": "node_modules",
"path": "node_modules",
"exists": node_modules.exists() and node_modules.is_dir(),
}
)
# Python: .venv or venv
for venv_dir in [".venv", "venv"]:
venv_path = self.path / venv_dir
if venv_path.exists() and venv_path.is_dir():
entry: dict[str, Any] = {
"type": "venv",
"path": venv_dir,
"exists": True,
}
# Find requirements file
for req_file in ["requirements.txt", "pyproject.toml", "Pipfile"]:
if self._exists(req_file):
entry["requirements_file"] = req_file
break
locations.append(entry)
break
else:
# No venv found, still record requirements file if present
for req_file in ["requirements.txt", "pyproject.toml", "Pipfile"]:
if self._exists(req_file):
locations.append(
{
"type": "venv",
"path": ".venv",
"exists": False,
"requirements_file": req_file,
}
)
break
# PHP: vendor
vendor_path = self.path / "vendor"
if vendor_path.exists() and vendor_path.is_dir():
locations.append(
{
"type": "vendor_php",
"path": "vendor",
"exists": True,
}
)
# Rust: target
target_path = self.path / "target"
if target_path.exists() and target_path.is_dir():
locations.append(
{
"type": "cargo_target",
"path": "target",
"exists": True,
}
)
# Ruby: vendor/bundle
bundle_path = self.path / "vendor" / "bundle"
if bundle_path.exists() and bundle_path.is_dir():
locations.append(
{
"type": "vendor_bundle",
"path": "vendor/bundle",
"exists": True,
}
)
self.analysis["dependency_locations"] = locations
def _detect_package_manager(self) -> None:
"""Detect the package manager used by this service."""
# Node.js package managers
if self._exists("package-lock.json"):
self.analysis["package_manager"] = "npm"
elif self._exists("yarn.lock"):
self.analysis["package_manager"] = "yarn"
elif self._exists("pnpm-lock.yaml"):
self.analysis["package_manager"] = "pnpm"
elif self._exists("bun.lockb") or self._exists("bun.lock"):
self.analysis["package_manager"] = "bun"
# Python package managers
elif self._exists("Pipfile"):
self.analysis["package_manager"] = "pipenv"
elif self._exists("pyproject.toml"):
if self._exists("uv.lock"):
self.analysis["package_manager"] = "uv"
elif self._exists("poetry.lock"):
self.analysis["package_manager"] = "poetry"
else:
self.analysis["package_manager"] = "pip"
elif self._exists("requirements.txt"):
self.analysis["package_manager"] = "pip"
# Other
elif self._exists("Cargo.toml"):
self.analysis["package_manager"] = "cargo"
elif self._exists("go.mod"):
self.analysis["package_manager"] = "go_mod"
elif self._exists("Gemfile"):
self.analysis["package_manager"] = "gem"
elif self._exists("composer.json"):
self.analysis["package_manager"] = "composer"
else:
self.analysis["package_manager"] = None
def _detect_testing(self) -> None:
"""Detect testing framework and configuration."""
if self._exists("package.json"):
+8 -21
View File
@@ -10,7 +10,6 @@ import shutil
import subprocess
from pathlib import Path
from qa.criteria import is_fixes_applied, is_qa_approved, is_qa_rejected
from ui import highlight, print_status
@@ -152,22 +151,13 @@ def handle_batch_status_command(project_dir: str) -> bool:
except json.JSONDecodeError:
pass
# Determine status (highest priority first)
# Use authoritative QA status check, not just file existence
if is_qa_approved(spec_dir):
status = "qa_approved"
elif is_qa_rejected(spec_dir):
status = "qa_rejected"
elif is_fixes_applied(spec_dir):
status = "fixes_applied"
elif (spec_dir / "implementation_plan.json").exists():
# Check if there's a qa_report.md but no approval yet (QA in progress)
if (spec_dir / "qa_report.md").exists():
status = "qa_in_progress"
else:
status = "building"
elif (spec_dir / "spec.md").exists():
# Determine status
if (spec_dir / "spec.md").exists():
status = "spec_created"
elif (spec_dir / "implementation_plan.json").exists():
status = "building"
elif (spec_dir / "qa_report.md").exists():
status = "qa_approved"
else:
status = "pending_spec"
@@ -175,10 +165,7 @@ def handle_batch_status_command(project_dir: str) -> bool:
"pending_spec": "",
"spec_created": "📋",
"building": "⚙️",
"qa_in_progress": "🔍",
"qa_approved": "",
"qa_rejected": "",
"fixes_applied": "🔧",
"unknown": "",
}.get(status, "")
@@ -205,10 +192,10 @@ def handle_batch_cleanup_command(project_dir: str, dry_run: bool = True) -> bool
print_status("No specs directory found", "info")
return True
# Find completed specs (only QA-approved, matching status display logic)
# Find completed specs
completed = []
for spec_dir in specs_dir.iterdir():
if spec_dir.is_dir() and is_qa_approved(spec_dir):
if spec_dir.is_dir() and (spec_dir / "qa_report.md").exists():
completed.append(spec_dir.name)
if not completed:
+1 -1
View File
@@ -449,7 +449,7 @@ def _handle_build_interrupt(
if choice == "skip":
print()
print_status("Resuming build...", "info")
status_manager.update(state=BuildState.BUILDING)
status_manager.update(state=BuildState.RUNNING)
asyncio.run(
run_autonomous_agent(
project_dir=working_dir,
+7 -54
View File
@@ -694,25 +694,10 @@ def get_auth_token(config_dir: str | None = None) -> str | None:
Returns:
Token string if found, None otherwise
"""
_debug = os.environ.get("DEBUG", "").lower() in ("true", "1")
if _debug:
# Log which auth env vars are set (presence only, never values)
set_vars = [v for v in AUTH_TOKEN_ENV_VARS if os.environ.get(v)]
logger.info(
"[Auth] get_auth_token() called — config_dir param=%s, "
"env vars present: %s, CLAUDE_CONFIG_DIR env=%s",
repr(config_dir),
set_vars or "(none)",
"set" if os.environ.get("CLAUDE_CONFIG_DIR") else "unset",
)
# First check environment variables (highest priority)
for var in AUTH_TOKEN_ENV_VARS:
token = os.environ.get(var)
if token:
if _debug:
logger.info("[Auth] Token resolved from env var: %s", var)
return _try_decrypt_token(token)
# Check CLAUDE_CONFIG_DIR environment variable (profile's custom config directory)
@@ -720,13 +705,12 @@ def get_auth_token(config_dir: str | None = None) -> str | None:
effective_config_dir = config_dir or env_config_dir
# Debug: Log which config_dir is being used for credential resolution
if _debug and effective_config_dir:
debug = os.environ.get("DEBUG", "").lower() in ("true", "1")
if debug and effective_config_dir:
service_name = _get_keychain_service_name(effective_config_dir)
logger.info(
"[Auth] Resolving credentials for profile config_dir: %s "
"(Keychain service: %s)",
effective_config_dir,
service_name,
f"[Auth] Resolving credentials for profile config_dir: {effective_config_dir} "
f"(Keychain service: {service_name})"
)
# If a custom config directory is specified, read from there first
@@ -734,37 +718,24 @@ def get_auth_token(config_dir: str | None = None) -> str | None:
# Try reading from .credentials.json file in the config directory
token = _get_token_from_config_dir(effective_config_dir)
if token:
if _debug:
logger.info(
"[Auth] Token resolved from config dir file: %s",
effective_config_dir,
)
return _try_decrypt_token(token)
# Also try the system credential store with hash-based service name
# This is needed because macOS stores credentials in Keychain, not files
token = get_token_from_keychain(effective_config_dir)
if token:
if _debug:
logger.info("[Auth] Token resolved from Keychain (profile-specific)")
return _try_decrypt_token(token)
# If config_dir was explicitly provided, DON'T fall back to default keychain
# - that would return the wrong profile's token
logger.debug(
"No credentials found for config_dir '%s' in file or keychain",
effective_config_dir,
f"No credentials found for config_dir '{effective_config_dir}' "
"in file or keychain"
)
return None
# No config_dir specified - use default system credential store
keychain_token = get_token_from_keychain()
if _debug:
logger.info(
"[Auth] Token resolved from default Keychain: %s",
"found" if keychain_token else "not found",
)
return _try_decrypt_token(keychain_token)
return _try_decrypt_token(get_token_from_keychain())
def get_auth_token_source(config_dir: str | None = None) -> str | None:
@@ -999,18 +970,8 @@ def configure_sdk_authentication(config_dir: str | None = None) -> None:
- API profile mode: requires ANTHROPIC_AUTH_TOKEN
- OAuth mode: requires CLAUDE_CODE_OAUTH_TOKEN (from Keychain or env)
"""
_debug = os.environ.get("DEBUG", "").lower() in ("true", "1")
api_profile_mode = bool(os.environ.get("ANTHROPIC_BASE_URL", "").strip())
if _debug:
logger.info(
"[Auth] configure_sdk_authentication() — mode=%s, config_dir=%s, "
"CLAUDE_CONFIG_DIR env=%s",
"api_profile" if api_profile_mode else "oauth",
repr(config_dir),
"set" if os.environ.get("CLAUDE_CONFIG_DIR") else "unset",
)
if api_profile_mode:
# API profile mode: ensure ANTHROPIC_AUTH_TOKEN is present
if not os.environ.get("ANTHROPIC_AUTH_TOKEN"):
@@ -1038,14 +999,6 @@ def configure_sdk_authentication(config_dir: str | None = None) -> None:
os.environ["CLAUDE_CODE_OAUTH_TOKEN"] = oauth_token
logger.info("Using OAuth authentication")
if _debug:
logger.info(
"[Auth] SDK env check — CLAUDE_CONFIG_DIR=%s, "
"CLAUDE_CODE_OAUTH_TOKEN=%s",
"set" if os.environ.get("CLAUDE_CONFIG_DIR") else "unset",
"set" if os.environ.get("CLAUDE_CODE_OAUTH_TOKEN") else "unset",
)
def ensure_claude_code_oauth_token() -> None:
"""
+3 -31
View File
@@ -9,11 +9,8 @@ Enhanced with colored output, icons, and better visual formatting.
"""
import json
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
from core.plan_normalization import normalize_subtask_aliases
from ui import (
Icons,
@@ -233,8 +230,8 @@ def print_progress_summary(spec_dir: Path, show_next: bool = True) -> None:
f" {icon(Icons.ARROW_RIGHT)} Next: {highlight(next_id)} - {next_desc}"
)
except (OSError, json.JSONDecodeError, UnicodeDecodeError) as e:
logger.debug(f"Failed to load plan file for phase summary: {e}")
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
pass # Ignore corrupted/unreadable progress files
else:
print()
print_status("No implementation subtasks yet - planner needs to run", "pending")
@@ -407,8 +404,6 @@ def get_next_subtask(spec_dir: Path) -> dict | None:
"""
Find the next subtask to work on, respecting phase dependencies.
Skips subtasks that are marked as stuck in the recovery manager's attempt history.
Args:
spec_dir: Directory containing implementation_plan.json
@@ -420,23 +415,6 @@ def get_next_subtask(spec_dir: Path) -> dict | None:
if not plan_file.exists():
return None
# Load stuck subtasks from recovery manager's attempt history
stuck_subtask_ids = set()
attempt_history_file = spec_dir / "memory" / "attempt_history.json"
if attempt_history_file.exists():
try:
with open(attempt_history_file, encoding="utf-8") as f:
attempt_history = json.load(f)
# Collect IDs of subtasks marked as stuck
stuck_subtask_ids = {
entry["subtask_id"]
for entry in attempt_history.get("stuck_subtasks", [])
if "subtask_id" in entry
}
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
# If we can't read the file, continue without stuck checking
pass
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
@@ -477,15 +455,9 @@ def get_next_subtask(spec_dir: Path) -> dict | None:
if not deps_satisfied:
continue
# Find first pending subtask in this phase (skip stuck subtasks)
# Find first pending subtask in this phase
for subtask in phase.get("subtasks", phase.get("chunks", [])):
status = subtask.get("status", "pending")
subtask_id = subtask.get("id")
# Skip stuck subtasks
if subtask_id in stuck_subtask_ids:
continue
if status in {"pending", "not_started", "not started"}:
subtask_out, _changed = normalize_subtask_aliases(subtask)
subtask_out["status"] = "pending"
@@ -1,176 +0,0 @@
"""
Dependency Strategy Mapping
============================
Maps dependency types to sharing strategies for worktree creation.
Each dependency ecosystem has different constraints:
- **node_modules**: Safe to symlink. Node's resolution algorithm follows symlinks
correctly, and the directory is self-contained.
- **venv / .venv**: Must be recreated. Python's ``pyvenv.cfg`` discovery walks the
real directory hierarchy without resolving symlinks (CPython bug #106045), so a
symlinked venv resolves paths relative to the *target*, not the worktree.
- **vendor (PHP)**: Safe to symlink. Composer's autoloader uses ``__DIR__``-relative
paths that resolve correctly through symlinks.
- **cargo target / go modules**: Skip entirely. Rust's ``target/`` dir contains
per-machine build artifacts that must be rebuilt. Go uses a global module cache
(``$GOPATH/pkg/mod``), so there is nothing in-tree to share.
"""
from __future__ import annotations
import logging
import os
from pathlib import Path, PurePosixPath, PureWindowsPath
logger = logging.getLogger(__name__)
from .models import DependencyShareConfig, DependencyStrategy
# ---------------------------------------------------------------------------
# Default strategy map
# ---------------------------------------------------------------------------
# Maps dependency type identifiers to the strategy that should be used when
# sharing that dependency across worktrees. Data-driven — add new entries
# here rather than writing if/else branches.
# ---------------------------------------------------------------------------
DEFAULT_STRATEGY_MAP: dict[str, DependencyStrategy] = {
# JavaScript / Node.js — symlink is safe and fast
"node_modules": DependencyStrategy.SYMLINK,
# Python — venvs MUST be recreated (pyvenv.cfg symlink bug)
"venv": DependencyStrategy.RECREATE,
".venv": DependencyStrategy.RECREATE,
# PHP — Composer vendor dir is safe to symlink
"vendor_php": DependencyStrategy.SYMLINK,
# Ruby — Bundler vendor/bundle is safe to symlink
"vendor_bundle": DependencyStrategy.SYMLINK,
# Rust — build output dir, skip (rebuilt per-worktree)
"cargo_target": DependencyStrategy.SKIP,
# Go — global module cache, nothing in-tree to share
"go_modules": DependencyStrategy.SKIP,
}
def get_dependency_configs(
project_index: dict | None,
project_dir: Path | None = None,
) -> list[DependencyShareConfig]:
"""Derive dependency share configs from a project index.
If *project_index* is ``None`` or lacks ``dependency_locations``,
falls back to a hardcoded node_modules config for backward compatibility
with existing worktree setups.
Args:
project_index: Parsed ``project_index.json`` dict, or ``None``.
project_dir: Project root directory for resolved-path containment
checks (defense-in-depth). Should always be provided when
*project_index* is not ``None`` — omitting it disables the
resolved-path security check.
Returns:
List of :class:`DependencyShareConfig` objects — one per discovered
dependency location.
"""
configs: list[DependencyShareConfig] = []
seen: set[str] = set()
if project_index is not None:
if project_dir is None:
logger.warning(
"get_dependency_configs called with project_index but no "
"project_dir — resolved-path containment check is disabled"
)
# Use the aggregated top-level dependency_locations which already
# contain project-relative paths (e.g. "apps/backend/.venv" instead
# of just ".venv"). This avoids a monorepo path resolution bug
# where service-relative paths were incorrectly treated as project-
# relative.
dep_locations = project_index.get("dependency_locations") or []
for dep in dep_locations:
if not isinstance(dep, dict):
continue
dep_type = dep.get("type", "")
rel_path = dep.get("path", "")
if not dep_type or not rel_path:
continue
# Path containment: reject absolute paths and traversals.
# Check both POSIX and Windows path styles for cross-platform safety.
p = PurePosixPath(rel_path)
if p.is_absolute() or PureWindowsPath(rel_path).is_absolute():
continue
if ".." in p.parts or ".." in PureWindowsPath(rel_path).parts:
continue
# Defense-in-depth: verify the resolved path stays within project_dir
if project_dir is not None:
resolved = (project_dir / rel_path).resolve()
if not str(resolved).startswith(str(project_dir.resolve()) + os.sep):
continue
# Deduplicate by relative path
if rel_path in seen:
continue
seen.add(rel_path)
strategy = DEFAULT_STRATEGY_MAP.get(dep_type, DependencyStrategy.SKIP)
# Validate requirements_file path containment too
req_file = dep.get("requirements_file")
if req_file:
rp = PurePosixPath(req_file)
if (
rp.is_absolute()
or PureWindowsPath(req_file).is_absolute()
or ".." in rp.parts
or ".." in PureWindowsPath(req_file).parts
):
req_file = None
# Defense-in-depth: resolved-path containment (matches rel_path check)
if req_file and project_dir is not None:
resolved_req = (project_dir / req_file).resolve()
if not str(resolved_req).startswith(
str(project_dir.resolve()) + os.sep
):
req_file = None
configs.append(
DependencyShareConfig(
dep_type=dep_type,
strategy=strategy,
source_rel_path=rel_path,
requirements_file=req_file,
package_manager=dep.get("package_manager"),
)
)
# Fallback: if no configs were discovered, default to node_modules-only
# so existing worktree behaviour is preserved.
if not configs:
configs.append(
DependencyShareConfig(
dep_type="node_modules",
strategy=DependencyStrategy.SYMLINK,
source_rel_path="node_modules",
)
)
configs.append(
DependencyShareConfig(
dep_type="node_modules",
strategy=DependencyStrategy.SYMLINK,
source_rel_path="apps/frontend/node_modules",
)
)
return configs
-28
View File
@@ -273,31 +273,3 @@ class SpecNumberLock:
pass
return max_num
class DependencyStrategy(Enum):
"""Strategy for sharing dependency directories across worktrees.
SYMLINK is fast but unsafe for certain ecosystems. Notably, Python venv
breaks when symlinked because CPython's pyvenv.cfg discovery walks the
real directory hierarchy without resolving symlinks first
(CPython bug #106045). This means a symlinked venv resolves its home
path relative to the symlink target's parent, not the worktree, causing
import failures and broken interpreters.
"""
SYMLINK = "symlink" # Create a symlink to the source (fast, works for node_modules)
RECREATE = "recreate" # Re-run the package manager to create a fresh copy
COPY = "copy" # Deep-copy the directory (slow but always correct)
SKIP = "skip" # Do nothing; let the agent handle it
@dataclass
class DependencyShareConfig:
"""Configuration for how a specific dependency type should be shared."""
dep_type: str # e.g. "node_modules", "venv", ".venv"
strategy: DependencyStrategy
source_rel_path: str # Relative path from project root, e.g. "node_modules"
requirements_file: str | None = None # e.g. "requirements.txt", "pyproject.toml"
package_manager: str | None = None # e.g. "npm", "uv", "pip"
+80 -392
View File
@@ -14,7 +14,6 @@ import sys
from pathlib import Path
from core.git_executable import run_git
from core.platform import is_windows
from merge import FileTimelineTracker
from security.constants import ALLOWLIST_FILENAME, PROFILE_FILENAME
from ui import (
@@ -29,9 +28,8 @@ from ui import (
)
from worktree import WorktreeManager
from .dependency_strategy import get_dependency_configs
from .git_utils import has_uncommitted_changes
from .models import DependencyShareConfig, DependencyStrategy, WorkspaceMode
from .models import WorkspaceMode
# Import debug utilities
try:
@@ -191,37 +189,11 @@ def symlink_node_modules_to_worktree(
"""
Symlink node_modules directories from project root to worktree.
.. deprecated::
Use :func:`setup_worktree_dependencies` instead, which handles all
dependency types (node_modules, venvs, vendor dirs, etc.) via
strategy-based dispatch.
This ensures the worktree has access to dependencies for TypeScript checks
and other tooling without requiring a separate npm install.
This is a thin backward-compatibility wrapper that delegates to
``setup_worktree_dependencies()`` with no project index (fallback mode).
Args:
project_dir: The main project directory
worktree_path: Path to the worktree
Returns:
List of symlinked paths (relative to worktree)
"""
results = setup_worktree_dependencies(
project_dir, worktree_path, project_index=None
)
# Flatten all processed paths for backward-compatible return value
return [path for paths in results.values() for path in paths]
def symlink_claude_config_to_worktree(
project_dir: Path, worktree_path: Path
) -> list[str]:
"""
Symlink .claude/ directory from project root to worktree.
This ensures the worktree has access to Claude Code configuration
(settings, CLAUDE.md, MCP servers, etc.) so that terminals opened
in the worktree behave identically to the project root.
Works with npm workspace hoisting where dependencies are hoisted to root
and workspace-specific dependencies remain in nested node_modules.
Args:
project_dir: The main project directory
@@ -232,52 +204,81 @@ def symlink_claude_config_to_worktree(
"""
symlinked = []
source_path = project_dir / ".claude"
target_path = worktree_path / ".claude"
# Node modules locations to symlink for TypeScript and tooling support.
# These are the standard locations for this monorepo structure.
#
# Design rationale:
# - Hardcoded paths are intentional for simplicity and reliability
# - Dynamic discovery (reading workspaces from package.json) would add complexity
# and potential failure points without significant benefit
# - This monorepo uses npm workspaces with hoisting, so dependencies are primarily
# in root node_modules with workspace-specific deps in apps/frontend/node_modules
#
# To add new workspace locations:
# 1. Add (source_rel, target_rel) tuple below
# 2. Update the parallel TypeScript implementation in
# apps/frontend/src/main/ipc-handlers/terminal/worktree-handlers.ts
# 3. Update the pre-commit hook check in .husky/pre-commit if needed
node_modules_locations = [
("node_modules", "node_modules"),
("apps/frontend/node_modules", "apps/frontend/node_modules"),
]
# Skip if source doesn't exist
if not source_path.exists():
debug(MODULE, "Skipping .claude/ - source does not exist")
return symlinked
for source_rel, target_rel in node_modules_locations:
source_path = project_dir / source_rel
target_path = worktree_path / target_rel
# Skip if target already exists
if target_path.exists():
debug(MODULE, "Skipping .claude/ - target already exists")
return symlinked
# Skip if source doesn't exist
if not source_path.exists():
debug(MODULE, f"Skipping {source_rel} - source does not exist")
continue
# Also skip if target is a symlink (even if broken)
if target_path.is_symlink():
debug(MODULE, "Skipping .claude/ - symlink already exists (possibly broken)")
return symlinked
# Skip if target already exists (don't overwrite existing node_modules)
if target_path.exists():
debug(MODULE, f"Skipping {target_rel} - target already exists")
continue
# Ensure parent directory exists
target_path.parent.mkdir(parents=True, exist_ok=True)
try:
if sys.platform == "win32":
# On Windows, use junctions instead of symlinks (no admin rights required)
result = subprocess.run(
["cmd", "/c", "mklink", "/J", str(target_path), str(source_path)],
capture_output=True,
text=True,
# Also skip if target is a symlink (even if broken - exists() returns False for broken symlinks)
if target_path.is_symlink():
debug(
MODULE,
f"Skipping {target_rel} - symlink already exists (possibly broken)",
)
continue
# Ensure parent directory exists
target_path.parent.mkdir(parents=True, exist_ok=True)
try:
if sys.platform == "win32":
# On Windows, use junctions instead of symlinks (no admin rights required)
# Junctions require absolute paths
result = subprocess.run(
["cmd", "/c", "mklink", "/J", str(target_path), str(source_path)],
capture_output=True,
text=True,
)
if result.returncode != 0:
raise OSError(result.stderr or "mklink /J failed")
else:
# On macOS/Linux, use relative symlinks for portability
relative_source = os.path.relpath(source_path, target_path.parent)
os.symlink(relative_source, target_path)
symlinked.append(target_rel)
debug(MODULE, f"Symlinked {target_rel} -> {source_path}")
except OSError as e:
# Symlink/junction creation can fail on some systems (e.g., FAT32 filesystem)
# Log warning but don't fail - worktree is still usable, just without
# TypeScript checking
debug_warning(
MODULE,
f"Could not symlink {target_rel}: {e}. TypeScript checks may fail.",
)
# Warn user - pre-commit hooks may fail without dependencies
print_status(
f"Warning: Could not link {target_rel} - TypeScript checks may fail",
"warning",
)
if result.returncode != 0:
raise OSError(result.stderr or "mklink /J failed")
else:
# On macOS/Linux, use relative symlinks for portability
relative_source = os.path.relpath(source_path, target_path.parent)
os.symlink(relative_source, target_path)
symlinked.append(".claude")
debug(MODULE, f"Symlinked .claude/ -> {source_path}")
except OSError as e:
debug_warning(
MODULE,
f"Could not symlink .claude/: {e}. Claude Code features may not work in worktree terminals.",
)
print_status(
"Warning: Could not link .claude/ - Claude Code features may not work in terminals",
"warning",
)
return symlinked
@@ -373,33 +374,13 @@ def setup_workspace(
f"Environment files copied: {', '.join(copied_env_files)}", "success"
)
# Set up dependencies in worktree using strategy-based dispatch
# Load project index if available for ecosystem-aware dependency handling
project_index = None
project_index_path = project_dir / ".auto-claude" / "project_index.json"
if project_index_path.is_file():
try:
with open(project_index_path, encoding="utf-8") as f:
project_index = json.load(f)
debug(MODULE, "Loaded project_index.json for dependency setup")
except (OSError, json.JSONDecodeError) as e:
debug_warning(MODULE, f"Could not load project_index.json: {e}")
dep_results = setup_worktree_dependencies(
project_dir, worktree_info.path, project_index=project_index
)
for strategy_name, paths in dep_results.items():
if paths:
print_status(
f"Dependencies ({strategy_name}): {', '.join(paths)}", "success"
)
# Symlink .claude/ config to worktree for Claude Code features (settings, commands, etc.)
symlinked_claude = symlink_claude_config_to_worktree(
# Symlink node_modules to worktree for TypeScript and tooling support
# This allows pre-commit hooks to run typecheck without npm install in worktree
symlinked_modules = symlink_node_modules_to_worktree(
project_dir, worktree_info.path
)
if symlinked_claude:
print_status(f"Claude config linked: {', '.join(symlinked_claude)}", "success")
if symlinked_modules:
print_status(f"Dependencies linked: {', '.join(symlinked_modules)}", "success")
# Copy security configuration files if they exist
# Note: Unlike env files, security files always overwrite to ensure
@@ -593,299 +574,6 @@ def initialize_timeline_tracking(
print(muted(f" Note: Timeline tracking could not be initialized: {e}"))
def setup_worktree_dependencies(
project_dir: Path,
worktree_path: Path,
project_index: dict | None = None,
) -> dict[str, list[str]]:
"""
Set up dependencies in a worktree using strategy-based dispatch.
Reads dependency configs from the project index and applies the correct
strategy for each: symlink, recreate, copy, or skip.
All operations are non-blocking — failures produce warnings but do not
prevent worktree creation.
Args:
project_dir: The main project directory
worktree_path: Path to the worktree
project_index: Parsed project_index.json dict, or None
Returns:
Dict mapping strategy names to lists of paths that were processed.
"""
configs = get_dependency_configs(project_index, project_dir=project_dir)
results: dict[str, list[str]] = {}
for config in configs:
strategy_name = config.strategy.value
if strategy_name not in results:
results[strategy_name] = []
try:
performed = True
if config.strategy == DependencyStrategy.SYMLINK:
performed = _apply_symlink_strategy(project_dir, worktree_path, config)
elif config.strategy == DependencyStrategy.RECREATE:
performed = _apply_recreate_strategy(project_dir, worktree_path, config)
elif config.strategy == DependencyStrategy.COPY:
performed = _apply_copy_strategy(project_dir, worktree_path, config)
elif config.strategy == DependencyStrategy.SKIP:
_apply_skip_strategy(config)
# Don't record skipped entries — only report actual work
continue
if performed:
results[strategy_name].append(config.source_rel_path)
except Exception as e:
debug_warning(
MODULE,
f"Failed to apply {strategy_name} strategy for "
f"{config.source_rel_path}: {e}",
)
return results
def _apply_symlink_strategy(
project_dir: Path,
worktree_path: Path,
config: DependencyShareConfig,
) -> bool:
"""Create a symlink (or Windows junction) from worktree to project source.
Returns True if a symlink was created, False if skipped.
"""
source_path = project_dir / config.source_rel_path
target_path = worktree_path / config.source_rel_path
if not source_path.exists():
debug(MODULE, f"Skipping symlink {config.source_rel_path} - source missing")
return False
if target_path.exists() or target_path.is_symlink():
debug(MODULE, f"Skipping symlink {config.source_rel_path} - target exists")
return False
target_path.parent.mkdir(parents=True, exist_ok=True)
try:
if is_windows():
# Windows: use directory junctions (no admin rights required).
# os.symlink creates a directory symlink that needs admin/DevMode,
# so we use mklink /J which creates a junction without privileges.
result = subprocess.run(
["cmd", "/c", "mklink", "/J", str(target_path), str(source_path)],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
raise OSError(result.stderr or "mklink /J failed")
else:
# macOS/Linux: relative symlinks for portability
relative_source = os.path.relpath(source_path, target_path.parent)
os.symlink(relative_source, target_path)
debug(MODULE, f"Symlinked {config.source_rel_path} -> {source_path}")
return True
except subprocess.TimeoutExpired:
debug_warning(
MODULE,
f"Symlink creation timed out for {config.source_rel_path}",
)
print_status(
f"Warning: Symlink creation timed out for {config.source_rel_path}",
"warning",
)
return False
except OSError as e:
debug_warning(
MODULE,
f"Could not symlink {config.source_rel_path}: {e}",
)
print_status(f"Warning: Could not link {config.source_rel_path}", "warning")
return False
def _apply_recreate_strategy(
project_dir: Path,
worktree_path: Path,
config: DependencyShareConfig,
) -> bool:
"""Create a fresh virtual environment in the worktree and install deps.
Returns True if the venv was successfully created, False if skipped or failed.
"""
venv_path = worktree_path / config.source_rel_path
if venv_path.exists():
debug(MODULE, f"Skipping recreate {config.source_rel_path} - already exists")
return False
# Detect Python executable from the source venv or fall back to sys.executable
source_venv = project_dir / config.source_rel_path
python_exec = sys.executable
if source_venv.exists():
# Try to use the same Python version as the source venv
for candidate in ("bin/python", "Scripts/python.exe"):
candidate_path = source_venv / candidate
if candidate_path.exists():
python_exec = str(candidate_path.resolve())
break
# Create the venv
try:
debug(MODULE, f"Creating venv at {venv_path}")
result = subprocess.run(
[python_exec, "-m", "venv", str(venv_path)],
capture_output=True,
text=True,
timeout=120,
)
if result.returncode != 0:
debug_warning(MODULE, f"venv creation failed: {result.stderr}")
print_status(
f"Warning: Could not create venv at {config.source_rel_path}",
"warning",
)
# Clean up partial venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"venv creation timed out for {config.source_rel_path}")
print_status(
f"Warning: venv creation timed out for {config.source_rel_path}",
"warning",
)
# Clean up partial venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
# Install from requirements file if specified
req_file = config.requirements_file
if req_file:
req_path = project_dir / req_file
if req_path.is_file():
# Determine pip executable inside the new venv
if is_windows():
pip_exec = str(venv_path / "Scripts" / "pip.exe")
else:
pip_exec = str(venv_path / "bin" / "pip")
# Build install command based on file type
req_basename = Path(req_file).name
if req_basename == "pyproject.toml":
# pyproject.toml: snapshot-install from the worktree copy.
# Non-editable so the venv doesn't symlink back to the source.
worktree_req = worktree_path / req_file
install_dir = str(
worktree_req.parent if worktree_req.is_file() else req_path.parent
)
install_cmd = [pip_exec, "install", install_dir]
elif req_basename == "Pipfile":
# Pipfile: not directly installable via pip, skip
debug(
MODULE,
f"Skipping Pipfile-based install for {req_file} "
"(use pipenv in the worktree)",
)
install_cmd = None
else:
# requirements.txt or similar: pip install -r
install_cmd = [pip_exec, "install", "-r", str(req_path)]
if install_cmd:
try:
debug(MODULE, f"Installing deps from {req_file}")
pip_result = subprocess.run(
install_cmd,
capture_output=True,
text=True,
timeout=120,
)
if pip_result.returncode != 0:
debug_warning(
MODULE,
f"pip install failed (exit {pip_result.returncode}): "
f"{pip_result.stderr}",
)
print_status(
f"Warning: Dependency install failed for {req_file}",
"warning",
)
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except subprocess.TimeoutExpired:
debug_warning(
MODULE,
f"pip install timed out for {req_file}",
)
print_status(
f"Warning: Dependency install timed out for {req_file}",
"warning",
)
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except OSError as e:
debug_warning(MODULE, f"pip install failed: {e}")
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
debug(MODULE, f"Recreated venv at {config.source_rel_path}")
return True
def _apply_copy_strategy(
project_dir: Path,
worktree_path: Path,
config: DependencyShareConfig,
) -> bool:
"""Deep-copy a dependency directory from project to worktree.
Returns True if the copy was performed, False if skipped.
"""
source_path = project_dir / config.source_rel_path
target_path = worktree_path / config.source_rel_path
if not source_path.exists():
debug(MODULE, f"Skipping copy {config.source_rel_path} - source missing")
return False
if target_path.exists():
debug(MODULE, f"Skipping copy {config.source_rel_path} - target exists")
return False
target_path.parent.mkdir(parents=True, exist_ok=True)
try:
if source_path.is_file():
shutil.copy2(source_path, target_path)
else:
shutil.copytree(source_path, target_path)
debug(MODULE, f"Copied {config.source_rel_path} to worktree")
return True
except (OSError, shutil.Error) as e:
debug_warning(MODULE, f"Could not copy {config.source_rel_path}: {e}")
print_status(f"Warning: Could not copy {config.source_rel_path}", "warning")
return False
def _apply_skip_strategy(config: DependencyShareConfig) -> None:
"""Skip — nothing to do for this dependency type."""
debug(
MODULE, f"Skipping {config.dep_type} ({config.source_rel_path}) - skip strategy"
)
# Export private functions for backward compatibility
_ensure_timeline_hook_installed = ensure_timeline_hook_installed
_initialize_timeline_tracking = initialize_timeline_tracking
-2
View File
@@ -430,7 +430,6 @@ class WorktreeManager:
if os.path.samefile(resolved_path, current_path):
return line[len("branch refs/heads/") :]
except OSError:
# File system comparison errors are handled by fallback below
pass
# Fallback to normalized case comparison
if os.path.normcase(str(resolved_path)) == os.path.normcase(
@@ -511,7 +510,6 @@ class WorktreeManager:
if os.path.samefile(resolved_path, registered_path):
return True
except OSError:
# File system errors handled by fallback comparison below
pass
# Fallback to normalized case comparison for non-existent paths
if os.path.normcase(str(resolved_path)) == os.path.normcase(
@@ -5,9 +5,7 @@ Handles database connection, initialization, and lifecycle management.
Uses LadybugDB as the embedded graph database (no Docker required, Python 3.12+).
"""
import asyncio
import logging
import random
import sys
from datetime import datetime, timezone
@@ -16,27 +14,6 @@ from graphiti_config import GraphitiConfig, GraphitiState
logger = logging.getLogger(__name__)
# Retry configuration for LadybugDB lock contention
MAX_LOCK_RETRIES = 5
INITIAL_BACKOFF_SECONDS = 0.5
MAX_BACKOFF_SECONDS = 8.0
JITTER_PERCENT = 0.2
def _is_lock_error(error: Exception) -> bool:
"""Check if an error indicates database lock contention."""
error_msg = str(error).lower()
return "could not set lock" in error_msg or (
"lock" in error_msg and ("file" in error_msg or "database" in error_msg)
)
def _backoff_with_jitter(attempt: int) -> float:
"""Calculate exponential backoff with jitter for retry delays."""
backoff = min(INITIAL_BACKOFF_SECONDS * (2**attempt), MAX_BACKOFF_SECONDS)
jitter = backoff * JITTER_PERCENT * (2 * random.random() - 1)
return max(0.01, backoff + jitter)
def _apply_ladybug_monkeypatch() -> bool:
"""
@@ -219,36 +196,32 @@ class GraphitiClient:
)
db_path = self.config.get_db_path()
# Retry with exponential backoff for lock contention
for attempt in range(MAX_LOCK_RETRIES + 1):
try:
self._driver = create_patched_kuzu_driver(db=str(db_path))
if attempt > 0:
logger.info(
f"LadybugDB lock acquired after {attempt} retries"
)
break # Success
except Exception as e:
if _is_lock_error(e) and attempt < MAX_LOCK_RETRIES:
wait_time = _backoff_with_jitter(attempt)
logger.debug(
f"LadybugDB lock contention (attempt {attempt + 1}/{MAX_LOCK_RETRIES}), retrying in {wait_time:.2f}s"
)
await asyncio.sleep(wait_time)
continue
logger.warning(
f"Failed to initialize LadybugDB driver at {db_path}: {e}"
)
capture_exception(
e,
error_type=type(e).__name__,
db_path=str(db_path),
llm_provider=self.config.llm_provider,
embedder_provider=self.config.embedder_provider,
)
return False
try:
self._driver = create_patched_kuzu_driver(db=str(db_path))
except (OSError, PermissionError) as e:
logger.warning(
f"Failed to initialize LadybugDB driver at {db_path}: {e}"
)
capture_exception(
e,
error_type=type(e).__name__,
db_path=str(db_path),
llm_provider=self.config.llm_provider,
embedder_provider=self.config.embedder_provider,
)
return False
except Exception as e:
logger.warning(
f"Unexpected error initializing LadybugDB driver at {db_path}: {e}"
)
capture_exception(
e,
error_type=type(e).__name__,
db_path=str(db_path),
llm_provider=self.config.llm_provider,
embedder_provider=self.config.embedder_provider,
)
return False
logger.info(f"Initialized LadybugDB driver (patched) at: {db_path}")
except ImportError as e:
logger.warning(f"KuzuDriver not available: {e}")
-2
View File
@@ -215,7 +215,6 @@ async def run_qa_validation_loop(
"Removed QA_FIX_REQUEST.md after permanent fixer error",
)
except OSError:
# File removal failure is not critical here
pass
return False
@@ -231,7 +230,6 @@ async def run_qa_validation_loop(
fix_request_file.unlink()
debug("qa_loop", "Removed processed QA_FIX_REQUEST.md")
except OSError:
# File removal failure is not critical here
pass # Ignore if file removal fails
# Check for no-test projects
-7
View File
@@ -572,9 +572,6 @@ class PRReviewResult:
) # IDs of posted findings
posted_at: str | None = None # Timestamp when findings were posted
# In-progress review tracking
in_progress_since: str | None = None # ISO timestamp when active review started
def to_dict(self) -> dict:
return {
"pr_number": self.pr_number,
@@ -606,8 +603,6 @@ class PRReviewResult:
"has_posted_findings": self.has_posted_findings,
"posted_finding_ids": self.posted_finding_ids,
"posted_at": self.posted_at,
# In-progress review tracking
"in_progress_since": self.in_progress_since,
}
@classmethod
@@ -655,8 +650,6 @@ class PRReviewResult:
has_posted_findings=data.get("has_posted_findings", False),
posted_finding_ids=data.get("posted_finding_ids", []),
posted_at=data.get("posted_at"),
# In-progress review tracking
in_progress_since=data.get("in_progress_since"),
)
async def save(self, github_dir: Path) -> None:
+1 -21
View File
@@ -395,28 +395,8 @@ class GitHubOrchestrator:
else:
# No existing review found, create skip result
return await self._create_skip_result(pr_number, skip_reason)
elif "Review already in progress" in skip_reason:
# Return an in-progress result WITHOUT saving to disk
# to avoid overwriting the partial result being written by the active review
started_at = self.bot_detector.state.in_progress_reviews.get(
str(pr_number)
)
safe_print(
f"[BOT DETECTION] Review in progress for PR #{pr_number} "
f"(started: {started_at})",
flush=True,
)
return PRReviewResult(
pr_number=pr_number,
repo=self.config.repo,
success=True,
findings=[],
summary="Review in progress",
overall_status="in_progress",
in_progress_since=started_at,
)
else:
# For other skip reasons (bot-authored, cooling off), create a skip result
# For other skip reasons (bot-authored, cooling off, in-progress), create a skip result
return await self._create_skip_result(pr_number, skip_reason)
# Mark review as started (prevents concurrent reviews)
-6
View File
@@ -235,12 +235,6 @@ async def cmd_review_pr(args) -> int:
safe_print(f"[DEBUG] review_pr returned, success={result.success}")
if result.success:
# For in_progress results (not saved to disk), output JSON so the frontend
# can parse it from stdout instead of relying on the disk file.
if result.overall_status == "in_progress":
safe_print(f"__RESULT_JSON__:{json.dumps(result.to_dict())}")
return 0
safe_print(f"\n{'=' * 60}")
safe_print(f"PR #{result.pr_number} Review Complete")
safe_print(f"{'=' * 60}")
@@ -25,8 +25,6 @@ if TYPE_CHECKING:
from ..models import FollowupReviewContext, GitHubRunnerConfig
try:
from ...core.client import create_client
from ...phase_config import resolve_model_id
from ..gh_client import GHClient
from ..models import (
MergeVerdict,
@@ -39,11 +37,8 @@ try:
from .category_utils import map_category
from .io_utils import safe_print
from .prompt_manager import PromptManager
from .pydantic_models import FollowupExtractionResponse, FollowupReviewResponse
from .recovery_utils import create_finding_from_summary
from .sdk_utils import process_sdk_stream
from .pydantic_models import FollowupReviewResponse
except (ImportError, ValueError, SystemError):
from core.client import create_client
from gh_client import GHClient
from models import (
MergeVerdict,
@@ -53,16 +48,10 @@ except (ImportError, ValueError, SystemError):
ReviewSeverity,
_utc_now_iso,
)
from phase_config import resolve_model_id
from services.category_utils import map_category
from services.io_utils import safe_print
from services.prompt_manager import PromptManager
from services.pydantic_models import (
FollowupExtractionResponse,
FollowupReviewResponse,
)
from services.recovery_utils import create_finding_from_summary
from services.sdk_utils import process_sdk_stream
from services.pydantic_models import FollowupReviewResponse
logger = logging.getLogger(__name__)
@@ -709,9 +698,6 @@ Analyze this follow-up review context and provide your structured response.
)
safe_print(f"[Followup] SDK query with output_format, model={model}")
# Capture assistant text for extraction fallback
captured_text = ""
# Iterate through messages from the query
# Note: max_turns=2 because structured output uses a tool call + response
async for message in query(
@@ -736,9 +722,7 @@ Analyze this follow-up review context and provide your structured response.
content = getattr(message, "content", [])
for block in content:
block_type = type(block).__name__
if block_type == "TextBlock":
captured_text += getattr(block, "text", "")
elif block_type == "ToolUseBlock":
if block_type == "ToolUseBlock":
tool_name = getattr(block, "name", "")
if tool_name == "StructuredOutput":
# Extract structured data from tool input
@@ -781,31 +765,9 @@ Analyze this follow-up review context and provide your structured response.
logger.warning(
"Claude could not produce valid structured output after retries"
)
# Attempt extraction call recovery before giving up
if captured_text:
safe_print(
"[Followup] Attempting extraction call recovery...",
flush=True,
)
extraction_result = await self._attempt_extraction_call(
captured_text, context
)
if extraction_result is not None:
return extraction_result
return None
logger.warning("No structured output received from AI")
# Attempt extraction call recovery before giving up
if captured_text:
safe_print(
"[Followup] No structured output — attempting extraction call recovery...",
flush=True,
)
extraction_result = await self._attempt_extraction_call(
captured_text, context
)
if extraction_result is not None:
return extraction_result
return None
except ValueError as e:
@@ -878,124 +840,6 @@ Analyze this follow-up review context and provide your structured response.
"verdict_reasoning": result.verdict_reasoning,
}
async def _attempt_extraction_call(
self,
text: str,
context: FollowupReviewContext,
) -> dict[str, Any] | None:
"""Attempt a short SDK call with minimal schema to recover review data.
This is the extraction recovery step when full structured output validation fails.
Uses FollowupExtractionResponse (small schema with ExtractedFindingSummary nesting)
which has near-100% success rate.
Uses create_client() + process_sdk_stream() for proper OAuth handling,
matching the pattern in parallel_followup_reviewer.py.
Returns parsed result dict on success, None on failure.
"""
if not text or not text.strip():
return None
try:
extraction_prompt = (
"Extract the key review data from the following AI analysis output. "
"Return the verdict, reasoning, resolved finding IDs, unresolved finding IDs, "
"structured summaries of any new findings (including severity, description, file path, and line number), "
"and counts of confirmed/dismissed findings.\n\n"
f"--- AI ANALYSIS OUTPUT ---\n{text[:8000]}\n--- END ---"
)
model_shorthand = self.config.model or "sonnet"
model = resolve_model_id(model_shorthand)
extraction_client = create_client(
project_dir=self.project_dir,
spec_dir=self.github_dir,
model=model,
agent_type="pr_followup_extraction",
output_format={
"type": "json_schema",
"schema": FollowupExtractionResponse.model_json_schema(),
},
)
async with extraction_client:
await extraction_client.query(extraction_prompt)
stream_result = await process_sdk_stream(
client=extraction_client,
context_name="FollowupExtraction",
model=model,
system_prompt=extraction_prompt,
max_messages=20,
)
if stream_result.get("error"):
logger.warning(
f"[Followup] Extraction call also failed: {stream_result['error']}"
)
return None
extraction_output = stream_result.get("structured_output")
if not extraction_output:
logger.warning(
"[Followup] Extraction call returned no structured output"
)
return None
extracted = FollowupExtractionResponse.model_validate(extraction_output)
# Convert extraction to internal format with reconstructed findings
new_findings = []
for i, summary_obj in enumerate(extracted.new_finding_summaries):
new_findings.append(
create_finding_from_summary(
summary=summary_obj.description,
index=i,
id_prefix="FR",
severity_override=summary_obj.severity,
file=summary_obj.file,
line=summary_obj.line,
)
)
# Build finding_resolutions from extraction data for _apply_ai_resolutions
# (unresolved findings are handled via finding_resolutions + _apply_ai_resolutions)
finding_resolutions = []
for fid in extracted.resolved_finding_ids:
finding_resolutions.append(
{"finding_id": fid, "status": "resolved", "resolution_notes": None}
)
for fid in extracted.unresolved_finding_ids:
finding_resolutions.append(
{
"finding_id": fid,
"status": "unresolved",
"resolution_notes": None,
}
)
safe_print(
f"[Followup] Extraction recovered: verdict={extracted.verdict}, "
f"{len(extracted.resolved_finding_ids)} resolved, "
f"{len(extracted.unresolved_finding_ids)} unresolved, "
f"{len(new_findings)} new findings",
flush=True,
)
return {
"finding_resolutions": finding_resolutions,
"new_findings": new_findings,
"comment_findings": [],
"verdict": extracted.verdict,
"verdict_reasoning": f"[Recovered via extraction] {extracted.verdict_reasoning}",
}
except Exception as e:
logger.warning(f"[Followup] Extraction call failed: {e}")
return None
def _apply_ai_resolutions(
self,
previous_findings: list[PRReviewFinding],
@@ -52,7 +52,6 @@ try:
from .io_utils import safe_print
from .pr_worktree_manager import PRWorktreeManager
from .pydantic_models import FollowupExtractionResponse, ParallelFollowupResponse
from .recovery_utils import create_finding_from_summary
from .sdk_utils import process_sdk_stream
except (ImportError, ValueError, SystemError):
from context_gatherer import _validate_git_ref
@@ -80,7 +79,6 @@ except (ImportError, ValueError, SystemError):
FollowupExtractionResponse,
ParallelFollowupResponse,
)
from services.recovery_utils import create_finding_from_summary
from services.sdk_utils import process_sdk_stream
@@ -1129,8 +1127,7 @@ The SDK will run invoked agents in parallel automatically.
"""Attempt a short SDK call with a minimal schema to recover review data.
This is the Tier 2 recovery step when full structured output validation fails.
Uses FollowupExtractionResponse (small schema with ExtractedFindingSummary nesting)
which has near-100% success rate.
Uses FollowupExtractionResponse (~6 flat fields) which has near-100% success rate.
Returns parsed result dict on success, None on failure.
"""
@@ -1147,8 +1144,7 @@ The SDK will run invoked agents in parallel automatically.
extraction_prompt = (
"Extract the key review data from the following AI analysis output. "
"Return the verdict, reasoning, resolved finding IDs, unresolved finding IDs, "
"structured summaries of any new findings (including severity, description, file path, and line number), "
"and counts of confirmed/dismissed findings.\n\n"
"one-line summaries of any new findings, and counts of confirmed/dismissed findings.\n\n"
f"--- AI ANALYSIS OUTPUT ---\n{text[:8000]}\n--- END ---"
)
@@ -1203,59 +1199,18 @@ The SDK will run invoked agents in parallel automatically.
}
verdict = verdict_map.get(extracted.verdict, MergeVerdict.NEEDS_REVISION)
# Reconstruct findings from extraction data
findings = []
new_finding_ids = []
# 1. Convert new_finding_summaries to PRReviewFinding objects
# ExtractedFindingSummary objects carry file/line from extraction
for i, summary_obj in enumerate(extracted.new_finding_summaries):
finding = create_finding_from_summary(
summary=summary_obj.description,
index=i,
id_prefix="FU",
severity_override=summary_obj.severity,
file=summary_obj.file,
line=summary_obj.line,
)
new_finding_ids.append(finding.id)
findings.append(finding)
# 2. Reconstruct unresolved findings from previous review context
if extracted.unresolved_finding_ids and context.previous_review.findings:
previous_map = {f.id: f for f in context.previous_review.findings}
for uid in extracted.unresolved_finding_ids:
original = previous_map.get(uid)
if original:
findings.append(
PRReviewFinding(
id=original.id,
severity=original.severity,
category=original.category,
title=f"[UNRESOLVED] {original.title}",
description=original.description,
file=original.file,
line=original.line,
suggested_fix=original.suggested_fix,
fixable=original.fixable,
is_impact_finding=original.is_impact_finding,
)
)
safe_print(
f"[ParallelFollowup] Extraction recovered: verdict={extracted.verdict}, "
f"{len(extracted.resolved_finding_ids)} resolved, "
f"{len(extracted.unresolved_finding_ids)} unresolved, "
f"{len(new_finding_ids)} new findings, "
f"{len(findings)} total findings reconstructed",
f"{len(extracted.new_finding_summaries)} new findings",
flush=True,
)
return {
"findings": findings,
"findings": [], # Full findings not recoverable via extraction
"resolved_ids": extracted.resolved_finding_ids,
"unresolved_ids": extracted.unresolved_finding_ids,
"new_finding_ids": new_finding_ids,
"new_finding_ids": [],
"dismissed_false_positive_ids": [],
"confirmed_valid_count": extracted.confirmed_finding_count,
"dismissed_finding_count": extracted.dismissed_finding_count,
@@ -1295,7 +1250,6 @@ The SDK will run invoked agents in parallel automatically.
This handles cases where the AI produced valid data but it doesn't exactly
match the expected schema (missing optional fields, type mismatches, etc.).
Defensively extracts findings from the raw dict so partial results are preserved.
"""
if not isinstance(data, dict):
return None
@@ -1303,7 +1257,6 @@ The SDK will run invoked agents in parallel automatically.
resolved_ids = []
unresolved_ids = []
new_finding_ids = []
findings = []
# Try to extract resolution verifications
resolution_verifications = data.get("resolution_verifications", [])
@@ -1322,68 +1275,14 @@ The SDK will run invoked agents in parallel automatically.
):
unresolved_ids.append(finding_id)
# Try to extract new findings as PRReviewFinding objects
new_findings_raw = data.get("new_findings", [])
if isinstance(new_findings_raw, list):
for nf in new_findings_raw:
if not isinstance(nf, dict):
continue
try:
finding_id = nf.get("id", "") or self._generate_finding_id(
nf.get("file", "unknown"),
nf.get("line", 0),
nf.get("title", "unknown"),
)
new_finding_ids.append(finding_id)
findings.append(
PRReviewFinding(
id=finding_id,
severity=_map_severity(nf.get("severity", "medium")),
category=map_category(nf.get("category", "quality")),
title=nf.get("title", "Unknown issue"),
description=nf.get("description", ""),
file=nf.get("file", "unknown"),
line=nf.get("line", 0) or 0,
suggested_fix=nf.get("suggested_fix"),
fixable=bool(nf.get("fixable", False)),
is_impact_finding=bool(nf.get("is_impact_finding", False)),
)
)
except Exception as e:
logger.debug(
f"[ParallelFollowup] Skipping malformed new finding: {e}"
)
# Try to extract comment findings as PRReviewFinding objects
comment_findings_raw = data.get("comment_findings", [])
if isinstance(comment_findings_raw, list):
for cf in comment_findings_raw:
if not isinstance(cf, dict):
continue
try:
finding_id = cf.get("id", "") or self._generate_finding_id(
cf.get("file", "unknown"),
cf.get("line", 0),
cf.get("title", "unknown"),
)
new_finding_ids.append(finding_id)
findings.append(
PRReviewFinding(
id=finding_id,
severity=_map_severity(cf.get("severity", "medium")),
category=map_category(cf.get("category", "quality")),
title=f"[FROM COMMENTS] {cf.get('title', 'Unknown issue')}",
description=cf.get("description", ""),
file=cf.get("file", "unknown"),
line=cf.get("line", 0) or 0,
suggested_fix=cf.get("suggested_fix"),
fixable=bool(cf.get("fixable", False)),
)
)
except Exception as e:
logger.debug(
f"[ParallelFollowup] Skipping malformed comment finding: {e}"
)
# Try to extract new findings
new_findings = data.get("new_findings", [])
if isinstance(new_findings, list):
for nf in new_findings:
if isinstance(nf, dict):
finding_id = nf.get("id", "")
if finding_id:
new_finding_ids.append(finding_id)
# Try to extract verdict
verdict_str = data.get("verdict", "NEEDS_REVISION")
@@ -1398,15 +1297,14 @@ The SDK will run invoked agents in parallel automatically.
verdict_reasoning = data.get("verdict_reasoning", "Extracted from partial data")
# Only return if we got any useful data
if resolved_ids or unresolved_ids or new_finding_ids or findings:
if resolved_ids or unresolved_ids or new_finding_ids:
return {
"findings": findings,
"findings": [], # Can't reliably extract full findings without validation
"resolved_ids": resolved_ids,
"unresolved_ids": unresolved_ids,
"new_finding_ids": new_finding_ids,
"dismissed_false_positive_ids": [],
"confirmed_valid_count": 0,
"dismissed_finding_count": 0,
"needs_human_review_count": 0,
"verdict": verdict,
"verdict_reasoning": f"[Partial extraction] {verdict_reasoning}",
@@ -633,14 +633,7 @@ Report findings with specific file paths, line numbers, and code evidence.
logger.error(
f"[Specialist:{specialist_name}] Failed to parse structured output: {e}"
)
# Attempt to extract findings from raw dict before falling to text parsing
findings = self._extract_specialist_partial_data(
specialist_name, structured_output
)
if findings:
logger.info(
f"[Specialist:{specialist_name}] Recovered {len(findings)} findings from partial extraction"
)
# Fall through to text parsing
if not findings and result_text:
# Fallback to text parsing
@@ -650,63 +643,6 @@ Report findings with specific file paths, line numbers, and code evidence.
return findings
def _extract_specialist_partial_data(
self,
specialist_name: str,
data: dict[str, Any],
) -> list[PRReviewFinding]:
"""Extract findings from raw specialist dict when Pydantic validation fails.
Defensively extracts each finding individually so partial results are preserved
even if some findings have validation issues.
"""
findings = []
raw_findings = data.get("findings", [])
if not isinstance(raw_findings, list):
return findings
for f in raw_findings:
if not isinstance(f, dict):
continue
try:
file_path = f.get("file", "unknown")
line = f.get("line", 0) or 0
title = f.get("title", "Unknown issue")
finding_id = hashlib.md5(
f"{file_path}:{line}:{title}".encode(),
usedforsecurity=False,
).hexdigest()[:12]
category = map_category(f.get("category", "quality"))
try:
severity = ReviewSeverity(str(f.get("severity", "medium")).lower())
except ValueError:
severity = ReviewSeverity.MEDIUM
finding = PRReviewFinding(
id=finding_id,
file=file_path,
line=line,
end_line=f.get("end_line"),
title=title,
description=f.get("description", ""),
category=category,
severity=severity,
suggested_fix=f.get("suggested_fix", ""),
evidence=f.get("evidence"),
source_agents=[specialist_name],
is_impact_finding=bool(f.get("is_impact_finding", False)),
)
findings.append(finding)
except Exception as e:
logger.debug(
f"[Specialist:{specialist_name}] Skipping malformed finding: {e}"
)
return findings
async def _run_parallel_specialists(
self,
context: PRContext,
@@ -974,15 +910,13 @@ The SDK will run invoked agents in parallel automatically.
except ValueError:
severity = ReviewSeverity.MEDIUM
# Extract evidence from verification.code_examined if available
evidence = None
# Extract evidence: prefer verification.code_examined, fallback to evidence field
evidence = finding_data.evidence
if hasattr(finding_data, "verification") and finding_data.verification:
# Structured verification has more detailed evidence
verification = finding_data.verification
if hasattr(verification, "code_examined") and verification.code_examined:
evidence = verification.code_examined
# Fallback to evidence field if present (e.g. from dict-based parsing)
if not evidence:
evidence = getattr(finding_data, "evidence", None)
# Extract end_line if present
end_line = getattr(finding_data, "end_line", None)
@@ -1289,30 +1223,12 @@ The SDK will run invoked agents in parallel automatically.
f"{len(filtered_findings)} filtered"
)
# Separate active findings (drive verdict) from dismissed (shown in UI only)
active_findings = []
dismissed_findings = []
for f in validated_findings:
if f.validation_status == "dismissed_false_positive":
dismissed_findings.append(f)
else:
active_findings.append(f)
# No confidence routing - validation is binary via finding-validator
unique_findings = validated_findings
logger.info(f"[PRReview] Final findings: {len(unique_findings)} validated")
safe_print(
f"[ParallelOrchestrator] Final: {len(active_findings)} active, "
f"{len(dismissed_findings)} disputed by validator",
flush=True,
)
logger.info(
f"[PRReview] Final findings: {len(active_findings)} active, "
f"{len(dismissed_findings)} disputed"
)
# All findings (active + dismissed) go in the result for UI display
all_review_findings = validated_findings
logger.info(
f"[ParallelOrchestrator] Review complete: {len(all_review_findings)} findings "
f"({len(active_findings)} active, {len(dismissed_findings)} disputed)"
f"[ParallelOrchestrator] Review complete: {len(unique_findings)} findings"
)
# Fetch CI status for verdict consideration
@@ -1322,9 +1238,9 @@ The SDK will run invoked agents in parallel automatically.
f"{ci_status.get('failing', 0)} failing, {ci_status.get('pending', 0)} pending"
)
# Generate verdict from ACTIVE findings only (dismissed don't affect verdict)
# Generate verdict (includes merge conflict check, branch-behind check, and CI status)
verdict, verdict_reasoning, blockers = self._generate_verdict(
active_findings,
unique_findings,
has_merge_conflicts=context.has_merge_conflicts,
merge_state_status=context.merge_state_status,
ci_status=ci_status,
@@ -1335,7 +1251,7 @@ The SDK will run invoked agents in parallel automatically.
verdict=verdict,
verdict_reasoning=verdict_reasoning,
blockers=blockers,
findings=all_review_findings,
findings=unique_findings,
agents_invoked=agents_invoked,
)
@@ -1380,7 +1296,7 @@ The SDK will run invoked agents in parallel automatically.
pr_number=context.pr_number,
repo=self.config.repo,
success=True,
findings=all_review_findings,
findings=unique_findings,
summary=summary,
overall_status=overall_status,
verdict=verdict,
@@ -1890,7 +1806,6 @@ For EACH finding above:
break
except Exception as e:
# Part of retry loop structure - handles retryable errors
error_str = str(e).lower()
is_retryable = (
"400" in error_str
@@ -1955,38 +1870,12 @@ For EACH finding above:
validated_findings.append(finding)
elif validation.validation_status == "dismissed_false_positive":
# Protect cross-validated findings from dismissal —
# if multiple specialists independently found the same issue,
# a single validator should not override that consensus
if finding.cross_validated:
finding.validation_status = "confirmed_valid"
finding.validation_evidence = validation.code_evidence
finding.validation_explanation = (
f"[Auto-kept: cross-validated by {len(finding.source_agents)} agents] "
f"{validation.explanation}"
)
validated_findings.append(finding)
safe_print(
f"[FindingValidator] Kept cross-validated finding '{finding.title}' "
f"despite dismissal (agents={finding.source_agents})",
flush=True,
)
else:
# Keep finding but mark as dismissed (user can see it in UI)
finding.validation_status = "dismissed_false_positive"
finding.validation_evidence = validation.code_evidence
finding.validation_explanation = validation.explanation
validated_findings.append(finding)
dismissed_count += 1
safe_print(
f"[FindingValidator] Disputed '{finding.title}': "
f"{validation.explanation} (file={finding.file}:{finding.line})",
flush=True,
)
logger.info(
f"[PRReview] Disputed {finding.id}: "
f"{validation.explanation[:200]}"
)
# Dismiss - do not include
dismissed_count += 1
logger.info(
f"[PRReview] Dismissed {finding.id} as false positive: "
f"{validation.explanation[:100]}"
)
elif validation.validation_status == "needs_human_review":
# Keep but flag
@@ -2171,16 +2060,11 @@ For EACH finding above:
sev = f.severity.value
emoji = severity_emoji.get(sev, "")
is_disputed = f.validation_status == "dismissed_false_positive"
# Finding header with location
line_range = f"L{f.line}"
if f.end_line and f.end_line != f.line:
line_range = f"L{f.line}-L{f.end_line}"
if is_disputed:
lines.append(f"#### ⚪ [DISPUTED] ~~{f.title}~~")
else:
lines.append(f"#### {emoji} [{sev.upper()}] {f.title}")
lines.append(f"#### {emoji} [{sev.upper()}] {f.title}")
lines.append(f"**File:** `{f.file}` ({line_range})")
# Cross-validation badge
@@ -2210,7 +2094,6 @@ For EACH finding above:
status_label = {
"confirmed_valid": "Confirmed",
"needs_human_review": "Needs human review",
"dismissed_false_positive": "Disputed by validator",
}.get(f.validation_status, f.validation_status)
lines.append("")
lines.append(f"**Validation:** {status_label}")
@@ -2232,27 +2115,18 @@ For EACH finding above:
lines.append("")
# Findings count summary (exclude dismissed from active count)
active_count = 0
dismissed_count = 0
# Findings count summary
by_severity: dict[str, int] = {}
for f in findings:
if f.validation_status == "dismissed_false_positive":
dismissed_count += 1
continue
active_count += 1
sev = f.severity.value
by_severity[sev] = by_severity.get(sev, 0) + 1
summary_parts = []
for sev in ["critical", "high", "medium", "low"]:
if sev in by_severity:
summary_parts.append(f"{by_severity[sev]} {sev}")
count_text = (
f"**Total:** {active_count} finding(s) ({', '.join(summary_parts)})"
lines.append(
f"**Total:** {len(findings)} finding(s) ({', '.join(summary_parts)})"
)
if dismissed_count > 0:
count_text += f" + {dismissed_count} disputed"
lines.append(count_text)
lines.append("")
lines.append("---")
@@ -26,10 +26,10 @@ from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, Field
# =============================================================================
# Verification Evidence (Optional for findings — only code_examined is consumed)
# Verification Evidence (Required for All Findings)
# =============================================================================
@@ -50,28 +50,102 @@ class VerificationEvidence(BaseModel):
# =============================================================================
# Severity / Category Validators
# Common Finding Types
# =============================================================================
_VALID_SEVERITIES = {"critical", "high", "medium", "low"}
class BaseFinding(BaseModel):
"""Base class for all finding types."""
id: str = Field(description="Unique identifier for this finding")
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Issue severity level"
)
title: str = Field(description="Brief issue title (max 80 chars)")
description: str = Field(description="Detailed explanation of the issue")
file: str = Field(description="File path where issue was found")
line: int = Field(0, description="Line number of the issue")
suggested_fix: str | None = Field(None, description="How to fix this issue")
fixable: bool = Field(False, description="Whether this can be auto-fixed")
evidence: str | None = Field(
None,
description="DEPRECATED: Use verification.code_examined instead. Will be removed in Phase 5.",
)
verification: VerificationEvidence = Field(
description="Evidence that this finding was verified against actual code"
)
def _normalize_severity(v: str) -> str:
"""Normalize severity to a valid value, defaulting to 'medium'."""
if isinstance(v, str):
v = v.lower().strip()
if v not in _VALID_SEVERITIES:
return "medium"
return v
class SecurityFinding(BaseFinding):
"""A security vulnerability finding."""
category: Literal["security"] = Field(
default="security", description="Always 'security' for security findings"
)
def _normalize_category(v: str, valid_set: set[str], default: str = "quality") -> str:
"""Normalize category to a valid value, defaulting to given default."""
if isinstance(v, str):
v = v.lower().strip().replace("-", "_")
if v not in valid_set:
return default
return v
class QualityFinding(BaseFinding):
"""A code quality or redundancy finding."""
category: Literal[
"redundancy", "quality", "test", "performance", "pattern", "docs"
] = Field(description="Issue category")
redundant_with: str | None = Field(
None, description="Reference to duplicate code (file:line) if redundant"
)
class DeepAnalysisFinding(BaseFinding):
"""A finding from deep analysis with verification info."""
category: Literal[
"verification_failed",
"redundancy",
"quality",
"pattern",
"performance",
"logic",
] = Field(description="Issue category")
verification_note: str | None = Field(
None, description="What evidence is missing or couldn't be verified"
)
class StructuralIssue(BaseModel):
"""A structural issue with the PR."""
id: str = Field(description="Unique identifier")
issue_type: Literal[
"feature_creep", "scope_creep", "architecture_violation", "poor_structure"
] = Field(description="Type of structural issue")
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Issue severity"
)
title: str = Field(description="Brief issue title")
description: str = Field(description="Detailed explanation")
impact: str = Field(description="Why this matters")
suggestion: str = Field(description="How to fix")
class AICommentTriage(BaseModel):
"""Triage result for an AI tool comment."""
comment_id: int = Field(description="GitHub comment ID")
tool_name: str = Field(
description="AI tool name (CodeRabbit, Cursor, Greptile, etc.)"
)
verdict: Literal[
"critical",
"important",
"nice_to_have",
"trivial",
"addressed",
"false_positive",
] = Field(description="Verdict on the comment")
reasoning: str = Field(description="Why this verdict was chosen")
response_comment: str | None = Field(
None, description="Optional comment to post in reply"
)
# =============================================================================
@@ -89,34 +163,25 @@ class FindingResolution(BaseModel):
)
_FOLLOWUP_CATEGORIES = {"security", "quality", "logic", "test", "docs"}
class FollowupFinding(BaseModel):
"""A new finding from follow-up review (simpler than initial review).
verification is intentionally omitted not consumed by followup_reviewer.py.
"""
"""A new finding from follow-up review (simpler than initial review)."""
id: str = Field(description="Unique identifier for this finding")
severity: str = Field(description="Issue severity level")
category: str = Field(description="Issue category")
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Issue severity level"
)
category: Literal["security", "quality", "logic", "test", "docs"] = Field(
description="Issue category"
)
title: str = Field(description="Brief issue title")
description: str = Field(description="Detailed explanation of the issue")
file: str = Field(description="File path where issue was found")
line: int = Field(0, description="Line number of the issue")
suggested_fix: str | None = Field(None, description="How to fix this issue")
fixable: bool = Field(False, description="Whether this can be auto-fixed")
@field_validator("severity", mode="before")
@classmethod
def _normalize_severity(cls, v: str) -> str:
return _normalize_severity(v)
@field_validator("category", mode="before")
@classmethod
def _normalize_category(cls, v: str) -> str:
return _normalize_category(v, _FOLLOWUP_CATEGORIES)
verification: VerificationEvidence = Field(
description="Evidence that this finding was verified against actual code"
)
class FollowupReviewResponse(BaseModel):
@@ -138,6 +203,81 @@ class FollowupReviewResponse(BaseModel):
verdict_reasoning: str = Field(description="Explanation for the verdict")
# =============================================================================
# Initial Review Responses (Multi-Pass)
# =============================================================================
class QuickScanResult(BaseModel):
"""Result from the quick scan pass."""
purpose: str = Field(description="Brief description of what the PR claims to do")
actual_changes: str = Field(
description="Brief description of what the code actually does"
)
purpose_match: bool = Field(
description="Whether actual changes match the claimed purpose"
)
purpose_match_note: str | None = Field(
None, description="Explanation if purpose doesn't match actual changes"
)
risk_areas: list[str] = Field(
default_factory=list, description="Areas needing careful review"
)
red_flags: list[str] = Field(
default_factory=list, description="Obvious issues or concerns"
)
requires_deep_verification: bool = Field(
description="Whether deep verification is needed"
)
complexity: Literal["low", "medium", "high"] = Field(description="PR complexity")
class SecurityPassResult(BaseModel):
"""Result from the security pass - array of security findings."""
findings: list[SecurityFinding] = Field(
default_factory=list, description="Security vulnerabilities found"
)
class QualityPassResult(BaseModel):
"""Result from the quality pass - array of quality findings."""
findings: list[QualityFinding] = Field(
default_factory=list, description="Quality and redundancy issues found"
)
class DeepAnalysisResult(BaseModel):
"""Result from the deep analysis pass."""
findings: list[DeepAnalysisFinding] = Field(
default_factory=list,
description="Deep analysis findings with verification info",
)
class StructuralPassResult(BaseModel):
"""Result from the structural pass."""
issues: list[StructuralIssue] = Field(
default_factory=list, description="Structural issues found"
)
verdict: Literal[
"READY_TO_MERGE", "MERGE_WITH_CHANGES", "NEEDS_REVISION", "BLOCKED"
] = Field(description="Structural verdict")
verdict_reasoning: str = Field(description="Explanation for the verdict")
class AICommentTriageResult(BaseModel):
"""Result from AI comment triage pass."""
triages: list[AICommentTriage] = Field(
default_factory=list, description="Triage results for each AI comment"
)
# =============================================================================
# Issue Triage Response
# =============================================================================
@@ -180,21 +320,88 @@ class IssueTriageResponse(BaseModel):
comment: str | None = Field(None, description="Optional bot comment to post")
# =============================================================================
# Orchestrator Review Response
# =============================================================================
class OrchestratorFinding(BaseModel):
"""A finding from the orchestrator review."""
file: str = Field(description="File path where issue was found")
line: int = Field(0, description="Line number of the issue")
title: str = Field(description="Brief issue title")
description: str = Field(description="Detailed explanation of the issue")
category: Literal[
"security",
"quality",
"style",
"docs",
"redundancy",
"verification_failed",
"pattern",
"performance",
"logic",
"test",
] = Field(description="Issue category")
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Issue severity level"
)
suggestion: str | None = Field(None, description="How to fix this issue")
evidence: str | None = Field(
None,
description="DEPRECATED: Use verification.code_examined instead. Will be removed in Phase 5.",
)
verification: VerificationEvidence = Field(
description="Evidence that this finding was verified against actual code"
)
class OrchestratorReviewResponse(BaseModel):
"""Complete response schema for orchestrator PR review."""
verdict: Literal[
"READY_TO_MERGE", "MERGE_WITH_CHANGES", "NEEDS_REVISION", "BLOCKED"
] = Field(description="Overall merge verdict")
verdict_reasoning: str = Field(description="Explanation for the verdict")
findings: list[OrchestratorFinding] = Field(
default_factory=list, description="Issues found during review"
)
summary: str = Field(description="Brief summary of the review")
# =============================================================================
# Parallel Orchestrator Review Response (SDK Subagents)
# =============================================================================
_ORCHESTRATOR_CATEGORIES = {
"security",
"quality",
"logic",
"codebase_fit",
"test",
"docs",
"redundancy",
"pattern",
"performance",
}
class LogicFinding(BaseFinding):
"""A logic/correctness finding from the logic review agent."""
category: Literal["logic"] = Field(
default="logic", description="Always 'logic' for logic findings"
)
example_input: str | None = Field(
None, description="Concrete input that triggers the bug"
)
actual_output: str | None = Field(None, description="What the buggy code produces")
expected_output: str | None = Field(
None, description="What the code should produce"
)
class CodebaseFitFinding(BaseFinding):
"""A codebase fit finding from the codebase fit review agent."""
category: Literal["codebase_fit"] = Field(
default="codebase_fit", description="Always 'codebase_fit' for fit findings"
)
existing_code: str | None = Field(
None, description="Reference to existing code that should be used instead"
)
codebase_pattern: str | None = Field(
None, description="Description of the established pattern being violated"
)
class ParallelOrchestratorFinding(BaseModel):
@@ -206,11 +413,26 @@ class ParallelOrchestratorFinding(BaseModel):
end_line: int | None = Field(None, description="End line for multi-line issues")
title: str = Field(description="Brief issue title (max 80 chars)")
description: str = Field(description="Detailed explanation of the issue")
category: str = Field(description="Issue category")
severity: str = Field(description="Issue severity level")
verification: VerificationEvidence | None = Field(
category: Literal[
"security",
"quality",
"logic",
"codebase_fit",
"test",
"docs",
"redundancy",
"pattern",
"performance",
] = Field(description="Issue category")
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Issue severity level"
)
evidence: str | None = Field(
None,
description="Evidence that this finding was verified against actual code",
description="DEPRECATED: Use verification.code_examined instead. Will be removed in Phase 5.",
)
verification: VerificationEvidence = Field(
description="Evidence that this finding was verified against actual code"
)
is_impact_finding: bool = Field(
False,
@@ -237,16 +459,6 @@ class ParallelOrchestratorFinding(BaseModel):
False, description="Whether multiple agents agreed on this finding"
)
@field_validator("severity", mode="before")
@classmethod
def _normalize_severity(cls, v: str) -> str:
return _normalize_severity(v)
@field_validator("category", mode="before")
@classmethod
def _normalize_category(cls, v: str) -> str:
return _normalize_category(v, _ORCHESTRATOR_CATEGORIES)
class AgentAgreement(BaseModel):
"""Tracks agreement between agents on findings."""
@@ -302,22 +514,15 @@ class ValidationSummary(BaseModel):
)
_SPECIALIST_CATEGORIES = {
"security",
"quality",
"logic",
"performance",
"pattern",
"test",
"docs",
}
class SpecialistFinding(BaseModel):
"""A finding from a specialist agent (used in parallel SDK sessions)."""
severity: str = Field(description="Issue severity level")
category: str = Field(description="Issue category")
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Issue severity level"
)
category: Literal[
"security", "quality", "logic", "performance", "pattern", "test", "docs"
] = Field(description="Issue category")
title: str = Field(description="Brief issue title (max 80 chars)")
description: str = Field(description="Detailed explanation of the issue")
file: str = Field(description="File path where issue was found")
@@ -325,24 +530,14 @@ class SpecialistFinding(BaseModel):
end_line: int | None = Field(None, description="End line number if multi-line")
suggested_fix: str | None = Field(None, description="How to fix this issue")
evidence: str = Field(
default="",
description="Actual code snippet examined that shows the issue.",
min_length=1,
description="Actual code snippet examined that shows the issue. Required.",
)
is_impact_finding: bool = Field(
False,
description="True if this is about affected code outside the PR (callers, dependencies)",
)
@field_validator("severity", mode="before")
@classmethod
def _normalize_severity(cls, v: str) -> str:
return _normalize_severity(v)
@field_validator("category", mode="before")
@classmethod
def _normalize_category(cls, v: str) -> str:
return _normalize_category(v, _SPECIALIST_CATEGORIES)
class SpecialistResponse(BaseModel):
"""Response schema for individual specialist agent (parallel SDK sessions).
@@ -416,17 +611,6 @@ class ResolutionVerification(BaseModel):
)
_PARALLEL_FOLLOWUP_CATEGORIES = {
"security",
"quality",
"logic",
"test",
"docs",
"regression",
"incomplete_fix",
}
class ParallelFollowupFinding(BaseModel):
"""A finding from parallel follow-up review."""
@@ -435,8 +619,18 @@ class ParallelFollowupFinding(BaseModel):
line: int = Field(0, description="Line number of the issue")
title: str = Field(description="Brief issue title")
description: str = Field(description="Detailed explanation of the issue")
category: str = Field(description="Issue category")
severity: str = Field(description="Issue severity level")
category: Literal[
"security",
"quality",
"logic",
"test",
"docs",
"regression",
"incomplete_fix",
] = Field(description="Issue category")
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Issue severity level"
)
suggested_fix: str | None = Field(None, description="How to fix this issue")
fixable: bool = Field(False, description="Whether this can be auto-fixed")
is_impact_finding: bool = Field(
@@ -444,16 +638,6 @@ class ParallelFollowupFinding(BaseModel):
description="True if this finding is about impact on OTHER files outside the PR diff",
)
@field_validator("severity", mode="before")
@classmethod
def _normalize_severity(cls, v: str) -> str:
return _normalize_severity(v)
@field_validator("category", mode="before")
@classmethod
def _normalize_category(cls, v: str) -> str:
return _normalize_category(v, _PARALLEL_FOLLOWUP_CATEGORIES)
class ParallelFollowupResponse(BaseModel):
"""Complete response schema for parallel follow-up PR review.
@@ -533,26 +717,10 @@ class FindingValidationResponse(BaseModel):
# =============================================================================
class ExtractedFindingSummary(BaseModel):
"""Per-finding summary with file location for extraction recovery."""
severity: str = Field(description="Severity level: LOW, MEDIUM, HIGH, or CRITICAL")
description: str = Field(description="One-line description of the finding")
file: str = Field(
default="unknown", description="File path where the issue was found"
)
line: int = Field(default=0, description="Line number in the file (0 if unknown)")
@field_validator("severity", mode="before")
@classmethod
def _normalize_severity(cls, v: str) -> str:
return _normalize_severity(v)
class FollowupExtractionResponse(BaseModel):
"""Minimal extraction schema for recovering data when full structured output fails.
Uses ExtractedFindingSummary for new findings to preserve file/line information.
Deliberately kept small (~6 fields, no nesting) for near-100% validation success.
Used as an intermediate recovery step before falling back to raw text parsing.
"""
@@ -568,9 +736,9 @@ class FollowupExtractionResponse(BaseModel):
default_factory=list,
description="IDs of previous findings that remain unresolved",
)
new_finding_summaries: list[ExtractedFindingSummary] = Field(
new_finding_summaries: list[str] = Field(
default_factory=list,
description="Structured summary of each new finding with file location",
description="One-line summary of each new finding (e.g. 'HIGH: cleanup deletes QA-rejected specs in batch_commands.py')",
)
confirmed_finding_count: int = Field(
0, description="Number of findings confirmed as valid"
@@ -1,120 +0,0 @@
"""
Recovery Utilities for PR Review
=================================
Shared helpers for extraction recovery in followup and parallel followup reviewers.
These utilities consolidate duplicated logic for:
- Parsing "SEVERITY: description" patterns from extraction summaries
- Generating consistent, traceable finding IDs with prefixes
- Creating PRReviewFinding objects from extraction data
"""
from __future__ import annotations
import hashlib
try:
from ..models import (
PRReviewFinding,
ReviewCategory,
ReviewSeverity,
)
except (ImportError, ValueError, SystemError):
from models import (
PRReviewFinding,
ReviewCategory,
ReviewSeverity,
)
# Severity mapping for parsing "SEVERITY: description" patterns
_EXTRACTION_SEVERITY_MAP: list[tuple[str, ReviewSeverity]] = [
("CRITICAL:", ReviewSeverity.CRITICAL),
("HIGH:", ReviewSeverity.HIGH),
("MEDIUM:", ReviewSeverity.MEDIUM),
("LOW:", ReviewSeverity.LOW),
]
def parse_severity_from_summary(
summary: str,
) -> tuple[ReviewSeverity, str]:
"""Parse a "SEVERITY: description" pattern from an extraction summary.
Args:
summary: Raw summary string, e.g. "HIGH: Missing null check in parser.py"
Returns:
Tuple of (severity, cleaned_description).
Defaults to MEDIUM severity if no prefix is found.
"""
upper_summary = summary.upper()
for sev_name, sev_val in _EXTRACTION_SEVERITY_MAP:
if upper_summary.startswith(sev_name):
return sev_val, summary[len(sev_name) :].strip()
return ReviewSeverity.MEDIUM, summary
def generate_recovery_finding_id(
index: int, description: str, prefix: str = "FR"
) -> str:
"""Generate a consistent, traceable finding ID for recovery findings.
Args:
index: The index of the finding in the extraction list.
description: The finding description (used for hash uniqueness).
prefix: ID prefix for traceability. Default "FR" (Followup Recovery).
Use "FU" for parallel followup findings.
Returns:
A prefixed finding ID like "FR-A1B2C3D4" or "FU-A1B2C3D4".
"""
content = f"extraction-{index}-{description}"
hex_hash = (
hashlib.md5(content.encode(), usedforsecurity=False).hexdigest()[:8].upper()
)
return f"{prefix}-{hex_hash}"
def create_finding_from_summary(
summary: str,
index: int,
id_prefix: str = "FR",
severity_override: str | None = None,
file: str = "unknown",
line: int = 0,
) -> PRReviewFinding:
"""Create a PRReviewFinding from an extraction summary string.
Parses "SEVERITY: description" patterns, generates a traceable finding ID,
and returns a fully constructed PRReviewFinding.
Args:
summary: Raw summary string, e.g. "HIGH: Missing null check in parser.py"
index: The index of the finding in the extraction list.
id_prefix: ID prefix for traceability. Default "FR" (Followup Recovery).
severity_override: If provided, use this severity instead of parsing from summary.
file: File path where the issue was found (default "unknown").
line: Line number in the file (default 0).
Returns:
A PRReviewFinding with parsed severity, generated ID, and description.
"""
severity, description = parse_severity_from_summary(summary)
# Use severity_override if provided
if severity_override is not None:
severity_map = {k.rstrip(":"): v for k, v in _EXTRACTION_SEVERITY_MAP}
severity = severity_map.get(severity_override.upper(), severity)
finding_id = generate_recovery_finding_id(index, description, prefix=id_prefix)
return PRReviewFinding(
id=finding_id,
severity=severity,
category=ReviewCategory.QUALITY,
title=description[:80],
description=f"[Recovered via extraction] {description}",
file=file,
line=line,
)
+13 -60
View File
@@ -14,19 +14,12 @@ Key Features:
"""
import json
import logging
import subprocess
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from datetime import datetime
from enum import Enum
from pathlib import Path
# Recovery manager configuration
ATTEMPT_WINDOW_SECONDS = 7200 # Only count attempts within last 2 hours
MAX_ATTEMPT_HISTORY_PER_SUBTASK = 50 # Cap stored attempts per subtask
logger = logging.getLogger(__name__)
class FailureType(Enum):
"""Types of failures that can occur during autonomous builds."""
@@ -89,8 +82,8 @@ class RecoveryManager:
"subtasks": {},
"stuck_subtasks": [],
"metadata": {
"created_at": datetime.now(timezone.utc).isoformat(),
"last_updated": datetime.now(timezone.utc).isoformat(),
"created_at": datetime.now().isoformat(),
"last_updated": datetime.now().isoformat(),
},
}
with open(self.attempt_history_file, "w", encoding="utf-8") as f:
@@ -102,8 +95,8 @@ class RecoveryManager:
"commits": [],
"last_good_commit": None,
"metadata": {
"created_at": datetime.now(timezone.utc).isoformat(),
"last_updated": datetime.now(timezone.utc).isoformat(),
"created_at": datetime.now().isoformat(),
"last_updated": datetime.now().isoformat(),
},
}
with open(self.build_commits_file, "w", encoding="utf-8") as f:
@@ -121,7 +114,7 @@ class RecoveryManager:
def _save_attempt_history(self, data: dict) -> None:
"""Save attempt history to JSON file."""
data["metadata"]["last_updated"] = datetime.now(timezone.utc).isoformat()
data["metadata"]["last_updated"] = datetime.now().isoformat()
with open(self.attempt_history_file, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
@@ -137,7 +130,7 @@ class RecoveryManager:
def _save_build_commits(self, data: dict) -> None:
"""Save build commits to JSON file."""
data["metadata"]["last_updated"] = datetime.now(timezone.utc).isoformat()
data["metadata"]["last_updated"] = datetime.now().isoformat()
with open(self.build_commits_file, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
@@ -192,44 +185,17 @@ class RecoveryManager:
def get_attempt_count(self, subtask_id: str) -> int:
"""
Get how many times this subtask has been attempted within the time window.
Only counts attempts within ATTEMPT_WINDOW_SECONDS (default: 2 hours).
This prevents unbounded accumulation across crash/restart cycles.
Get how many times this subtask has been attempted.
Args:
subtask_id: ID of the subtask
Returns:
Number of attempts within the time window
Number of attempts
"""
history = self._load_attempt_history()
subtask_data = history["subtasks"].get(subtask_id, {})
attempts = subtask_data.get("attempts", [])
# Calculate cutoff time for the window
cutoff_time = datetime.now(timezone.utc) - timedelta(
seconds=ATTEMPT_WINDOW_SECONDS
)
# For backward compatibility with naive timestamps, also create naive cutoff
cutoff_time_naive = datetime.now() - timedelta(seconds=ATTEMPT_WINDOW_SECONDS)
# Count only attempts within the time window
recent_count = 0
for attempt in attempts:
try:
attempt_time = datetime.fromisoformat(attempt["timestamp"])
# Use appropriate cutoff based on whether timestamp is naive or aware
cutoff = (
cutoff_time_naive if attempt_time.tzinfo is None else cutoff_time
)
if attempt_time >= cutoff:
recent_count += 1
except (KeyError, ValueError):
# If timestamp is missing or invalid, count it (backward compatibility)
recent_count += 1
return recent_count
return len(subtask_data.get("attempts", []))
def record_attempt(
self,
@@ -242,8 +208,6 @@ class RecoveryManager:
"""
Record an attempt at a subtask.
Automatically trims old attempts if the history exceeds MAX_ATTEMPT_HISTORY_PER_SUBTASK.
Args:
subtask_id: ID of the subtask
session: Session number
@@ -260,24 +224,13 @@ class RecoveryManager:
# Add the attempt
attempt = {
"session": session,
"timestamp": datetime.now(timezone.utc).isoformat(),
"timestamp": datetime.now().isoformat(),
"approach": approach,
"success": success,
"error": error,
}
history["subtasks"][subtask_id]["attempts"].append(attempt)
# Hard cap: trim oldest attempts if we exceed the maximum
attempts = history["subtasks"][subtask_id]["attempts"]
if len(attempts) > MAX_ATTEMPT_HISTORY_PER_SUBTASK:
trimmed_count = len(attempts) - MAX_ATTEMPT_HISTORY_PER_SUBTASK
history["subtasks"][subtask_id]["attempts"] = attempts[
-MAX_ATTEMPT_HISTORY_PER_SUBTASK:
]
logger.debug(
f"Trimmed {trimmed_count} old attempts for subtask {subtask_id} (cap: {MAX_ATTEMPT_HISTORY_PER_SUBTASK})"
)
# Update status
if success:
history["subtasks"][subtask_id]["status"] = "completed"
@@ -452,7 +405,7 @@ class RecoveryManager:
commit_record = {
"hash": commit_hash,
"subtask_id": subtask_id,
"timestamp": datetime.now(timezone.utc).isoformat(),
"timestamp": datetime.now().isoformat(),
}
commits["commits"].append(commit_record)
@@ -497,7 +450,7 @@ class RecoveryManager:
stuck_entry = {
"subtask_id": subtask_id,
"reason": reason,
"escalated_at": datetime.now(timezone.utc).isoformat(),
"escalated_at": datetime.now().isoformat(),
"attempt_count": self.get_attempt_count(subtask_id),
}
+6 -1
View File
@@ -27,6 +27,8 @@ export default defineConfig({
plugins: [externalizeDepsPlugin({
// Bundle these packages into the main process (they won't be in node_modules in packaged app)
exclude: [
// Workspace packages — must be bundled, not externalized
'@auto-claude/types',
'uuid',
'chokidar',
'dotenv',
@@ -90,7 +92,10 @@ export default defineConfig({
'@features': resolve(__dirname, 'src/renderer/features'),
'@components': resolve(__dirname, 'src/renderer/shared/components'),
'@hooks': resolve(__dirname, 'src/renderer/shared/hooks'),
'@lib': resolve(__dirname, 'src/renderer/shared/lib')
'@lib': resolve(__dirname, 'src/renderer/shared/lib'),
// Workspace packages — resolve to source for HMR support
'@auto-claude/types': resolve(__dirname, '../../packages/types/src'),
'@auto-claude/ui': resolve(__dirname, '../../packages/ui/src')
}
},
server: {
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "auto-claude-ui",
"version": "2.7.6-beta.5",
"version": "2.7.7",
"type": "module",
"description": "Desktop UI for Auto Claude autonomous coding framework",
"homepage": "https://github.com/AndyMik90/Auto-Claude",
@@ -51,6 +51,8 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@auto-claude/types": "*",
"@auto-claude/ui": "*",
"@anthropic-ai/sdk": "^0.71.2",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
@@ -1012,115 +1012,3 @@ Please add credits to continue.`;
});
});
});
describe('ensureCleanProfileEnv', () => {
beforeEach(() => {
vi.resetModules();
});
afterEach(() => {
vi.clearAllMocks();
});
describe('with CLAUDE_CONFIG_DIR set', () => {
it('should preserve CLAUDE_CONFIG_DIR while clearing CLAUDE_CODE_OAUTH_TOKEN', async () => {
const { ensureCleanProfileEnv } = await import('../rate-limit-detector');
const env = {
CLAUDE_CONFIG_DIR: '/tmp/profile-1',
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-123',
ANTHROPIC_API_KEY: 'sk-ant-key-456'
};
const result = ensureCleanProfileEnv(env);
expect(result.CLAUDE_CONFIG_DIR).toBe('/tmp/profile-1');
expect(result.CLAUDE_CODE_OAUTH_TOKEN).toBe('');
expect(result.ANTHROPIC_API_KEY).toBe('');
});
it('should preserve other environment variables', async () => {
const { ensureCleanProfileEnv } = await import('../rate-limit-detector');
const env = {
CLAUDE_CONFIG_DIR: '/tmp/profile-1',
CLAUDE_CODE_OAUTH_TOKEN: 'token',
ANTHROPIC_API_KEY: 'key',
SOME_OTHER_VAR: 'value'
};
const result = ensureCleanProfileEnv(env);
expect(result.CLAUDE_CONFIG_DIR).toBe('/tmp/profile-1');
expect(result.SOME_OTHER_VAR).toBe('value');
expect(result.CLAUDE_CODE_OAUTH_TOKEN).toBe('');
expect(result.ANTHROPIC_API_KEY).toBe('');
});
it('should clear tokens even if they are not present in input', async () => {
const { ensureCleanProfileEnv } = await import('../rate-limit-detector');
const env = {
CLAUDE_CONFIG_DIR: '/tmp/profile-1'
};
const result = ensureCleanProfileEnv(env);
expect(result.CLAUDE_CONFIG_DIR).toBe('/tmp/profile-1');
expect(result.CLAUDE_CODE_OAUTH_TOKEN).toBe('');
expect(result.ANTHROPIC_API_KEY).toBe('');
});
});
describe('without CLAUDE_CONFIG_DIR', () => {
it('should return env unchanged when CLAUDE_CONFIG_DIR is not set', async () => {
const { ensureCleanProfileEnv } = await import('../rate-limit-detector');
const env = {
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-123',
ANTHROPIC_API_KEY: 'sk-ant-key-456'
};
const result = ensureCleanProfileEnv(env);
expect(result).toEqual(env);
expect(result.CLAUDE_CODE_OAUTH_TOKEN).toBe('oauth-token-123');
expect(result.ANTHROPIC_API_KEY).toBe('sk-ant-key-456');
});
});
describe('edge cases', () => {
it('should handle empty profile env', async () => {
const { ensureCleanProfileEnv } = await import('../rate-limit-detector');
const result = ensureCleanProfileEnv({});
// Empty env has no CLAUDE_CONFIG_DIR, so should return as-is
expect(result).toEqual({});
});
it('should handle env with empty string CLAUDE_CONFIG_DIR', async () => {
const { ensureCleanProfileEnv } = await import('../rate-limit-detector');
const env = {
CLAUDE_CONFIG_DIR: '',
CLAUDE_CODE_OAUTH_TOKEN: 'token'
};
const result = ensureCleanProfileEnv(env);
// Empty string is falsy, so should not trigger clearing
expect(result.CLAUDE_CODE_OAUTH_TOKEN).toBe('token');
});
it('should return a new object when clearing (not mutate input)', async () => {
const { ensureCleanProfileEnv } = await import('../rate-limit-detector');
const env = {
CLAUDE_CONFIG_DIR: '/tmp/profile-1',
CLAUDE_CODE_OAUTH_TOKEN: 'token'
};
const result = ensureCleanProfileEnv(env);
// Original should not be mutated
expect(env.CLAUDE_CODE_OAUTH_TOKEN).toBe('token');
expect(result.CLAUDE_CODE_OAUTH_TOKEN).toBe('');
expect(result).not.toBe(env);
});
});
});
@@ -799,127 +799,4 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
expect(envArg.GITHUB_CLI_PATH).toBe('/opt/homebrew/bin/gh');
});
});
describe('CLAUDE_CONFIG_DIR Propagation', () => {
let originalEnv: NodeJS.ProcessEnv;
beforeEach(() => {
originalEnv = { ...process.env };
delete process.env.CLAUDE_CONFIG_DIR;
});
afterEach(() => {
process.env = originalEnv;
});
it('should propagate CLAUDE_CONFIG_DIR from profile env in OAuth mode', async () => {
// OAuth mode - no active API profile
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
// Profile provides CLAUDE_CONFIG_DIR (OAuth subscription profile)
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: {
CLAUDE_CONFIG_DIR: '/home/user/.config/claude-profile-1',
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-abc'
},
profileId: 'profile-1',
profileName: 'Profile 1',
wasSwapped: false
});
await processManager.spawnProcess('task-1', '/fake/cwd', ['run.py'], {}, 'task-execution');
expect(spawnCalls).toHaveLength(1);
const envArg = spawnCalls[0].options.env as Record<string, unknown>;
// CLAUDE_CONFIG_DIR should be present in spawn env
expect(envArg.CLAUDE_CONFIG_DIR).toBe('/home/user/.config/claude-profile-1');
});
it('should clear ANTHROPIC_API_KEY in OAuth mode with CLAUDE_CONFIG_DIR', async () => {
// Simulate stale ANTHROPIC_API_KEY in process.env
process.env.ANTHROPIC_API_KEY = 'sk-stale-key';
// OAuth mode - no active API profile
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
// Profile provides CLAUDE_CONFIG_DIR
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: {
CLAUDE_CONFIG_DIR: '/home/user/.config/claude-profile-2',
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-def'
},
profileId: 'profile-2',
profileName: 'Profile 2',
wasSwapped: false
});
await processManager.spawnProcess('task-1', '/fake/cwd', ['run.py'], {}, 'task-execution');
expect(spawnCalls).toHaveLength(1);
const envArg = spawnCalls[0].options.env as Record<string, unknown>;
// ANTHROPIC_API_KEY should be cleared (empty string) in OAuth mode
expect(envArg.ANTHROPIC_API_KEY).toBe('');
// CLAUDE_CONFIG_DIR should still be set
expect(envArg.CLAUDE_CONFIG_DIR).toBe('/home/user/.config/claude-profile-2');
});
it('should pass ANTHROPIC_* vars without CLAUDE_CONFIG_DIR interference in API profile mode', async () => {
// API Profile mode - active profile with custom endpoint
const mockApiProfileEnv = {
ANTHROPIC_AUTH_TOKEN: 'sk-api-profile-key',
ANTHROPIC_BASE_URL: 'https://custom-api.example.com',
ANTHROPIC_MODEL: 'claude-sonnet-4-5-20250929'
};
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue(mockApiProfileEnv);
// Profile env without CLAUDE_CONFIG_DIR (API profile mode)
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: {},
profileId: 'api-profile-1',
profileName: 'Custom API',
wasSwapped: false
});
await processManager.spawnProcess('task-1', '/fake/cwd', ['run.py'], {}, 'task-execution');
expect(spawnCalls).toHaveLength(1);
const envArg = spawnCalls[0].options.env as Record<string, unknown>;
// ANTHROPIC_* vars from API profile should be passed through
expect(envArg.ANTHROPIC_AUTH_TOKEN).toBe('sk-api-profile-key');
expect(envArg.ANTHROPIC_BASE_URL).toBe('https://custom-api.example.com');
expect(envArg.ANTHROPIC_MODEL).toBe('claude-sonnet-4-5-20250929');
// CLAUDE_CONFIG_DIR should NOT be present since profile didn't provide it
expect(envArg.CLAUDE_CONFIG_DIR).toBeUndefined();
});
it('should clear CLAUDE_CODE_OAUTH_TOKEN when CLAUDE_CONFIG_DIR is provided by profile', async () => {
// OAuth mode
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
// Profile provides CLAUDE_CONFIG_DIR - agent should use config dir for auth
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: {
CLAUDE_CONFIG_DIR: '/home/user/.config/claude-profile-3',
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-ghi'
},
profileId: 'profile-3',
profileName: 'Profile 3',
wasSwapped: false
});
await processManager.spawnProcess('task-1', '/fake/cwd', ['run.py'], {}, 'task-execution');
expect(spawnCalls).toHaveLength(1);
const envArg = spawnCalls[0].options.env as Record<string, unknown>;
// When CLAUDE_CONFIG_DIR is present, CLAUDE_CODE_OAUTH_TOKEN should be cleared
// because Claude Code resolves auth from the config dir instead
expect(envArg.CLAUDE_CONFIG_DIR).toBe('/home/user/.config/claude-profile-3');
expect(envArg.CLAUDE_CODE_OAUTH_TOKEN).toBeFalsy();
});
});
});
+1 -65
View File
@@ -26,7 +26,6 @@ import { getOAuthModeClearVars } from './env-utils';
import { getAugmentedEnv } from '../env-utils';
import { getToolInfo, getClaudeCliPathForSdk } from '../cli-tool-manager';
import { killProcessGracefully, isWindows } from '../platform';
import { debugLog } from '../../shared/utils/debug-logger';
/**
* Type for supported CLI tools
@@ -179,29 +178,6 @@ export class AgentProcessManager {
// Get best available Claude profile environment (automatically handles rate limits)
const profileResult = getBestAvailableProfileEnv();
const profileEnv = profileResult.env;
debugLog('[AgentProcess:setupEnv] Profile result:', {
profileId: profileResult.profileId,
hasOAuthToken: !!profileEnv.CLAUDE_CODE_OAUTH_TOKEN,
hasApiKey: !!profileEnv.ANTHROPIC_API_KEY,
hasConfigDir: !!profileEnv.CLAUDE_CONFIG_DIR,
configDir: profileEnv.CLAUDE_CONFIG_DIR || '(not set)',
oauthTokenPrefix: profileEnv.CLAUDE_CODE_OAUTH_TOKEN?.substring(0, 8) || '(not set)',
apiKeyPrefix: profileEnv.ANTHROPIC_API_KEY?.substring(0, 8) || '(not set)',
});
// Warn if profile lacks CLAUDE_CONFIG_DIR - this means the profile has no configDir
// and subscription metadata may not propagate correctly to the agent subprocess
if (!profileEnv.CLAUDE_CONFIG_DIR) {
console.warn('[AgentProcess:setupEnv] WARNING: Profile env lacks CLAUDE_CONFIG_DIR - profile may not have a configDir set. Subscription metadata may not reach agent subprocess.');
}
debugLog('[AgentProcess:setupEnv] extraEnv auth keys:', {
hasOAuthToken: !!extraEnv.CLAUDE_CODE_OAUTH_TOKEN,
hasApiKey: !!extraEnv.ANTHROPIC_API_KEY,
hasConfigDir: !!extraEnv.CLAUDE_CONFIG_DIR,
});
// Use getAugmentedEnv() to ensure common tool paths (dotnet, homebrew, etc.)
// are available even when app is launched from Finder/Dock
const augmentedEnv = getAugmentedEnv();
@@ -229,9 +205,7 @@ export class AgentProcessManager {
const ghCliEnv = this.detectAndSetCliPath('gh');
const glabCliEnv = this.detectAndSetCliPath('glab');
// Profile env is spread last to ensure CLAUDE_CONFIG_DIR and auth vars
// from the active profile always win over extraEnv or augmentedEnv.
const mergedEnv = {
return {
...augmentedEnv,
...gitBashEnv,
...claudeCliEnv,
@@ -243,29 +217,6 @@ export class AgentProcessManager {
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
} as NodeJS.ProcessEnv;
// When the active profile provides CLAUDE_CONFIG_DIR, clear CLAUDE_CODE_OAUTH_TOKEN
// from the spawn environment. CLAUDE_CONFIG_DIR lets Claude Code resolve its own
// OAuth tokens from the config directory, making an explicit token unnecessary.
// This matches the terminal pattern in claude-integration-handler.ts where
// configDir is preferred over direct token injection.
// We check profileEnv specifically (not mergedEnv) to avoid clearing the token
// when CLAUDE_CONFIG_DIR comes from the shell environment rather than the profile.
if (profileEnv.CLAUDE_CONFIG_DIR) {
mergedEnv.CLAUDE_CODE_OAUTH_TOKEN = '';
debugLog('[AgentProcess:setupEnv] Profile provides CLAUDE_CONFIG_DIR, cleared CLAUDE_CODE_OAUTH_TOKEN from spawn env');
}
debugLog('[AgentProcess:setupEnv] Final merged env auth state:', {
hasOAuthToken: !!mergedEnv.CLAUDE_CODE_OAUTH_TOKEN,
hasApiKey: !!mergedEnv.ANTHROPIC_API_KEY,
hasConfigDir: !!mergedEnv.CLAUDE_CONFIG_DIR,
configDir: mergedEnv.CLAUDE_CONFIG_DIR || '(not set)',
oauthTokenPrefix: mergedEnv.CLAUDE_CODE_OAUTH_TOKEN?.substring(0, 8) || '(not set)',
apiKeyPrefix: mergedEnv.ANTHROPIC_API_KEY?.substring(0, 8) || '(not set)',
});
return mergedEnv;
}
private handleProcessFailure(
@@ -664,21 +615,6 @@ export class AgentProcessManager {
// Get OAuth mode clearing vars (clears stale ANTHROPIC_* vars when in OAuth mode)
const oauthModeClearVars = getOAuthModeClearVars(apiProfileEnv);
debugLog('[AgentProcess:spawnProcess] Environment merge chain for task:', taskId, {
baseEnv: {
hasOAuthToken: !!env.CLAUDE_CODE_OAUTH_TOKEN,
hasApiKey: !!env.ANTHROPIC_API_KEY,
hasConfigDir: !!env.CLAUDE_CONFIG_DIR,
configDir: env.CLAUDE_CONFIG_DIR || '(not set)',
},
oauthModeClearVars: Object.keys(oauthModeClearVars),
apiProfileEnv: {
hasApiKey: !!apiProfileEnv.ANTHROPIC_API_KEY,
hasBaseUrl: !!apiProfileEnv.ANTHROPIC_BASE_URL,
apiKeyPrefix: apiProfileEnv.ANTHROPIC_API_KEY?.substring(0, 8) || '(not set)',
},
});
// Parse Python commandto handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.getPythonPath());
let childProcess;
+2 -44
View File
@@ -38,18 +38,6 @@ log.transports.file.fileName = 'main.log';
// Console transport - always show warnings and errors, debug only in dev mode
log.transports.console.level = process.env.NODE_ENV === 'development' ? 'debug' : 'warn';
log.transports.console.format = '[{h}:{i}:{s}] [{level}] {text}';
// Guard console transport writes so broken stdio streams do not crash the app.
{
const originalConsoleWriteFn = log.transports.console.writeFn as (...args: unknown[]) => void;
log.transports.console.writeFn = (...args: unknown[]) => {
try {
originalConsoleWriteFn(...args);
} catch (error) {
const err = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
safeStderrWrite(`[app-logger] console transport write failed: ${err}`);
}
};
}
// Determine if this is a beta version
function isBetaVersion(): boolean {
@@ -216,44 +204,14 @@ export const appLog = {
log: (...args: unknown[]) => log.info(...args),
};
/**
* Best-effort stderr fallback used when electron-log itself throws (e.g. EIO).
* Must never throw, especially inside uncaught exception handlers.
*/
function safeStderrWrite(message: string): void {
try {
process.stderr.write(`${message}\n`);
} catch {
// Ignore - nothing else we can safely do here.
}
}
/**
* Log an unhandled error without risking recursive crashes if logger transport fails.
*/
function safeLogUnhandled(prefix: string, value: unknown): void {
try {
log.error(prefix, value);
} catch (loggingError) {
const loggingFailure = loggingError instanceof Error
? `${loggingError.name}: ${loggingError.message}`
: String(loggingError);
const original = value instanceof Error
? (value.stack || `${value.name}: ${value.message}`)
: String(value);
safeStderrWrite(`[app-logger] ${prefix} (logger failed: ${loggingFailure})`);
safeStderrWrite(original);
}
}
// Log unhandled errors
export function setupErrorLogging(): void {
process.on('uncaughtException', (error) => {
safeLogUnhandled('Uncaught exception:', error);
log.error('Uncaught exception:', error);
});
process.on('unhandledRejection', (reason) => {
safeLogUnhandled('Unhandled rejection:', reason);
log.error('Unhandled rejection:', reason);
});
log.info('Error logging initialized');
@@ -56,7 +56,6 @@ import {
expandHomePath,
getEmailFromConfigDir
} from './claude-profile/profile-utils';
import { debugLog } from '../shared/utils/debug-logger';
/**
* Manages Claude Code profiles for multi-account support.
@@ -87,8 +86,6 @@ export class ClaudeProfileManager {
return;
}
console.log('[ClaudeProfileManager] Starting initialization...');
// Ensure directory exists (async) - mkdir with recursive:true is idempotent
await mkdir(this.configDir, { recursive: true });
@@ -96,9 +93,6 @@ export class ClaudeProfileManager {
const loadedData = await loadProfileStoreAsync(this.storePath);
if (loadedData) {
this.data = loadedData;
debugLog('[ClaudeProfileManager] Loaded profile store with', this.data.profiles.length, 'profiles');
} else {
debugLog('[ClaudeProfileManager] No existing profile store found, using defaults');
}
// Run one-time migration to fix corrupted emails
@@ -110,7 +104,6 @@ export class ClaudeProfileManager {
this.populateSubscriptionMetadata();
this.initialized = true;
console.log('[ClaudeProfileManager] Initialization complete');
}
/**
@@ -156,20 +149,13 @@ export class ClaudeProfileManager {
private populateSubscriptionMetadata(): void {
let needsSave = false;
debugLog('[ClaudeProfileManager] populateSubscriptionMetadata: checking', this.data.profiles.length, 'profiles');
for (const profile of this.data.profiles) {
if (!profile.configDir) {
debugLog('[ClaudeProfileManager] populateSubscriptionMetadata: skipping profile', profile.id, '(no configDir)');
continue;
}
// Skip if profile already has subscription metadata
if (profile.subscriptionType && profile.rateLimitTier) {
debugLog('[ClaudeProfileManager] populateSubscriptionMetadata: profile', profile.id, 'already has metadata:', {
subscriptionType: profile.subscriptionType,
rateLimitTier: profile.rateLimitTier
});
continue;
}
@@ -556,27 +542,8 @@ export class ClaudeProfileManager {
if (process.env.DEBUG === 'true') {
console.warn('[ClaudeProfileManager] Using CLAUDE_CONFIG_DIR for profile:', profile.name, expandedConfigDir);
}
} else if (profile) {
// Fallback: retrieve OAuth token directly from Keychain when configDir is missing.
// Without configDir, Claude CLI cannot resolve credentials automatically,
// so we inject CLAUDE_CODE_OAUTH_TOKEN as a direct override.
debugLog(
'[ClaudeProfileManager] Profile has no configDir configured:',
profile.name,
'- falling back to Keychain token lookup. Subscription display may be degraded.'
);
const credentials = getCredentialsFromKeychain(undefined, true);
if (credentials.token) {
env.CLAUDE_CODE_OAUTH_TOKEN = credentials.token;
debugLog('[ClaudeProfileManager] Injected CLAUDE_CODE_OAUTH_TOKEN from Keychain for profile:', profile.name);
} else {
debugLog(
'[ClaudeProfileManager] No token found in Keychain for profile without configDir:',
profile.name,
credentials.error ? `(error: ${credentials.error})` : ''
);
}
} else {
console.warn('[ClaudeProfileManager] Profile has no configDir configured:', profile?.name);
}
return env;
@@ -834,26 +801,8 @@ export class ClaudeProfileManager {
return {};
}
// If no configDir is defined, fall back to default
if (!profile.configDir) {
// Fallback: retrieve OAuth token directly from Keychain when configDir is missing.
// Without configDir, Claude CLI cannot resolve credentials automatically,
// so we inject CLAUDE_CODE_OAUTH_TOKEN as a direct override.
// This mirrors the fallback in getActiveProfileEnv().
debugLog(
'[ClaudeProfileManager] getProfileEnv: profile has no configDir:',
profile.name,
'- falling back to Keychain token lookup.'
);
const credentials = getCredentialsFromKeychain(undefined, true);
if (credentials.token) {
debugLog('[ClaudeProfileManager] getProfileEnv: injected CLAUDE_CODE_OAUTH_TOKEN from Keychain for profile:', profile.name);
return { CLAUDE_CODE_OAUTH_TOKEN: credentials.token };
}
debugLog(
'[ClaudeProfileManager] getProfileEnv: no token found in Keychain for profile without configDir:',
profile.name
);
return {};
}
@@ -1825,7 +1825,6 @@ function updateLinuxFileCredentials(
}
// Write to file with secure permissions (0600)
// lgtm[js/http-to-file-access] - credentialsPath is from controlled configDir
writeFileSync(credentialsPath, credentialsJson, { mode: 0o600, encoding: 'utf-8' });
if (isDebug) {
@@ -2087,7 +2086,6 @@ function updateWindowsFileCredentials(
const tempPath = `${credentialsPath}.${Date.now()}.tmp`;
try {
// Write to temp file
// lgtm[js/http-to-file-access] - credentialsPath is from controlled configDir
writeFileSync(tempPath, credentialsJson, { encoding: 'utf-8' });
// Restrict temp file permissions to current user only (mimics Unix 0600)
+1 -15
View File
@@ -49,7 +49,7 @@ import { initializeAppUpdater, stopPeriodicUpdates } from './app-updater';
import { DEFAULT_APP_SETTINGS, IPC_CHANNELS, SPELL_CHECK_LANGUAGE_MAP, DEFAULT_SPELL_CHECK_LANGUAGE, ADD_TO_DICTIONARY_LABELS } from '../shared/constants';
import { getAppLanguage, initAppLanguage } from './app-language';
import { readSettingsFile } from './settings-utils';
import { appLog, setupErrorLogging } from './app-logger';
import { setupErrorLogging } from './app-logger';
import { initSentryMain } from './sentry';
import { preWarmToolCache } from './cli-tool-manager';
import { initializeClaudeProfileManager, getClaudeProfileManager } from './claude-profile-manager';
@@ -143,11 +143,6 @@ let mainWindow: BrowserWindow | null = null;
let agentManager: AgentManager | null = null;
let terminalManager: TerminalManager | null = null;
// Capture child process exits (renderer/GPU/utility) for crash diagnostics.
app.on('child-process-gone', (_event, details) => {
appLog.error('[main] child-process-gone:', details);
});
// Re-entrancy guard for before-quit handler.
// The first before-quit call pauses quit for async cleanup, then calls app.quit() again.
// The second call sees isQuitting=true and allows quit to proceed immediately.
@@ -219,11 +214,6 @@ function createWindow(): void {
mainWindow?.show();
});
// Capture renderer process crashes/termination reasons for diagnostics.
mainWindow.webContents.on('render-process-gone', (_event, details) => {
appLog.error('[main] render-process-gone:', details);
});
// Configure initial spell check languages with proper fallback logic
// Uses shared constant for consistency with the IPC handler
const defaultLanguage = 'en';
@@ -340,10 +330,6 @@ function createWindow(): void {
// Clean up on close
mainWindow.on('closed', () => {
// Kill all agents when window closes (prevents orphaned processes)
agentManager?.killAll?.()?.catch((err: unknown) => {
console.warn('[main] Error killing agents on window close:', err);
});
mainWindow = null;
});
}
@@ -112,7 +112,6 @@ async function githubGraphQL<T>(
query: string,
variables: Record<string, unknown> = {}
): Promise<T> {
// lgtm[js/file-access-to-http] - Official GitHub GraphQL API endpoint
const response = await fetch("https://api.github.com/graphql", {
method: "POST",
headers: {
@@ -268,10 +267,6 @@ export interface PRReviewFinding {
endLine?: number;
suggestedFix?: string;
fixable: boolean;
validationStatus?: "confirmed_valid" | "dismissed_false_positive" | "needs_human_review" | null;
validationExplanation?: string;
sourceAgents?: string[];
crossValidated?: boolean;
}
/**
@@ -283,7 +278,7 @@ export interface PRReviewResult {
success: boolean;
findings: PRReviewFinding[];
summary: string;
overallStatus: "approve" | "request_changes" | "comment" | "in_progress";
overallStatus: "approve" | "request_changes" | "comment";
reviewId?: number;
reviewedAt: string;
error?: string;
@@ -299,8 +294,6 @@ export interface PRReviewResult {
hasPostedFindings?: boolean;
postedFindingIds?: string[];
postedAt?: string;
// In-progress review tracking
inProgressSince?: string;
}
/**
@@ -1345,10 +1338,6 @@ function getReviewResult(project: Project, prNumber: number): PRReviewResult | n
endLine: f.end_line,
suggestedFix: f.suggested_fix,
fixable: f.fixable ?? false,
validationStatus: f.validation_status ?? null,
validationExplanation: f.validation_explanation ?? undefined,
sourceAgents: f.source_agents ?? [],
crossValidated: f.cross_validated ?? false,
})) ?? [],
summary: data.summary ?? "",
overallStatus: data.overall_status ?? "comment",
@@ -1367,8 +1356,6 @@ function getReviewResult(project: Project, prNumber: number): PRReviewResult | n
hasPostedFindings: data.has_posted_findings ?? false,
postedFindingIds: data.posted_finding_ids ?? [],
postedAt: data.posted_at,
// In-progress review tracking
inProgressSince: data.in_progress_since,
};
} catch {
// File doesn't exist or couldn't be read
@@ -1527,32 +1514,7 @@ async function runPRReview(
debugLog("Auth failure detected in PR review", authFailureInfo);
mainWindow.webContents.send(IPC_CHANNELS.CLAUDE_AUTH_FAILURE, authFailureInfo);
},
onComplete: (stdout: string) => {
// Check stdout for in_progress JSON marker (not saved to disk by backend)
const inProgressMarker = "__RESULT_JSON__:";
for (const line of stdout.split("\n")) {
if (line.startsWith(inProgressMarker)) {
try {
const data = JSON.parse(line.slice(inProgressMarker.length));
if (data.overall_status === "in_progress") {
debugLog("In-progress result parsed from stdout", { prNumber });
return {
prNumber: data.pr_number,
repo: data.repo,
success: data.success,
findings: [],
summary: data.summary ?? "",
overallStatus: "in_progress" as const,
reviewedAt: data.reviewed_at ?? new Date().toISOString(),
inProgressSince: data.in_progress_since,
};
}
} catch {
debugLog("Failed to parse __RESULT_JSON__ line", { line });
}
}
}
onComplete: () => {
// Load the result from disk
const reviewResult = getReviewResult(project, prNumber);
if (!reviewResult) {
@@ -1902,15 +1864,9 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
projectId
);
// Check if already running — notify renderer so it can display ongoing logs
// Check if already running
if (runningReviews.has(reviewKey)) {
debugLog("Review already running, notifying renderer", { reviewKey });
sendProgress({
phase: "analyzing",
prNumber,
progress: 50,
message: "Review is already in progress. Reconnecting to ongoing review...",
});
debugLog("Review already running", { reviewKey });
return;
}
@@ -1980,20 +1936,6 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
const result = await runPRReview(project, prNumber, mainWindow);
if (result.overallStatus === "in_progress") {
// Review is already running externally (detected by BotDetector).
// Send the result as-is so the renderer can activate external review polling.
debugLog("PR review already in progress externally", { prNumber });
sendProgress({
phase: "complete",
prNumber,
progress: 100,
message: "Review already in progress",
});
sendComplete(result);
return;
}
debugLog("PR review completed", { prNumber, findingsCount: result.findings.length });
sendProgress({
phase: "complete",
@@ -137,7 +137,6 @@ export async function createSpecForIssue(
status: 'pending',
phases: []
};
// lgtm[js/http-to-file-access] - specDir is controlled, slugifiedTitle sanitizes input
writeFileSync(
path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN),
JSON.stringify(implementationPlan, null, 2),
@@ -149,7 +148,6 @@ export async function createSpecForIssue(
task_description: safeDescription,
workflow_type: 'feature'
};
// lgtm[js/http-to-file-access] - specDir is controlled, slugifiedTitle sanitizes input
writeFileSync(
path.join(specDir, AUTO_BUILD_PATHS.REQUIREMENTS),
JSON.stringify(requirements, null, 2),
@@ -169,7 +167,6 @@ export async function createSpecForIssue(
// This comes from project.settings.mainBranch or task-level override
...(baseBranch && { baseBranch })
};
// lgtm[js/http-to-file-access] - specDir is controlled, slugifiedTitle sanitizes input
writeFileSync(
path.join(specDir, 'task_metadata.json'),
JSON.stringify(metadata, null, 2),
@@ -8,8 +8,8 @@ import { IPC_CHANNELS } from '../../../shared/constants';
import type { GitLabInvestigationStatus, GitLabInvestigationResult } from '../../../shared/types';
import { projectStore } from '../../project-store';
import { getGitLabConfig, gitlabFetch, encodeProjectPath } from './utils';
import type { GitLabAPIIssue, GitLabAPINoteBasic } from './types';
import { createSpecForIssue, fetchAllIssueNotes } from './spec-utils';
import type { GitLabAPIIssue, GitLabAPINote } from './types';
import { buildIssueContext, createSpecForIssue } from './spec-utils';
import type { AgentManager } from '../../agent';
// Debug logging helper
@@ -109,31 +109,51 @@ export function registerInvestigateIssue(
`/projects/${encodedProject}/issues/${issueIid}`
) as GitLabAPIIssue;
// Fetch notes if any selected (with pagination to get all notes)
let filteredNotes: GitLabAPINoteBasic[] = [];
// Fetch notes if any selected
let selectedNotes: GitLabAPINote[] = [];
if (selectedNoteIds && selectedNoteIds.length > 0) {
// Fetch all notes using the paginated utility function
const allNotes = await fetchAllIssueNotes(config, encodedProject, issueIid);
// Filter notes based on selection
filteredNotes = allNotes.filter(note => selectedNoteIds.includes(note.id));
const allNotes = await gitlabFetch(
config.token,
config.instanceUrl,
`/projects/${encodedProject}/issues/${issueIid}/notes`
) as GitLabAPINote[];
selectedNotes = allNotes.filter(note => selectedNoteIds.includes(note.id));
}
// Phase 2: Creating task
// Phase 2: Analyzing
sendProgress(getMainWindow, project.id, {
phase: 'analyzing',
issueIid,
progress: 30,
message: 'Analyzing issue with AI...'
});
// Note: Context building previously done here has been moved to createSpecForIssue utility.
// The buildIssueContext() function and selectedNotes processing are now handled internally
// by the spec creation pipeline. This avoids duplicate context generation.
// TODO: If advanced context customization is needed in the future, consider extracting
// context building into a reusable utility function.
// Use agent manager to investigate
// Note: This is a simplified version - full implementation would use Claude SDK
sendProgress(getMainWindow, project.id, {
phase: 'analyzing',
issueIid,
progress: 50,
message: 'AI analyzing the issue...'
});
// Phase 3: Creating task
sendProgress(getMainWindow, project.id, {
phase: 'creating_task',
issueIid,
progress: 50,
message: 'Creating task from issue...'
progress: 80,
message: 'Creating task from analysis...'
});
// Create spec for the issue with notes
const task = await createSpecForIssue(
project,
issue,
config,
project.settings?.mainBranch,
filteredNotes
);
// Create spec for the issue
const task = await createSpecForIssue(project, issue, config, project.settings?.mainBranch);
if (!task) {
sendError(getMainWindow, project.id, 'Failed to create task from issue');
@@ -6,7 +6,7 @@
import { mkdir, writeFile, readFile, stat } from 'fs/promises';
import path from 'path';
import type { Project } from '../../../shared/types';
import type { GitLabAPIIssue, GitLabAPINoteBasic, GitLabConfig } from './types';
import type { GitLabAPIIssue, GitLabConfig } from './types';
import { labelMatchesWholeWord } from '../shared/label-utils';
import { sanitizeText, sanitizeStringArray } from '../shared/sanitize';
@@ -208,12 +208,7 @@ function generateSpecDirName(issueIid: number, title: string): string {
/**
* Build issue context for spec creation
*/
export function buildIssueContext(
issue: IssueLike,
projectPath: string,
instanceUrl: string,
notes?: GitLabAPINoteBasic[]
): string {
export function buildIssueContext(issue: IssueLike, projectPath: string, instanceUrl: string): string {
const lines: string[] = [];
const safeProjectPath = sanitizeText(projectPath, 200);
const safeIssue = sanitizeIssueForSpec(issue, instanceUrl);
@@ -243,19 +238,6 @@ export function buildIssueContext(
lines.push('');
lines.push(`**Web URL:** ${safeIssue.web_url}`);
// Add notes section if notes are provided
if (notes && notes.length > 0) {
lines.push('');
lines.push(`## Notes (${notes.length})`);
lines.push('');
for (const note of notes) {
const safeAuthor = sanitizeText(note.author?.username || 'unknown', 100);
const safeBody = sanitizeText(note.body, 20000, true);
lines.push(`**${safeAuthor}:** ${safeBody}`);
lines.push('');
}
}
return lines.join('\n');
}
@@ -271,103 +253,6 @@ async function pathExists(filePath: string): Promise<boolean> {
}
}
/**
* Fetches all notes for a GitLab issue with pagination.
* Handles rate limiting and authentication errors gracefully.
*
* @param config GitLab configuration with token and instance URL
* @param encodedProject URL-encoded project path
* @param issueIid Issue IID to fetch notes for
* @returns Array of basic note objects with id, body, and author
*/
export async function fetchAllIssueNotes(
config: { token: string; instanceUrl: string },
encodedProject: string,
issueIid: number
): Promise<GitLabAPINoteBasic[]> {
const { gitlabFetch } = await import('./utils');
const { GitLabAPIError } = await import('./utils');
const allNotes: GitLabAPINoteBasic[] = [];
let page = 1;
const perPage = 100;
const MAX_PAGES = 50; // Safety limit: max 5000 notes
let hasMore = true;
while (hasMore && page <= MAX_PAGES) {
try {
const notesPage = await gitlabFetch(
config.token,
config.instanceUrl,
`/projects/${encodedProject}/issues/${issueIid}/notes?page=${page}&per_page=${perPage}`
) as unknown[];
// Runtime validation: ensure we got an array
if (!Array.isArray(notesPage)) {
debugLog('GitLab notes API returned non-array, stopping pagination');
break;
}
if (notesPage.length === 0) {
hasMore = false;
} else {
// Extract only needed fields with null-safe defaults
const noteSummaries: GitLabAPINoteBasic[] = notesPage
.filter((note: unknown): note is Record<string, unknown> =>
note !== null && typeof note === 'object' && typeof (note as Record<string, unknown>).id === 'number'
)
.map((note) => {
// Validate author structure defensively
const author = note.author;
const username = (author !== null && typeof author === 'object' && typeof (author as Record<string, unknown>).username === 'string')
? (author as Record<string, unknown>).username as string
: 'unknown';
return {
id: note.id as number,
body: (note.body as string | undefined) || '',
author: { username },
};
});
allNotes.push(...noteSummaries);
if (notesPage.length < perPage) {
hasMore = false;
} else {
page++;
}
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
// Check for authentication/rate-limit errors using structured status codes
const isAuthError = error instanceof GitLabAPIError && (error.statusCode === 401 || error.statusCode === 403);
const isRateLimited = error instanceof GitLabAPIError && error.statusCode === 429;
if (isAuthError || isRateLimited) {
// Re-throw critical errors to let the caller surface them to the user
const statusCode = error instanceof GitLabAPIError ? error.statusCode : undefined;
console.warn(`[GitLab Notes] ${isAuthError ? 'Authentication' : 'Rate limit'} error during notes fetch`, { page, error: errorMessage, statusCode });
throw error;
}
// For transient errors on page 1, warn the user but continue
if (page === 1 && allNotes.length === 0) {
console.warn('[GitLab Notes] Failed to fetch any notes, proceeding without notes context', { error: errorMessage });
} else {
// Log pagination failure for subsequent pages
debugLog('Failed to fetch notes page, using partial notes', { page, error: errorMessage, notesRetrieved: allNotes.length });
}
hasMore = false;
}
}
// Warn if we hit the pagination limit
if (page > MAX_PAGES && hasMore) {
debugLog('Pagination limit reached, some notes may be missing', { maxPages: MAX_PAGES, notesRetrieved: allNotes.length });
}
return allNotes;
}
/**
* Create a task spec from a GitLab issue
*/
@@ -375,8 +260,7 @@ export async function createSpecForIssue(
project: Project,
issue: GitLabAPIIssue,
config: GitLabConfig,
baseBranch?: string,
notes?: GitLabAPINoteBasic[]
baseBranch?: string
): Promise<GitLabTaskInfo | null> {
try {
// Validate and sanitize network data before writing to disk
@@ -435,8 +319,8 @@ export async function createSpecForIssue(
// Create spec directory
await mkdir(specDir, { recursive: true });
// Create TASK.md with issue context (including selected notes)
const taskContent = buildIssueContext(safeIssue, safeProject, safeInstanceUrl, notes);
// Create TASK.md with issue context
const taskContent = buildIssueContext(safeIssue, safeProject, config.instanceUrl);
await writeFile(path.join(specDir, 'TASK.md'), taskContent, 'utf-8');
// Create metadata.json (legacy format for GitLab-specific data)
@@ -420,7 +420,6 @@ export function registerTriageHandlers(
}
// Save result
// lgtm[js/http-to-file-access] - triageDir from controlled project path, issue_iid is numeric
fs.writeFileSync(
path.join(triageDir, `triage_${sanitizedResult.issue_iid}.json`),
JSON.stringify(sanitizedResult, null, 2),
@@ -51,13 +51,6 @@ export interface GitLabAPINote {
system: boolean;
}
// Basic note type with only fields needed by investigation handlers
export interface GitLabAPINoteBasic {
id: number;
body: string;
author: { username: string };
}
export interface GitLabAPIMergeRequest {
id: number;
iid: number;
@@ -13,19 +13,6 @@ import { getIsolatedGitEnv } from '../../utils/git-isolation';
const DEFAULT_GITLAB_URL = 'https://gitlab.com';
/**
* Custom error class for GitLab API errors with structured status code
*/
export class GitLabAPIError extends Error {
public readonly statusCode: number;
constructor(message: string, statusCode: number) {
super(message);
this.name = 'GitLabAPIError';
this.statusCode = statusCode;
}
}
function parseInstanceUrl(value: string): string | null {
const candidate = value.trim();
if (!candidate) return null;
@@ -274,16 +261,13 @@ export async function gitlabFetch(
if (!response.ok) {
const errorBody = await response.text();
throw new GitLabAPIError(
`GitLab API error: ${response.status} ${response.statusText} - ${errorBody}`,
response.status
);
throw new Error(`GitLab API error: ${response.status} ${response.statusText} - ${errorBody}`);
}
return response.json();
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
throw new GitLabAPIError(`GitLab API timeout after ${GITLAB_API_TIMEOUT_MS / 1000}s: ${url}`, 0);
throw new Error(`GitLab API timeout after ${GITLAB_API_TIMEOUT_MS / 1000}s: ${url}`);
}
throw error;
} finally {
@@ -332,10 +316,7 @@ export async function gitlabFetchWithCount(
if (!response.ok) {
const errorBody = await response.text();
throw new GitLabAPIError(
`GitLab API error: ${response.status} ${response.statusText} - ${errorBody}`,
response.status
);
throw new Error(`GitLab API error: ${response.status} ${response.statusText} - ${errorBody}`);
}
// Get total count from X-Total header (GitLab's pagination header)
@@ -346,7 +327,7 @@ export async function gitlabFetchWithCount(
return { data, totalCount };
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
throw new GitLabAPIError(`GitLab API timeout after ${GITLAB_API_TIMEOUT_MS / 1000}s: ${url}`, 0);
throw new Error(`GitLab API timeout after ${GITLAB_API_TIMEOUT_MS / 1000}s: ${url}`);
}
throw error;
} finally {
@@ -35,7 +35,6 @@ import { registerProfileHandlers } from './profile-handlers';
import { registerScreenshotHandlers } from './screenshot-handlers';
import { registerTerminalWorktreeIpcHandlers } from './terminal';
import { notificationService } from '../notification-service';
import { setAgentManagerRef } from './utils';
/**
* Setup all IPC handlers across all domains
@@ -54,9 +53,6 @@ export function setupIpcHandlers(
// Initialize notification service
notificationService.initialize(getMainWindow);
// Wire up agent manager for circuit breaker cleanup
setAgentManagerRef(agentManager);
// Project handlers (including Python environment setup)
registerProjectHandlers(pythonEnvManager, agentManager, getMainWindow);
@@ -507,7 +507,6 @@ ${safeDescription || 'No description provided.'}
status: 'pending',
phases: []
};
// lgtm[js/http-to-file-access] - specDir is controlled, Linear data sanitized
writeFileSync(path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN), JSON.stringify(implementationPlan, null, 2), 'utf-8');
// Create requirements.json
@@ -515,7 +514,6 @@ ${safeDescription || 'No description provided.'}
task_description: description,
workflow_type: 'feature'
};
// lgtm[js/http-to-file-access] - specDir is controlled, Linear data sanitized
writeFileSync(path.join(specDir, AUTO_BUILD_PATHS.REQUIREMENTS), JSON.stringify(requirements, null, 2), 'utf-8');
// Build metadata
@@ -526,7 +524,6 @@ ${safeDescription || 'No description provided.'}
linearUrl: safeUrl,
category: 'feature'
};
// lgtm[js/http-to-file-access] - specDir is controlled, Linear data sanitized
writeFileSync(path.join(specDir, 'task_metadata.json'), JSON.stringify(metadata, null, 2), 'utf-8');
// Start spec creation with the existing spec directory
@@ -1,5 +1,6 @@
import { ipcMain } from 'electron';
import { existsSync } from 'fs';
import { ipcMain, app } from 'electron';
import { existsSync, } from 'fs';
import path from 'path';
import { execFileSync } from 'child_process';
import { IPC_CHANNELS } from '../../shared/constants';
import type {
@@ -8,7 +8,7 @@ import type {
OtherWorktreeInfo,
} from '../../../shared/types';
import path from 'path';
import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, symlinkSync, lstatSync, copyFileSync, cpSync, statSync } from 'fs';
import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, symlinkSync, lstatSync } from 'fs';
import { execFileSync, execFile } from 'child_process';
import { promisify } from 'util';
import { minimatch } from 'minimatch';
@@ -226,405 +226,87 @@ function getDefaultBranch(projectPath: string): string {
}
/**
* Configuration for a single dependency to be shared in a worktree.
*/
interface DependencyConfig {
/** Dependency type identifier (e.g., 'node_modules', 'venv') */
depType: string;
/** Strategy for sharing this dependency in worktrees */
strategy: 'symlink' | 'recreate' | 'copy' | 'skip';
/** Relative path from project root to the dependency directory */
sourceRelPath: string;
/** Path to requirements file for recreate strategy (e.g., 'requirements.txt') */
requirementsFile?: string;
/** Package manager used (e.g., 'npm', 'pip', 'uv') */
packageManager?: string;
}
/**
* Default mapping from dependency type to sharing strategy.
*
* Data-driven add new entries here rather than writing if/else branches.
* Mirrors the Python implementation in apps/backend/core/workspace/dependency_strategy.py.
*/
const DEFAULT_STRATEGY_MAP: Record<string, 'symlink' | 'recreate' | 'copy' | 'skip'> = {
// JavaScript / Node.js — symlink is safe and fast
node_modules: 'symlink',
// Python — venvs MUST be recreated, not symlinked.
// CPython bug #106045: pyvenv.cfg discovery does not resolve symlinks,
// so a symlinked venv resolves paths relative to the target, not the worktree.
venv: 'recreate',
'.venv': 'recreate',
// PHP — Composer vendor dir is safe to symlink
vendor_php: 'symlink',
// Ruby — Bundler vendor/bundle is safe to symlink
vendor_bundle: 'symlink',
// Rust — build output dir, skip (rebuilt per-worktree)
cargo_target: 'skip',
// Go — global module cache, nothing in-tree to share
go_modules: 'skip',
};
/**
* Load dependency configs from the project index, or fall back to hardcoded
* node_modules-only behavior for backward compatibility.
*/
function loadDependencyConfigs(projectPath: string): DependencyConfig[] {
const indexPath = path.join(projectPath, '.auto-claude', 'project_index.json');
if (existsSync(indexPath)) {
try {
const index = JSON.parse(readFileSync(indexPath, 'utf-8'));
// Use the aggregated top-level dependency_locations which already
// contain project-relative paths (e.g. "apps/backend/.venv" instead
// of just ".venv"), avoiding a monorepo path resolution bug.
const depLocations = index?.dependency_locations;
if (Array.isArray(depLocations)) {
const configs: DependencyConfig[] = [];
const seen = new Set<string>();
for (const dep of depLocations) {
if (!dep || typeof dep !== 'object') continue;
const depObj = dep as Record<string, unknown>;
const depType = String(depObj.type || '');
const relPath = String(depObj.path || '');
if (!depType || !relPath || seen.has(relPath)) continue;
// Path containment: reject absolute paths and traversals
if (path.isAbsolute(relPath)) continue;
if (relPath.split('/').includes('..') || relPath.split('\\').includes('..')) continue;
// Defense-in-depth: verify resolved path stays within project
const resolved = path.resolve(projectPath, relPath);
if (!resolved.startsWith(path.resolve(projectPath) + path.sep)) continue;
seen.add(relPath);
const strategy = DEFAULT_STRATEGY_MAP[depType] ?? 'skip';
// Validate requirementsFile path containment
let reqFile: string | undefined;
if (depObj.requirements_file) {
const rf = String(depObj.requirements_file);
const rfParts = rf.split('/');
const rfPartsWin = rf.split('\\');
if (!path.isAbsolute(rf) && !rfParts.includes('..') && !rfPartsWin.includes('..')) {
// Defense-in-depth: resolved-path containment (matches relPath check)
const resolvedReq = path.resolve(projectPath, rf);
if (resolvedReq.startsWith(path.resolve(projectPath) + path.sep)) {
reqFile = rf;
}
}
}
configs.push({
depType,
strategy,
sourceRelPath: relPath,
requirementsFile: reqFile,
packageManager: depObj.package_manager ? String(depObj.package_manager) : undefined,
});
}
if (configs.length > 0) {
return configs;
}
}
} catch (error) {
debugError('[TerminalWorktree] Failed to read project index:', error);
}
}
// Fallback: hardcoded node_modules-only behavior (same as legacy)
return [
{ depType: 'node_modules', strategy: 'symlink', sourceRelPath: 'node_modules' },
{ depType: 'node_modules', strategy: 'symlink', sourceRelPath: 'apps/frontend/node_modules' },
];
}
/**
* Set up dependencies in a worktree using strategy-based dispatch.
*
* Reads dependency configs from the project index and applies the correct
* strategy for each: symlink, recreate, copy, or skip.
*
* All operations are non-blocking on failure errors are logged but never thrown.
* Symlink node_modules from project root to worktree for TypeScript and tooling support.
* This allows pre-commit hooks and IDE features to work without npm install in the worktree.
*
* @param projectPath - The main project directory
* @param worktreePath - Path to the worktree
* @returns Array of successfully processed dependency relative paths
* @returns Array of symlinked paths (relative to worktree)
*/
async function setupWorktreeDependencies(projectPath: string, worktreePath: string): Promise<string[]> {
const configs = loadDependencyConfigs(projectPath);
const processed: string[] = [];
for (const config of configs) {
try {
let performed = false;
switch (config.strategy) {
case 'symlink':
performed = applySymlinkStrategy(projectPath, worktreePath, config);
break;
case 'recreate':
performed = await applyRecreateStrategy(projectPath, worktreePath, config);
break;
case 'copy':
performed = applyCopyStrategy(projectPath, worktreePath, config);
break;
case 'skip':
debugLog('[TerminalWorktree] Skipping', config.depType, `(${config.sourceRelPath}) - skip strategy`);
continue; // Don't record skipped entries in processed list
}
if (performed) processed.push(config.sourceRelPath);
} catch (error) {
debugError('[TerminalWorktree] Failed to apply', config.strategy, 'strategy for', config.sourceRelPath, ':', error);
console.warn(`[TerminalWorktree] Warning: Failed to set up ${config.sourceRelPath}`);
}
}
return processed;
}
/**
* Apply symlink strategy: create a symlink (or Windows junction) from worktree to project source.
* Reuses the existing platform-specific symlink creation pattern.
*/
function applySymlinkStrategy(projectPath: string, worktreePath: string, config: DependencyConfig): boolean {
const sourcePath = path.join(projectPath, config.sourceRelPath);
const targetPath = path.join(worktreePath, config.sourceRelPath);
if (!existsSync(sourcePath)) {
debugLog('[TerminalWorktree] Skipping symlink', config.sourceRelPath, '- source missing');
return false;
}
if (existsSync(targetPath)) {
debugLog('[TerminalWorktree] Skipping symlink', config.sourceRelPath, '- target exists');
return false;
}
// Check for broken symlinks
try {
lstatSync(targetPath);
debugLog('[TerminalWorktree] Skipping symlink', config.sourceRelPath, '- target exists (possibly broken symlink)');
return false;
} catch {
// Target doesn't exist at all — good, we can create symlink
}
const targetDir = path.dirname(targetPath);
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
try {
if (isWindows()) {
symlinkSync(sourcePath, targetPath, 'junction');
debugLog('[TerminalWorktree] Created junction (Windows):', config.sourceRelPath, '->', sourcePath);
} else {
const relativePath = path.relative(path.dirname(targetPath), sourcePath);
symlinkSync(relativePath, targetPath);
debugLog('[TerminalWorktree] Created symlink (Unix):', config.sourceRelPath, '->', relativePath);
}
return true;
} catch (error) {
debugError('[TerminalWorktree] Could not create symlink for', config.sourceRelPath, ':', error);
console.warn(`[TerminalWorktree] Warning: Failed to link ${config.sourceRelPath}`);
return false;
}
}
/**
* Apply recreate strategy: create a fresh virtual environment in the worktree.
*
* Python venvs cannot be symlinked due to CPython bug #106045 pyvenv.cfg
* discovery does not resolve symlinks, so paths resolve relative to the
* symlink target instead of the worktree.
*/
async function applyRecreateStrategy(projectPath: string, worktreePath: string, config: DependencyConfig): Promise<boolean> {
const venvPath = path.join(worktreePath, config.sourceRelPath);
if (existsSync(venvPath)) {
debugLog('[TerminalWorktree] Skipping recreate', config.sourceRelPath, '- already exists');
return false;
}
// Detect Python executable from the source venv or fall back to system Python
const sourceVenv = path.join(projectPath, config.sourceRelPath);
let pythonExec = isWindows() ? 'python' : 'python3';
if (existsSync(sourceVenv)) {
const unixCandidate = path.join(sourceVenv, 'bin', 'python');
const winCandidate = path.join(sourceVenv, 'Scripts', 'python.exe');
if (existsSync(unixCandidate)) {
pythonExec = unixCandidate;
} else if (existsSync(winCandidate)) {
pythonExec = winCandidate;
}
}
// Create the venv
try {
debugLog('[TerminalWorktree] Creating venv at', config.sourceRelPath);
await execFileAsync(pythonExec, ['-m', 'venv', venvPath], {
encoding: 'utf-8',
timeout: 120000,
});
} catch (error) {
if (isTimeoutError(error)) {
debugError('[TerminalWorktree] venv creation timed out for', config.sourceRelPath);
console.warn(`[TerminalWorktree] Warning: venv creation timed out for ${config.sourceRelPath}`);
} else {
debugError('[TerminalWorktree] venv creation failed for', config.sourceRelPath, ':', error);
console.warn(`[TerminalWorktree] Warning: Could not create venv at ${config.sourceRelPath}`);
}
// Clean up partial venv so retries aren't blocked
if (existsSync(venvPath)) {
try { rmSync(venvPath, { recursive: true, force: true }); } catch { /* best-effort */ }
}
return false;
}
// Install from requirements file if specified
if (config.requirementsFile) {
const reqPath = path.join(projectPath, config.requirementsFile);
if (existsSync(reqPath)) {
const pipExec = isWindows()
? path.join(venvPath, 'Scripts', 'pip.exe')
: path.join(venvPath, 'bin', 'pip');
// Build install command based on file type
const reqBasename = path.basename(config.requirementsFile);
let installArgs: string[] | null;
if (reqBasename === 'pyproject.toml') {
// Snapshot-install from worktree copy (non-editable to avoid
// symlinking back to the main project source tree).
const worktreeReq = path.join(worktreePath, config.requirementsFile!);
const installDir = existsSync(worktreeReq) ? path.dirname(worktreeReq) : path.dirname(reqPath);
installArgs = ['install', installDir];
} else if (reqBasename === 'Pipfile') {
debugLog('[TerminalWorktree] Skipping Pipfile-based install (use pipenv in worktree)');
installArgs = null;
} else {
installArgs = ['install', '-r', reqPath];
}
if (installArgs) {
try {
debugLog('[TerminalWorktree] Installing deps from', config.requirementsFile);
await execFileAsync(pipExec, installArgs, {
encoding: 'utf-8',
timeout: 120000,
});
} catch (error) {
if (isTimeoutError(error)) {
debugError('[TerminalWorktree] pip install timed out for', config.requirementsFile);
console.warn(`[TerminalWorktree] Warning: Dependency install timed out for ${config.requirementsFile}`);
} else {
debugError('[TerminalWorktree] pip install failed:', error);
}
// Clean up broken venv so retries aren't blocked
if (existsSync(venvPath)) {
try { rmSync(venvPath, { recursive: true, force: true }); } catch { /* best-effort */ }
}
return false;
}
}
}
}
debugLog('[TerminalWorktree] Recreated venv at', config.sourceRelPath);
return true;
}
/**
* Apply copy strategy: copy a file or directory from project to worktree.
*/
function applyCopyStrategy(projectPath: string, worktreePath: string, config: DependencyConfig): boolean {
const sourcePath = path.join(projectPath, config.sourceRelPath);
const targetPath = path.join(worktreePath, config.sourceRelPath);
if (!existsSync(sourcePath)) {
debugLog('[TerminalWorktree] Skipping copy', config.sourceRelPath, '- source missing');
return false;
}
if (existsSync(targetPath)) {
debugLog('[TerminalWorktree] Skipping copy', config.sourceRelPath, '- target exists');
return false;
}
const targetDir = path.dirname(targetPath);
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
try {
if (statSync(sourcePath).isDirectory()) {
cpSync(sourcePath, targetPath, { recursive: true });
} else {
copyFileSync(sourcePath, targetPath);
}
debugLog('[TerminalWorktree] Copied', config.sourceRelPath, 'to worktree');
return true;
} catch (error) {
debugError('[TerminalWorktree] Could not copy', config.sourceRelPath, ':', error);
console.warn(`[TerminalWorktree] Warning: Could not copy ${config.sourceRelPath}`);
return false;
}
}
/**
* Symlink the project root's .claude/ directory into a terminal worktree.
* This enables Claude Code features (settings, commands, memory) in worktree terminals.
* Follows the same pattern as setupWorktreeDependencies().
*/
function symlinkClaudeConfigToWorktree(projectPath: string, worktreePath: string): string[] {
function symlinkNodeModulesToWorktree(projectPath: string, worktreePath: string): string[] {
const symlinked: string[] = [];
const sourceRel = '.claude';
const sourcePath = path.join(projectPath, sourceRel);
const targetPath = path.join(worktreePath, sourceRel);
// Node modules locations to symlink for TypeScript and tooling support.
// These are the standard locations for this monorepo structure.
//
// Design rationale:
// - Hardcoded paths are intentional for simplicity and reliability
// - Dynamic discovery (reading workspaces from package.json) would add complexity
// and potential failure points without significant benefit
// - This monorepo uses npm workspaces with hoisting, so dependencies are primarily
// in root node_modules with workspace-specific deps in apps/frontend/node_modules
//
// To add new workspace locations:
// 1. Add [sourceRelPath, targetRelPath] tuple below
// 2. Update the parallel Python implementation in apps/backend/core/workspace/setup.py
// 3. Update the pre-commit hook check in .husky/pre-commit if needed
const nodeModulesLocations = [
['node_modules', 'node_modules'],
['apps/frontend/node_modules', 'apps/frontend/node_modules'],
];
// Skip if source doesn't exist
if (!existsSync(sourcePath)) {
debugLog('[TerminalWorktree] Skipping .claude symlink - source does not exist:', sourcePath);
return symlinked;
}
for (const [sourceRel, targetRel] of nodeModulesLocations) {
const sourcePath = path.join(projectPath, sourceRel);
const targetPath = path.join(worktreePath, targetRel);
// Skip if target already exists
if (existsSync(targetPath)) {
debugLog('[TerminalWorktree] Skipping .claude symlink - target already exists:', targetPath);
return symlinked;
}
// Also skip if target is a symlink (even if broken)
try {
lstatSync(targetPath);
debugLog('[TerminalWorktree] Skipping .claude symlink - target exists (possibly broken symlink):', targetPath);
return symlinked;
} catch {
// Target doesn't exist at all - good, we can create symlink
}
// Ensure parent directory exists
const targetDir = path.dirname(targetPath);
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
try {
if (isWindows()) {
symlinkSync(sourcePath, targetPath, 'junction');
debugLog('[TerminalWorktree] Created .claude junction (Windows):', sourceRel, '->', sourcePath);
} else {
const relativePath = path.relative(path.dirname(targetPath), sourcePath);
symlinkSync(relativePath, targetPath);
debugLog('[TerminalWorktree] Created .claude symlink (Unix):', sourceRel, '->', relativePath);
// Skip if source doesn't exist
if (!existsSync(sourcePath)) {
debugLog('[TerminalWorktree] Skipping symlink - source does not exist:', sourceRel);
continue;
}
// Skip if target already exists (don't overwrite existing node_modules)
if (existsSync(targetPath)) {
debugLog('[TerminalWorktree] Skipping symlink - target already exists:', targetRel);
continue;
}
// Also skip if target is a symlink (even if broken)
try {
lstatSync(targetPath);
debugLog('[TerminalWorktree] Skipping symlink - target exists (possibly broken symlink):', targetRel);
continue;
} catch {
// Target doesn't exist at all - good, we can create symlink
}
// Ensure parent directory exists
const targetDir = path.dirname(targetPath);
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
try {
// Platform-specific symlink creation:
// - Windows: Use 'junction' type which requires absolute paths (no admin rights required)
// - Unix (macOS/Linux): Use relative paths for portability (worktree can be moved)
if (isWindows()) {
symlinkSync(sourcePath, targetPath, 'junction');
debugLog('[TerminalWorktree] Created junction (Windows):', targetRel, '->', sourcePath);
} else {
// On Unix, use relative symlinks for portability (matches Python implementation)
const relativePath = path.relative(path.dirname(targetPath), sourcePath);
symlinkSync(relativePath, targetPath);
debugLog('[TerminalWorktree] Created symlink (Unix):', targetRel, '->', relativePath);
}
symlinked.push(targetRel);
} catch (error) {
// Symlink creation can fail on some systems (e.g., FAT32 filesystem, or permission issues)
// Log warning but don't fail - worktree is still usable, just without TypeScript checking
// Note: This warning appears in dev console. Users may see TypeScript errors in pre-commit hooks.
debugError('[TerminalWorktree] Could not create symlink for', targetRel, ':', error);
console.warn(`[TerminalWorktree] Warning: Failed to link ${targetRel} - TypeScript checks may fail in this worktree`);
}
symlinked.push(sourceRel);
} catch (error) {
debugError('[TerminalWorktree] Could not create symlink for .claude:', error);
}
return symlinked;
@@ -834,17 +516,11 @@ async function createTerminalWorktree(
debugLog('[TerminalWorktree] Created worktree in detached HEAD mode from', baseRef);
}
// Set up dependencies (node_modules, venvs, etc.) for tooling support
// Symlink node_modules for TypeScript and tooling support
// This allows pre-commit hooks to run typecheck without npm install in worktree
const setupDeps = await setupWorktreeDependencies(projectPath, worktreePath);
if (setupDeps.length > 0) {
debugLog('[TerminalWorktree] Set up worktree dependencies:', setupDeps.join(', '));
}
// Symlink .claude/ config for Claude Code features (settings, commands, memory)
const symlinkedClaude = symlinkClaudeConfigToWorktree(projectPath, worktreePath);
if (symlinkedClaude.length > 0) {
debugLog('[TerminalWorktree] Symlinked Claude config:', symlinkedClaude.join(', '));
const symlinkedModules = symlinkNodeModulesToWorktree(projectPath, worktreePath);
if (symlinkedModules.length > 0) {
debugLog('[TerminalWorktree] Symlinked dependencies:', symlinkedModules.join(', '));
}
const config: TerminalWorktreeConfig = {
@@ -12,17 +12,6 @@ import type { BrowserWindow } from "electron";
const warnTimestamps = new Map<string, number>();
const WARN_COOLDOWN_MS = 5000; // 5 seconds between warnings per channel
/** Circuit breaker: kill agents after consecutive renderer disposal errors */
const MAX_CONSECUTIVE_DISPOSAL_ERRORS = 10;
let consecutiveDisposalErrors = 0;
let agentManagerRef: { killAll: () => void | Promise<void> } | null = null;
let circuitBreakerTriggered = false;
/** Set agent manager reference for circuit breaker cleanup */
export function setAgentManagerRef(manager: { killAll: () => void | Promise<void> }): void {
agentManagerRef = manager;
}
/**
* Check if a channel is within the warning cooldown period.
* @returns true if within cooldown (should skip warning), false if cooldown expired
@@ -119,9 +108,6 @@ export function safeSendToRenderer(
// All checks passed - safe to send
mainWindow.webContents.send(channel, ...args);
// On successful send, reset circuit breaker state (allow re-trigger after recovery)
consecutiveDisposalErrors = 0;
circuitBreakerTriggered = false;
return true;
} catch (error) {
// Catch any disposal errors that might occur between our checks and the actual send
@@ -129,16 +115,6 @@ export function safeSendToRenderer(
// Only log disposal errors once per channel to avoid log spam
if (errorMessage.includes("disposed") || errorMessage.includes("destroyed")) {
// Circuit breaker: track consecutive disposal errors
consecutiveDisposalErrors++;
if (consecutiveDisposalErrors >= MAX_CONSECUTIVE_DISPOSAL_ERRORS && !circuitBreakerTriggered && agentManagerRef) {
circuitBreakerTriggered = true;
console.error('[safeSendToRenderer] Circuit breaker triggered: killing all agents after renderer death');
Promise.resolve(agentManagerRef.killAll()).catch((err) => {
console.error('[safeSendToRenderer] Error killing agents:', err);
});
}
if (!isWithinCooldown(channel)) {
console.warn(`[safeSendToRenderer] Frame disposed, skipping send: ${channel}`);
recordWarning(channel);
+28 -80
View File
@@ -5,7 +5,6 @@
import { getClaudeProfileManager } from './claude-profile-manager';
import { getUsageMonitor } from './claude-profile/usage-monitor';
import { debugLog } from '../shared/utils/debug-logger';
/**
* Regex pattern to detect Claude Code rate limit messages
@@ -477,14 +476,6 @@ export function getBestAvailableProfileEnv(): BestProfileEnvResult {
const profileManager = getClaudeProfileManager();
const activeProfile = profileManager.getActiveProfile();
debugLog('[RateLimitDetector] getBestAvailableProfileEnv() called:', {
activeProfileId: activeProfile.id,
activeProfileName: activeProfile.name,
hasConfigDir: !!activeProfile.configDir,
configDir: activeProfile.configDir,
weeklyUsagePercent: activeProfile.usage?.weeklyUsagePercent,
});
// Check for explicit rate limit (from previous API errors)
const rateLimitStatus = profileManager.isProfileRateLimited(activeProfile.id);
@@ -501,24 +492,28 @@ export function getBestAvailableProfileEnv(): BestProfileEnvResult {
: undefined;
if (needsSwap) {
debugLog('[RateLimitDetector] Active profile needs swap:', {
activeProfile: activeProfile.name,
isRateLimited: rateLimitStatus.limited,
isAtCapacity,
weeklyUsage: activeProfile.usage?.weeklyUsagePercent,
limitType: rateLimitStatus.type,
resetAt: rateLimitStatus.resetAt
});
if (process.env.DEBUG === 'true') {
console.warn('[RateLimitDetector] Active profile needs swap:', {
activeProfile: activeProfile.name,
isRateLimited: rateLimitStatus.limited,
isAtCapacity,
weeklyUsage: activeProfile.usage?.weeklyUsagePercent,
limitType: rateLimitStatus.type,
resetAt: rateLimitStatus.resetAt
});
}
// Try to find a better profile
const bestProfile = profileManager.getBestAvailableProfile(activeProfile.id);
if (bestProfile) {
debugLog('[RateLimitDetector] Using alternative profile:', {
originalProfile: activeProfile.name,
alternativeProfile: bestProfile.name,
reason: swapReason
});
if (process.env.DEBUG === 'true') {
console.warn('[RateLimitDetector] Using alternative profile:', {
originalProfile: activeProfile.name,
alternativeProfile: bestProfile.name,
reason: swapReason
});
}
// Persist the swap by updating the active profile
// This ensures the UI reflects which account is actually being used
@@ -569,14 +564,6 @@ export function getBestAvailableProfileEnv(): BestProfileEnvResult {
const profileEnv = profileManager.getProfileEnv(bestProfile.id);
debugLog('[RateLimitDetector] Profile env for swapped profile:', {
profileId: bestProfile.id,
hasClaudeConfigDir: !!profileEnv.CLAUDE_CONFIG_DIR,
claudeConfigDir: profileEnv.CLAUDE_CONFIG_DIR,
hasOAuthToken: !!profileEnv.CLAUDE_CODE_OAUTH_TOKEN,
envKeys: Object.keys(profileEnv),
});
return {
env: ensureCleanProfileEnv(profileEnv),
profileId: bestProfile.id,
@@ -589,21 +576,14 @@ export function getBestAvailableProfileEnv(): BestProfileEnvResult {
}
};
} else {
debugLog('[RateLimitDetector] No alternative profile available, using rate-limited/at-capacity profile');
if (process.env.DEBUG === 'true') {
console.warn('[RateLimitDetector] No alternative profile available, using rate-limited/at-capacity profile');
}
}
}
// Use active profile (either it's fine, or no better alternative exists)
const activeEnv = profileManager.getActiveProfileEnv();
debugLog('[RateLimitDetector] Using active profile env (no swap):', {
profileId: activeProfile.id,
hasClaudeConfigDir: !!activeEnv.CLAUDE_CONFIG_DIR,
claudeConfigDir: activeEnv.CLAUDE_CONFIG_DIR,
hasOAuthToken: !!activeEnv.CLAUDE_CODE_OAUTH_TOKEN,
envKeys: Object.keys(activeEnv),
});
return {
env: ensureCleanProfileEnv(activeEnv),
profileId: activeProfile.id,
@@ -615,55 +595,23 @@ export function getBestAvailableProfileEnv(): BestProfileEnvResult {
/**
* Ensure the profile environment is clean for subprocess invocation.
*
* When CLAUDE_CONFIG_DIR is set, we MUST clear both CLAUDE_CODE_OAUTH_TOKEN and
* ANTHROPIC_API_KEY to prevent the Claude Agent SDK from using hardcoded/cached
* tokens or API keys (e.g., from .env file or shell environment) instead of reading
* fresh credentials from the specified config directory.
*
* ANTHROPIC_API_KEY is cleared to prevent Claude Code from using API keys present
* in the shell environment, which would cause it to show "Claude API" instead of
* "Claude Max" and bypass the intended config dir credentials.
* When CLAUDE_CONFIG_DIR is set, we MUST clear CLAUDE_CODE_OAUTH_TOKEN to prevent
* the Claude Agent SDK from using a hardcoded/cached token (e.g., from .env file)
* instead of reading fresh credentials from the specified config directory.
*
* This is critical for multi-account switching: when switching from a rate-limited
* account to an available one, the subprocess must use the new account's credentials.
*
* Also warns if the profile env is empty, which indicates a misconfigured profile.
*
* @param env - Profile environment from getProfileEnv() or getActiveProfileEnv()
* @returns Environment with CLAUDE_CODE_OAUTH_TOKEN and ANTHROPIC_API_KEY cleared if CLAUDE_CONFIG_DIR is set
* @returns Environment with CLAUDE_CODE_OAUTH_TOKEN cleared if CLAUDE_CONFIG_DIR is set
*/
export function ensureCleanProfileEnv(env: Record<string, string>): Record<string, string> {
debugLog('[RateLimitDetector] ensureCleanProfileEnv() input:', {
hasClaudeConfigDir: !!env.CLAUDE_CONFIG_DIR,
claudeConfigDir: env.CLAUDE_CONFIG_DIR,
hasOAuthToken: !!env.CLAUDE_CODE_OAUTH_TOKEN,
willClearOAuthToken: !!env.CLAUDE_CONFIG_DIR,
willClearApiKey: !!env.CLAUDE_CONFIG_DIR,
});
// Warn if the profile environment is empty — this likely indicates a misconfigured profile
if (Object.keys(env).length === 0) {
console.warn('[RateLimitDetector] ensureCleanProfileEnv() received empty profile env — profile may be misconfigured');
}
function ensureCleanProfileEnv(env: Record<string, string>): Record<string, string> {
if (env.CLAUDE_CONFIG_DIR) {
// Clear CLAUDE_CODE_OAUTH_TOKEN and ANTHROPIC_API_KEY to ensure SDK uses credentials from CLAUDE_CONFIG_DIR
// ANTHROPIC_API_KEY must also be cleared to prevent Claude Code from using
// API keys that may be present in the shell environment instead of the config dir credentials.
const cleanedEnv = {
// Clear CLAUDE_CODE_OAUTH_TOKEN to ensure SDK uses credentials from CLAUDE_CONFIG_DIR
return {
...env,
CLAUDE_CODE_OAUTH_TOKEN: '',
ANTHROPIC_API_KEY: ''
CLAUDE_CODE_OAUTH_TOKEN: ''
};
debugLog('[RateLimitDetector] ensureCleanProfileEnv() output:', {
claudeConfigDirPreserved: 'CLAUDE_CONFIG_DIR' in cleanedEnv,
claudeConfigDir: (cleanedEnv as Record<string, string>).CLAUDE_CONFIG_DIR,
oauthTokenCleared: cleanedEnv.CLAUDE_CODE_OAUTH_TOKEN === '',
envKeys: Object.keys(cleanedEnv),
});
return cleanedEnv;
}
return env;
}
@@ -195,20 +195,8 @@ export class TerminalSessionStore {
* 1. Write to temp file
* 2. Rotate current file to backup
* 3. Rename temp to target (atomic on most filesystems)
*
* If an async write is in progress, defers to the async writer to avoid
* both operations competing for the same temp file (ENOENT race condition).
*/
private save(): void {
// If an async write is in progress, don't write synchronously — the async
// writer shares the same temp file path. Instead, mark a pending write so
// saveAsync() will re-save with the latest in-memory data when it finishes.
if (this.writeInProgress) {
this.writePending = true;
debugLog('[TerminalSessionStore] Deferring sync save — async write in progress');
return;
}
try {
const content = JSON.stringify(this.data, null, 2);
@@ -378,9 +366,7 @@ export class TerminalSessionStore {
private updateSessionInMemory(session: TerminalSession): boolean {
// Check if session was deleted - skip if pending deletion
if (this.pendingDelete.has(session.id)) {
debugLog('[TerminalSessionStore] Skipping save for deleted session:', session.id,
'pendingDelete size:', this.pendingDelete.size,
'all pending IDs:', [...this.pendingDelete].join(', '));
console.warn('[TerminalSessionStore] Skipping save for deleted session:', session.id);
return false;
}
@@ -610,27 +596,6 @@ export class TerminalSessionStore {
return sessions.find(s => s.id === sessionId);
}
/**
* Clear a session ID from pendingDelete, allowing saves to proceed.
*
* Called when a terminal is legitimately re-created with the same ID
* (e.g., worktree switching, terminal restart after exit). Without this,
* the 5-second pendingDelete window blocks session persistence for the
* new terminal.
*/
clearPendingDelete(sessionId: string): void {
if (this.pendingDelete.has(sessionId)) {
this.pendingDelete.delete(sessionId);
// Also clear the cleanup timer since we're explicitly clearing
const timer = this.pendingDeleteTimers.get(sessionId);
if (timer) {
clearTimeout(timer);
this.pendingDeleteTimers.delete(sessionId);
}
debugLog('[TerminalSessionStore] Cleared pendingDelete for re-created terminal:', sessionId);
}
}
/**
* Remove a session (from today's sessions)
*
@@ -641,9 +606,6 @@ export class TerminalSessionStore {
// Mark as pending delete BEFORE modifying data to prevent race condition
// with in-flight saveSessionAsync() calls
this.pendingDelete.add(sessionId);
debugLog('[TerminalSessionStore] removeSession: added to pendingDelete:', sessionId,
'pendingDelete size:', this.pendingDelete.size,
'all pending IDs:', [...this.pendingDelete].join(', '));
const todaySessions = this.getTodaysSessions();
if (todaySessions[projectPath]) {
@@ -665,8 +627,6 @@ export class TerminalSessionStore {
const timer = setTimeout(() => {
this.pendingDelete.delete(sessionId);
this.pendingDeleteTimers.delete(sessionId);
debugLog('[TerminalSessionStore] Cleanup timer fired for:', sessionId,
'removing from pendingDelete. Remaining:', this.pendingDelete.size);
}, 5000);
this.pendingDeleteTimers.set(sessionId, timer);
}
@@ -109,16 +109,7 @@ function mockPlatform(platform: 'win32' | 'darwin' | 'linux') {
/**
* Helper to get platform-specific expectations for PATH prefix
*/
function getPathPrefixExpectation(
platform: 'win32' | 'darwin' | 'linux',
pathValue: string,
command: string
): string {
// Absolute executable commands no longer need PATH prefix injection.
if (path.isAbsolute(command)) {
return '';
}
function getPathPrefixExpectation(platform: 'win32' | 'darwin' | 'linux', pathValue: string): string {
if (platform === 'win32') {
// Windows: set "PATH=value" &&
return `set "PATH=${pathValue}" && `;
@@ -127,20 +118,6 @@ function getPathPrefixExpectation(
return `PATH='${pathValue}' `;
}
function expectPathPrefix(
written: string,
platform: 'win32' | 'darwin' | 'linux',
pathValue: string,
command: string
): void {
const expectedPrefix = getPathPrefixExpectation(platform, pathValue, command);
if (expectedPrefix) {
expect(written).toContain(expectedPrefix);
} else {
expect(written).not.toContain('PATH=');
}
}
/**
* Helper to get platform-specific expectations for command quoting
*/
@@ -264,7 +241,7 @@ describe('claude-integration-handler', () => {
const written = mockWriteToPty.mock.calls[0][1] as string;
expect(written).toContain(buildCdCommand('/tmp/project'));
expectPathPrefix(written, platform, '/opt/claude/bin:/usr/bin', "/opt/claude bin/claude's");
expect(written).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expect(written).toContain(getQuotedCommand(platform, "/opt/claude bin/claude's"));
expect(mockReleaseSessionId).toHaveBeenCalledWith('term-1');
expect(mockPersistSession).toHaveBeenCalledWith(terminal);
@@ -425,7 +402,7 @@ describe('claude-integration-handler', () => {
expect(written).toContain(histPrefix);
expect(written).toContain(configDir);
expectPathPrefix(written, platform, '/opt/claude/bin:/usr/bin', command);
expect(written).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expect(written).toContain(getQuotedCommand(platform, command));
expect(written).toContain(clearCmd);
expect(profileManager.getProfile).toHaveBeenCalledWith('prof-2');
@@ -459,7 +436,7 @@ describe('claude-integration-handler', () => {
const written = mockWriteToPty.mock.calls[0][1] as string;
expect(written).toContain(getQuotedCommand(platform, command));
expectPathPrefix(written, platform, '/opt/claude/bin:/usr/bin', command);
expect(written).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expect(profileManager.getProfile).toHaveBeenCalledWith('prof-3');
expect(profileManager.markProfileUsed).toHaveBeenCalledWith('prof-3');
expect(mockPersistSession).toHaveBeenCalledWith(terminal);
@@ -483,7 +460,7 @@ describe('claude-integration-handler', () => {
resumeClaude(terminal, 'abc123', () => null);
const resumeCall = mockWriteToPty.mock.calls[0][1] as string;
expectPathPrefix(resumeCall, platform, '/opt/claude/bin:/usr/bin', '/opt/claude/bin/claude');
expect(resumeCall).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expect(resumeCall).toContain(getQuotedCommand(platform, '/opt/claude/bin/claude') + ' --continue');
expect(resumeCall).not.toContain('--resume');
// sessionId is cleared because --continue doesn't track specific sessions
@@ -679,7 +656,7 @@ describe('invokeClaudeAsync', () => {
const written = mockWriteToPty.mock.calls[0][1] as string;
expect(written).toContain(buildCdCommand('/tmp/project'));
expectPathPrefix(written, platform, '/opt/claude/bin:/usr/bin', '/opt/claude/bin/claude');
expect(written).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expect(mockReleaseSessionId).toHaveBeenCalledWith('term-1');
expect(mockPersistSession).toHaveBeenCalledWith(terminal);
expect(profileManager.markProfileUsed).toHaveBeenCalledWith('default');
@@ -937,8 +914,7 @@ describe('claude-integration-handler - Helper Functions', () => {
// Use a default terminal name pattern so renaming logic kicks in
const terminal = createMockTerminal({ title: 'Terminal 1' });
const mockWindow = {
isDestroyed: () => false,
webContents: { send: vi.fn(), isDestroyed: () => false }
webContents: { send: vi.fn() }
};
finalizeClaudeInvoke(
@@ -958,8 +934,7 @@ describe('claude-integration-handler - Helper Functions', () => {
// Use a default terminal name pattern so renaming logic kicks in
const terminal = createMockTerminal({ title: 'Terminal 2' });
const mockWindow = {
isDestroyed: () => false,
webContents: { send: vi.fn(), isDestroyed: () => false }
webContents: { send: vi.fn() }
};
finalizeClaudeInvoke(
@@ -980,8 +955,7 @@ describe('claude-integration-handler - Helper Functions', () => {
const terminal = createMockTerminal({ title: 'Terminal 3' });
const mockSend = vi.fn();
const mockWindow = {
isDestroyed: () => false,
webContents: { send: mockSend, isDestroyed: () => false }
webContents: { send: mockSend }
};
finalizeClaudeInvoke(
@@ -1006,8 +980,7 @@ describe('claude-integration-handler - Helper Functions', () => {
const terminal = createMockTerminal({ title: 'Claude' });
const mockSend = vi.fn();
const mockWindow = {
isDestroyed: () => false,
webContents: { send: mockSend, isDestroyed: () => false }
webContents: { send: mockSend }
};
finalizeClaudeInvoke(
@@ -1031,8 +1004,7 @@ describe('claude-integration-handler - Helper Functions', () => {
const terminal = createMockTerminal({ title: 'My Custom Terminal' });
const mockSend = vi.fn();
const mockWindow = {
isDestroyed: () => false,
webContents: { send: mockSend, isDestroyed: () => false }
webContents: { send: mockSend }
};
finalizeClaudeInvoke(
@@ -16,7 +16,6 @@ import { getEmailFromConfigDir } from '../claude-profile/profile-utils';
import * as OutputParser from './output-parser';
import * as SessionHandler from './session-handler';
import * as PtyManager from './pty-manager';
import { safeSendToRenderer } from '../ipc-handlers/utils';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
import { escapeShellArg, escapeForWindowsDoubleQuote, buildCdCommand } from '../../shared/utils/shell-escape';
import { getClaudeCliInvocation, getClaudeCliInvocationAsync } from '../claude-cli-utils';
@@ -117,19 +116,6 @@ function normalizePathForBash(envPath: string): string {
return isWindows() ? envPath.replace(/;/g, ':') : envPath;
}
/**
* Determine whether a command already resolves via an absolute executable path.
*
* When true, we should avoid prefixing PATH=... into the typed shell command because:
* 1) PATH is not needed to locate the executable
* 2) very long PATH prefixes create huge echoed command lines that can stress terminal rendering
*/
function isAbsoluteExecutableCommand(command: string): boolean {
const trimmed = command.trim();
if (!trimmed) return false;
return path.isAbsolute(trimmed);
}
/**
* Generate temp file content for OAuth token based on platform
*
@@ -394,8 +380,11 @@ export function finalizeClaudeInvoke(
: 'Claude';
terminal.title = title;
// Notify renderer of title change (use safeSendToRenderer to prevent SIGABRT on disposed frame)
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, title);
// Notify renderer of title change
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, title);
}
}
// Persist session if project path is available
@@ -445,15 +434,18 @@ export function handleRateLimit(
const autoSwitchSettings = profileManager.getAutoSwitchSettings();
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_RATE_LIMIT, {
terminalId: terminal.id,
resetTime,
detectedAt: new Date().toISOString(),
profileId: currentProfileId,
suggestedProfileId: bestProfile?.id,
suggestedProfileName: bestProfile?.name,
autoSwitchEnabled: autoSwitchSettings.autoSwitchOnRateLimit
} as RateLimitEvent);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_RATE_LIMIT, {
terminalId: terminal.id,
resetTime,
detectedAt: new Date().toISOString(),
profileId: currentProfileId,
suggestedProfileId: bestProfile?.id,
suggestedProfileName: bestProfile?.name,
autoSwitchEnabled: autoSwitchSettings.autoSwitchOnRateLimit
} as RateLimitEvent);
}
if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit && bestProfile) {
console.warn('[ClaudeIntegration] Auto-switching to profile:', bestProfile.name);
@@ -543,16 +535,19 @@ export function handleOAuthToken(
// Set flag to watch for Claude's ready state (onboarding complete)
terminal.awaitingOnboardingComplete = true;
// needsOnboarding: true tells the UI to show "complete setup" message
// instead of "success" - user should finish Claude's onboarding before closing
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email: emailFromOutput || keychainCreds.email || profile?.email,
success: true,
needsOnboarding: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
const win = getWindow();
if (win) {
// needsOnboarding: true tells the UI to show "complete setup" message
// instead of "success" - user should finish Claude's onboarding before closing
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email: emailFromOutput || keychainCreds.email || profile?.email,
success: true,
needsOnboarding: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
} else {
// Token not in Keychain yet, but profile may still be authenticated via configDir
// Check if profile has valid auth (credentials exist in configDir)
@@ -564,16 +559,19 @@ export function handleOAuthToken(
// Set flag to watch for Claude's ready state (onboarding complete)
terminal.awaitingOnboardingComplete = true;
// needsOnboarding: true tells the UI to show "complete setup" message
// instead of "success" - user should finish Claude's onboarding before closing
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email: emailFromOutput || profile?.email,
success: true,
needsOnboarding: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
const win = getWindow();
if (win) {
// needsOnboarding: true tells the UI to show "complete setup" message
// instead of "success" - user should finish Claude's onboarding before closing
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email: emailFromOutput || profile?.email,
success: true,
needsOnboarding: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
} else {
console.warn('[ClaudeIntegration] Login successful but Keychain token not found and no credentials in configDir - user may need to complete authentication manually');
}
@@ -624,13 +622,16 @@ export function handleOAuthToken(
clearKeychainCache(profile.configDir);
console.warn('[ClaudeIntegration] Profile credentials verified (not caching token):', profileId);
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email,
success: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email,
success: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
} else {
console.error('[ClaudeIntegration] Profile not found for OAuth token:', profileId);
}
@@ -644,14 +645,17 @@ export function handleOAuthToken(
// Defensive null check for active profile
if (!activeProfile) {
console.error('[ClaudeIntegration] Failed to update profile: no active profile found');
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: undefined,
email,
success: false,
message: 'No active profile found',
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: undefined,
email,
success: false,
message: 'No active profile found',
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
return;
}
@@ -682,13 +686,16 @@ export function handleOAuthToken(
clearKeychainCache(activeProfile.configDir);
console.warn('[ClaudeIntegration] Active profile credentials verified (not caching token):', activeProfile.name);
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: activeProfile.id,
email,
success: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: activeProfile.id,
email,
success: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
}
}
@@ -778,11 +785,14 @@ export function handleOnboardingComplete(
}
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_ONBOARDING_COMPLETE, {
terminalId: terminal.id,
profileId,
detectedAt: new Date().toISOString()
} as OnboardingCompleteEvent);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_ONBOARDING_COMPLETE, {
terminalId: terminal.id,
profileId,
detectedAt: new Date().toISOString()
} as OnboardingCompleteEvent);
}
// Trigger immediate usage fetch after successful re-authentication
// This gives the user immediate feedback that their account is working
@@ -835,7 +845,10 @@ export function handleClaudeSessionId(
SessionHandler.updateClaudeSessionId(terminal.projectPath, terminal.id, sessionId);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_CLAUDE_SESSION, terminal.id, sessionId);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_CLAUDE_SESSION, terminal.id, sessionId);
}
}
/**
@@ -866,7 +879,10 @@ export function handleClaudeExit(
}
// Notify renderer to update UI
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_CLAUDE_EXIT, terminal.id);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_CLAUDE_EXIT, terminal.id);
}
}
/**
@@ -1093,9 +1109,7 @@ export function invokeClaude(
const cwdCommand = buildCdCommand(cwd, terminal.shellType);
const { command: claudeCmd, env: claudeEnv } = getClaudeCliInvocation();
const escapedClaudeCmd = escapeShellCommand(claudeCmd);
const pathPrefix = isAbsoluteExecutableCommand(claudeCmd)
? ''
: buildPathPrefix(claudeEnv.PATH || '');
const pathPrefix = buildPathPrefix(claudeEnv.PATH || '');
const needsEnvOverride: boolean = !!(profileId && profileId !== previousProfileId);
debugLog('[ClaudeIntegration:invokeClaude] Environment override check:', {
@@ -1182,9 +1196,7 @@ export function resumeClaude(
const { command: claudeCmd, env: claudeEnv } = getClaudeCliInvocation();
const escapedClaudeCmd = escapeShellCommand(claudeCmd);
const pathPrefix = isAbsoluteExecutableCommand(claudeCmd)
? ''
: buildPathPrefix(claudeEnv.PATH || '');
const pathPrefix = buildPathPrefix(claudeEnv.PATH || '');
// Always use --continue which resumes the most recent session in the current directory.
// This is more reliable than --resume with session IDs since Auto Claude already restores
@@ -1208,7 +1220,10 @@ export function resumeClaude(
// This preserves user-customized names and prevents renaming on every resume
if (shouldAutoRenameTerminal(terminal.title)) {
terminal.title = 'Claude';
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, 'Claude');
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, 'Claude');
}
}
// Persist session
@@ -1298,9 +1313,7 @@ export async function invokeClaudeAsync(
});
const escapedClaudeCmd = escapeShellCommand(claudeCmd);
const pathPrefix = isAbsoluteExecutableCommand(claudeCmd)
? ''
: buildPathPrefix(claudeEnv.PATH || '');
const pathPrefix = buildPathPrefix(claudeEnv.PATH || '');
const needsEnvOverride: boolean = !!(profileId && profileId !== previousProfileId);
debugLog('[ClaudeIntegration:invokeClaudeAsync] Environment override check:', {
@@ -1396,9 +1409,7 @@ export async function resumeClaudeAsync(
});
const escapedClaudeCmd = escapeShellCommand(claudeCmd);
const pathPrefix = isAbsoluteExecutableCommand(claudeCmd)
? ''
: buildPathPrefix(claudeEnv.PATH || '');
const pathPrefix = buildPathPrefix(claudeEnv.PATH || '');
// Always use --continue which resumes the most recent session in the current directory.
// This is more reliable than --resume with session IDs since Auto Claude already restores
@@ -1422,7 +1433,10 @@ export async function resumeClaudeAsync(
// This preserves user-customized names and prevents renaming on every resume
if (shouldAutoRenameTerminal(terminal.title)) {
terminal.title = 'Claude';
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, 'Claude');
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, 'Claude');
}
}
// Persist session (async, fire-and-forget to prevent main process blocking)
+9 -47
View File
@@ -209,25 +209,18 @@ export function setupPtyHandlers(
onExitCallback: (terminal: TerminalProcess) => void
): void {
const { id, pty: ptyProcess } = terminal;
terminal.hasExited = false;
// Handle data from terminal
ptyProcess.onData((data) => {
// Shutdown guard (GitHub #1469): skip processing to avoid accessing
// destroyed BrowserWindow.webContents, which triggers pty.node SIGABRT
if (isShuttingDown) return;
if (terminal.hasExited) return;
// Append to output buffer (limit to 100KB)
terminal.outputBuffer = (terminal.outputBuffer + data).slice(-100000);
// Call custom data handler. This must never crash the main process:
// parser logic in higher layers can throw on unexpected output.
try {
onDataCallback(terminal, data);
} catch (error) {
debugError('[PtyManager] onData callback failed for terminal:', id, 'error:', error);
}
// Call custom data handler
onDataCallback(terminal, data);
// Send to renderer with isDestroyed() check to prevent crashes
// when the window is closed during terminal activity
@@ -236,9 +229,6 @@ export function setupPtyHandlers(
// Handle terminal exit
ptyProcess.onExit(({ exitCode }) => {
terminal.hasExited = true;
// Drop any queued writes for this terminal to avoid writing to dead PTYs.
pendingWrites.delete(id);
debugLog('[PtyManager] Terminal exited:', id, 'code:', exitCode);
// Always resolve pending exit promises, even during shutdown
@@ -258,13 +248,8 @@ export function setupPtyHandlers(
// when the window is closed during terminal exit
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_EXIT, id, exitCode);
// Call custom exit handler. Guard against unexpected exceptions so PTY exit
// handling remains robust and doesn't take down the main process.
try {
onExitCallback(terminal);
} catch (error) {
debugError('[PtyManager] onExit callback failed for terminal:', id, 'error:', error);
}
// Call custom exit handler
onExitCallback(terminal);
// Only delete if this is the SAME terminal object (not a newly created one with same ID).
// This prevents a race where destroyTerminal() awaits PTY exit, a new terminal is created
@@ -277,16 +262,11 @@ export function setupPtyHandlers(
/**
* Constants for chunked write behavior
* CHUNKED_WRITE_THRESHOLD: Data larger than this (bytes) will be written in chunks.
* Set high enough that typical pastes go through as a single synchronous write.
* CHUNK_SIZE: Size of each chunk. Larger chunks = fewer event-loop yields = less
* GPU pressure when many terminals are rendering simultaneously.
* Previous values (1000/100) caused GPU context exhaustion: a 9KB paste produced
* ~91 setImmediate yields, letting GPU rendering tasks from 8+ terminals pile up
* until ContextResult::kTransientFailure crashed the app.
* CHUNKED_WRITE_THRESHOLD: Data larger than this (bytes) will be written in chunks
* CHUNK_SIZE: Size of each chunk - smaller chunks yield to event loop more frequently
*/
const CHUNKED_WRITE_THRESHOLD = 16_384;
const CHUNK_SIZE = 8_192;
const CHUNKED_WRITE_THRESHOLD = 1000;
const CHUNK_SIZE = 100;
/**
* Write queue per terminal to prevent interleaving of concurrent writes.
@@ -300,11 +280,6 @@ const pendingWrites = new Map<string, Promise<void>>();
*/
function performWrite(terminal: TerminalProcess, data: string): Promise<void> {
return new Promise((resolve) => {
if (terminal.hasExited) {
resolve();
return;
}
// For large commands, write in chunks to prevent blocking
if (data.length > CHUNKED_WRITE_THRESHOLD) {
debugLog('[PtyManager:writeToPty] Large write detected, using chunked write');
@@ -313,7 +288,7 @@ function performWrite(terminal: TerminalProcess, data: string): Promise<void> {
const writeChunk = () => {
// Check if terminal is still valid before writing
if (!terminal.pty || terminal.hasExited) {
if (!terminal.pty) {
debugError('[PtyManager:writeToPty] Terminal PTY no longer valid, aborting chunked write');
resolve();
return;
@@ -359,10 +334,6 @@ function performWrite(terminal: TerminalProcess, data: string): Promise<void> {
*/
export function writeToPty(terminal: TerminalProcess, data: string): void {
debugLog('[PtyManager:writeToPty] About to write to pty, data length:', data.length);
if (terminal.hasExited) {
debugError('[PtyManager:writeToPty] Skipping write to exited terminal:', terminal.id);
return;
}
// Get the previous write Promise for this terminal (if any)
const previousWrite = pendingWrites.get(terminal.id) || Promise.resolve();
@@ -390,11 +361,6 @@ export function writeToPty(terminal: TerminalProcess, data: string): void {
* @returns true if resize was successful, false otherwise
*/
export function resizePty(terminal: TerminalProcess, cols: number, rows: number): boolean {
if (terminal.hasExited) {
debugError('[PtyManager] Resize skipped for exited terminal:', terminal.id);
return false;
}
// Validate dimensions
if (cols <= 0 || rows <= 0 || !Number.isFinite(cols) || !Number.isFinite(rows)) {
debugError('[PtyManager] Invalid resize dimensions - terminal:', terminal.id, 'cols:', cols, 'rows:', rows);
@@ -423,10 +389,6 @@ export function resizePty(terminal: TerminalProcess, cols: number, rows: number)
export function killPty(terminal: TerminalProcess, waitForExit: true): Promise<void>;
export function killPty(terminal: TerminalProcess, waitForExit?: false): void;
export function killPty(terminal: TerminalProcess, waitForExit?: boolean): Promise<void> | void {
if (terminal.hasExited) {
return waitForExit ? Promise.resolve() : undefined;
}
if (waitForExit) {
const exitPromise = waitForPtyExit(terminal.id);
try {
@@ -225,18 +225,6 @@ export function persistAllSessions(terminals: Map<string, TerminalProcess>): voi
});
}
/**
* Clear a terminal ID from pendingDelete, allowing session saves to proceed.
*
* Must be called when re-creating a terminal with a previously-used ID
* (e.g., worktree switching, terminal restart after shell exit). Without this,
* the pendingDelete guard blocks persistence for the new terminal.
*/
export function clearPendingDelete(terminalId: string): void {
const store = getTerminalSessionStore();
store.clearPendingDelete(terminalId);
}
/**
* Remove a session from persistent storage
*/
@@ -7,7 +7,6 @@ import * as OutputParser from './output-parser';
import * as ClaudeIntegration from './claude-integration-handler';
import type { TerminalProcess, WindowGetter } from './types';
import { IPC_CHANNELS } from '../../shared/constants';
import { safeSendToRenderer } from '../ipc-handlers/utils';
/**
* Event handler callbacks
@@ -110,7 +109,10 @@ export function createEventCallbacks(
ClaudeIntegration.handleOnboardingComplete(terminal, data, getWindow);
},
onClaudeBusyChange: (terminal, isBusy) => {
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_CLAUDE_BUSY, terminal.id, isBusy);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_CLAUDE_BUSY, terminal.id, isBusy);
}
},
onClaudeExit: (terminal) => {
ClaudeIntegration.handleClaudeExit(terminal, getWindow);
@@ -54,13 +54,6 @@ export async function createTerminal(
return { success: true };
}
// Clear any pendingDelete for this terminal ID. This handles the case where
// a terminal is destroyed and immediately re-created with the same ID (e.g.,
// worktree switching, terminal restart after shell exit). Without this, the
// pendingDelete guard (5-second window) blocks session persistence for the
// new terminal, causing it to be invisible to the session store.
SessionHandler.clearPendingDelete(id);
try {
// For auth terminals, don't inject existing OAuth token - we want a fresh login
const profileEnv = skipOAuthToken ? {} : PtyManager.getActiveProfileEnv();
@@ -108,7 +101,6 @@ export async function createTerminal(
id,
pty: ptyProcess,
isClaudeMode: false,
hasExited: false,
projectPath,
cwd: terminalCwd,
outputBuffer: '',
-2
View File
@@ -28,8 +28,6 @@ export interface TerminalProcess {
shellType?: WindowsShellType;
/** Whether this terminal is waiting for Claude onboarding to complete (login flow) */
awaitingOnboardingComplete?: boolean;
/** Whether PTY has emitted exit; used to avoid writes/resizes on dead PTYs */
hasExited?: boolean;
}
/**
@@ -376,10 +376,6 @@ export interface PRReviewFinding {
endLine?: number;
suggestedFix?: string;
fixable: boolean;
validationStatus?: 'confirmed_valid' | 'dismissed_false_positive' | 'needs_human_review' | null;
validationExplanation?: string;
sourceAgents?: string[];
crossValidated?: boolean;
}
/**
@@ -391,7 +387,7 @@ export interface PRReviewResult {
success: boolean;
findings: PRReviewFinding[];
summary: string;
overallStatus: 'approve' | 'request_changes' | 'comment' | 'in_progress';
overallStatus: 'approve' | 'request_changes' | 'comment';
reviewId?: number;
reviewedAt: string;
error?: string;
@@ -407,8 +403,6 @@ export interface PRReviewResult {
hasPostedFindings?: boolean;
postedFindingIds?: string[];
postedAt?: string;
// In-progress review tracking
inProgressSince?: string;
}
/**
@@ -6,7 +6,7 @@
import { ipcRenderer } from 'electron';
import { IPC_CHANNELS } from '../../../shared/constants/ipc';
import type { IPCResult } from '../../../shared/types/common';
import type { IPCResult } from '@auto-claude/types';
import type { CustomMcpServer, McpHealthCheckResult, McpTestConnectionResult } from '../../../shared/types/project';
export interface McpAPI {
@@ -19,7 +19,6 @@ import {
Sparkles,
GitBranch,
HelpCircle,
Heart,
Wrench,
PanelLeft,
PanelLeftClose
@@ -453,26 +452,6 @@ export function Sidebar({
</Tooltip>
</div>
{/* Sponsor link */}
<Tooltip>
<TooltipTrigger asChild>
<button
onClick={() => window.open('https://github.com/sponsors/AndyMik90', '_blank')}
className={cn(
'flex w-full items-center text-xs transition-colors',
'text-amber-500/70 hover:text-amber-400',
isCollapsed ? 'justify-center' : 'gap-1.5 px-3'
)}
>
<Heart className="h-3.5 w-3.5" />
{!isCollapsed && <span>{t('actions.sponsor')}</span>}
</button>
</TooltipTrigger>
{isCollapsed && (
<TooltipContent side="right">{t('actions.sponsor')}</TooltipContent>
)}
</Tooltip>
{/* New Task button */}
<Tooltip>
<TooltipTrigger asChild>
@@ -66,7 +66,6 @@ export function GitHubPRs({ onOpenSettings, isActive = false }: GitHubPRsProps)
reviewProgress,
startedAt,
isReviewing,
isExternalReview,
previousReviewResult,
hasMore,
selectPR,
@@ -270,7 +269,6 @@ export function GitHubPRs({ onOpenSettings, isActive = false }: GitHubPRsProps)
reviewProgress={reviewProgress}
startedAt={startedAt}
isReviewing={isReviewing}
isExternalReview={isExternalReview}
initialNewCommitsCheck={storedNewCommitsCheck}
isActive={isActive}
isLoadingFiles={isLoadingPRDetails}
@@ -14,7 +14,6 @@ interface FindingItemProps {
finding: PRReviewFinding;
selected: boolean;
posted?: boolean;
disputed?: boolean;
onToggle: () => void;
}
@@ -34,7 +33,7 @@ function getCategoryTranslationKey(category: string): string {
return categoryMap[category.toLowerCase()] || category;
}
export function FindingItem({ finding, selected, posted = false, disputed = false, onToggle }: FindingItemProps) {
export function FindingItem({ finding, selected, posted = false, onToggle }: FindingItemProps) {
const { t } = useTranslation('common');
const CategoryIcon = getCategoryIcon(finding.category);
@@ -46,9 +45,8 @@ export function FindingItem({ finding, selected, posted = false, disputed = fals
<div
className={cn(
"rounded-lg border bg-background p-3 space-y-2 transition-colors",
selected && !posted && !disputed && "ring-2 ring-primary/50",
selected && disputed && "ring-2 ring-purple-500/50",
(posted || (disputed && !selected)) && "opacity-60"
selected && !posted && "ring-2 ring-primary/50",
posted && "opacity-60"
)}
>
{/* Finding Header */}
@@ -74,16 +72,6 @@ export function FindingItem({ finding, selected, posted = false, disputed = fals
{t('prReview.posted')}
</Badge>
)}
{disputed && (
<Badge variant="outline" className="text-xs shrink-0 bg-purple-500/10 text-purple-500 border-purple-500/30">
{t('prReview.disputed')}
</Badge>
)}
{finding.crossValidated && finding.sourceAgents && finding.sourceAgents.length > 1 && (
<Badge variant="outline" className="text-xs shrink-0 bg-green-500/10 text-green-500 border-green-500/30">
{t('prReview.crossValidatedBy', { count: finding.sourceAgents.length })}
</Badge>
)}
<span className="font-medium text-sm break-words">
{finding.title}
</span>
@@ -91,11 +79,6 @@ export function FindingItem({ finding, selected, posted = false, disputed = fals
<p className="text-sm text-muted-foreground break-words">
{finding.description}
</p>
{disputed && finding.validationExplanation && (
<p className="text-xs text-purple-500/80 italic break-words">
{finding.validationExplanation}
</p>
)}
<div className="text-xs text-muted-foreground">
<code className="bg-muted px-1 py-0.5 rounded break-all">
{finding.file}:{finding.line}
@@ -9,10 +9,9 @@ import type { PRReviewFinding } from '../hooks/useGitHubPRs';
interface FindingsSummaryProps {
findings: PRReviewFinding[];
selectedCount: number;
disputedCount?: number;
}
export function FindingsSummary({ findings, selectedCount, disputedCount = 0 }: FindingsSummaryProps) {
export function FindingsSummary({ findings, selectedCount }: FindingsSummaryProps) {
const { t } = useTranslation('common');
// Count findings by severity
@@ -47,11 +46,6 @@ export function FindingsSummary({ findings, selectedCount, disputedCount = 0 }:
{counts.low} {t('prReview.severity.low')}
</Badge>
)}
{disputedCount > 0 && (
<Badge variant="outline" className="bg-purple-500/10 text-purple-500 border-purple-500/30">
{disputedCount} {t('prReview.disputed')}
</Badge>
)}
</div>
<span className="text-xs text-muted-foreground">
{t('prReview.selectedOfTotal', { selected: selectedCount, total: counts.total })}
@@ -35,7 +35,6 @@ import { PRLogs } from './PRLogs';
import type { PRData, PRReviewResult, PRReviewProgress } from '../hooks/useGitHubPRs';
import type { NewCommitsCheck, MergeReadiness, PRLogs as PRLogsType, WorkflowsAwaitingApprovalResult } from '../../../../preload/api/modules/github-api';
import { usePRReviewStore } from '../../../stores/github';
interface PRDetailProps {
pr: PRData;
@@ -45,7 +44,6 @@ interface PRDetailProps {
reviewProgress: PRReviewProgress | null;
startedAt: string | null;
isReviewing: boolean;
isExternalReview?: boolean;
initialNewCommitsCheck?: NewCommitsCheck | null;
isActive?: boolean;
isLoadingFiles?: boolean;
@@ -80,7 +78,6 @@ export function PRDetail({
reviewProgress,
startedAt,
isReviewing,
isExternalReview = false,
initialNewCommitsCheck,
isActive: _isActive = false,
isLoadingFiles = false,
@@ -401,59 +398,6 @@ export function PRDetail({
};
}, [isReviewing, onGetLogs]);
/**
* Completion detection for external (in-progress) reviews
*
* When the backend reports overallStatus === 'in_progress', the store sets
* isExternalReview = true and isReviewing = true. This effect polls the
* review result file every 3 seconds to detect when the external review
* finishes. Once a completed result is found (overallStatus !== 'in_progress'),
* we update the store which will set isReviewing = false and display the result.
*/
useEffect(() => {
if (!isReviewing || !isExternalReview) return;
const POLL_INTERVAL_MS = 3000;
const MAX_POLL_DURATION_MS = 30 * 60 * 1000; // 30 minutes
const pollStart = Date.now();
const pollForCompletion = async () => {
// Timeout: stop polling after 30 minutes to avoid indefinite polling
if (Date.now() - pollStart > MAX_POLL_DURATION_MS) {
usePRReviewStore.getState().setPRReviewResult(projectId, {
prNumber: pr.number,
repo: '',
success: false,
findings: [],
summary: '',
overallStatus: 'comment',
reviewedAt: new Date().toISOString(),
error: 'External review polling timed out after 30 minutes',
});
return;
}
try {
const result = await window.electronAPI.github.getPRReview(projectId, pr.number);
if (result && result.overallStatus !== 'in_progress') {
// Only accept results that were produced AFTER we detected the external review.
// Otherwise this is a stale result from a previous review still on disk
// (in-progress results are intentionally NOT saved to disk).
if (startedAt && result.reviewedAt && new Date(result.reviewedAt) > new Date(startedAt)) {
usePRReviewStore.getState().setPRReviewResult(projectId, result);
}
}
} catch {
// Ignore errors — transient file read failures shouldn't stop polling
}
};
// Poll immediately, then every 3 seconds
pollForCompletion();
const interval = setInterval(pollForCompletion, POLL_INTERVAL_MS);
return () => clearInterval(interval);
}, [isReviewing, isExternalReview, projectId, pr.number, startedAt]);
/**
* Fallback mechanism: Load logs after review completes if not already loaded
*
@@ -1123,7 +1067,6 @@ ${t('prReview.blockedStatusMessageFooter')}`;
<ReviewStatusTree
status={prStatus.status}
isReviewing={isReviewing}
isExternalReview={isExternalReview}
startedAt={startedAt}
reviewResult={reviewResult}
previousReviewResult={previousReviewResult}
@@ -7,7 +7,6 @@
* - Quick select actions (Critical/High, All, None)
* - Collapsible sections for less important findings
* - Visual summary of finding counts
* - Disputed findings shown in a separate collapsible section
*/
import { useState, useMemo } from 'react';
@@ -17,9 +16,6 @@ import {
CheckSquare,
Square,
Send,
ChevronDown,
ChevronRight,
ShieldQuestion,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '../../ui/button';
@@ -51,7 +47,6 @@ export function ReviewFindings({
const [expandedSections, setExpandedSections] = useState<Set<SeverityGroup>>(
new Set<SeverityGroup>(['critical', 'high']) // Critical and High expanded by default
);
const [disputedExpanded, setDisputedExpanded] = useState(false);
// Filter out posted findings - only show unposted findings for selection
const unpostedFindings = useMemo(() =>
@@ -59,24 +54,10 @@ export function ReviewFindings({
[findings, postedIds]
);
// Split unposted findings into active vs disputed (single pass)
const { activeFindings, disputedFindings } = useMemo(() => {
const active: PRReviewFinding[] = [];
const disputed: PRReviewFinding[] = [];
for (const finding of unpostedFindings) {
if (finding.validationStatus === 'dismissed_false_positive') {
disputed.push(finding);
} else {
active.push(finding);
}
}
return { activeFindings: active, disputedFindings: disputed };
}, [unpostedFindings]);
// Check if all findings are posted
const allFindingsPosted = findings.length > 0 && unpostedFindings.length === 0;
// Group ACTIVE unposted findings by severity (disputed go in their own section)
// Group unposted findings by severity (only show findings that haven't been posted)
const groupedFindings = useMemo(() => {
const groups: Record<SeverityGroup, PRReviewFinding[]> = {
critical: [],
@@ -85,7 +66,7 @@ export function ReviewFindings({
low: [],
};
for (const finding of activeFindings) {
for (const finding of unpostedFindings) {
const severity = finding.severity as SeverityGroup;
if (groups[severity]) {
groups[severity].push(finding);
@@ -93,20 +74,20 @@ export function ReviewFindings({
}
return groups;
}, [activeFindings]);
}, [unpostedFindings]);
// Count by severity (active findings only)
// Count by severity (unposted findings only)
const counts = useMemo(() => ({
critical: groupedFindings.critical.length,
high: groupedFindings.high.length,
medium: groupedFindings.medium.length,
low: groupedFindings.low.length,
total: activeFindings.length,
total: unpostedFindings.length,
important: groupedFindings.critical.length + groupedFindings.high.length,
posted: postedIds.size,
}), [groupedFindings, activeFindings.length, postedIds.size]);
}), [groupedFindings, unpostedFindings.length, postedIds.size]);
// Selection hooks - use ACTIVE unposted findings only (Select All excludes disputed)
// Selection hooks - use unposted findings only
const {
toggleFinding,
selectAll,
@@ -114,7 +95,7 @@ export function ReviewFindings({
selectImportant,
toggleSeverityGroup,
} = useFindingSelection({
findings: activeFindings,
findings: unpostedFindings,
selectedIds,
onSelectionChange,
groupedFindings,
@@ -133,12 +114,6 @@ export function ReviewFindings({
});
};
// Count only active findings that are selected (excludes disputed from count)
const selectedActiveCount = useMemo(
() => activeFindings.filter(f => selectedIds.has(f.id)).length,
[activeFindings, selectedIds]
);
// When all findings have been posted, show a success message instead of the selection UI
if (allFindingsPosted) {
return (
@@ -156,11 +131,10 @@ export function ReviewFindings({
return (
<div className="space-y-4">
{/* Summary Stats Bar - show active findings + disputed count */}
{/* Summary Stats Bar - show unposted findings only */}
<FindingsSummary
findings={activeFindings}
selectedCount={selectedActiveCount}
disputedCount={disputedFindings.length}
findings={unpostedFindings}
selectedCount={selectedIds.size}
/>
{/* Quick Select Actions */}
@@ -196,7 +170,7 @@ export function ReviewFindings({
</Button>
</div>
{/* Grouped Findings (active only) */}
{/* Grouped Findings (unposted only) */}
<div className="space-y-3">
{SEVERITY_ORDER.map((severity) => {
const group = groupedFindings[severity];
@@ -246,48 +220,6 @@ export function ReviewFindings({
})}
</div>
{/* Disputed Findings Section */}
{disputedFindings.length > 0 && (
<div className="rounded-lg border border-purple-500/20 bg-purple-500/5">
{/* Disputed Header */}
<button
type="button"
onClick={() => setDisputedExpanded(!disputedExpanded)}
aria-expanded={disputedExpanded}
className="w-full flex items-center gap-2 p-3 text-left hover:bg-purple-500/10 transition-colors rounded-t-lg"
>
{disputedExpanded ? (
<ChevronDown className="h-4 w-4 text-purple-500 shrink-0" />
) : (
<ChevronRight className="h-4 w-4 text-purple-500 shrink-0" />
)}
<ShieldQuestion className="h-4 w-4 text-purple-500 shrink-0" />
<span className="text-sm font-medium text-purple-500">
{t('prReview.disputedByValidator', { count: disputedFindings.length })}
</span>
</button>
{/* Disputed Content */}
{disputedExpanded && (
<div className="p-3 pt-0 space-y-2">
<p className="text-xs text-muted-foreground italic mb-2">
{t('prReview.disputedSectionHint')}
</p>
{disputedFindings.map((finding) => (
<FindingItem
key={finding.id}
finding={finding}
selected={selectedIds.has(finding.id)}
posted={false}
disputed
onToggle={() => toggleFinding(finding.id)}
/>
))}
</div>
)}
</div>
)}
{/* Empty State - no findings at all */}
{findings.length === 0 && (
<div className="text-center py-8 text-muted-foreground">
@@ -21,7 +21,6 @@ export type ReviewStatus =
export interface ReviewStatusTreeProps {
status: ReviewStatus;
isReviewing: boolean;
isExternalReview?: boolean;
startedAt: string | null;
reviewResult: PRReviewResult | null;
previousReviewResult: PRReviewResult | null;
@@ -40,7 +39,6 @@ export interface ReviewStatusTreeProps {
export function ReviewStatusTree({
status,
isReviewing,
isExternalReview = false,
startedAt,
reviewResult,
previousReviewResult,
@@ -139,9 +137,7 @@ export function ReviewStatusTree({
if (isReviewing) {
steps.push({
id: 'analysis',
label: isExternalReview
? t('prReview.reviewStartedExternally')
: t('prReview.analysisInProgress'),
label: t('prReview.analysisInProgress'),
status: 'current',
date: null
});
@@ -259,7 +255,7 @@ export function ReviewStatusTree({
// Status label - explicitly handle all statuses
const getStatusLabel = (): string => {
if (isReviewing) return isExternalReview ? t('prReview.externalReviewDetected') : t('prReview.aiReviewInProgress');
if (isReviewing) return t('prReview.aiReviewInProgress');
switch (status) {
case 'ready_to_merge':
return t('prReview.readyToMerge');
@@ -283,7 +279,7 @@ export function ReviewStatusTree({
<CollapsibleCard
title={statusLabel}
icon={<div className={statusDotColor} />}
headerAction={isReviewing && !isExternalReview ? (
headerAction={isReviewing ? (
<Button
variant="ghost"
size="sm"
@@ -30,31 +30,21 @@ export function useFindingSelection({
onSelectionChange(next);
}, [selectedIds, onSelectionChange]);
// Select all findings (preserving any disputed selections not in active findings)
// Select all findings
const selectAll = useCallback(() => {
const activeIds = new Set(findings.map(f => f.id));
// Preserve selections for disputed findings (IDs not in active findings list)
for (const id of selectedIds) {
if (!findings.some(f => f.id === id)) activeIds.add(id);
}
onSelectionChange(activeIds);
}, [findings, selectedIds, onSelectionChange]);
onSelectionChange(new Set(findings.map(f => f.id)));
}, [findings, onSelectionChange]);
// Clear all selections
const selectNone = useCallback(() => {
onSelectionChange(new Set());
}, [onSelectionChange]);
// Select only critical and high severity findings (preserving disputed selections)
// Select only critical and high severity findings
const selectImportant = useCallback(() => {
const important = [...groupedFindings.critical, ...groupedFindings.high];
const importantIds = new Set(important.map(f => f.id));
// Preserve selections for disputed findings (IDs not in active findings list)
for (const id of selectedIds) {
if (!findings.some(f => f.id === id)) importantIds.add(id);
}
onSelectionChange(importantIds);
}, [groupedFindings, findings, selectedIds, onSelectionChange]);
onSelectionChange(new Set(important.map(f => f.id)));
}, [groupedFindings, onSelectionChange]);
// Toggle entire severity group selection
const toggleSeverityGroup = useCallback((severity: SeverityGroup) => {
@@ -32,7 +32,6 @@ interface UseGitHubPRsResult {
reviewProgress: PRReviewProgress | null;
startedAt: string | null;
isReviewing: boolean;
isExternalReview: boolean;
previousReviewResult: PRReviewResult | null;
isConnected: boolean;
repoFullName: string | null;
@@ -114,7 +113,6 @@ export function useGitHubPRs(
const reviewResult = selectedPRReviewState?.result ?? null;
const reviewProgress = selectedPRReviewState?.progress ?? null;
const isReviewing = selectedPRReviewState?.isReviewing ?? false;
const isExternalReview = selectedPRReviewState?.isExternalReview ?? false;
const previousReviewResult = selectedPRReviewState?.previousResult ?? null;
const startedAt = selectedPRReviewState?.startedAt ?? null;
@@ -729,7 +727,6 @@ export function useGitHubPRs(
reviewProgress,
startedAt,
isReviewing,
isExternalReview,
previousReviewResult,
isConnected,
repoFullName,
@@ -1,6 +1,4 @@
import { useState } from 'react';
import { CheckCircle2, ChevronDown, ChevronUp, Circle, ExternalLink, Play, TrendingUp } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { CheckCircle2, Circle, ExternalLink, Play, TrendingUp } from 'lucide-react';
import { TaskOutcomeBadge } from './TaskOutcomeBadge';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
@@ -9,8 +7,6 @@ import { Progress } from '../ui/progress';
import { ROADMAP_PRIORITY_COLORS } from '../../../shared/constants';
import type { PhaseCardProps } from './types';
const INITIAL_VISIBLE_COUNT = 5;
export function PhaseCard({
phase,
features,
@@ -19,13 +15,8 @@ export function PhaseCard({
onConvertToSpec,
onGoToTask,
}: PhaseCardProps) {
const { t } = useTranslation('common');
const [isExpanded, setIsExpanded] = useState(false);
const completedCount = features.filter((f) => f.status === 'done').length;
const progress = features.length > 0 ? (completedCount / features.length) * 100 : 0;
const visibleFeatures = isExpanded ? features : features.slice(0, INITIAL_VISIBLE_COUNT);
const hiddenCount = features.length - INITIAL_VISIBLE_COUNT;
const hasMoreFeatures = hiddenCount > 0;
return (
<Card className="p-4">
@@ -96,16 +87,13 @@ export function PhaseCard({
<div>
<h4 className="text-sm font-medium mb-2">Features ({features.length})</h4>
<div className="grid gap-2">
{visibleFeatures.map((feature) => (
{features.slice(0, 5).map((feature) => (
<div
key={feature.id}
className="flex items-center justify-between p-2 rounded-md bg-muted/50 hover:bg-muted transition-colors"
className="flex items-center justify-between p-2 rounded-md bg-muted/50 hover:bg-muted cursor-pointer transition-colors"
onClick={() => onFeatureSelect(feature)}
>
<button
type="button"
className="flex items-center gap-2 flex-1 min-w-0 text-left cursor-pointer rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
onClick={() => onFeatureSelect(feature)}
>
<div className="flex items-center gap-2 flex-1 min-w-0">
<Badge
variant="outline"
className={`text-xs ${ROADMAP_PRIORITY_COLORS[feature.priority]}`}
@@ -116,7 +104,7 @@ export function PhaseCard({
{feature.competitorInsightIds && feature.competitorInsightIds.length > 0 && (
<TrendingUp className="h-3 w-3 text-primary flex-shrink-0" />
)}
</button>
</div>
{feature.taskOutcome ? (
<span className="flex-shrink-0">
<TaskOutcomeBadge outcome={feature.taskOutcome} size="lg" showLabel={false} />
@@ -152,26 +140,10 @@ export function PhaseCard({
)}
</div>
))}
{hasMoreFeatures && (
<Button
type="button"
variant="ghost"
onClick={() => setIsExpanded((prev) => !prev)}
aria-expanded={isExpanded}
className="flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground w-full"
>
{isExpanded ? (
<>
<ChevronUp className="h-4 w-4" />
{t('roadmap.showLessFeatures')}
</>
) : (
<>
<ChevronDown className="h-4 w-4" />
{t('roadmap.showMoreFeatures', { count: hiddenCount })}
</>
)}
</Button>
{features.length > 5 && (
<div className="text-sm text-muted-foreground text-center py-1">
+{features.length - 5} more features
</div>
)}
</div>
</div>
@@ -6,7 +6,7 @@ import { Label } from '../ui/label';
import { SettingsSection } from './SettingsSection';
import { useSettingsStore } from '../../stores/settings-store';
import { UI_SCALE_MIN, UI_SCALE_MAX, UI_SCALE_DEFAULT, UI_SCALE_STEP } from '../../../shared/constants';
import type { AppSettings, GpuAcceleration } from '../../../shared/types';
import type { AppSettings } from '../../../shared/types';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
interface DisplaySettingsProps {
@@ -274,45 +274,6 @@ export function DisplaySettings({ settings, onSettingsChange }: DisplaySettingsP
</Select>
</div>
</div>
{/* GPU Acceleration Setting */}
<div className="space-y-3">
<div className="flex items-center justify-between max-w-md">
<div className="space-y-1">
<Label htmlFor="gpuAcceleration" className="text-sm font-medium text-foreground">
{t('gpuAcceleration.label')}
</Label>
<p className="text-sm text-muted-foreground">
{t('gpuAcceleration.description')}
</p>
</div>
<Select
value={settings.gpuAcceleration || 'off'}
onValueChange={(value) => onSettingsChange({
...settings,
gpuAcceleration: value as GpuAcceleration
})}
>
<SelectTrigger id="gpuAcceleration" className="w-72">
<SelectValue />
</SelectTrigger>
<SelectContent className="max-h-60 overflow-y-auto">
<SelectItem value="auto">
{t('gpuAcceleration.auto')}
</SelectItem>
<SelectItem value="on">
{t('gpuAcceleration.on')}
</SelectItem>
<SelectItem value="off">
{t('gpuAcceleration.off')}
</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-xs text-muted-foreground">
{t('gpuAcceleration.helperText')}
</p>
</div>
</div>
</SettingsSection>
);
@@ -1,157 +0,0 @@
/**
* @vitest-environment jsdom
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import '../../../../shared/i18n';
import { DisplaySettings } from '../DisplaySettings';
import type { AppSettings } from '../../../../shared/types';
// Mock the settings store
vi.mock('../../../stores/settings-store', () => ({
useSettingsStore: vi.fn(() => ({
updateSettings: vi.fn()
}))
}));
// Track onValueChange callbacks per Select instance, keyed by the SelectTrigger id
let selectCallbacks: Map<string, (v: string) => void> = new Map();
let currentSelectCallback: ((v: string) => void) | null = null;
// Mock Radix Select to make it testable in jsdom (portals don't work in jsdom)
vi.mock('../../ui/select', () => {
return {
Select: ({ value, onValueChange, children }: { value: string; onValueChange: (v: string) => void; children: React.ReactNode }) => {
currentSelectCallback = onValueChange;
return <div data-value={value}>{children}</div>;
},
SelectTrigger: ({ id, children }: { id?: string; className?: string; children: React.ReactNode }) => {
if (id && currentSelectCallback) {
selectCallbacks.set(id, currentSelectCallback);
currentSelectCallback = null;
}
return <button data-testid={`select-trigger-${id || 'unknown'}`}>{children}</button>;
},
SelectValue: () => null,
SelectContent: ({ children }: { className?: string; children: React.ReactNode }) => (
<div data-testid="select-content">{children}</div>
),
SelectItem: ({ value, children }: { value: string; children: React.ReactNode }) => (
<div role="option" data-testid={`select-item-${value}`} data-value={value}>
{children}
</div>
)
};
});
const defaultSettings: AppSettings = {
uiScale: 100,
logOrder: 'chronological',
gpuAcceleration: 'auto'
} as AppSettings;
describe('DisplaySettings - GPU Acceleration Dropdown', () => {
let mockOnSettingsChange: (settings: AppSettings) => void;
beforeEach(() => {
vi.clearAllMocks();
selectCallbacks = new Map();
currentSelectCallback = null;
mockOnSettingsChange = vi.fn();
});
it('should render the GPU acceleration dropdown with all 3 options', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
expect(screen.getByText('GPU Acceleration')).toBeInTheDocument();
expect(screen.getByTestId('select-item-auto')).toBeInTheDocument();
expect(screen.getByTestId('select-item-on')).toBeInTheDocument();
expect(screen.getByTestId('select-item-off')).toBeInTheDocument();
});
it('should display the correct translated labels for each option', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
expect(screen.getByText('Auto (use WebGL when supported)')).toBeInTheDocument();
expect(screen.getByText('Always on')).toBeInTheDocument();
expect(screen.getByText('Off (default)')).toBeInTheDocument();
});
it('should display the current GPU acceleration value from settings', () => {
const settingsWithOn: AppSettings = { ...defaultSettings, gpuAcceleration: 'on' };
render(
<DisplaySettings settings={settingsWithOn} onSettingsChange={mockOnSettingsChange} />
);
// The GPU acceleration select is identified by its trigger id
const gpuTrigger = screen.getByTestId('select-trigger-gpuAcceleration');
const gpuSelect = gpuTrigger.closest('[data-value]');
expect(gpuSelect).toHaveAttribute('data-value', 'on');
});
it('should default to "off" when gpuAcceleration is not set', () => {
const settingsWithoutGpu: AppSettings = { ...defaultSettings, gpuAcceleration: undefined };
render(
<DisplaySettings settings={settingsWithoutGpu} onSettingsChange={mockOnSettingsChange} />
);
const gpuTrigger = screen.getByTestId('select-trigger-gpuAcceleration');
const gpuSelect = gpuTrigger.closest('[data-value]');
expect(gpuSelect).toHaveAttribute('data-value', 'off');
});
it('should call onSettingsChange with gpuAcceleration "on" when selected', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
selectCallbacks.get('gpuAcceleration')!('on');
expect(mockOnSettingsChange).toHaveBeenCalledWith(
expect.objectContaining({ gpuAcceleration: 'on' })
);
});
it('should call onSettingsChange with gpuAcceleration "off" when selected', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
selectCallbacks.get('gpuAcceleration')!('off');
expect(mockOnSettingsChange).toHaveBeenCalledWith(
expect.objectContaining({ gpuAcceleration: 'off' })
);
});
it('should call onSettingsChange with gpuAcceleration "auto" when selected', () => {
const settingsWithOff: AppSettings = { ...defaultSettings, gpuAcceleration: 'off' };
render(
<DisplaySettings settings={settingsWithOff} onSettingsChange={mockOnSettingsChange} />
);
selectCallbacks.get('gpuAcceleration')!('auto');
expect(mockOnSettingsChange).toHaveBeenCalledWith(
expect.objectContaining({ gpuAcceleration: 'auto' })
);
});
it('should render the GPU acceleration description text', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
expect(
screen.getByText('Use WebGL for terminal rendering (experimental, faster with many terminals)')
).toBeInTheDocument();
});
});
@@ -66,35 +66,11 @@ vi.mock('@xterm/addon-serialize', () => ({
vi.mock('../../../../lib/terminal-buffer-manager', () => ({
terminalBufferManager: {
get: vi.fn(() => ''),
getAndClear: vi.fn(() => ''),
set: vi.fn(),
clear: vi.fn()
}
}));
// Mock WebGL context manager
const mockWebglRegister = vi.fn();
const mockWebglAcquire = vi.fn();
const mockWebglUnregister = vi.fn();
vi.mock('../../../lib/webgl-context-manager', () => ({
webglContextManager: {
register: (...args: unknown[]) => mockWebglRegister(...args),
acquire: (...args: unknown[]) => mockWebglAcquire(...args),
unregister: (...args: unknown[]) => mockWebglUnregister(...args),
}
}));
// Mock settings store (for gpuAcceleration setting)
const mockSettingsStoreState = {
settings: { gpuAcceleration: 'auto' as string | undefined }
};
vi.mock('../../../stores/settings-store', () => ({
useSettingsStore: Object.assign(vi.fn(), {
getState: () => mockSettingsStoreState,
subscribe: vi.fn(() => vi.fn()),
})
}));
// Mock navigator.platform for platform detection
const originalNavigatorPlatform = navigator.platform;
@@ -861,186 +837,3 @@ describe('useXterm keyboard handlers', () => {
});
});
});
describe('useXterm WebGL context management', () => {
// Mock requestAnimationFrame for jsdom environment
const originalRequestAnimationFrame = global.requestAnimationFrame;
const originalCancelAnimationFrame = global.cancelAnimationFrame;
beforeAll(() => {
global.requestAnimationFrame = vi.fn((cb: FrameRequestCallback) => setTimeout(cb, 0) as unknown as number);
global.cancelAnimationFrame = vi.fn((id: number) => clearTimeout(id));
});
afterAll(() => {
global.requestAnimationFrame = originalRequestAnimationFrame;
global.cancelAnimationFrame = originalCancelAnimationFrame;
});
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
// Reset gpuAcceleration to default
mockSettingsStoreState.settings.gpuAcceleration = 'auto';
// Mock ResizeObserver
global.ResizeObserver = vi.fn().mockImplementation(function() {
return { observe: vi.fn(), unobserve: vi.fn(), disconnect: vi.fn() };
});
// Mock window.electronAPI
(window as unknown as { electronAPI: unknown }).electronAPI = {
sendTerminalInput: vi.fn(),
openExternal: vi.fn(),
};
});
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.restoreAllMocks();
});
/**
* Helper to render useXterm and wait for initialization
*/
async function renderUseXterm(terminalId = 'test-webgl-terminal') {
// Set up XTerm mock with dispose tracking
const mockDispose = vi.fn();
(XTerm as unknown as Mock).mockImplementation(function() {
return {
open: vi.fn(),
loadAddon: vi.fn(),
attachCustomKeyEventHandler: vi.fn(),
hasSelection: vi.fn(() => false),
getSelection: vi.fn(() => ''),
paste: vi.fn(),
input: vi.fn(),
onData: vi.fn(),
onResize: vi.fn(),
dispose: mockDispose,
write: vi.fn(),
cols: 80,
rows: 24,
options: {
cursorBlink: true,
cursorStyle: 'block',
fontSize: 14,
fontFamily: 'monospace',
fontWeight: 'normal',
lineHeight: 1,
letterSpacing: 0,
theme: { cursorAccent: '#000000' },
scrollback: 1000
},
refresh: vi.fn()
};
});
const { FitAddon } = await import('@xterm/addon-fit');
(FitAddon as unknown as Mock).mockImplementation(function() {
return { fit: vi.fn(), dispose: vi.fn() };
});
const { WebLinksAddon } = await import('@xterm/addon-web-links');
(WebLinksAddon as unknown as Mock).mockImplementation(function() {
return {};
});
const { SerializeAddon } = await import('@xterm/addon-serialize');
(SerializeAddon as unknown as Mock).mockImplementation(function() {
return { serialize: vi.fn(() => ''), dispose: vi.fn() };
});
let disposeHook: (() => void) | null = null;
const TestWrapper = () => {
const result = useXterm({ terminalId });
// Expose dispose via ref so tests can call it
disposeHook = result.dispose;
return React.createElement('div', { ref: result.terminalRef });
};
await act(async () => {
render(React.createElement(TestWrapper));
});
return { disposeHook: () => disposeHook?.() };
}
it('should lazily import and acquire WebGL context when gpuAcceleration is "auto"', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'auto';
await renderUseXterm('terminal-auto');
// Flush the dynamic import() promise + microtasks
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(mockWebglRegister).toHaveBeenCalledWith('terminal-auto', expect.anything());
expect(mockWebglAcquire).toHaveBeenCalledWith('terminal-auto');
});
it('should lazily import and acquire WebGL context when gpuAcceleration is "on"', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'on';
await renderUseXterm('terminal-on');
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(mockWebglRegister).toHaveBeenCalledWith('terminal-on', expect.anything());
expect(mockWebglAcquire).toHaveBeenCalledWith('terminal-on');
});
it('should NOT import WebGL module at all when gpuAcceleration is "off"', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'off';
await renderUseXterm('terminal-off');
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
// When off, the dynamic import() never fires — no GPU code runs
expect(mockWebglRegister).not.toHaveBeenCalled();
expect(mockWebglAcquire).not.toHaveBeenCalled();
});
it('should unregister WebGL context on terminal disposal', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'auto';
const { disposeHook } = await renderUseXterm('terminal-dispose');
// Flush the dynamic import so the manager ref is populated
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(mockWebglRegister).toHaveBeenCalledWith('terminal-dispose', expect.anything());
// Dispose the terminal
act(() => {
disposeHook();
});
expect(mockWebglUnregister).toHaveBeenCalledWith('terminal-dispose');
});
it('should NOT unregister on disposal when WebGL was never loaded (off)', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'off';
const { disposeHook } = await renderUseXterm('terminal-off-dispose');
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
// Dispose the terminal
act(() => {
disposeHook();
});
// WebGL was never loaded, so unregister should not be called
expect(mockWebglUnregister).not.toHaveBeenCalled();
});
it('should fallback to "off" when gpuAcceleration is undefined (upgrading users)', async () => {
mockSettingsStoreState.settings.gpuAcceleration = undefined;
await renderUseXterm('terminal-undefined');
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
// When undefined, the ?? 'off' fallback means no WebGL import at all
expect(mockWebglRegister).not.toHaveBeenCalled();
expect(mockWebglAcquire).not.toHaveBeenCalled();
});
});
@@ -10,8 +10,6 @@ import { isWindows as checkIsWindows, isLinux as checkIsLinux } from '../../lib/
import { debounce } from '../../lib/debounce';
import { DEFAULT_TERMINAL_THEME } from '../../lib/terminal-theme';
import { debugLog, debugError } from '../../../shared/utils/debug-logger';
import { useSettingsStore } from '../../stores/settings-store';
import type { WebGLContextManagerType } from '../../lib/webgl-context-manager';
interface UseXtermOptions {
terminalId: string;
@@ -60,8 +58,6 @@ export function useXterm({ terminalId, onCommandEnter, onResize, onDimensionsRea
const commandBufferRef = useRef<string>('');
const isDisposedRef = useRef<boolean>(false);
const dimensionsReadyCalledRef = useRef<boolean>(false);
// Lazily-loaded WebGL context manager — only populated when gpuAcceleration !== 'off'
const webglManagerRef = useRef<WebGLContextManagerType | null>(null);
const onResizeRef = useRef(onResize);
const [dimensions, setDimensions] = useState<{ cols: number; rows: number }>({ cols: 80, rows: 24 });
@@ -121,29 +117,6 @@ export function useXterm({ terminalId, onCommandEnter, onResize, onDimensionsRea
xterm.open(terminalRef.current);
// WebGL acceleration: lazily load the WebGL module and acquire a context.
// The dynamic import() ensures NO GPU code (WebGL2 probing, context creation)
// runs unless the user has explicitly enabled GPU acceleration.
// This prevents GPU process instability on systems where WebGL2 is problematic
// (e.g., Apple Silicon Macs with certain macOS / Electron combinations).
const gpuAcceleration = useSettingsStore.getState().settings.gpuAcceleration ?? 'off';
debugLog(`[useXterm] WebGL check for ${terminalId}: gpuAcceleration=${gpuAcceleration}`);
if (gpuAcceleration !== 'off') {
import('../../lib/webgl-context-manager')
.then(({ webglContextManager }) => {
// Guard: terminal may have been disposed while the import was resolving
if (isDisposedRef.current) return;
webglManagerRef.current = webglContextManager;
webglContextManager.register(terminalId, xterm);
webglContextManager.acquire(terminalId);
debugLog(`[useXterm] WebGL acquired for ${terminalId}`);
})
.catch((error) => {
// WebGL is a progressive enhancement — terminal works fine without it
debugError(`[useXterm] WebGL initialization failed for ${terminalId}, falling back to canvas renderer:`, error);
});
}
// Platform detection for copy/paste shortcuts
// Use existing os-detection module instead of custom implementation
const isWindows = checkIsWindows();
@@ -166,18 +139,11 @@ export function useXterm({ terminalId, onCommandEnter, onResize, onDimensionsRea
};
// Helper function to handle paste from clipboard
// Cap paste size to prevent GPU/memory pressure from extremely large clipboard contents.
const MAX_PASTE_BYTES = 1_048_576; // 1 MB
const handlePasteFromClipboard = (): void => {
navigator.clipboard.readText()
.then((text) => {
if (text) {
if (text.length > MAX_PASTE_BYTES) {
console.warn(`[useXterm] Paste truncated from ${text.length} to ${MAX_PASTE_BYTES} bytes`);
xterm.paste(text.slice(0, MAX_PASTE_BYTES));
} else {
xterm.paste(text);
}
xterm.paste(text);
}
})
.catch((err) => {
@@ -579,16 +545,6 @@ export function useXterm({ terminalId, onCommandEnter, onResize, onDimensionsRea
// Serialize buffer before disposing to preserve ANSI formatting
serializeBuffer();
// Release WebGL context before disposing addons and xterm (only if WebGL was loaded)
if (webglManagerRef.current) {
try {
webglManagerRef.current.unregister(terminalId);
} catch (error) {
debugError(`[useXterm] WebGL cleanup failed for ${terminalId}:`, error);
}
webglManagerRef.current = null;
}
// Dispose addons explicitly before disposing xterm
// While xterm.dispose() handles loaded addons, explicit disposal ensures
// resources are freed in a predictable order and prevents potential leaks
@@ -1,149 +1 @@
import * as React from 'react';
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
import { cn } from '../../lib/utils';
import { buttonVariants } from './button';
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
'fixed inset-0 z-50 bg-black/80 backdrop-blur-sm',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 w-full max-w-lg max-h-[90vh]',
'translate-x-[-50%] translate-y-[-50%]',
'bg-card border border-border rounded-2xl p-6',
'shadow-xl',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]',
'data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]',
'duration-200',
className
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-2 text-center sm:text-left',
className
)}
{...props}
/>
);
AlertDialogHeader.displayName = 'AlertDialogHeader';
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-3 mt-6',
className
)}
{...props}
/>
);
AlertDialogFooter.displayName = 'AlertDialogFooter';
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn('text-lg font-semibold text-foreground', className)}
{...props}
/>
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: 'outline' }),
'mt-2 sm:mt-0',
className
)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
export * from '@auto-claude/ui/primitives/alert-dialog';
@@ -1,37 +1 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../../lib/utils';
const badgeVariants = cva(
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
default: 'border-transparent bg-primary text-primary-foreground',
secondary: 'border-transparent bg-secondary text-secondary-foreground',
destructive: 'border-transparent bg-destructive text-destructive-foreground',
outline: 'text-foreground',
success: 'border-transparent bg-success/10 text-success',
warning: 'border-transparent bg-warning/10 text-warning',
info: 'border-transparent bg-info/10 text-info',
purple: 'border-transparent bg-purple-500/10 text-purple-400',
muted: 'border-transparent bg-muted text-muted-foreground',
},
},
defaultVariants: {
variant: 'default',
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };
export * from '@auto-claude/ui/primitives/badge';
@@ -1,64 +1 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../../lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center whitespace-nowrap font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50',
{
variants: {
variant: {
default:
'bg-primary text-primary-foreground hover:bg-primary/90 active:scale-[0.98]',
destructive:
'bg-destructive text-destructive-foreground hover:bg-destructive/90 active:scale-[0.98]',
outline:
'border border-border bg-transparent hover:bg-accent hover:text-accent-foreground active:scale-[0.98]',
secondary:
'bg-secondary text-secondary-foreground hover:bg-secondary/80 active:scale-[0.98]',
ghost:
'hover:bg-accent hover:text-accent-foreground',
link:
'text-primary underline-offset-4 hover:underline',
success:
'bg-[var(--success)] text-[var(--success-foreground)] hover:bg-[var(--success)]/90 active:scale-[0.98]',
warning:
'bg-warning text-warning-foreground hover:bg-warning/90 active:scale-[0.98]',
info:
'bg-info text-info-foreground hover:bg-info/90 active:scale-[0.98]',
},
size: {
default: 'h-10 px-4 py-2 text-sm rounded-lg',
sm: 'h-8 px-3 text-xs rounded-md',
lg: 'h-12 px-6 text-base rounded-lg',
icon: 'h-10 w-10 rounded-lg',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
}
);
Button.displayName = 'Button';
export { Button, buttonVariants };
export * from '@auto-claude/ui/primitives/button';
@@ -1,58 +1 @@
import * as React from 'react';
import { cn } from '../../lib/utils';
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
'rounded-xl border border-border bg-card text-card-foreground transition-all duration-200',
className
)}
{...props}
/>
)
);
Card.displayName = 'Card';
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
)
);
CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn('text-xl font-semibold leading-none tracking-tight', className)}
{...props}
/>
)
);
CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
));
CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
)
);
CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />
)
);
CardFooter.displayName = 'CardFooter';
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
export * from '@auto-claude/ui/primitives/card';
@@ -1,36 +1 @@
import * as React from 'react';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
import { Check, Minus } from 'lucide-react';
import { cn } from '../../lib/utils';
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, checked, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
checked={checked}
className={cn(
'peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
'disabled:cursor-not-allowed disabled:opacity-50',
'data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
'data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground',
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn('flex items-center justify-center text-current')}
>
{checked === 'indeterminate' ? (
<Minus className="h-3 w-3" />
) : (
<Check className="h-3 w-3" />
)}
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
export * from '@auto-claude/ui/primitives/checkbox';
@@ -1,9 +1 @@
import * as CollapsiblePrimitive from '@radix-ui/react-collapsible';
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
export * from '@auto-claude/ui/primitives/collapsible';
@@ -1,301 +1 @@
import * as React from 'react';
import { Check, ChevronDown, Search } from 'lucide-react';
import { cn } from '../../lib/utils';
import { Popover, PopoverContent, PopoverTrigger } from './popover';
import { ScrollArea } from './scroll-area';
export interface ComboboxOption {
value: string;
label: string;
description?: string;
/** Optional group name for grouping options (e.g., "Local Branches", "Remote Branches") */
group?: string;
/** Optional icon to display before the label */
icon?: React.ReactNode;
/** Optional badge to display after the label */
badge?: React.ReactNode;
}
interface ComboboxProps {
/** Currently selected value */
value: string;
/** Callback when value changes */
onValueChange: (value: string) => void;
/** Available options */
options: ComboboxOption[];
/** Placeholder text for the trigger button */
placeholder?: string;
/** Placeholder text for the search input */
searchPlaceholder?: string;
/** Message shown when no results match the search */
emptyMessage?: string;
/** Whether the combobox is disabled */
disabled?: boolean;
/** Additional class names for the trigger */
className?: string;
/** ID for the trigger element */
id?: string;
}
const Combobox = React.forwardRef<HTMLButtonElement, ComboboxProps>(
(
{
value,
onValueChange,
options,
placeholder = 'Select...',
searchPlaceholder = 'Search...',
emptyMessage = 'No results found',
disabled = false,
className,
id,
},
ref
) => {
const [open, setOpen] = React.useState(false);
const [search, setSearch] = React.useState('');
const [focusedIndex, setFocusedIndex] = React.useState(-1);
const inputRef = React.useRef<HTMLInputElement>(null);
const optionRefs = React.useRef<Map<number, HTMLButtonElement>>(new Map());
const listboxId = React.useId();
// Find the selected option's label
const selectedOption = options.find((opt) => opt.value === value);
const displayValue = selectedOption?.label || placeholder;
// Filter options based on search
const filteredOptions = React.useMemo(() => {
if (!search.trim()) return options;
const searchLower = search.toLowerCase();
return options.filter(
(opt) =>
opt.label.toLowerCase().includes(searchLower) ||
opt.description?.toLowerCase().includes(searchLower)
);
}, [options, search]);
// Get option ID for aria-activedescendant
const getOptionId = (index: number) => `${listboxId}-option-${index}`;
// Get the currently focused option ID
const activeDescendant =
focusedIndex >= 0 && focusedIndex < filteredOptions.length
? getOptionId(focusedIndex)
: undefined;
// Focus input when popover opens, reset focused index
React.useEffect(() => {
if (open) {
// Small delay to ensure the popover is rendered
const timer = setTimeout(() => {
inputRef.current?.focus();
}, 0);
// Reset focused index when opening
setFocusedIndex(-1);
return () => clearTimeout(timer);
} else {
// Clear search when closing
setSearch('');
setFocusedIndex(-1);
}
}, [open]);
// Reset focused index when filtered options change
React.useEffect(() => {
setFocusedIndex(-1);
}, []);
// Scroll focused option into view
React.useEffect(() => {
if (focusedIndex >= 0) {
const optionEl = optionRefs.current.get(focusedIndex);
optionEl?.scrollIntoView({ block: 'nearest' });
}
}, [focusedIndex]);
const handleSelect = (optionValue: string) => {
onValueChange(optionValue);
setOpen(false);
setSearch('');
setFocusedIndex(-1);
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (!open) return;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setFocusedIndex((prev) =>
prev < filteredOptions.length - 1 ? prev + 1 : 0
);
break;
case 'ArrowUp':
e.preventDefault();
setFocusedIndex((prev) =>
prev > 0 ? prev - 1 : filteredOptions.length - 1
);
break;
case 'Enter':
e.preventDefault();
if (focusedIndex >= 0 && focusedIndex < filteredOptions.length) {
handleSelect(filteredOptions[focusedIndex].value);
}
break;
case 'Escape':
e.preventDefault();
setOpen(false);
break;
case 'Home':
e.preventDefault();
if (filteredOptions.length > 0) {
setFocusedIndex(0);
}
break;
case 'End':
e.preventDefault();
if (filteredOptions.length > 0) {
setFocusedIndex(filteredOptions.length - 1);
}
break;
}
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild disabled={disabled}>
<button
ref={ref}
type="button"
role="combobox"
aria-expanded={open}
aria-haspopup="listbox"
aria-controls={open ? listboxId : undefined}
id={id}
className={cn(
'flex h-10 w-full items-center justify-between rounded-lg',
'border border-border bg-card px-3 py-2 text-sm',
'text-foreground placeholder:text-muted-foreground',
'focus:outline-none focus:ring-2 focus:ring-ring focus:border-primary',
'disabled:cursor-not-allowed disabled:opacity-50',
'transition-colors duration-200',
className
)}
>
<span className={cn('flex items-center gap-2 truncate', !selectedOption && 'text-muted-foreground')}>
{selectedOption?.icon && (
<span className="shrink-0 text-muted-foreground">{selectedOption.icon}</span>
)}
<span className="truncate">{displayValue}</span>
{selectedOption?.badge && (
<span className="shrink-0">{selectedOption.badge}</span>
)}
</span>
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" />
</button>
</PopoverTrigger>
<PopoverContent
className="w-[var(--radix-popover-trigger-width)] p-0"
align="start"
sideOffset={4}
onKeyDown={handleKeyDown}
>
{/* Search input */}
<div className="flex items-center border-b border-border px-3">
<Search className="h-4 w-4 shrink-0 text-muted-foreground" />
<input
ref={inputRef}
type="text"
role="searchbox"
aria-controls={listboxId}
aria-activedescendant={activeDescendant}
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={searchPlaceholder}
className={cn(
'flex h-10 w-full bg-transparent py-3 px-2 text-sm',
'placeholder:text-muted-foreground',
'focus:outline-none',
'disabled:cursor-not-allowed disabled:opacity-50'
)}
/>
</div>
{/* Options list */}
<ScrollArea className="max-h-[300px]">
<div id={listboxId} role="listbox" aria-label={searchPlaceholder || placeholder} className="p-1">
{filteredOptions.length === 0 ? (
<div className="py-6 text-center text-sm text-muted-foreground">
{emptyMessage}
</div>
) : (
filteredOptions.map((option, index) => {
// Check if we need to render a group header
const prevOption = index > 0 ? filteredOptions[index - 1] : null;
const showGroupHeader = option.group && option.group !== prevOption?.group;
return (
<React.Fragment key={option.value}>
{/* Group header */}
{showGroupHeader && (
<div
role="presentation"
className={cn(
'px-2 py-1.5 text-xs font-semibold text-muted-foreground',
index > 0 && 'mt-1 border-t border-border pt-2'
)}
>
{option.group}
</div>
)}
{/* Option item */}
<button
ref={(el) => {
if (el) {
optionRefs.current.set(index, el);
} else {
optionRefs.current.delete(index);
}
}}
id={getOptionId(index)}
type="button"
role="option"
aria-selected={value === option.value}
onClick={() => handleSelect(option.value)}
onMouseEnter={() => setFocusedIndex(index)}
className={cn(
'relative flex w-full cursor-default select-none items-center',
'rounded-md py-2 pl-8 pr-2 text-sm outline-none',
'hover:bg-accent hover:text-accent-foreground',
'transition-colors duration-150',
focusedIndex === index && 'bg-accent text-accent-foreground'
)}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
{value === option.value && <Check className="h-4 w-4 text-primary" />}
</span>
<span className="flex flex-1 items-center gap-2 truncate">
{option.icon && (
<span className="shrink-0 text-muted-foreground">{option.icon}</span>
)}
<span className="truncate">{option.label}</span>
{option.badge && (
<span className="shrink-0">{option.badge}</span>
)}
</span>
</button>
</React.Fragment>
);
})
)}
</div>
</ScrollArea>
</PopoverContent>
</Popover>
);
}
);
Combobox.displayName = 'Combobox';
export { Combobox };
export * from '@auto-claude/ui/primitives/combobox';
@@ -1,126 +1 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '../../lib/utils';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/80 backdrop-blur-sm',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
interface DialogContentProps extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
hideCloseButton?: boolean;
}
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, hideCloseButton, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 w-full max-w-lg max-h-[90vh]',
'translate-x-[-50%] translate-y-[-50%]',
'bg-card border border-border rounded-2xl p-6',
'shadow-xl',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]',
'data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]',
'duration-200 overflow-hidden flex flex-col',
className
)}
{...props}
>
{children}
{!hideCloseButton && (
<DialogPrimitive.Close
className={cn(
'absolute right-4 top-4 rounded-lg p-1 z-10',
'text-muted-foreground hover:text-foreground',
'hover:bg-accent transition-colors',
'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background',
'disabled:pointer-events-none'
)}
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col space-y-2 text-center sm:text-left', className)} {...props} />
);
DialogHeader.displayName = 'DialogHeader';
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-3 mt-6', className)}
{...props}
/>
);
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn('text-lg font-semibold leading-none tracking-tight text-foreground', className)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
export * from '@auto-claude/ui/primitives/dialog';
@@ -1,201 +1 @@
import * as React from 'react';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { Check, ChevronRight, Circle } from 'lucide-react';
import { cn } from '../../lib/utils';
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent',
inset && 'pl-8',
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
/>
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, collisionPadding = 8, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
collisionPadding={collisionPadding}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md',
'max-h-[var(--radix-dropdown-menu-content-available-height,400px)]',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
inset && 'pl-8',
className
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
'px-2 py-1.5 text-sm font-semibold',
inset && 'pl-8',
className
)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn('ml-auto text-xs tracking-widest opacity-60', className)}
{...props}
/>
);
};
DropdownMenuShortcut.displayName = 'DropdownMenuShortcut';
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};
export * from '@auto-claude/ui/primitives/dropdown-menu';
@@ -1,80 +1,22 @@
import React from 'react';
import { AlertTriangle, RefreshCw } from 'lucide-react';
import { Button } from './button';
import { Card, CardContent } from './card';
import type React from 'react';
import { ErrorBoundary as BaseErrorBoundary } from '@auto-claude/ui/primitives/error-boundary';
import { captureException } from '../../lib/sentry';
interface ErrorBoundaryProps {
children: React.ReactNode;
fallback?: React.ReactNode;
onReset?: () => void;
}
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
}
type BaseErrorBoundaryProps = React.ComponentProps<typeof BaseErrorBoundary>;
/**
* Error boundary component to gracefully handle render errors.
* Prevents the entire page from crashing when a component fails.
* App-level ErrorBoundary that automatically reports errors to Sentry.
* Wraps the shared @auto-claude/ui ErrorBoundary with Sentry integration.
*/
export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
console.error('ErrorBoundary caught an error:', error, errorInfo);
// Report to Sentry with React component stack
captureException(error, {
componentStack: errorInfo.componentStack,
});
}
handleReset = (): void => {
this.setState({ hasError: false, error: null });
this.props.onReset?.();
export function ErrorBoundary(props: BaseErrorBoundaryProps) {
const handleError = (error: Error, errorInfo: React.ErrorInfo): void => {
captureException(error, { componentStack: errorInfo.componentStack });
props.onError?.(error, errorInfo);
};
render(): React.ReactNode {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<Card className="border-destructive m-4">
<CardContent className="pt-6">
<div className="flex flex-col items-center gap-4 text-center">
<AlertTriangle className="h-10 w-10 text-destructive" />
<div className="space-y-2">
<h3 className="font-semibold text-lg">Something went wrong</h3>
<p className="text-sm text-muted-foreground">
An error occurred while rendering this content.
</p>
{this.state.error && (
<p className="text-xs text-muted-foreground font-mono bg-muted p-2 rounded max-w-md overflow-auto">
{this.state.error.message}
</p>
)}
</div>
<Button onClick={this.handleReset} variant="outline" size="sm">
<RefreshCw className="h-4 w-4 mr-2" />
Try Again
</Button>
</div>
</CardContent>
</Card>
);
}
return this.props.children;
}
return (
<BaseErrorBoundary {...props} onError={handleError}>
{props.children}
</BaseErrorBoundary>
);
}
@@ -1,144 +1 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '../../lib/utils';
const FullScreenDialog = DialogPrimitive.Root;
const FullScreenDialogTrigger = DialogPrimitive.Trigger;
const FullScreenDialogPortal = DialogPrimitive.Portal;
const FullScreenDialogClose = DialogPrimitive.Close;
const FullScreenDialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-background/95 backdrop-blur-sm',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
FullScreenDialogOverlay.displayName = 'FullScreenDialogOverlay';
const FullScreenDialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<FullScreenDialogPortal>
<FullScreenDialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed inset-4 z-50 flex flex-col',
'bg-card border border-border rounded-2xl',
'shadow-2xl overflow-hidden',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-98 data-[state=open]:zoom-in-98',
'duration-200',
className
)}
{...props}
>
{children}
<DialogPrimitive.Close
className={cn(
'absolute right-4 top-4 rounded-lg p-2',
'text-muted-foreground hover:text-foreground',
'hover:bg-accent transition-colors',
'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background',
'disabled:pointer-events-none z-10'
)}
>
<X className="h-5 w-5" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</FullScreenDialogPortal>
));
FullScreenDialogContent.displayName = 'FullScreenDialogContent';
const FullScreenDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-1.5 p-6 pb-4 border-b border-border',
className
)}
{...props}
/>
);
FullScreenDialogHeader.displayName = 'FullScreenDialogHeader';
const FullScreenDialogBody = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex-1 overflow-hidden', className)} {...props} />
);
FullScreenDialogBody.displayName = 'FullScreenDialogBody';
const FullScreenDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex items-center justify-end gap-3 p-6 pt-4 border-t border-border',
className
)}
{...props}
/>
);
FullScreenDialogFooter.displayName = 'FullScreenDialogFooter';
const FullScreenDialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
'text-xl font-semibold leading-none tracking-tight text-foreground',
className
)}
{...props}
/>
));
FullScreenDialogTitle.displayName = 'FullScreenDialogTitle';
const FullScreenDialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
FullScreenDialogDescription.displayName = 'FullScreenDialogDescription';
export {
FullScreenDialog,
FullScreenDialogPortal,
FullScreenDialogOverlay,
FullScreenDialogClose,
FullScreenDialogTrigger,
FullScreenDialogContent,
FullScreenDialogHeader,
FullScreenDialogBody,
FullScreenDialogFooter,
FullScreenDialogTitle,
FullScreenDialogDescription,
};
export * from '@auto-claude/ui/primitives/full-screen-dialog';
@@ -1,16 +1,5 @@
// Re-export all UI components
export * from './badge';
export * from './button';
export * from './card';
export * from './combobox';
export * from './dialog';
export * from './input';
export * from './label';
export * from './progress';
export * from './scroll-area';
export * from './select';
export * from './separator';
export * from './switch';
export * from './tabs';
export * from './textarea';
export * from './tooltip';
// Re-export all UI primitives from shared @auto-claude/ui package
export * from '@auto-claude/ui/primitives';
// Override base ErrorBoundary with Sentry-integrated version
export { ErrorBoundary } from './error-boundary';
@@ -1,33 +1 @@
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import { cn } from '../../lib/utils';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, spellCheck, lang, ...props }, ref) => {
const { i18n } = useTranslation();
return (
<input
type={type}
spellCheck={spellCheck ?? true}
lang={lang ?? i18n.language}
className={cn(
'flex h-10 w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground',
'placeholder:text-muted-foreground',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:border-primary',
'disabled:cursor-not-allowed disabled:opacity-50',
'transition-colors duration-200',
'file:border-0 file:bg-transparent file:text-sm file:font-medium',
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = 'Input';
export { Input };
export * from '@auto-claude/ui/primitives/input';
@@ -1,20 +1 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../../lib/utils';
const labelVariants = cva(
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
);
export interface LabelProps
extends React.LabelHTMLAttributes<HTMLLabelElement>,
VariantProps<typeof labelVariants> {}
const Label = React.forwardRef<HTMLLabelElement, LabelProps>(
({ className, ...props }, ref) => (
<label ref={ref} className={cn(labelVariants(), className)} {...props} />
)
);
Label.displayName = 'Label';
export { Label };
export * from '@auto-claude/ui/primitives/label';
@@ -1,36 +1 @@
import * as React from 'react';
import * as PopoverPrimitive from '@radix-ui/react-popover';
import { cn } from '../../lib/utils';
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverAnchor = PopoverPrimitive.Anchor;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2',
'data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
export * from '@auto-claude/ui/primitives/popover';
@@ -1,32 +1 @@
import * as React from 'react';
import * as ProgressPrimitive from '@radix-ui/react-progress';
import { cn } from '../../lib/utils';
interface ProgressProps extends React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> {
animated?: boolean;
}
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
ProgressProps
>(({ className, value, animated, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
'relative h-2 w-full overflow-hidden rounded-full bg-border',
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className={cn(
'h-full w-full flex-1 bg-primary transition-all duration-300 ease-out',
animated && 'progress-working'
)}
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
));
Progress.displayName = ProgressPrimitive.Root.displayName;
export { Progress };
export * from '@auto-claude/ui/primitives/progress';
@@ -1,43 +1 @@
import * as React from 'react';
import * as RadioGroupPrimitive from '@radix-ui/react-radio-group';
import { Circle } from 'lucide-react';
import { cn } from '../../lib/utils';
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn('grid gap-2', className)}
{...props}
ref={ref}
/>
);
});
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
'aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
'disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
});
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export { RadioGroup, RadioGroupItem };
export * from '@auto-claude/ui/primitives/radio-group';
@@ -1,165 +1 @@
/**
* ResizablePanels - A split panel layout with a draggable divider
*
* Features:
* - Smooth drag-to-resize functionality
* - Min/max width constraints
* - Persists width to localStorage
* - Visual feedback on hover and drag
* - Touch support for mobile devices
*/
import { useState, useRef, useEffect, useCallback, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
interface ResizablePanelsProps {
leftPanel: ReactNode;
rightPanel: ReactNode;
defaultLeftWidth?: number; // percentage, default 50
minLeftWidth?: number; // percentage, default 30
maxLeftWidth?: number; // percentage, default 70
storageKey?: string; // localStorage key for persistence
className?: string;
}
export function ResizablePanels({
leftPanel,
rightPanel,
defaultLeftWidth = 50,
minLeftWidth = 30,
maxLeftWidth = 70,
storageKey,
className,
}: ResizablePanelsProps) {
// Load initial width from storage or use default
const [leftWidth, setLeftWidth] = useState(() => {
if (storageKey) {
try {
const stored = localStorage.getItem(storageKey);
if (stored) {
const parsed = parseFloat(stored);
if (!Number.isNaN(parsed) && parsed >= minLeftWidth && parsed <= maxLeftWidth) {
return parsed;
}
}
} catch {
// localStorage may be unavailable (e.g., private browsing)
}
}
return defaultLeftWidth;
});
const [isDragging, setIsDragging] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
// Save to storage when width changes (debounced by only saving when not dragging)
useEffect(() => {
if (storageKey && !isDragging) {
try {
localStorage.setItem(storageKey, leftWidth.toString());
} catch {
// localStorage may be unavailable (e.g., private browsing, quota exceeded)
}
}
}, [leftWidth, storageKey, isDragging]);
const handleMouseDown = useCallback((e: React.MouseEvent) => {
e.preventDefault();
setIsDragging(true);
}, []);
const handleTouchStart = useCallback((e: React.TouchEvent) => {
e.preventDefault();
setIsDragging(true);
}, []);
useEffect(() => {
if (!isDragging) return;
const handleMouseMove = (e: MouseEvent) => {
if (!containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
// Guard against division by zero when container has no width
if (rect.width <= 0) return;
const newWidth = ((e.clientX - rect.left) / rect.width) * 100;
const clampedWidth = Math.max(minLeftWidth, Math.min(maxLeftWidth, newWidth));
setLeftWidth(clampedWidth);
};
const handleMouseUp = () => {
setIsDragging(false);
};
const handleTouchMove = (e: TouchEvent) => {
if (!containerRef.current || e.touches.length === 0) return;
const rect = containerRef.current.getBoundingClientRect();
if (rect.width <= 0) return;
const touch = e.touches[0];
const newWidth = ((touch.clientX - rect.left) / rect.width) * 100;
const clampedWidth = Math.max(minLeftWidth, Math.min(maxLeftWidth, newWidth));
setLeftWidth(clampedWidth);
};
const handleTouchEnd = () => {
setIsDragging(false);
};
// Add user-select: none to body during drag to prevent text selection
document.body.style.userSelect = 'none';
document.body.style.cursor = 'col-resize';
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('touchmove', handleTouchMove, { passive: false });
document.addEventListener('touchend', handleTouchEnd);
return () => {
document.body.style.userSelect = '';
document.body.style.cursor = '';
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
document.removeEventListener('touchmove', handleTouchMove);
document.removeEventListener('touchend', handleTouchEnd);
};
}, [isDragging, minLeftWidth, maxLeftWidth]);
return (
<div
ref={containerRef}
className={cn("flex-1 flex min-h-0", className)}
>
{/* Left panel */}
<div
className="flex flex-col min-w-0 overflow-hidden"
style={{ width: `${leftWidth}%` }}
>
{leftPanel}
</div>
{/* Resizable divider */}
<div
className={cn(
"w-1 flex-shrink-0 relative cursor-col-resize touch-none",
"bg-border transition-colors duration-150",
"hover:bg-primary/40",
isDragging && "bg-primary/60"
)}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
>
{/* Wider invisible hit area for easier grabbing */}
<div className="absolute inset-y-0 -left-1 -right-1 z-10" />
</div>
{/* Right panel */}
<div
className="flex flex-col min-w-0 overflow-hidden"
style={{ width: `${100 - leftWidth}%` }}
>
{rightPanel}
</div>
</div>
);
}
export * from '@auto-claude/ui/primitives/resizable-panels';
@@ -1,58 +1 @@
import * as React from 'react';
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
import { cn } from '../../lib/utils';
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> & {
viewportClassName?: string;
onViewportRef?: (element: HTMLDivElement | null) => void;
}
>(({ className, children, viewportClassName, onViewportRef, ...props }, ref) => {
const viewportRef = React.useCallback(
(element: HTMLDivElement | null) => {
onViewportRef?.(element);
},
[onViewportRef]
);
return (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn('relative overflow-hidden', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
ref={viewportRef}
className={cn('h-full w-full rounded-[inherit]', viewportClassName)}
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
);
});
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = 'vertical', ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
'flex touch-none select-none transition-colors',
orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent p-[1px]',
orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent p-[1px]',
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
export { ScrollArea, ScrollBar };
export * from '@auto-claude/ui/primitives/scroll-area';
@@ -1,166 +1 @@
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '../../lib/utils';
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
'flex h-10 w-full items-center justify-between rounded-lg',
'border border-border bg-card px-3 py-2 text-sm',
'text-foreground placeholder:text-muted-foreground',
'focus:outline-none focus:ring-2 focus:ring-ring focus:border-primary',
'disabled:cursor-not-allowed disabled:opacity-50',
'transition-colors duration-200',
'[&>span]:line-clamp-1',
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 text-muted-foreground" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronUp className="h-4 w-4 text-muted-foreground" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronDown className="h-4 w-4 text-muted-foreground" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden',
'rounded-lg border border-border bg-card text-foreground shadow-lg',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2',
'data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
'p-1 max-h-[300px] overflow-y-auto',
position === 'popper' &&
'w-full min-w-(--radix-select-trigger-width)'
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn('py-1.5 pl-8 pr-2 text-sm font-semibold text-muted-foreground', className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
'relative flex w-full cursor-default select-none items-center',
'rounded-md py-2 pl-8 pr-2 text-sm outline-none',
'focus:bg-accent focus:text-accent-foreground',
'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'transition-colors duration-150',
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4 text-primary" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-border', className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
export * from '@auto-claude/ui/primitives/select';
@@ -1,23 +1 @@
import * as React from 'react';
import * as SeparatorPrimitive from '@radix-ui/react-separator';
import { cn } from '../../lib/utils';
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
'shrink-0 bg-border',
orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',
className
)}
{...props}
/>
));
Separator.displayName = SeparatorPrimitive.Root.displayName;
export { Separator };
export * from '@auto-claude/ui/primitives/separator';
@@ -1,33 +1 @@
import * as React from 'react';
import * as SwitchPrimitives from '@radix-ui/react-switch';
import { cn } from '../../lib/utils';
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
'peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full',
'border-2 border-transparent transition-all duration-200',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-50',
'data-[state=checked]:bg-primary data-[state=unchecked]:bg-border',
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
'pointer-events-none block h-5 w-5 rounded-full shadow-sm ring-0 transition-transform duration-200',
'bg-white dark:bg-foreground',
'data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0',
'data-[state=checked]:bg-primary-foreground'
)}
/>
</SwitchPrimitives.Root>
));
Switch.displayName = SwitchPrimitives.Root.displayName;
export { Switch };
export * from '@auto-claude/ui/primitives/switch';
@@ -1,57 +1 @@
import * as React from 'react';
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '../../lib/utils';
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
'inline-flex h-10 items-center justify-center rounded-lg bg-secondary p-1 text-muted-foreground',
className
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium',
'transition-all duration-200',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
'disabled:pointer-events-none disabled:opacity-50',
'data-[state=active]:bg-card data-[state=active]:text-foreground',
'data-[state=inactive]:hover:text-foreground/80',
className
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
'mt-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
className
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };
export * from '@auto-claude/ui/primitives/tabs';
@@ -1,32 +1 @@
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import { cn } from '../../lib/utils';
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, spellCheck, lang, ...props }, ref) => {
const { i18n } = useTranslation();
return (
<textarea
spellCheck={spellCheck ?? true}
lang={lang ?? i18n.language}
className={cn(
'flex min-h-[80px] w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground',
'placeholder:text-muted-foreground',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:border-primary',
'disabled:cursor-not-allowed disabled:opacity-50',
'transition-colors duration-200',
'resize-none',
className
)}
ref={ref}
{...props}
/>
);
}
);
Textarea.displayName = 'Textarea';
export { Textarea };
export * from '@auto-claude/ui/primitives/textarea';

Some files were not shown because too many files have changed in this diff Show More